diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 449317f5..f91b1285 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -119,17 +119,17 @@ jobs:
print(pathlib.Path(testsuite.__file__).parent)
PY
)
- python -m pytest \
+ python -m pytest -p tests.benchmark.providers \
--rootdir=. \
--confcutdir=. \
- "$TESTSUITE_DIR/benchmark/crud/test_delete_async.py" \
- "$TESTSUITE_DIR/benchmark/crud/test_delete.py" \
- "$TESTSUITE_DIR/benchmark/crud/test_insert_async.py" \
- "$TESTSUITE_DIR/benchmark/crud/test_insert.py" \
- "$TESTSUITE_DIR/benchmark/crud/test_query_async.py" \
- "$TESTSUITE_DIR/benchmark/crud/test_query.py" \
- "$TESTSUITE_DIR/benchmark/crud/test_update_async.py" \
- "$TESTSUITE_DIR/benchmark/crud/test_update.py" \
+ "$TESTSUITE_DIR/benchmark/crud/core/test_delete_async.py" \
+ "$TESTSUITE_DIR/benchmark/crud/core/test_delete.py" \
+ "$TESTSUITE_DIR/benchmark/crud/core/test_insert_async.py" \
+ "$TESTSUITE_DIR/benchmark/crud/core/test_insert.py" \
+ "$TESTSUITE_DIR/benchmark/crud/core/test_query_async.py" \
+ "$TESTSUITE_DIR/benchmark/crud/core/test_query.py" \
+ "$TESTSUITE_DIR/benchmark/crud/core/test_update_async.py" \
+ "$TESTSUITE_DIR/benchmark/crud/core/test_update.py" \
"$TESTSUITE_DIR/benchmark/query" \
"$TESTSUITE_DIR/benchmark/transaction" \
"$TESTSUITE_DIR/benchmark/mixin" \
@@ -221,7 +221,7 @@ jobs:
test-python-315:
name: Python ${{ matrix.python-version }}${{ matrix.freethreaded && 't' || '' }} / postgres ${{ matrix.postgres-version }}
- runs-on: ubuntu-latest
+ runs-on: ${{ matrix.os }}
permissions:
contents: read
strategy:
@@ -236,7 +236,7 @@ jobs:
# psycopg does not support free-threaded builds -- tracked as
# psycopg/psycopg#1095 -- so the GIL leg is the only one this backend
# has, on 3.15 as on every other interpreter.
- - { python-version: '3.15', postgres-version: '18', freethreaded: false }
+ - { python-version: '3.15', postgres-version: '18', freethreaded: false, os: ubuntu-26.04 }
services:
postgres:
@@ -326,25 +326,25 @@ jobs:
- name: Run tests
run: |
export PYTHONPATH=src:tests
- python -m pytest tests/ --tb=short -n 8 --dist=loadgroup
+ python -m pytest tests/ --tb=short -n 8 --dist=loadgroup --ignore=tests/benchmark
test:
name: Python ${{ matrix.python-version }} / postgres ${{ matrix.postgres-version }}
- runs-on: ubuntu-latest
+ runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- - { python-version: '3.8', postgres-version: '9' }
- - { python-version: '3.8', postgres-version: '10' }
- - { python-version: '3.9', postgres-version: '11' }
- - { python-version: '3.10', postgres-version: '12' }
- - { python-version: '3.11', postgres-version: '13' }
- - { python-version: '3.12', postgres-version: '14' }
- - { python-version: '3.13', postgres-version: '15' }
- - { python-version: '3.13', postgres-version: '16' }
- - { python-version: '3.14', postgres-version: '17' }
- - { python-version: '3.14', postgres-version: '18' }
+ - { python-version: '3.8', postgres-version: '9', os: ubuntu-22.04 }
+ - { python-version: '3.8', postgres-version: '10', os: ubuntu-22.04 }
+ - { python-version: '3.9', postgres-version: '11', os: ubuntu-22.04 }
+ - { python-version: '3.10', postgres-version: '12', os: ubuntu-24.04 }
+ - { python-version: '3.11', postgres-version: '13', os: ubuntu-24.04 }
+ - { python-version: '3.12', postgres-version: '14', os: ubuntu-24.04 }
+ - { python-version: '3.13', postgres-version: '15', os: ubuntu-24.04 }
+ - { python-version: '3.13', postgres-version: '16', os: ubuntu-24.04 }
+ - { python-version: '3.14', postgres-version: '17', os: ubuntu-26.04 }
+ - { python-version: '3.14', postgres-version: '18', os: ubuntu-26.04 }
services:
postgres:
@@ -439,14 +439,14 @@ jobs:
if: matrix.postgres-version != '18'
run: |
export PYTHONPATH=src:tests
- python -m pytest tests/ --tb=short -n 8 --dist=loadgroup
+ python -m pytest tests/ --tb=short -n 8 --dist=loadgroup --ignore=tests/benchmark
- name: Run tests with coverage (only for postgres 18 on Python 3.14)
if: matrix.postgres-version == '18' && matrix.python-version == '3.14'
run: |
export PYTHONPATH=src:tests
pip install codecov
- python -m pytest tests/ --tb=short -n auto --dist=loadgroup --cov=src/rhosocial --cov-report=xml
+ python -m pytest tests/ --tb=short -n auto --dist=loadgroup --cov=rhosocial.activerecord.backend.impl.postgres --cov-report=xml --ignore=tests/benchmark
- name: Upload coverage to Codecov
if: matrix.postgres-version == '18' && matrix.python-version == '3.14'
@@ -459,12 +459,12 @@ jobs:
fail_ci_if_error: false
test-postgres-19:
- name: Python 3.14 / postgres 19rc1
+ name: Python 3.14 / postgres 19
runs-on: ubuntu-latest
services:
postgres:
- image: postgres:19rc1
+ image: postgres:19
env:
POSTGRES_DB: test_db
POSTGRES_USER: root
@@ -525,4 +525,4 @@ jobs:
- name: Run tests
run: |
export PYTHONPATH=src:tests
- python -m pytest tests/ --tb=short -n 8 --dist=loadgroup
+ python -m pytest tests/ --tb=short -n 8 --dist=loadgroup --ignore=tests/benchmark
diff --git a/README.md b/README.md
index 0fba9c78..6b008def 100644
--- a/README.md
+++ b/README.md
@@ -1,9 +1,11 @@
+
# rhosocial-activerecord-postgres ($\rho_{\mathbf{AR}\text{-postgres}}$)
[](https://badge.fury.io/py/rhosocial-activerecord-postgres)
[](https://pypi.org/project/rhosocial-activerecord-postgres/)
[](https://github.com/rhosocial/python-activerecord-postgres/actions)
[](https://app.codecov.io/gh/rhosocial/python-activerecord-postgres/tree/main)
+[](docs/en_US/introduction/supported_versions.md)
[](https://github.com/rhosocial/python-activerecord-postgres/blob/main/LICENSE)
@@ -12,64 +14,60 @@
Native arrays & JSONB · Range types · DDL expressions · Sync & async
-This is a backend implementation for [rhosocial-activerecord](https://github.com/rhosocial/python-activerecord).
-It cannot be used standalone.
+This is a PostgreSQL backend implementation for [rhosocial-activerecord](https://github.com/rhosocial/python-activerecord). It cannot be used standalone.
-## Requirements
+**Keywords:** orm, activerecord, postgresql, psycopg, pydantic, python, async, type-safe
-
+## Why This Project?
-_979088a_
+PostgreSQL is a mature, standards-compliant database with a rich type system — native arrays, JSONB, range types, UUID, full-text search, and more. This backend brings the familiar, intuitive ActiveRecord experience to PostgreSQL without trading any of that away.
-- **Python**: `>=3.8`
-- **Core**: `rhosocial-activerecord>=1.0.0.dev0,<2.0.0`
-- **Driver**: `psycopg[binary]>=3.2.13`
-- **CI-tested server versions**: 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19rc1
-- **Published**: PyPI `1.0.0.dev16`
+- **One consistent model API.** A class represents a table; an instance represents a row. No Session object to manage — the same typed models, field mixins, and query expressions used throughout rhosocial-activerecord, now backed by PostgreSQL.
+- **PostgreSQL-native SQL, not a lowest common denominator.** The dialect renders expressions as real PostgreSQL SQL with version-aware capability gating, so native features such as array operators, JSONB containment, ranges, advanced indexes, and `RETURNING` are available when your server supports them.
+- **Sync and async parity.** `PostgresBackend` and `AsyncPostgresBackend` expose the same method names and patterns; the async variant just adds `await`.
-## Installation
+## Quick Start
+
+### Installation
```bash
pip install rhosocial-activerecord-postgres
```
-## Quick Start
+Requires Python 3.8+ and a reachable PostgreSQL server (9.6+); the example below uses the synchronous `PostgresBackend` with `psycopg`.
+
+### End-to-End Example
```python
-from typing import ClassVar, Optional
-from uuid import UUID, uuid4
+"""Save as demo.py and run with: python demo.py"""
+from typing import Annotated, ClassVar
-from rhosocial.activerecord.base import FieldProxy
+from rhosocial.activerecord.base import FieldProxy, UseSqlType
+from rhosocial.activerecord.backend.expression.types import VarCharType
from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig
-from rhosocial.activerecord.backend.expression import CreateTableStatement
-from rhosocial.activerecord.backend.expression.statements import (
- ColumnConstraint,
- ColumnDefinition,
- ColumnPrimaryKeyConstraint,
-)
-from rhosocial.activerecord.backend.expression.types import (
- ArrayType,
- JsonBType,
- TextType,
- UUIDType,
- VarCharType,
-)
+from rhosocial.activerecord.field import DefaultTimestampMixin, IntegerPKMixin
from rhosocial.activerecord.model import ActiveRecord
-class Article(ActiveRecord):
- __table_name__ = "articles"
+class User(
+ IntegerPKMixin, # auto-increment integer primary key (`id`)
+ DefaultTimestampMixin, # injects `created_at` / `updated_at` timestamps
+ ActiveRecord, # persistence, query builder, relations
+):
+ name: Annotated[str, UseSqlType(VarCharType(length=100))]
+ email: Annotated[str, UseSqlType(VarCharType(length=255))]
+ age: int = 0
- id: Optional[UUID] = None
- title: str
- tags: list[str] # maps to text[] / TEXT[]
- metadata: dict # maps to JSONB
+ c: ClassVar[FieldProxy] = FieldProxy() # enables User.c. expressions
- c: ClassVar[FieldProxy] = FieldProxy()
+ @classmethod
+ def table_name(cls) -> str:
+ return "users"
-Article.configure(
+# Configure the PostgreSQL backend and create the table from the model declaration
+User.configure(
PostgresConnectionConfig(
host="localhost",
port=5432,
@@ -79,139 +77,63 @@ Article.configure(
),
PostgresBackend,
)
+User.create_table()
-dialect = Article.__backend__.dialect
-Article.__backend__.execute(*CreateTableStatement(
- dialect,
- "articles",
- columns=[
- ColumnDefinition(
- dialect, "id", UUIDType(dialect),
- constraints=[ColumnConstraint(
- dialect, branch=ColumnPrimaryKeyConstraint(dialect),
- )],
- ),
- ColumnDefinition(dialect, "title", VarCharType(dialect, 200)),
- ColumnDefinition(dialect, "tags", ArrayType(dialect, TextType(dialect))),
- ColumnDefinition(dialect, "metadata", JsonBType(dialect)),
- ],
-).to_sql())
-# CREATE TABLE "articles" ("id" UUID PRIMARY KEY, "title" VARCHAR(200),
-# "tags" TEXT[], "metadata" JSONB)
-```
-
-> Type mapping is not automatic for every field. `list[str]` and `dict` need
-> either an explicit `DataType` in the DDL above or a type adapter; check
-> [type adapters](docs/en_US/type_adapters/) before assuming the column
-> matches your annotation.
+# Create
+alice = User(name="Alice", email="alice@example.com", age=30)
+alice.save()
+print(alice.id) # database-assigned integer primary key
-### Async
+# Query with type-safe expressions
+adults = User.query().where(User.c.age >= 18).all()
+print([user.name for user in adults])
-`AsyncPostgresBackend` exposes the same API. Method names are identical; add
-`await`.
+# Inspect the generated SQL without executing it
+sql, params = User.query().where(User.c.age >= 18).to_sql()
+print(sql, params) # SELECT ... FROM "users" WHERE "users"."age" >= %s (18,)
+```
-```python
-from rhosocial.activerecord.backend.impl.postgres.backend import AsyncPostgresBackend
-from rhosocial.activerecord.model import AsyncActiveRecord
+> **Async parity:** use `AsyncActiveRecord` with `AsyncPostgresBackend` for the async model — same method names, same patterns, just add `await`.
+## Project Architecture
-class Article(AsyncActiveRecord):
- ...
+This package plugs into the rhosocial-activerecord stack as a single layer: models and query expressions come from the core library, the PostgreSQL dialect binds them to PostgreSQL SQL, and psycopg 3 carries the statements to the server. Both the synchronous (`PostgresBackend`) and asynchronous (`AsyncPostgresBackend`) implementations share the same API.
+For the full picture, start with the [Documentation](docs/en_US/README.md).
-Article.configure(config, AsyncPostgresBackend)
-rows = await Article.query().where(Article.c.title == "hello").all()
-```
+**PostgreSQL highlights.** Native arrays, JSONB, UUID, range and geometric types, full-text search, advanced indexing (GIN / GiST / BRIN), and version-gated `RETURNING`. Connection settings live in `PostgresConnectionConfig`; connection management follows a connect-on-use pattern.
-## PostgreSQL-Specific Features
+## Backend Support & Progress
-### Native arrays
+PostgreSQL 9.6 is the minimum tested server version; releases through 19 are supported. See [Supported Versions](docs/en_US/introduction/supported_versions.md) for the full matrix and for which features are version-gated. Requires Python 3.8+ and `psycopg[binary]` 3.2.13+.
-No serialization adapter is needed for `text[]`; operators map straight
-through.
-
-```python
-Article.query().where("tags @> ARRAY[?]", ("python",)).all()
-Article.query().where("? = ANY(tags)", ("python",)).all()
-Article.query().where("tags && ARRAY[?]", ("python",)).all()
-```
+This backend ships as a separate package on top of `rhosocial-activerecord`; the core library provides the framework and this package provides the PostgreSQL implementation.
-### JSONB
+> **⚠️ Development Stage:** This project is under active development. APIs may change, and some features are not yet production-ready.
-```python
-Product.query().where("metadata->>'brand' = ?", ("Dell",)).all()
-Product.query().where("metadata @> ?", ('{"brand": "Dell"}',)).all()
-```
+## Documentation
-## Version Gates
-
-Gates below are the versions at which this backend's own `supports_*`
-switch returns `True`, probed at 8.2, 8.4, 9, 9.2, 9.4, 9.5, 10, 12, 13, 14, 15, 16, 17, 18.
-A version is the first probe at or above the real gate, so each is an
-upper bound within one ladder step. Switches already `True` at the
-oldest release carry no gate and are omitted.
-
-| Min version | Capabilities that turn on |
-|---|---|
-| 8.4 | `array_fill`, `full_text_search`, `truncate_restart_identity`, `xmlagg`, `xmlattributes`, `xmlcomment`, `xmlconcat`, `xmlelement`, `xmlexists`, `xmlforest`, `xmlparse`, `xmlpi`, `xmlroot`, `xmlserialize` |
-| 9 | `for_no_key_update`, `for_share`, `ts_rank_cd` |
-| 9.2 | `json_type`, `range_constructors`, `range_functions`, `range_operators`, `range_type` |
-| 9.4 | `alter_materialized_view`, `filter_clause`, `for_key_share`, `jsonb`, `lateral_join`, `materialized_view`, `materialized_view_concurrent_refresh`, `materialized_view_if_not_exists`, `materialized_view_storage_options`, `materialized_view_tablespace`, `ordered_set_aggregation`, `refresh_materialized_view` |
-| 9.5 | `alter_policy_rename`, `alter_policy_replace`, `array_position`, `create_policy`, `cube`, `drop_policy_if_exists`, `for_update_skip_locked`, `grouping_sets`, `if_not_exists_table`, `index_if_not_exists`, `rls_enable_always`, `rls_enable_disable`, `rls_force`, `rollup`, `trigger_if_not_exists`, `unlogged_table`, `upsert` |
-| 10 | `add_partition`, `aggregate_ddl`, `alter_domain`, `alter_type`, `attach_partition`, `cluster`, `collation_ddl`, `commit_timestamp`, `copy_from`, `copy_to`, `create_domain`, `create_statistics`, `create_type`, `detach_partition`, `foreign_table_ddl`, `function_ddl`, `parallel_append`, `parallel_gather_merge`, `parallel_index_scan`, `parallel_query`, `partitioned_table_creation`, `partition_metadata_introspection`, `phrase_search`, `publication`, `safe_hash_index`, `statistics_dependencies`, `statistics_ndistinct`, `subscription`, `table_logging_switch`, `table_partitioning`, `trigger_referencing`, `type_objects`, `xmltable` |
-| 12 | `call_statement`, `composite_domains`, `concurrent_index`, `default_partition`, `domain_arrays`, `generated_columns`, `gist_include`, `hash_partitioning`, `index_include`, `jit`, `json_path`, `json_table`, `jsonb_subscript`, `materialized_cte`, `nondeterministic_collation`, `parallel_create_index`, `parallel_hash_join`, `parallel_index_only_scan`, `partition_key_update`, `partitionwise_aggregate`, `partitionwise_join`, `reindex_concurrently`, `statistics_mcv`, `stored_generated_columns`, `websearch_tsquery` |
-| 13 | `btree_deduplication`, `database_if_exists`, `database_if_not_exists`, `incremental_sort`, `parallel_vacuum`, `xid8_type` |
-| 14 | `async_foreign_scan`, `binary_replication`, `brin_bloom`, `brin_multivalue`, `concurrent_detach`, `cte_search_cycle`, `multirange`, `multirange_agg`, `multirange_constructor`, `multirange_type`, `numeric_infinity`, `spgist_include`, `streaming_transactions`, `two_phase_decoding`, `vacuum_process_toast` |
-| 15 | `copy_header_match`, `copy_text_header`, `current_role_keyword`, `merge_statement`, `nulls_not_distinct_unique`, `table_set_access_method` |
-| 16 | `concurrent_unique_nulls_not_distinct`, `random_normal`, `regexp_like` |
-| 17 | `copy_force_all`, `copy_log_verbosity`, `copy_on_error`, `json_table_nested_path`, `merge_with_cte`, `returning_old_new`, `update_returning_old` |
-| 18 | `constraint_enforced`, `copy_reject_limit`, `copy_silent_log`, `streaming_btree_index_build` |
-
-PostgreSQL 12 or newer is the practical baseline; anything older misses
-JSON_TABLE, materialized CTEs, generated columns and concurrent index
-operations.
-
-## Known Limitations
-
-- **No connection pooling by default.** This backend connects on use and
- keeps a single connection. Optional pooling is a separate extra:
- `pip install rhosocial-activerecord-postgres[pooling]`, configured with
- `pool_min_size` / `pool_max_size` / `pool_timeout`. See
- [connection management](docs/en_US/installation_and_configuration/pool.md).
-- **`RETURNING` is version-gated.** The basic clause works broadly, but
- `returning_old_new` and `update_returning_old` need PostgreSQL 18.
-- Field annotations do not drive DDL. `list[str]`, `dict` and `UUID` columns
- are described explicitly in the `CreateTableStatement` above.
-
-## Testing
-
-Tests require a reachable PostgreSQL server and must run serially.
+### Contributing
-```bash
-export PYTHONPATH=src:tests
-.venv3.14-ubuntu26.04/bin/pytest tests/
-```
+We welcome contributions! Please see [CONTRIBUTING.md](https://github.com/rhosocial/python-activerecord/blob/main/CONTRIBUTING.md) for guidelines.
-The shared contract suite lives in
-[python-activerecord-testsuite](https://github.com/rhosocial/python-activerecord-testsuite):
+### License
-```bash
-PYTHONPATH=tests .venv3.14-ubuntu26.04/bin/pytest \
- ../python-activerecord-testsuite/src/rhosocial/activerecord/testsuite/feature/
-```
+[Apache License 2.0](LICENSE) — Copyright © 2026 [vistart](https://github.com/vistart)
-## Documentation
+### Documentation
+- **[Documentation Home](docs/en_US/README.md)** — the full documentation table of contents
+- **[Supported Versions](docs/en_US/introduction/supported_versions.md)** — PostgreSQL and Python version matrix
- **[Getting started](docs/en_US/installation_and_configuration/)** — installation, connection configuration, SSL, encoding
- **[PostgreSQL features](docs/en_US/postgres_specific_features/)** — PostgreSQL-specific capabilities
-- **[Type adapters](docs/en_US/type_adapters/)** — type conversion rules, array comparison across databases
+- **[Type adapters](docs/en_US/type_adapters/)** — type conversion rules and array comparison
- **[Transactions](docs/en_US/transaction_support/)** — isolation levels and savepoints
- **[Troubleshooting](docs/en_US/troubleshooting/)** — connection, performance and encoding issues
-## Contributing
-
-See [CONTRIBUTING.md](https://github.com/rhosocial/python-activerecord/blob/main/CONTRIBUTING.md).
-
-## License
+---
-[Apache License 2.0](LICENSE) — Copyright © 2026 [vistart](https://github.com/vistart)
+
diff --git a/changelog.d/72.added.md b/changelog.d/72.added.md
new file mode 100644
index 00000000..b6cc35a9
--- /dev/null
+++ b/changelog.d/72.added.md
@@ -0,0 +1 @@
+Add PostgreSQL-side DDL and migration support: auto-increment suggestions with `SERIAL` on every server version, expression-built DDL, the full 24-entry column-class table including PostGIS `ST_*` plus hstore, vector, text-search, range, multirange, bit-string and geometric operators, the suggested data-type table with the `substitute_data_types` hook, neutral and network-address adapters, a backend migration guide with examples, live and offline CLI tests, RawSQL-free deep EXPLAIN tests, and bridges for the rebuilt testsuite's DDLSource, query/relation/typed_column, restructured query topics, feature CLI and shared benchmarks on directory-owned databases.
diff --git a/changelog.d/72.changed.md b/changelog.d/72.changed.md
new file mode 100644
index 00000000..1357c37c
--- /dev/null
+++ b/changelog.d/72.changed.md
@@ -0,0 +1 @@
+Change the PostgreSQL backend's internal test layout to directory-owned databases built from dialect-only definition classes (no raw SQL in `basic/core`, `query/collation` or `connection`), moving connection-pool tables into `pool_definitions.py`, and decide every capability skip from dialect probes rather than server-version tuples. These are internal changes with no public API impact.
diff --git a/docs/LANGS.md b/docs/LANGS.md
new file mode 100644
index 00000000..e38ff32b
--- /dev/null
+++ b/docs/LANGS.md
@@ -0,0 +1,4 @@
+# Languages
+
+* [English](en_US/)
+* [中文 (Chinese)](zh_CN/)
diff --git a/docs/en_US/README.md b/docs/en_US/README.md
index 55e644f7..24667497 100644
--- a/docs/en_US/README.md
+++ b/docs/en_US/README.md
@@ -4,7 +4,7 @@
> **Example:** "How does the PostgreSQL backend handle JSONB data types? What are the advantages over regular JSON?"
-> 📖 **For detailed usage, please refer to**: [AI-Assisted Development Guide](introduction/ai_assistance.md)
+> 📖 **For detailed usage, please refer to**: [AI-Assisted Development Guide](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/introduction/ai_assistance.md)
## Table of Contents
@@ -44,18 +44,21 @@
7. **[Testing](testing/README.md)**
* **[Test Configuration](testing/configuration.md)**: test environment setup
- * **[Using testsuite for Testing](testing/testsuite.md)**: test suite usage
+ * **[Using testsuite for Testing](https://github.com/rhosocial/python-activerecord-testsuite/blob/main/docs/en_US/README.md)**: test suite usage
* **[Local PostgreSQL Testing](testing/local.md)**: local database testing
8. **[Troubleshooting](troubleshooting/README.md)**
* **[Common Connection Errors](troubleshooting/connection.md)**: connection issue diagnosis
* **[Performance Issues](troubleshooting/performance.md)**: performance bottleneck analysis
- * **[SQL Standard Compliance](troubleshooting/sql_standard.md)**: strict SQL compliance handling
9. **[Scenarios](scenarios/README.md)**
* **[Parallel Worker Processing](scenarios/parallel_workers.md)**: correct usage in multi-process/async concurrent scenarios
-10. **[Worker Isolation Experiment](examples/chapter_05_worker_isolation/README.md)**
- * **[Worker Connection Isolation](examples/chapter_05_worker_isolation/README.md)**: worker process isolation experiment
+10. **[Worker Isolation Experiment](../examples/chapter_05_worker_isolation/README.md)**
+ * **[Worker Connection Isolation](../examples/chapter_05_worker_isolation/README.md)**: worker process isolation experiment
+
+11. **[Migrations](migration/README.md)**
+ * **[PostgreSQL Migration Guide](migration/README.md)**: configuration, transactional DDL, version-gated features, function-style and class-style usage
+ * **[Migration Examples](../examples/migration/README.md)**: runnable PostgreSQL migration scripts
> 📖 **Core Library Documentation**: To learn about the complete functionality of the ActiveRecord framework, please refer to [rhosocial-activerecord documentation](https://github.com/rhosocial/python-activerecord/tree/main/docs/en_US).
diff --git a/docs/en_US/SUMMARY.md b/docs/en_US/SUMMARY.md
new file mode 100644
index 00000000..2c3dad4e
--- /dev/null
+++ b/docs/en_US/SUMMARY.md
@@ -0,0 +1,90 @@
+# Table of Contents
+
+* [rhosocial-activerecord PostgreSQL Backend Documentation](README.md)
+
+## Introduction
+
+* [Overview](introduction/README.md)
+* [Relationship with the core library](introduction/relationship.md)
+* [Supported versions](introduction/supported_versions.md)
+
+## Installation & Configuration
+
+* [Installation & Configuration overview](installation_and_configuration/README.md)
+* [Installation guide](installation_and_configuration/installation.md)
+* [Connection configuration](installation_and_configuration/configuration.md)
+* [SSL/TLS configuration](installation_and_configuration/ssl.md)
+* [Connection management](installation_and_configuration/pool.md)
+* [Client encoding](installation_and_configuration/encoding.md)
+* [Backend groups](installation_and_configuration/backend_group.md)
+
+## Plugins
+
+* [Plugins overview](plugins/README.md)
+* [hstore](plugins/hstore.md)
+* [pg_trgm](plugins/pg_trgm.md)
+* [pgvector](plugins/pgvector.md)
+* [PostGIS](plugins/postgis.md)
+
+## PostgreSQL Specific Features
+
+* [PostgreSQL Specific Features overview](postgres_specific_features/README.md)
+* [PostgreSQL-specific field types](postgres_specific_features/field_types.md)
+* [PostgreSQL dialect expressions](postgres_specific_features/dialect.md)
+* [Advanced indexing](postgres_specific_features/indexing.md)
+* [RETURNING clause](postgres_specific_features/returning.md)
+* [EXPLAIN support](postgres_specific_features/explain.md)
+* [Introspection](postgres_specific_features/introspection.md)
+* [Partitioning](postgres_specific_features/partition.md)
+* [Property graph queries](postgres_specific_features/property_graph_query.md)
+* [Protocol support](postgres_specific_features/protocol_support.md)
+
+## DDL Operations
+
+* [DDL overview](ddl/README.md)
+* [Materialized views](ddl/materialized_view.md)
+* [DDL example](../examples/chapter_04_ddl/ddl.py)
+
+## Migrations
+
+* [Migrations overview](migration/README.md)
+* [Migration examples](../examples/migration/README.md)
+
+## Transaction Support
+
+* [Transaction Support overview](transaction_support/README.md)
+* [Transaction isolation levels](transaction_support/isolation_level.md)
+* [Savepoint support](transaction_support/savepoint.md)
+* [DEFERRABLE mode](transaction_support/deferrable.md)
+* [Deadlock handling](transaction_support/deadlock.md)
+
+## Type Adapters
+
+* [Type Adapters overview](type_adapters/README.md)
+* [PostgreSQL to Python type mapping](type_adapters/mapping.md)
+* [Custom type adapters](type_adapters/custom.md)
+* [Timezone handling](type_adapters/timezone.md)
+* [Array type handling](type_adapters/arrays.md)
+* [Array comparison](type_adapters/array_comparison.md)
+
+## Testing
+
+* [Testing overview](testing/README.md)
+* [Test configuration](testing/configuration.md)
+* [Using testsuite for testing](https://github.com/rhosocial/python-activerecord-testsuite/blob/main/docs/en_US/README.md)
+* [Local PostgreSQL testing](testing/local.md)
+
+## Troubleshooting
+
+* [Troubleshooting overview](troubleshooting/README.md)
+* [Common connection errors](troubleshooting/connection.md)
+* [Performance issues](troubleshooting/performance.md)
+
+## Scenarios
+
+* [Scenarios overview](scenarios/README.md)
+* [Parallel worker processing](scenarios/parallel_workers.md)
+
+## Worker Isolation Experiment
+
+* [Worker connection isolation](../examples/chapter_05_worker_isolation/README.md)
diff --git a/docs/en_US/migration/README.md b/docs/en_US/migration/README.md
new file mode 100644
index 00000000..f30d1859
--- /dev/null
+++ b/docs/en_US/migration/README.md
@@ -0,0 +1,182 @@
+# Migrations — PostgreSQL Backend
+
+> **Scope:** This chapter covers only the PostgreSQL backend's migration-specific concerns:
+> configuring a PostgreSQL backend for migrations, transactional DDL, version-gated features/types,
+> and how the two migration APIs are wired to this backend. It does **not** re-explain the migration
+> system itself — the two authoring APIs, ordering and dependency rules, version records, dry-run
+> internals, the `migrate` CLI, and the exception hierarchy are all documented in the
+> [core migration chapter](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md).
+> Read that chapter first if you are new to migrations; come back here for PostgreSQL details.
+
+> 💡 **AI Prompt:** "Show me a PostgreSQL migration that renders its DDL in a dry run, then applies it
+> inside a transaction and rolls back cleanly if a later statement fails."
+
+## 1. Configuring a PostgreSQL backend for migrations
+
+Migrations run on a backend instance you supply. Build this backend's `PostgresConnectionConfig` and
+`PostgresBackend`, then — importantly — call `introspect_and_adapt()` before running migrations. That
+call detects the live server version and installed extensions so the dialect renders version-gated
+DDL correctly (see §3).
+
+```python
+import os
+
+from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
+from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig
+
+config = PostgresConnectionConfig(
+ host=os.getenv("POSTGRES_HOST", "localhost"),
+ port=int(os.getenv("POSTGRES_PORT", "5432")),
+ database=os.getenv("POSTGRES_DATABASE", "test"),
+ username=os.getenv("POSTGRES_USER", "postgres"),
+ password=os.getenv("POSTGRES_PASSWORD", ""),
+)
+backend = PostgresBackend(connection_config=config)
+backend.connect()
+backend.introspect_and_adapt() # detect server version + installed extensions
+```
+
+Notes specific to this backend:
+
+- `PostgresConnectionConfig` accepts PostgreSQL/libpq-style options (`sslmode`, `search_path`,
+ `default_schema`, `application_name`, `target_session_attrs`, `connect_timeout`, `service`, …).
+ `search_path` / `default_schema` are worth setting when migrations target a non-`public` schema.
+ See [Connection configuration](../installation_and_configuration/configuration.md).
+- The connection runs with driver-level autocommit; transaction boundaries are managed explicitly by
+ the framework. You do **not** need to open a transaction yourself around a migration group —
+ `run_migration_group` does it (§2).
+- `introspect_and_adapt()` falls back to a default version when the server cannot be queried. If a
+ migration needs a specific server version, check it explicitly rather than assuming (§3).
+
+## 2. Transactional DDL — PostgreSQL's key advantage
+
+**PostgreSQL DDL is transactional.** Schema statements such as `CREATE TABLE`, `ALTER TABLE`, and
+`DROP TABLE` participate in a transaction and can be **rolled back cleanly**. This is a genuine
+advantage over backends whose DDL is *non-transactional*: on those, a failure part-way through a
+migration leaves a partially applied schema that must be repaired by hand. On PostgreSQL the same
+failure leaves the schema exactly as it was.
+
+How the system uses this:
+
+- This backend's dialect declares `supports_transactional_ddl() -> True`. The
+ `run_migration_group` path probes `backend.dialect.supports_transactional_ddl()` and records the
+ answer on `MigrationFunctionExecutionError.transactional_ddl` when a function fails.
+- With the default `TransactionMode.AUTO`, a group begins one transaction, runs every function in
+ the group, and commits only if all succeed. Any exception rolls the whole group back — DDL
+ included. A dry run never begins a transaction or writes anything.
+- Consequently a multi-statement migration on PostgreSQL is effectively **all-or-nothing**: you can
+ write `up()`/`down()` functions as a sequence of DDL steps without hand-rolled compensation for a
+ failed step.
+
+```python
+from rhosocial.activerecord.backend.migration import (
+ MigrationFunctionExecutionError,
+ run_migration_group,
+)
+
+assert backend.dialect.supports_transactional_ddl() is True
+
+run_migration_group(backend, [user_fqn], dry_run=True) # renders SQL, writes nothing
+run_migration_group(backend, [user_fqn], record_store=store) # one transaction, then commit
+
+try:
+ run_migration_group(backend, [failing_fqn], record_store=store)
+except MigrationFunctionExecutionError as exc:
+ assert exc.transactional_ddl is True # the failed DDL was rolled back
+```
+
+PostgreSQL-specific caveats that still apply:
+
+- A few PostgreSQL statements cannot run inside a transaction block at all — notably
+ `CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `REFRESH MATERIALIZED VIEW CONCURRENTLY`,
+ and `CREATE DATABASE`/`DROP DATABASE`. Keep them out of a transactional migration group (run them
+ with `transaction_mode=TransactionMode.NONE` from
+ `rhosocial.activerecord.backend.named_expression`) and handle compensation yourself.
+- DDL takes locks; concurrent migrations against the same relations can block or deadlock. Use the
+ backend's [deadlock handling](../transaction_support/deadlock.md) guidance where appropriate.
+- See [Transaction support](../transaction_support/README.md) for isolation levels, savepoints, and
+ DEFERRABLE constraints.
+
+## 3. Version-gated features and types
+
+PostgreSQL features arrive at different server versions, and this backend renders only what the
+target server supports. `introspect_and_adapt()` caches the live server version on the dialect;
+migrations should gate version-specific DDL on it.
+
+- `backend.dialect.version_at_least((major, minor, patch))` — safe predicates; returns `False` when
+ the version is unknown (never raises). `backend.dialect.version_or_none` returns the tuple or
+ `None`. `backend.get_server_version()` queries the server directly.
+- Examples of gated capabilities: `JSONB` (9.4+), stored generated columns (12+), `multirange` types
+ such as `PostgresInt4MultirangeType` (14+), `UNIQUE NULLS NOT DISTINCT` and `MERGE` (15+).
+ The full table is in [Supported versions](../introduction/supported_versions.md), and this
+ backend's version-specific types live under `rhosocial.activerecord.backend.impl.postgres.expression.types`.
+
+```python
+from rhosocial.activerecord.backend.impl.postgres.expression.types import (
+ PostgresInt4MultirangeType,
+)
+
+def create_archive(ctx): # decorated with @migration in a real module
+ # Archive has a PostgresInt4MultirangeType column (PG 14+); skip on older servers.
+ if not ctx.backend.dialect.version_at_least((14, 0, 0)):
+ return
+ ctx.apply(Archive.create_table_statement(backend=ctx.backend))
+```
+
+Always emit DDL through `ctx.apply(...)` so dry runs and version records behave correctly.
+
+## 4. Function-style migrations (`run_migration_group`)
+
+For new work, use `@migration` functions and `run_migration_group`, exactly as the core chapter
+describes — only the backend differs. A complete, PostgreSQL-specific script is
+[`docs/examples/migration/01_transactional_ddl.py`](../../examples/migration/01_transactional_ddl.py):
+it creates a `PostgresBackend`, renders a migration with `dry_run=True`, applies it with a
+`JSONFileMigrationRecordStore`, demonstrates a version-gated type, and shows the
+`transactional_ddl` flag on a failure.
+
+```bash
+# from the repository root
+PYTHONPATH=src python docs/examples/migration/01_transactional_ddl.py
+```
+
+A successful setup requires a reachable PostgreSQL server; configure it with the `POSTGRES_*`
+environment variables. Ordering, dependency validation, and record-store semantics are the system's
+business — see the core chapter, not this page.
+
+## 5. Class-style `named-migration` CLI wiring
+
+The class-style (`NamedMigration`) API is fully supported for existing migrations. This backend's
+CLI exposes a `named-migration` subcommand whose handler lives in
+[`cli/named_migration.py`](../../../src/rhosocial/activerecord/backend/impl/postgres/cli/named_migration.py)
+and delegates to the shared core helper. It builds a `PostgresBackend` (or `AsyncPostgresBackend`
+with `--async`) from the connection arguments and calls `introspect_and_adapt()` before running.
+
+```bash
+python -m rhosocial.activerecord.backend.impl.postgres named-migration \
+ myapp.migrations.v001.CreateUsersTable --host localhost --database mydb --direction up \
+ --record-store ./migrations.json
+python -m rhosocial.activerecord.backend.impl.postgres named-migration \
+ myapp.migrations.v001.CreateUsersTable --database mydb --direction up --dry-run
+python -m rhosocial.activerecord.backend.impl.postgres named-migration \
+ myapp.migrations --all --record-store ./migrations.json --single-transaction
+```
+
+`--direction up|down`, `--record-store`, `--dry-run`, `--describe`, `--list`, `--param KEY=VALUE`,
+`--all`, `--single-transaction`, and `--async` are all supported. `--single-transaction` wraps a
+whole batch in one transaction — which, because PostgreSQL DDL is transactional, genuinely rolls the
+entire batch back on failure. The full end-to-end demos (single migration, dependency chain, batch,
+async, parameters) are in
+[`src/rhosocial/activerecord/backend/impl/postgres/examples/named_migrations/`](../../../src/rhosocial/activerecord/backend/impl/postgres/examples/named_migrations/)
+and the CLI's own options are in the [CLI README](../../../src/rhosocial/activerecord/backend/impl/postgres/cli/README.md).
+
+A programmatic class-style run is also available through `MigrationRunner`; see the second example,
+[`docs/examples/migration/02_named_migration.py`](../../examples/migration/02_named_migration.py).
+
+## 6. Where to go next
+
+- Migration **system** (the authoritative guide):
+ [core migration chapter](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md)
+- Runnable examples: [local migration examples](../../examples/migration/README.md)
+- PostgreSQL DDL statements: [DDL overview](../ddl/README.md)
+- Server capabilities by version: [Supported versions](../introduction/supported_versions.md)
+- Transaction behaviour: [Transaction support](../transaction_support/README.md)
diff --git a/docs/examples/migration/01_transactional_ddl.py b/docs/examples/migration/01_transactional_ddl.py
new file mode 100644
index 00000000..0a18fe13
--- /dev/null
+++ b/docs/examples/migration/01_transactional_ddl.py
@@ -0,0 +1,144 @@
+# docs/examples/migration/01_transactional_ddl.py
+"""Function-style PostgreSQL migrations: dry run, transactional DDL, version gating.
+
+Requires a reachable PostgreSQL server; configure it with the POSTGRES_* environment
+variables. Run from the repository root with PYTHONPATH=src.
+
+Demonstrates (see docs/en_US/migration/README.md for the system itself):
+ - configuring this repo's PostgresConnectionConfig / PostgresBackend
+ - the dialect's transactional DDL support and the all-or-nothing failure path
+ - @migration functions emitted through ctx.apply() and run via run_migration_group
+ - gating a PostgreSQL 14+ type on the adapted server version
+No raw SQL strings are built here: every DDL statement comes from a model helper.
+"""
+import os
+import tempfile
+from typing import Annotated, Optional
+
+from rhosocial.activerecord.base import UseSqlType
+from rhosocial.activerecord.backend.expression.types import IntegerType, VarCharType
+from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
+from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig
+from rhosocial.activerecord.backend.impl.postgres.expression.types import (
+ PostgresInt4MultirangeType,
+)
+from rhosocial.activerecord.backend.migration import (
+ JSONFileMigrationRecordStore,
+ MigrationDirection,
+ MigrationFunctionExecutionError,
+ migration,
+ run_migration_group,
+)
+from rhosocial.activerecord.model import ActiveRecord
+
+
+class User(ActiveRecord):
+ @classmethod
+ def table_name(cls) -> str:
+ return "users"
+
+ id: Annotated[Optional[int], UseSqlType(IntegerType())] = None
+ name: Annotated[str, UseSqlType(VarCharType(length=64))]
+
+
+class Archive(ActiveRecord):
+ """Uses INT4MULTIRANGE, which exists only on PostgreSQL 14+."""
+
+ @classmethod
+ def table_name(cls) -> str:
+ return "archives"
+
+ id: Annotated[Optional[int], UseSqlType(IntegerType())] = None
+ spans: Annotated[Optional[tuple], UseSqlType(PostgresInt4MultirangeType())] = None
+
+
+@migration("v001_create_users", description="create the initial users table")
+def create_users(ctx):
+ if ctx.direction == MigrationDirection.UP:
+ ctx.apply(User.create_table_statement(backend=ctx.backend))
+ else:
+ ctx.apply(User.drop_table_statement(if_exists=True, backend=ctx.backend))
+
+
+@migration("v002_create_archive", description="create a PostgreSQL 14+ multirange table")
+def create_archive(ctx):
+ # The dialect carries the version detected by introspect_and_adapt().
+ if not ctx.backend.dialect.version_at_least((14, 0, 0)):
+ print(" [gate] server < 14: skipping INT4MULTIRANGE archive table")
+ return
+ if ctx.direction == MigrationDirection.UP:
+ ctx.apply(Archive.create_table_statement(backend=ctx.backend))
+ else:
+ ctx.apply(Archive.drop_table_statement(if_exists=True, backend=ctx.backend))
+
+
+@migration("v003_failing_step", description="intentional failure to show DDL rollback")
+def failing_step(ctx):
+ raise RuntimeError("intentional failure for the transactional DDL demo")
+
+
+def build_backend():
+ config = PostgresConnectionConfig(
+ host=os.getenv("POSTGRES_HOST", "localhost"),
+ port=int(os.getenv("POSTGRES_PORT", "5432")),
+ database=os.getenv("POSTGRES_DATABASE", "test"),
+ username=os.getenv("POSTGRES_USER", "postgres"),
+ password=os.getenv("POSTGRES_PASSWORD", ""),
+ )
+ backend = PostgresBackend(connection_config=config)
+ backend.connect()
+ backend.introspect_and_adapt()
+ return backend
+
+
+def main():
+ backend = build_backend()
+ rec_path = tempfile.mktemp(suffix=".json")
+ store = JSONFileMigrationRecordStore(rec_path)
+ users = f"{__name__}:create_users"
+ archive = f"{__name__}:create_archive"
+ failing = f"{__name__}:failing_step"
+
+ try:
+ print("dialect supports transactional DDL:",
+ backend.dialect.supports_transactional_ddl())
+
+ # 1) dry run — renders SQL through the backend, writes nothing.
+ preview = run_migration_group(backend, [users, archive], dry_run=True)
+ print("\n== dry run ==")
+ print(" statements:", preview.dry_run_total)
+ for label, sql, _params in preview.dry_run_sql:
+ print(f" [{label}] {sql}")
+ print(" records written:", preview.records_written)
+
+ # 2) real UP — one transaction, DDL committed only if every step succeeds.
+ up = run_migration_group(backend, [users, archive], record_store=store)
+ print("\n== UP ==")
+ print(" applied:", up.applied)
+ print(" records written:", up.records_written)
+
+ # 3) a failing step — on PostgreSQL the group's DDL is rolled back cleanly.
+ print("\n== failing step (expect rollback) ==")
+ try:
+ run_migration_group(backend, [failing], record_store=store)
+ except MigrationFunctionExecutionError as exc:
+ print(" version:", exc.version)
+ print(" transactional_ddl:", exc.transactional_ddl)
+ print(" cause:", exc.cause)
+
+ # 4) DOWN — reverse order; a clean rollback removes the applied versions.
+ down = run_migration_group(
+ backend, [users, archive], direction=MigrationDirection.DOWN, record_store=store
+ )
+ print("\n== DOWN ==")
+ print(" rolled back:", down.rolled_back)
+ print(" applied versions after rollback:",
+ [r.version for r in store.get_applied()])
+ finally:
+ backend.disconnect()
+ if os.path.exists(rec_path):
+ os.remove(rec_path)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docs/examples/migration/02_named_migration.py b/docs/examples/migration/02_named_migration.py
new file mode 100644
index 00000000..a8a6baa6
--- /dev/null
+++ b/docs/examples/migration/02_named_migration.py
@@ -0,0 +1,80 @@
+# docs/examples/migration/02_named_migration.py
+"""Class-style ``NamedMigration`` on PostgreSQL, plus the CLI wiring.
+
+Runs the repo's own example migration (V001CreateUsers) through MigrationRunner with
+this backend's PostgresConnectionConfig / PostgresBackend, and prints the equivalent
+``named-migration`` CLI commands. Requires a reachable PostgreSQL server; configure it
+with POSTGRES_*. Run from the repository root with PYTHONPATH=src.
+
+For the migration system itself see the core migration chapter; for the full set of
+class-style demos see src/rhosocial/activerecord/backend/impl/postgres/examples/named_migrations/.
+"""
+import os
+import tempfile
+
+from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
+from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig
+from rhosocial.activerecord.backend.migration import (
+ JSONFileMigrationRecordStore,
+ MigrationDirection,
+ MigrationRunner,
+)
+
+MIGRATION_FQN = (
+ "rhosocial.activerecord.backend.impl.postgres.examples"
+ ".named_migrations.migrations.V001CreateUsers"
+)
+
+
+def build_backend():
+ config = PostgresConnectionConfig(
+ host=os.getenv("POSTGRES_HOST", "localhost"),
+ port=int(os.getenv("POSTGRES_PORT", "5432")),
+ database=os.getenv("POSTGRES_DATABASE", "test"),
+ username=os.getenv("POSTGRES_USER", "postgres"),
+ password=os.getenv("POSTGRES_PASSWORD", ""),
+ )
+ backend = PostgresBackend(connection_config=config)
+ backend.connect()
+ backend.introspect_and_adapt()
+ return backend
+
+
+def main():
+ backend = build_backend()
+ rec_path = tempfile.mktemp(suffix=".json")
+ store = JSONFileMigrationRecordStore(rec_path)
+ runner = MigrationRunner(MIGRATION_FQN)
+
+ try:
+ # The class-style dry run captures ctx.execute(...) named-expression SQL.
+ preview = runner.run(backend, MigrationDirection.UP, dry_run=True)
+ print("\n== dry run ==")
+ print(" version:", preview.version)
+ for fqn, sql, _params in preview.dry_run_sql or []:
+ print(f" [{fqn}] {sql}")
+
+ up = runner.run(backend, MigrationDirection.UP, record_store=store)
+ print("\n== UP ==")
+ print(" version:", up.version, "success:", up.success)
+ print(" applied:", [r.version for r in store.get_applied()])
+
+ down = runner.run(backend, MigrationDirection.DOWN, record_store=store)
+ print("\n== DOWN ==")
+ print(" version:", down.version, "success:", down.success)
+ print(" applied after rollback:", [r.version for r in store.get_applied()])
+ finally:
+ backend.disconnect()
+ if os.path.exists(rec_path):
+ os.remove(rec_path)
+
+ print("\n== equivalent CLI (python -m ... named-migration) ==")
+ print(" ", f"python -m rhosocial.activerecord.backend.impl.postgres named-migration "
+ f"{MIGRATION_FQN} --host localhost --database mydb --direction up "
+ f"--record-store ./migrations.json")
+ print(" ", f"python -m rhosocial.activerecord.backend.impl.postgres named-migration "
+ f"{MIGRATION_FQN} --database mydb --direction up --dry-run")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docs/examples/migration/README.md b/docs/examples/migration/README.md
new file mode 100644
index 00000000..30ddce38
--- /dev/null
+++ b/docs/examples/migration/README.md
@@ -0,0 +1,25 @@
+# PostgreSQL Migration Examples
+
+Runnable examples for migrations **on this PostgreSQL backend**. They cover only this backend's
+concerns (configuration, transactional DDL, version-gated types, and CLI wiring); the migration
+system itself is documented in the
+[core migration chapter](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md)
+and summarised in the [backend migration guide](../../en_US/migration/README.md).
+
+All scripts need a reachable PostgreSQL server. Configure it with the `POSTGRES_*` environment
+variables (`POSTGRES_HOST`, `POSTGRES_PORT`, `POSTGRES_DATABASE`, `POSTGRES_USER`,
+`POSTGRES_PASSWORD`) and run from the repository root with `PYTHONPATH=src`:
+
+```bash
+PYTHONPATH=src python docs/examples/migration/01_transactional_ddl.py
+PYTHONPATH=src python docs/examples/migration/02_named_migration.py
+```
+
+| Script | Demonstrates |
+|---|---|
+| `01_transactional_ddl.py` | `PostgresConnectionConfig` + `PostgresBackend`; `introspect_and_adapt()`; `@migration` + `ctx.apply()`; `run_migration_group` dry run → UP → DOWN; dialect's `supports_transactional_ddl()` and `MigrationFunctionExecutionError.transactional_ddl`; a PostgreSQL 14+ `INT4MULTIRANGE` type gated by `version_at_least()` |
+| `02_named_migration.py` | class-style `NamedMigration` via `MigrationRunner` with the PostgreSQL backend; class-style dry-run SQL capture; equivalent `named-migration` CLI commands |
+
+> The longer-running class-style demos (single migration, dependency chain, batch, async, parameters)
+> live in
+> `src/rhosocial/activerecord/backend/impl/postgres/examples/named_migrations/`.
diff --git a/docs/zh_CN/README.md b/docs/zh_CN/README.md
index ab1a61a3..1c9423ab 100644
--- a/docs/zh_CN/README.md
+++ b/docs/zh_CN/README.md
@@ -4,7 +4,7 @@
> **示例:** "PostgreSQL 后端如何处理 JSONB 数据类型?与普通 JSON 有什么优势?"
-> 📖 **详细用法请参考**:[AI 辅助开发指南](introduction/ai_assistance.md)
+> 📖 **详细用法请参考**:[AI 辅助开发指南](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/introduction/ai_assistance.md)
## 目录 (Table of Contents)
@@ -53,7 +53,11 @@
9. **[场景实战 (Scenarios)](scenarios/README.md)**
* **[并行 Worker 处理](scenarios/parallel_workers.md)**: 多进程/异步并发场景的正确用法
-10. **[Worker 隔离实验](examples/chapter_05_worker_isolation/README.md)**
- * **[Worker 连接隔离实验](examples/chapter_05_worker_isolation/README.md)**: Worker 进程隔离实验
+10. **[Worker 隔离实验](../examples/chapter_05_worker_isolation/README.md)**
+ * **[Worker 连接隔离实验](../examples/chapter_05_worker_isolation/README.md)**: Worker 进程隔离实验
+
+11. **[迁移 (Migrations)](migration/README.md)**
+ * **[PostgreSQL 迁移指南](migration/README.md)**: 配置、事务性 DDL、受版本门禁的特性、函数式与类式用法
+ * **[迁移示例](../examples/migration/README.md)**: 可运行的 PostgreSQL 迁移脚本
> 📖 **核心库文档**:要了解 ActiveRecord 框架的完整功能,请参考 [rhosocial-activerecord 文档](https://github.com/Rhosocial/python-activerecord/tree/main/docs/zh_CN)。
diff --git a/docs/zh_CN/migration/README.md b/docs/zh_CN/migration/README.md
new file mode 100644
index 00000000..76fd5a5f
--- /dev/null
+++ b/docs/zh_CN/migration/README.md
@@ -0,0 +1,169 @@
+# 迁移(Migrations)— PostgreSQL 后端
+
+> **范围说明:** 本章只讲 PostgreSQL 后端与迁移相关的特有事项:如何为迁移配置 PostgreSQL 后端、
+> 事务性 DDL、受版本门禁的特性/类型,以及两套迁移 API 如何接到本后端上。本章**不**重复讲解迁移
+> 系统本身——两套编写 API、顺序与依赖规则、版本记录、dry run 内部机制、`migrate` CLI 以及异常
+> 层级,全部记录在[核心库迁移章节](https://github.com/rhosocial/python-activerecord/blob/main/docs/zh_CN/migration/README.md)中。
+> 如果你是初次接触迁移,请先阅读那一章;需要 PostgreSQL 细节时再回到这里。
+
+> 💡 **AI 提示词:** "给我展示一个 PostgreSQL 迁移:先在 dry run 中渲染 DDL,然后在事务中应用它,
+> 并在后续语句失败时干净地回滚。"
+
+## 1. 为迁移配置 PostgreSQL 后端
+
+迁移运行在由你提供的后端实例上。构造本后端的 `PostgresConnectionConfig` 与 `PostgresBackend`,
+然后——很重要——在运行迁移前调用 `introspect_and_adapt()`。该调用会探测实际服务器版本与已安装
+的扩展,使方言能正确渲染受版本门禁的 DDL(见 §3)。
+
+```python
+import os
+
+from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
+from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig
+
+config = PostgresConnectionConfig(
+ host=os.getenv("POSTGRES_HOST", "localhost"),
+ port=int(os.getenv("POSTGRES_PORT", "5432")),
+ database=os.getenv("POSTGRES_DATABASE", "test"),
+ username=os.getenv("POSTGRES_USER", "postgres"),
+ password=os.getenv("POSTGRES_PASSWORD", ""),
+)
+backend = PostgresBackend(connection_config=config)
+backend.connect()
+backend.introspect_and_adapt() # detect server version + installed extensions
+```
+
+本后端特有的注意点:
+
+- `PostgresConnectionConfig` 接受 PostgreSQL/libpq 风格的选项(`sslmode`、`search_path`、
+ `default_schema`、`application_name`、`target_session_attrs`、`connect_timeout`、`service` 等)。
+ 当迁移面向非 `public` schema 时,设置 `search_path` / `default_schema` 很有价值。参见
+ [连接配置](../installation_and_configuration/configuration.md)。
+- 连接以驱动层 autocommit 运行;事务边界由框架显式管理。你**不需要**自己在迁移组外层开启事务——
+ `run_migration_group` 会处理(§2)。
+- 当无法查询服务器时,`introspect_and_adapt()` 会回退到默认版本。如果某个迁移依赖特定服务器版本,
+ 请显式检查,而不要假设(§3)。
+
+## 2. 事务性 DDL — PostgreSQL 的关键优势
+
+**PostgreSQL 的 DDL 是事务性的。** `CREATE TABLE`、`ALTER TABLE`、`DROP TABLE` 等模式语句会参与事务,
+并且可以**干净地回滚**。这是相对于 DDL *非事务性* 的后端而言真正的优势:在那些后端上,迁移中途
+失败会留下部分应用的 schema,必须手工修复。而在 PostgreSQL 上,同样的失败会让 schema 保持原样。
+
+系统如何利用这一点:
+
+- 本后端的方言声明 `supports_transactional_ddl() -> True`。`run_migration_group` 路径会探测
+ `backend.dialect.supports_transactional_ddl()`,并在函数失败时把结果记录到
+ `MigrationFunctionExecutionError.transactional_ddl` 上。
+- 在默认的 `TransactionMode.AUTO` 下,一个组会开启一个事务,运行组内所有函数,只有全部成功才提交。
+ 任何异常都会回滚整个组——包括 DDL。dry run 从不开启事务,也不写入任何内容。
+- 因此,PostgreSQL 上的多语句迁移实际上是**全有或全无(all-or-nothing)**:你可以把
+ `up()`/`down()` 函数写成一串 DDL 步骤,而无需为某个失败步骤手写补偿逻辑。
+
+```python
+from rhosocial.activerecord.backend.migration import (
+ MigrationFunctionExecutionError,
+ run_migration_group,
+)
+
+assert backend.dialect.supports_transactional_ddl() is True
+
+run_migration_group(backend, [user_fqn], dry_run=True) # renders SQL, writes nothing
+run_migration_group(backend, [user_fqn], record_store=store) # one transaction, then commit
+
+try:
+ run_migration_group(backend, [failing_fqn], record_store=store)
+except MigrationFunctionExecutionError as exc:
+ assert exc.transactional_ddl is True # the failed DDL was rolled back
+```
+
+仍然适用的 PostgreSQL 特有注意事项:
+
+- 少数 PostgreSQL 语句根本不能在事务块中执行——尤其是 `CREATE INDEX CONCURRENTLY`、
+ `DROP INDEX CONCURRENTLY`、`REFRESH MATERIALIZED VIEW CONCURRENTLY` 以及
+ `CREATE DATABASE`/`DROP DATABASE`。请把它们排除在事务性迁移组之外(用
+ `rhosocial.activerecord.backend.named_expression` 中的 `transaction_mode=TransactionMode.NONE`
+ 单独运行),并自行处理补偿。
+- DDL 会加锁;针对同一关系的并发迁移可能阻塞或死锁。必要时参见本后端的
+ [死锁处理](../transaction_support/deadlock.md)指南。
+- 隔离级别、savepoint 与 DEFERRABLE 约束参见 [事务支持](../transaction_support/README.md)。
+
+## 3. 受版本门禁的特性与类型
+
+PostgreSQL 的特性在不同服务器版本中陆续引入,本后端只渲染目标服务器支持的内容。
+`introspect_and_adapt()` 会把实际服务器版本缓存到方言上;迁移应据此对版本相关 DDL 做门禁。
+
+- `backend.dialect.version_at_least((major, minor, patch))` —— 安全的判定方法;版本未知时返回
+ `False`(从不抛异常)。`backend.dialect.version_or_none` 返回版本元组或 `None`。
+ `backend.get_server_version()` 直接查询服务器。
+- 受门禁能力的例子:`JSONB`(9.4+)、存储生成列(12+)、`multirange` 类型(如
+ `PostgresInt4MultirangeType`,14+)、`UNIQUE NULLS NOT DISTINCT` 与 `MERGE`(15+)。
+ 完整表格见[支持版本](../introduction/supported_versions.md),本后端的版本相关类型位于
+ `rhosocial.activerecord.backend.impl.postgres.expression.types`。
+
+```python
+from rhosocial.activerecord.backend.impl.postgres.expression.types import (
+ PostgresInt4MultirangeType,
+)
+
+def create_archive(ctx): # decorated with @migration in a real module
+ # Archive has a PostgresInt4MultirangeType column (PG 14+); skip on older servers.
+ if not ctx.backend.dialect.version_at_least((14, 0, 0)):
+ return
+ ctx.apply(Archive.create_table_statement(backend=ctx.backend))
+```
+
+请始终通过 `ctx.apply(...)` 发出 DDL,这样 dry run 与版本记录才能正确工作。
+
+## 4. 函数式迁移(`run_migration_group`)
+
+对于新工作,使用 `@migration` 函数与 `run_migration_group`,与核心章节所述完全一致——只有后端不同。
+一个完整的 PostgreSQL 专用脚本见
+[`docs/examples/migration/01_transactional_ddl.py`](../../examples/migration/01_transactional_ddl.py):
+它创建 `PostgresBackend`,用 `dry_run=True` 渲染迁移,用 `JSONFileMigrationRecordStore` 实际应用,
+演示一个受版本门禁的类型,并展示失败时的 `transactional_ddl` 标记。
+
+```bash
+# from the repository root
+PYTHONPATH=src python docs/examples/migration/01_transactional_ddl.py
+```
+
+成功运行需要可连接的 PostgreSQL 服务器;请用 `POSTGRES_*` 环境变量配置。顺序、依赖校验与
+record-store 语义属于系统层面的内容——请看核心章节,而不是本页。
+
+## 5. 类式 `named-migration` CLI 接线
+
+类式(`NamedMigration`)API 对既有迁移提供完整支持。本后端的 CLI 暴露 `named-migration` 子命令,
+其处理器位于
+[`cli/named_migration.py`](../../../src/rhosocial/activerecord/backend/impl/postgres/cli/named_migration.py),
+并委托给共享的核心辅助函数。它根据连接参数构造 `PostgresBackend`(使用 `--async` 时为
+`AsyncPostgresBackend`),并在运行前调用 `introspect_and_adapt()`。
+
+```bash
+python -m rhosocial.activerecord.backend.impl.postgres named-migration \
+ myapp.migrations.v001.CreateUsersTable --host localhost --database mydb --direction up \
+ --record-store ./migrations.json
+python -m rhosocial.activerecord.backend.impl.postgres named-migration \
+ myapp.migrations.v001.CreateUsersTable --database mydb --direction up --dry-run
+python -m rhosocial.activerecord.backend.impl.postgres named-migration \
+ myapp.migrations --all --record-store ./migrations.json --single-transaction
+```
+
+`--direction up|down`、`--record-store`、`--dry-run`、`--describe`、`--list`、`--param KEY=VALUE`、
+`--all`、`--single-transaction` 与 `--async` 均受支持。`--single-transaction` 会把整批包装进一个事务——
+由于 PostgreSQL 的 DDL 是事务性的,这能真正做到整批失败即全部回滚。完整的端到端演示(单个迁移、
+依赖链、批量、异步、参数)位于
+[`src/rhosocial/activerecord/backend/impl/postgres/examples/named_migrations/`](../../../src/rhosocial/activerecord/backend/impl/postgres/examples/named_migrations/),
+CLI 自身的选项见 [CLI README](../../../src/rhosocial/activerecord/backend/impl/postgres/cli/README.md)。
+
+类式迁移也可以通过 `MigrationRunner` 以编程方式运行;见第二个示例
+[`docs/examples/migration/02_named_migration.py`](../../examples/migration/02_named_migration.py)。
+
+## 6. 下一步
+
+- 迁移**系统**(权威指南):
+ [核心库迁移章节](https://github.com/rhosocial/python-activerecord/blob/main/docs/zh_CN/migration/README.md)
+- 可运行示例:[本地迁移示例](../../examples/migration/README.md)
+- PostgreSQL DDL 语句:[DDL 概览](../ddl/README.md)
+- 各版本的服务器能力:[支持版本](../introduction/supported_versions.md)
+- 事务行为:[事务支持](../transaction_support/README.md)
diff --git a/pyproject.toml b/pyproject.toml
index f48098c1..1edd80f4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -85,7 +85,7 @@ minversion = "7.0"
# an explicit xdist_group is the only thing that serialises a case, and the
# worker count is the caller's (-n). The expression directory pins the same
# mode for its own runs; see its conftest.
-addopts = "-ra -q -p rhosocial.activerecord.testsuite.conftest --dist=loadgroup"
+addopts = "-ra -q --dist=loadgroup"
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
testpaths = [
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/__init__.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/__init__.py
index 94afacfe..02cec9a4 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/__init__.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/__init__.py
@@ -87,6 +87,15 @@
# hstore types
from .hstore import PostgresHstoreAdapter
+# Neutral value adapters (core driver-independent types)
+from .neutral import (
+ PostgresNeutralBitStringAdapter,
+ PostgresNeutralGeometryAdapter,
+ PostgresNeutralMacAddressAdapter,
+ PostgresNeutralRangeAdapter,
+ PostgresNeutralVectorAdapter,
+)
+
__all__ = [
# Basic types
"PostgresListAdapter",
@@ -126,4 +135,10 @@
"PostgresPostGISAdapter",
# hstore types
"PostgresHstoreAdapter",
+ # Neutral value adapters
+ "PostgresNeutralBitStringAdapter",
+ "PostgresNeutralGeometryAdapter",
+ "PostgresNeutralMacAddressAdapter",
+ "PostgresNeutralRangeAdapter",
+ "PostgresNeutralVectorAdapter",
]
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/base.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/base.py
index 27e10db3..ff5f60be 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/base.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/base.py
@@ -7,7 +7,7 @@
import json
from enum import Enum as PythonEnum
-from typing import Any, Dict, List, Type, Union, Optional, Set, get_args, get_origin # noqa: F401
+from typing import Any, Callable, Dict, List, Type, Union, Optional, Set, get_args, get_origin # noqa: F401
from psycopg.types.json import Jsonb
@@ -114,14 +114,48 @@ class PostgresJSONBAdapter(BaseSQLTypeAdapter):
Note: psycopg automatically serializes/deserializes JSON, so dict <-> JSON.
When reading from DB, psycopg returns dict. When target type is str,
we need to serialize back to JSON string.
+
+ The optional ``default`` and ``object_hook`` mirror their ``json.dumps`` /
+ ``json.loads`` namesakes:
+
+ - ``default`` is forwarded to psycopg's dumper through the per-value
+ ``Jsonb(value, dumps)`` hook, so it is applied when psycopg serialises
+ the value (psycopg's global ``dumps`` is replaced, not bypassed).
+ - ``object_hook`` is applied with ``json.loads``. psycopg has already
+ decoded a JSONB column to ``dict``/``list`` by the time the adapter sees
+ it, so the already-decoded value is re-encoded and decoded again to run
+ the hook over every object, exactly as ``json.loads`` would.
"""
- def __init__(self):
+ def __init__(
+ self,
+ default: Optional[Callable[[Any], Any]] = None,
+ object_hook: Optional[Callable[[dict], Any]] = None,
+ ):
super().__init__()
+ self.default = default
+ self.object_hook = object_hook
self.register_type(dict, Jsonb)
+ def _dumps(self, value: Any) -> str:
+ """Serialise for psycopg, applying the configured ``default``."""
+ return json.dumps(value, default=self.default)
+
+ def _wrap(self, value: Any) -> Jsonb:
+ """Build the psycopg wrapper, wiring ``default`` into the dumper."""
+ if self.default is None:
+ # Keep psycopg's default dumps function untouched.
+ return Jsonb(value)
+ return Jsonb(value, self._dumps)
+
+ def _apply_object_hook(self, value: Any) -> Any:
+ """Run ``object_hook`` over an already-decoded JSON value."""
+ if self.object_hook is None:
+ return value
+ return json.loads(json.dumps(value, default=self.default), object_hook=self.object_hook)
+
def _do_to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any:
- return Jsonb(value)
+ return self._wrap(value)
def _do_from_database(
self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None
@@ -131,15 +165,16 @@ def _do_from_database(
# but model fields may be defined as Optional[str] type
if target_type is str:
if isinstance(value, (dict, list)):
- return json.dumps(value, ensure_ascii=False)
+ return json.dumps(value, ensure_ascii=False, default=self.default)
return value
- # For dict/list target types, return as-is
+ # For dict/list target types, return the decoded value (running the
+ # hook if one was configured against the already-decoded document)
if isinstance(value, dict):
- return value
+ return self._apply_object_hook(value)
if isinstance(value, list):
- return value
+ return self._apply_object_hook(value)
# In case it's a string representation
- return json.loads(value)
+ return json.loads(value, object_hook=self.object_hook)
def to_database_batch(
self, values: List[Any], target_type: Type, options: Optional[Dict[str, Any]] = None
@@ -150,7 +185,7 @@ def to_database_batch(
if value is None:
result.append(None)
else:
- result.append(Jsonb(value))
+ result.append(self._wrap(value))
return result
def from_database_batch(
@@ -163,94 +198,11 @@ def from_database_batch(
result.append(None)
elif target_type is str:
if isinstance(value, (dict, list)):
- result.append(json.dumps(value, ensure_ascii=False))
+ result.append(json.dumps(value, ensure_ascii=False, default=self.default))
else:
result.append(value)
else:
- result.append(value)
- return result
-
-
-class PostgresNetworkAddressAdapter(BaseSQLTypeAdapter):
- """
- Adapts Python ipaddress objects to PostgreSQL network types.
- """
-
- def __init__(self):
- super().__init__()
- try:
- import ipaddress
- self.register_type(ipaddress.IPv4Address, str)
- self.register_type(ipaddress.IPv6Address, str)
- self.register_type(ipaddress.IPv4Network, str)
- self.register_type(ipaddress.IPv6Network, str)
- except ImportError:
- pass
-
- def _do_to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any:
- return str(value)
-
- def _do_from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any:
- try:
- import ipaddress
- return ipaddress.ip_address(value)
- except (ImportError, ValueError):
- try:
- import ipaddress
- return ipaddress.ip_network(value)
- except (ImportError, ValueError):
- return value
-
- def to_database_batch(
- self, values: List[Any], target_type: Type, options: Optional[Dict[str, Any]] = None
- ) -> List[Any]:
- """Optimized batch network address conversion.
-
- Converts all values to strings in a single pass.
-
- Args:
- values: List of values to convert
- target_type: Target type
- options: Optional conversion options
-
- Returns:
- List of string representations
- """
- result = []
- for value in values:
- if value is None:
- result.append(None)
- else:
- result.append(str(value))
- return result
-
- def from_database_batch(
- self, values: List[Any], target_type: Type, options: Optional[Dict[str, Any]] = None
- ) -> List[Any]:
- """Optimized batch network address parsing from database.
-
- Args:
- values: List of string values from database
- target_type: Target Python type
- options: Optional conversion options
-
- Returns:
- List of ipaddress objects or strings
- """
- import ipaddress
-
- result = []
- for value in values:
- if value is None:
- result.append(None)
- else:
- try:
- result.append(ipaddress.ip_address(value))
- except (ImportError, ValueError):
- try:
- result.append(ipaddress.ip_network(value))
- except (ImportError, ValueError):
- result.append(value)
+ result.append(self._apply_object_hook(value))
return result
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/bit_string.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/bit_string.py
index 49a38bc6..00e78331 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/bit_string.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/bit_string.py
@@ -68,7 +68,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
raise TypeError(f"Cannot convert {type(value).__name__} to bit string")
def from_database(
- self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[PostgresBitString]:
"""Convert PostgreSQL bit string to Python object.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/geometric.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/geometric.py
index 8c7f4abf..496ce46b 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/geometric.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/geometric.py
@@ -95,7 +95,9 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
raise TypeError(f"Cannot convert {type(value).__name__} to geometric type")
- def from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any:
+ def from_database(
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
+ ) -> Any:
"""Convert PostgreSQL geometric value to Python object.
Args:
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py
index db179ec9..ace59714 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/json.py
@@ -15,49 +15,12 @@
storage format. jsonb is generally preferred for query purposes.
"""
-import json
-from typing import Any, Dict, List, Optional, Set, Type, Union, get_args, get_origin # noqa: F401
-
-from psycopg.types.json import Jsonb
-
-from rhosocial.activerecord.backend.type_adapter import BaseSQLTypeAdapter
+from typing import Any, Callable, Dict, List, Optional, Set, Type, Union, get_args, get_origin # noqa: F401
from ..type_values.json import PostgresJsonPath
-
-class PostgresJSONBAdapter(BaseSQLTypeAdapter):
- """
- Adapts Python dict to PostgreSQL JSONB and vice-versa.
-
- Note: psycopg automatically serializes/deserializes JSON, so dict <-> JSON.
- When reading from DB, psycopg returns dict. When target type is str,
- we need to serialize back to JSON string.
- """
-
- def __init__(self):
- super().__init__()
- self.register_type(dict, Jsonb)
-
- def _do_to_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any:
- return Jsonb(value)
-
- def _do_from_database(
- self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None
- ) -> Union[dict, list, str]:
- # For string target type, serialize dict/list back to JSON string
- # This is needed because psycopg auto-deserializes JSON to dict,
- # but model fields may be defined as Optional[str] type
- if target_type is str:
- if isinstance(value, (dict, list)):
- return json.dumps(value, ensure_ascii=False)
- return value
- # For dict/list target types, return as-is
- if isinstance(value, dict):
- return value
- if isinstance(value, list):
- return value
- # In case it's a string representation
- return json.loads(value)
+# One implementation: the class lives in ``base`` beside the list adapter.
+from .base import PostgresJSONBAdapter # noqa: F401 (re-exported public name)
class PostgresJsonPathAdapter:
@@ -140,7 +103,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
raise TypeError(f"Cannot convert {type(value).__name__} to jsonpath")
def from_database(
- self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[PostgresJsonPath]:
"""Convert PostgreSQL jsonpath value to Python.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/monetary.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/monetary.py
index 3044b67f..89fe7564 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/monetary.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/monetary.py
@@ -87,7 +87,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
raise TypeError(f"Cannot convert {type(value).__name__} to MONEY")
def from_database(
- self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[PostgresMoney]:
"""Convert PostgreSQL MONEY value to Python.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/network_address.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/network_address.py
index ef8db097..1f1e6217 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/network_address.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/network_address.py
@@ -51,7 +51,9 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
return None
return str(value)
- def from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any:
+ def from_database(
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
+ ) -> Any:
if value is None:
return None
try:
@@ -123,7 +125,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
raise TypeError(f"Cannot convert {type(value).__name__} to MACADDR")
def from_database(
- self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[PostgresMacaddr]:
"""Convert PostgreSQL MACADDR to Python object.
@@ -206,7 +208,9 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
raise TypeError(f"Cannot convert {type(value).__name__} to MACADDR8")
- def from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any:
+ def from_database(
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
+ ) -> Any:
"""Convert PostgreSQL MACADDR8 to Python object.
Args:
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/neutral.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/neutral.py
new file mode 100644
index 00000000..30a5d8ae
--- /dev/null
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/neutral.py
@@ -0,0 +1,699 @@
+# src/rhosocial/activerecord/backend/impl/postgres/adapters/neutral.py
+"""PostgreSQL value adapters for the core neutral types.
+
+The adapters in this module speak the driver-independent types from
+``rhosocial.activerecord.backend.adapters`` only: :class:`Geometry`,
+:class:`Vector`, :class:`BitString`, :class:`Range`, :class:`Multirange`, and
+:class:`MacAddress`. They are deliberately separate from the backend-native
+adapters already exported by this package (``PostgresPostGISAdapter``,
+``PostgresVectorAdapter``, ``PostgresBitStringAdapter``, ``PostgresRangeAdapter``,
+``PostgresMacaddrAdapter``), whose Python surface is the PostgreSQL wrapper
+types (``PostgresGeometry``, ``PostgresVector`` ...). Keeping both lets an
+existing application keep its wrapper types while a new application can opt
+into the neutral ones.
+
+Wire formats:
+
+- geometry / geography: plain WKT, or ``SRID=n;WKT`` (EWKT) when the geometry
+ carries an SRID. Both types accept that text form, so one adapter serves
+ both. EWKB hex output is not decoded: select ``ST_AsEWKT``/``ST_AsText``
+ when reading.
+- pgvector ``vector``: ``[v1,v2,...]``.
+- ``bit`` / ``varbit``: the binary digits accepted by the bit input function.
+ ``options={"literal": True}`` produces the SQL literal form ``B'1010'``,
+ which is an expression rather than a bind parameter.
+- range / multirange: the PostgreSQL range literal produced by
+ ``to_postgres_literal()`` (bare numeric bounds, double-quoted text/temporal
+ bounds).
+- ``macaddr`` / ``macaddr8``: the canonical lowercase colon-separated form.
+"""
+
+from __future__ import annotations
+
+import math
+import re
+from datetime import date, datetime, time
+from decimal import Decimal, InvalidOperation
+from typing import Any, Dict, List, Optional, Tuple, Type
+
+from rhosocial.activerecord.backend.adapters import (
+ BitString,
+ BitStringAdapterBase,
+ Geometry,
+ GeometryAdapterBase,
+ MacAddress,
+ MacAddressAdapterBase,
+ Multirange,
+ Range,
+ RangeAdapterBase,
+ Vector,
+ VectorAdapterBase,
+)
+
+from ..type_values.bit_string import PostgresBitString
+from ..type_values.network_address import PostgresMacaddr, PostgresMacaddr8
+from ..type_values.pgvector import PostgresVector
+from ..type_values.postgis import PostgresGeometry
+from ..type_values.range import PostgresMultirange, PostgresRange
+
+_HEX_TEXT_RE = re.compile(r"^(?:0[xX])?[0-9A-Fa-f]+$")
+_INT_TEXT_RE = re.compile(r"^[+-]?\d+$")
+_NUMBER_TEXT_RE = re.compile(r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$")
+_NON_FINITE_NAMES = {
+ "nan": float("nan"),
+ "infinity": float("inf"),
+ "+infinity": float("inf"),
+ "inf": float("inf"),
+ "-infinity": float("-inf"),
+ "-inf": float("-inf"),
+}
+
+#: SQL range type names mapped onto the neutral range element labels.
+_RANGE_TYPE_LABELS = {
+ "int4range": "int",
+ "int8range": "int",
+ "numrange": "decimal",
+ "tsrange": "datetime",
+ "tstzrange": "datetime",
+ "daterange": "date",
+ "timerange": "time",
+ "timetzrange": "time",
+}
+#: Labels the neutral range decoder knows how to turn into Python values.
+_RANGE_ELEMENT_LABELS = frozenset(("int", "float", "decimal", "datetime", "date", "time", "str"))
+_ELEMENT_TYPE_ALIASES = {
+ "integer": "int",
+ "bigint": "int",
+ "smallint": "int",
+ "numeric": "decimal",
+ "number": "decimal",
+ "double": "float",
+ "double precision": "float",
+ "real": "float",
+ "timestamp": "datetime",
+ "timestamptz": "datetime",
+ "timestamp with time zone": "datetime",
+ "timestamp without time zone": "datetime",
+ "date": "date",
+ "time": "time",
+ "timetz": "time",
+ "text": "str",
+ "varchar": "str",
+ "character varying": "str",
+}
+
+
+# --- Geometry --------------------------------------------------------------
+
+
+def _looks_like_ewkb_hex(text: str) -> bool:
+ """Return whether ``text`` is PostGIS's default hex EWKB output."""
+ return bool(_HEX_TEXT_RE.match(text)) and len(text) >= 10
+
+
+class PostgresNeutralGeometryAdapter(GeometryAdapterBase):
+ """Encode neutral geometries as WKT/EWKT for ``geometry``/``geography``.
+
+ The wire format is text because both PostGIS types accept EWKT text and
+ psycopg binds text parameters without a driver-specific wrapper. On read,
+ WKT, EWKT and the backend wrapper :class:`PostgresGeometry` are accepted.
+ Hex EWKB output is rejected with an explicit message: requesting
+ ``ST_AsEWKT`` or ``ST_AsText`` is the caller's responsibility, and silently
+ guessing at the binary encoding would be worse than failing.
+
+ ``options``:
+
+ - ``srid``: overrides the geometry's own SRID in the emitted EWKT prefix.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.register_type(Geometry, str)
+
+ def _encode(self, geometry: Geometry, target_type: Type, options: Dict[str, Any]) -> str:
+ if target_type is not str:
+ raise TypeError("PostgreSQL geometry/geography binds as text; target_type must be str")
+
+ srid = options.get("srid", geometry.srid)
+ if srid is not None:
+ srid = int(srid)
+ return "SRID={};{}".format(srid, geometry.to_wkt())
+ return geometry.to_wkt()
+
+ def _decode(self, value: Any, options: Dict[str, Any]) -> Geometry:
+ if isinstance(value, Geometry) and type(value) is not Geometry:
+ return value
+ if isinstance(value, PostgresGeometry):
+ return Geometry.from_wkt(value.wkt, srid=value.srid)
+ if isinstance(value, str):
+ text = value.strip()
+ if _looks_like_ewkb_hex(text):
+ raise ValueError(
+ "PostGIS returned hex EWKB, which this adapter does not decode; "
+ "select ST_AsEWKT or ST_AsText instead"
+ )
+ return Geometry.from_wkt(text)
+ raise TypeError(
+ "PostgreSQL geometry/geography must decode from WKT/EWKT text or "
+ "PostgresGeometry, got {}".format(type(value).__name__)
+ )
+
+
+# --- Vector ----------------------------------------------------------------
+
+
+def _format_vector_component(value: Any) -> str:
+ """Render one component in the pgvector text form."""
+ if isinstance(value, float) and not math.isfinite(value):
+ if math.isnan(value):
+ return "NaN"
+ return "Infinity" if value > 0 else "-Infinity"
+ return repr(value)
+
+
+def _parse_vector_text(text: str) -> Vector:
+ """Parse the pgvector ``[v1,v2,...]`` text form into a neutral vector."""
+ stripped = text.strip()
+ if not stripped.startswith("[") or not stripped.endswith("]"):
+ raise ValueError("pgvector text must look like [v1,v2,...]")
+ inner = stripped[1:-1].strip()
+ if not inner:
+ raise ValueError("pgvector text must contain at least one component")
+
+ values: List[float] = []
+ allow_non_finite = False
+ for part in inner.split(","):
+ token = part.strip()
+ if not token:
+ raise ValueError("pgvector text contains an empty component")
+ lower = token.lower()
+ if lower in _NON_FINITE_NAMES:
+ values.append(_NON_FINITE_NAMES[lower])
+ allow_non_finite = True
+ continue
+ try:
+ number = float(token)
+ except ValueError:
+ raise ValueError("invalid pgvector component: {!r}".format(token)) from None
+ if not math.isfinite(number):
+ allow_non_finite = True
+ values.append(number)
+
+ return Vector(tuple(values), allow_non_finite=allow_non_finite)
+
+
+class PostgresNeutralVectorAdapter(VectorAdapterBase):
+ """Encode neutral vectors as pgvector text.
+
+ The text form ``[v1,v2,...]`` is accepted by the ``vector`` type's input
+ function, so it is bindable as a plain string parameter.
+ ``halfvec``/``sparsevec`` are not served: they have different wire formats
+ and are still gaps in the backend's coverage.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.register_type(Vector, str)
+
+ def _encode(self, vector: Vector, target_type: Type, options: Optional[Dict[str, Any]]) -> str:
+ if target_type is not str:
+ raise TypeError("pgvector binds as text; target_type must be str")
+ return "[{}]".format(",".join(_format_vector_component(v) for v in vector.values))
+
+ def _decode(self, value: Any, options: Optional[Dict[str, Any]]) -> Vector:
+ if isinstance(value, Vector):
+ return value
+ if isinstance(value, PostgresVector):
+ return Vector(tuple(value.values))
+ if isinstance(value, str):
+ return _parse_vector_text(value)
+ if isinstance(value, (list, tuple)):
+ return Vector.from_json_value(list(value))
+ raise TypeError(
+ "pgvector must decode from text, a sequence, or PostgresVector, got "
+ "{}".format(type(value).__name__)
+ )
+
+
+# --- Bit string ------------------------------------------------------------
+
+
+def _declared_bit_length(options: Optional[Dict[str, Any]]) -> Optional[int]:
+ """Read the column's declared bit length from the adapter options."""
+ if not options:
+ return None
+ for key in ("bit_length", "length"):
+ raw = options.get(key)
+ if raw is None:
+ continue
+ if isinstance(raw, bool) or not isinstance(raw, int):
+ raise ValueError("{} must be int, got {}".format(key, type(raw).__name__))
+ if raw < 1:
+ raise ValueError("{} must be at least 1, got {}".format(key, raw))
+ return raw
+ return None
+
+
+def _parse_bit_text(text: str) -> str:
+ """Return the binary digits of a bit string value."""
+ stripped = text.strip()
+ if len(stripped) >= 3 and stripped[0] in ("B", "b") and stripped[1] == "'":
+ if not stripped.endswith("'"):
+ raise ValueError("unterminated B'...' bit string")
+ stripped = stripped[2:-1]
+ if not stripped:
+ raise ValueError("bit string text must not be empty")
+ if any(char not in "01" for char in stripped):
+ raise ValueError("bit string text may only contain '0' and '1'")
+ return stripped
+
+
+class PostgresNeutralBitStringAdapter(BitStringAdapterBase):
+ """Encode neutral bit strings for PostgreSQL ``bit``/``varbit``.
+
+ The default encoding is the bare binary digits (``"1010"``), which the
+ bit input function accepts for a text-bound parameter. A literal
+ ``B'1010'`` is SQL syntax, not a bind parameter, so it is only produced
+ when ``options={"literal": True}`` is requested explicitly.
+
+ Reading recovers the declared length from ``options["bit_length"]`` (or
+ ``options["length"]``) when the column is fixed-width; otherwise the
+ length is taken from the returned text. A shorter text is right-padded
+ with zeros to the declared length, matching ``bit(n)`` casting rules.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.register_type(BitString, str)
+
+ def _encode(self, bits: BitString, target_type: Type, options: Optional[Dict[str, Any]]) -> str:
+ if target_type is not str:
+ raise TypeError("PostgreSQL bit/varbit binds as text; target_type must be str")
+ text = bits.to_bits()
+ if options and options.get("literal"):
+ return "B'{}'".format(text)
+ return text
+
+ def _decode(self, value: Any, options: Optional[Dict[str, Any]]) -> BitString:
+ if isinstance(value, BitString):
+ return value
+ declared = _declared_bit_length(options)
+
+ if isinstance(value, PostgresBitString):
+ text = value.bits
+ if declared is None and value.length is not None:
+ declared = value.length
+ elif isinstance(value, str):
+ text = _parse_bit_text(value)
+ elif isinstance(value, (bytes, bytearray)):
+ raw = bytes(value)
+ if not raw:
+ raise ValueError("bit string bytes must not be empty")
+ return BitString.from_bytes(raw, declared)
+ elif isinstance(value, int) and not isinstance(value, bool):
+ length = declared
+ if length is None:
+ length = max(1, value.bit_length())
+ return BitString.from_int(value, length)
+ else:
+ raise TypeError(
+ "PostgreSQL bit/varbit must decode from text, bytes, int, or "
+ "PostgresBitString, got {}".format(type(value).__name__)
+ )
+
+ if declared is not None:
+ if len(text) > declared:
+ raise ValueError(
+ "bit string text has {} bits, more than the declared {}".format(
+ len(text), declared
+ )
+ )
+ text = text + "0" * (declared - len(text))
+ return BitString.from_bits(text)
+
+
+# --- Range / multirange ----------------------------------------------------
+
+
+def _element_label(options: Optional[Dict[str, Any]]) -> Optional[str]:
+ """Resolve the neutral range element label from adapter options."""
+ if not options:
+ return None
+ for key in ("element_type", "range_type", "subtype"):
+ raw = options.get(key)
+ if raw is None:
+ continue
+ if not isinstance(raw, str):
+ raise ValueError("{} must be str, got {}".format(key, type(raw).__name__))
+ name = raw.strip().lower()
+ if name in _RANGE_TYPE_LABELS:
+ return _RANGE_TYPE_LABELS[name]
+ label = _ELEMENT_TYPE_ALIASES.get(name, name)
+ if label not in _RANGE_ELEMENT_LABELS:
+ raise ValueError(
+ "unsupported range element type hint {!r}; known labels are {}".format(
+ raw, ", ".join(sorted(_RANGE_ELEMENT_LABELS))
+ )
+ )
+ return label
+ return None
+
+
+def _split_range_parts(text: str, separator: str = ",") -> List[str]:
+ """Split a range/multirange body on top-level separators.
+
+ Brackets nest and quoted bounds shield commas, backslashes and brackets.
+ PostgreSQL quotes a bound that contains whitespace, a bracket, a comma,
+ a double quote or a backslash, and escapes ``"``/``\\`` with a backslash.
+ Doubled quotes are also accepted, as some callers spell them that way.
+ """
+ parts: List[str] = []
+ buffer: List[str] = []
+ in_quote = False
+ depth = 0
+ index = 0
+ while index < len(text):
+ char = text[index]
+ if in_quote:
+ if char == "\\" and index + 1 < len(text):
+ buffer.append(char)
+ buffer.append(text[index + 1])
+ index += 2
+ continue
+ if char == '"':
+ if index + 1 < len(text) and text[index + 1] == '"':
+ buffer.append('""')
+ index += 2
+ continue
+ in_quote = False
+ buffer.append(char)
+ index += 1
+ continue
+
+ if char == '"':
+ in_quote = True
+ buffer.append(char)
+ elif char in "([{":
+ depth += 1
+ buffer.append(char)
+ elif char in ")]}":
+ if depth == 0:
+ raise ValueError("unbalanced closing bracket in range literal")
+ depth -= 1
+ buffer.append(char)
+ elif char == separator and depth == 0:
+ parts.append("".join(buffer))
+ buffer = []
+ else:
+ buffer.append(char)
+ index += 1
+
+ if in_quote:
+ raise ValueError("unterminated quoted range bound")
+ if depth != 0:
+ raise ValueError("unbalanced brackets in range literal")
+ parts.append("".join(buffer))
+ return parts
+
+
+def _unquote_bound(text: str) -> Tuple[str, bool]:
+ """Return the raw bound text and whether it was quoted."""
+ text = text.strip()
+ if not text.startswith('"'):
+ return text, False
+ if len(text) < 2 or not text.endswith('"'):
+ raise ValueError("unterminated quoted range bound")
+
+ characters: List[str] = []
+ index = 1
+ end = len(text) - 1
+ while index < end:
+ char = text[index]
+ if char == "\\":
+ if index + 1 >= end:
+ raise ValueError("dangling escape in quoted range bound")
+ characters.append(text[index + 1])
+ index += 2
+ continue
+ if char == '"':
+ if index + 1 < end and text[index + 1] == '"':
+ characters.append('"')
+ index += 2
+ continue
+ raise ValueError("unescaped quote inside a quoted range bound")
+ characters.append(char)
+ index += 1
+ return "".join(characters), True
+
+
+def _parse_element(text: str, label: Optional[str]) -> Any:
+ """Convert one bound token to its Python value."""
+ if label == "datetime":
+ try:
+ return datetime.fromisoformat(text)
+ except ValueError:
+ raise ValueError("invalid datetime range bound: {!r}".format(text)) from None
+ if label == "date":
+ try:
+ return date.fromisoformat(text)
+ except ValueError:
+ raise ValueError("invalid date range bound: {!r}".format(text)) from None
+ if label == "time":
+ try:
+ return time.fromisoformat(text)
+ except ValueError:
+ raise ValueError("invalid time range bound: {!r}".format(text)) from None
+ if label == "int":
+ if not _INT_TEXT_RE.match(text):
+ raise ValueError("invalid integer range bound: {!r}".format(text))
+ return int(text)
+ if label == "decimal":
+ try:
+ return Decimal(text)
+ except (InvalidOperation, ValueError):
+ raise ValueError("invalid decimal range bound: {!r}".format(text)) from None
+ if label == "float":
+ try:
+ return float(text)
+ except ValueError:
+ raise ValueError("invalid float range bound: {!r}".format(text)) from None
+ if label == "str":
+ return text
+
+ # No label: infer the narrowest lossless type from the token.
+ lower = text.lower()
+ if lower in _NON_FINITE_NAMES:
+ return _NON_FINITE_NAMES[lower]
+ if _INT_TEXT_RE.match(text):
+ return int(text)
+ if _NUMBER_TEXT_RE.match(text):
+ try:
+ return Decimal(text)
+ except InvalidOperation:
+ return text
+ return text
+
+
+def _parse_range_literal(text: str, options: Optional[Dict[str, Any]]) -> Range:
+ """Parse one PostgreSQL range literal into a neutral range."""
+ stripped = text.strip()
+ if not stripped:
+ raise ValueError("range literal is empty")
+ if stripped.lower() == "empty":
+ return Range(None, None, "[)", True)
+ if len(stripped) < 2:
+ raise ValueError("range literal is too short: {!r}".format(stripped))
+
+ lower_bracket = stripped[0]
+ upper_bracket = stripped[-1]
+ if lower_bracket not in "[(":
+ raise ValueError("invalid lower bound bracket: {!r}".format(lower_bracket))
+ if upper_bracket not in "])":
+ raise ValueError("invalid upper bound bracket: {!r}".format(upper_bracket))
+
+ body = stripped[1:-1]
+ parts = _split_range_parts(body)
+ if len(parts) != 2:
+ raise ValueError(
+ "range literal must have exactly one bound separator, got {}".format(len(parts))
+ )
+
+ label = _element_label(options)
+ lower_text, _ = _unquote_bound(parts[0])
+ upper_text, _ = _unquote_bound(parts[1])
+
+ lower = _parse_element(lower_text, label) if lower_text else None
+ upper = _parse_element(upper_text, label) if upper_text else None
+
+ # PostgreSQL canonical output uses '(' for an infinite bound: normalize
+ # so an input such as '[,5]' does not produce a non-canonical neutral value.
+ if lower is None:
+ lower_bracket = "("
+ if upper is None:
+ upper_bracket = ")"
+
+ return Range(lower, upper, lower_bracket + upper_bracket, False)
+
+
+def _parse_multirange_literal(text: str, options: Optional[Dict[str, Any]]) -> Multirange:
+ """Parse one PostgreSQL multirange literal into a neutral multirange."""
+ stripped = text.strip()
+ if not stripped.startswith("{") or not stripped.endswith("}"):
+ raise ValueError("multirange literal must be enclosed in braces: {!r}".format(stripped))
+ body = stripped[1:-1]
+ if not body.strip():
+ return Multirange(())
+ pieces = [piece for piece in _split_range_parts(body) if piece.strip()]
+ return Multirange(tuple(_parse_range_literal(piece, options) for piece in pieces))
+
+
+def _neutral_range_from_parts(
+ lower: Any, upper: Any, lower_inc: bool, upper_inc: bool, empty: bool
+) -> Range:
+ """Build a neutral range from a backend range's parts."""
+ if empty:
+ return Range(None, None, "[)", True)
+ lower_bracket = "[" if (lower is not None and lower_inc) else "("
+ upper_bracket = "]" if (upper is not None and upper_inc) else ")"
+ return Range(lower, upper, lower_bracket + upper_bracket, False)
+
+
+def _is_range_like(value: Any) -> bool:
+ """Return whether ``value`` looks like a driver/backend range object."""
+ return all(hasattr(value, name) for name in ("lower", "upper", "bounds"))
+
+
+def _decode_range_like(value: Any) -> Range:
+ """Convert a psycopg-like range object into a neutral range."""
+ empty = bool(getattr(value, "isempty", False) or getattr(value, "empty", False))
+ bounds = getattr(value, "bounds", "[)") or "[)"
+ return _neutral_range_from_parts(
+ getattr(value, "lower", None),
+ getattr(value, "upper", None),
+ bounds[0] == "[",
+ len(bounds) > 1 and bounds[1] == "]",
+ empty,
+ )
+
+
+class PostgresNeutralRangeAdapter(RangeAdapterBase):
+ """Encode and decode neutral ``Range``/``Multirange`` values.
+
+ Writes delegate wholly to the neutral literal renderers
+ (``to_postgres_literal``), which now produce PostgreSQL's native range
+ syntax: numeric bounds are bare and text/temporal bounds are double-quoted
+ with ``"``/``\\`` escaped. Reads accept the PostgreSQL literal text, the
+ backend wrappers ``PostgresRange`` / ``PostgresMultirange``, psycopg's
+ range objects, and sequences of psycopg-like ranges.
+
+ Text parsing cannot recover an element type by itself. Unquoted numbers
+ become ``int``/``Decimal`` and quoted bounds stay ``str`` unless the caller
+ passes ``options={"element_type": "date", ...}`` or
+ ``options={"range_type": "daterange"}``. Without that hint, a quoted
+ ``"2024-01-01"`` remains a string; this is a documented limitation of
+ parsing PostgreSQL's text output, not a silent conversion.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.register_type(Range, str)
+ self.register_type(Multirange, str)
+
+ def _encode(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]]) -> str:
+ if target_type is not str:
+ raise TypeError("PostgreSQL range/multirange binds as text; target_type must be str")
+ return value.to_postgres_literal()
+
+ def _decode(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]]) -> Any:
+ if isinstance(value, (Range, Multirange)):
+ return value
+ if isinstance(value, PostgresRange):
+ return _neutral_range_from_parts(
+ value.lower, value.upper, value.lower_inc, value.upper_inc, value.is_empty
+ )
+ if isinstance(value, PostgresMultirange):
+ return Multirange(
+ tuple(
+ _neutral_range_from_parts(
+ item.lower,
+ item.upper,
+ item.lower_inc,
+ item.upper_inc,
+ item.is_empty,
+ )
+ for item in value.ranges
+ )
+ )
+ if _is_range_like(value):
+ return _decode_range_like(value)
+ if isinstance(value, (list, tuple)):
+ if not value:
+ return Multirange(())
+ if all(_is_range_like(item) for item in value):
+ return Multirange(tuple(_decode_range_like(item) for item in value))
+ raise TypeError("a sequence of ranges must contain range objects")
+ if isinstance(value, str):
+ text = value.strip()
+ if text.startswith("{"):
+ return _parse_multirange_literal(text, options)
+ return _parse_range_literal(text, options)
+ raise TypeError(
+ "PostgreSQL range/multirange must decode from text, a backend/driver "
+ "range, or a sequence of ranges, got {}".format(type(value).__name__)
+ )
+
+
+# --- MAC address -----------------------------------------------------------
+
+
+def _canonical_mac(mac: MacAddress) -> str:
+ return ":".join("{:02x}".format(octet) for octet in mac.octets)
+
+
+class PostgresNeutralMacAddressAdapter(MacAddressAdapterBase):
+ """Encode neutral MAC addresses as canonical ``macaddr``/``macaddr8`` text.
+
+ PostgreSQL accepts the lowercase colon-separated form for both types.
+ ``options={"eui64": True}`` (or ``{"version": 8}``) expands a 6-octet
+ address into the EUI-64 form (inserting ``ff:fe`` after the third octet)
+ before writing it to a ``macaddr8`` column; without that option the
+ canonical 6-octet text is emitted and the server performs its own
+ ``macaddr8`` conversion.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.register_type(MacAddress, str)
+
+ def _encode(self, mac: MacAddress, target_type: Type, options: Optional[Dict[str, Any]]) -> str:
+ if target_type is not str:
+ raise TypeError("PostgreSQL macaddr binds as text; target_type must be str")
+ options = options or {}
+ eui64 = options.get("eui64", False)
+ if "version" in options:
+ eui64 = eui64 or int(options["version"]) >= 8
+ if eui64 and len(mac.octets) == 6:
+ octets = mac.octets[:3] + b"\xff\xfe" + mac.octets[3:]
+ return ":".join("{:02x}".format(octet) for octet in octets)
+ return _canonical_mac(mac)
+
+ def _decode(self, value: Any, options: Optional[Dict[str, Any]]) -> MacAddress:
+ if isinstance(value, MacAddress):
+ return value
+ if isinstance(value, (PostgresMacaddr, PostgresMacaddr8)):
+ return MacAddress.parse(str(value))
+ if isinstance(value, (str, bytes, bytearray)):
+ return MacAddress.parse(value)
+ raise TypeError(
+ "PostgreSQL macaddr must decode from text, bytes, or a backend MAC "
+ "wrapper, got {}".format(type(value).__name__)
+ )
+
+
+__all__ = [
+ "PostgresNeutralBitStringAdapter",
+ "PostgresNeutralGeometryAdapter",
+ "PostgresNeutralMacAddressAdapter",
+ "PostgresNeutralRangeAdapter",
+ "PostgresNeutralVectorAdapter",
+]
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/object_identifier.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/object_identifier.py
index 37954ac1..4f3159be 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/object_identifier.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/object_identifier.py
@@ -133,7 +133,9 @@ def to_database(
raise TypeError(f"Cannot convert {type(value).__name__} to OID type")
- def from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any:
+ def from_database(
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
+ ) -> Any:
"""Convert PostgreSQL OID value to Python object.
Args:
@@ -229,7 +231,9 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
raise TypeError(f"Cannot convert {type(value).__name__} to transaction ID type")
- def from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any:
+ def from_database(
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
+ ) -> Any:
"""Convert PostgreSQL transaction ID to Python object.
Args:
@@ -314,7 +318,9 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
raise TypeError(f"Cannot convert {type(value).__name__} to TID")
- def from_database(self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None) -> Any:
+ def from_database(
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
+ ) -> Any:
"""Convert PostgreSQL tid to Python object.
Args:
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/pg_lsn.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/pg_lsn.py
index a317eb3c..07bf1cde 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/pg_lsn.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/pg_lsn.py
@@ -63,7 +63,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
raise TypeError(f"Cannot convert {type(value).__name__} to pg_lsn")
def from_database(
- self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[PostgresLsn]:
"""Convert PostgreSQL pg_lsn to Python object.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/pgvector.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/pgvector.py
index 2887793a..818e7181 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/pgvector.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/pgvector.py
@@ -68,7 +68,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
def from_database(
self, value: Any, target_type: Type,
- options: Optional[Dict[str, Any]] = None
+ options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[PostgresVector]:
"""Convert PostgreSQL vector to Python object.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/postgis.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/postgis.py
index 59aeed28..5b970c01 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/postgis.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/postgis.py
@@ -62,7 +62,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
def from_database(
self, value: Any, target_type: Type,
- options: Optional[Dict[str, Any]] = None
+ options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[PostgresGeometry]:
"""Convert PostgreSQL geometry/geography to Python object.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/range.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/range.py
index 8a8c583c..c2636c8b 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/range.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/range.py
@@ -83,7 +83,7 @@ def to_database(
raise TypeError(f"Cannot convert {type(value).__name__} to range")
def from_database(
- self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[PostgresRange]:
"""Convert PostgreSQL range value to PostgresRange object."""
if value is None:
@@ -164,7 +164,7 @@ def to_database(
raise TypeError(f"Cannot convert {type(value).__name__} to multirange")
def from_database(
- self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[PostgresMultirange]:
"""Convert from PostgreSQL multirange value."""
if value is None:
@@ -177,7 +177,12 @@ def from_database(
return PostgresMultirange.from_postgres_string(value)
try:
- from psycopg.types.range import Multirange
+ # psycopg 3.2+ keeps the multirange type beside the range one, in
+ # ``psycopg.types.multirange``. Importing it from
+ # ``psycopg.types.range`` silently failed (the ``ImportError`` below
+ # swallowed it), so a native multirange value never reached this
+ # branch.
+ from psycopg.types.multirange import Multirange
if isinstance(value, Multirange):
ranges = [
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/text_search.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/text_search.py
index 776b2126..2f8c96d7 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/text_search.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/text_search.py
@@ -89,7 +89,7 @@ def to_database(
raise TypeError(f"Cannot convert {type(value).__name__} to tsvector")
def from_database(
- self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[PostgresTsVector]:
"""Convert PostgreSQL tsvector value to PostgresTsVector object.
@@ -170,7 +170,7 @@ def to_database(
raise TypeError(f"Cannot convert {type(value).__name__} to tsquery")
def from_database(
- self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[PostgresTsQuery]:
"""Convert PostgreSQL tsquery value to PostgresTsQuery object.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/uuid.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/uuid.py
index e44ccb9e..2f680619 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/uuid.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/uuid.py
@@ -69,7 +69,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
def from_database(
self, value: Any, target_type: Type,
- options: Optional[Dict[str, Any]] = None
+ options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[uuid.UUID]:
"""Convert PostgreSQL uuid to Python object.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/adapters/xml.py b/src/rhosocial/activerecord/backend/impl/postgres/adapters/xml.py
index 8b05fee6..c6a0906f 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/adapters/xml.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/adapters/xml.py
@@ -83,7 +83,7 @@ def to_database(self, value: Any, target_type: Type, options: Optional[Dict[str,
raise TypeError(f"Cannot convert {type(value).__name__} to XML")
def from_database(
- self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None
+ self, value: Any, target_type: Type, options: Optional[Dict[str, Any]] = None, **kwargs
) -> Optional[PostgresXML]:
"""Convert PostgreSQL XML value to Python.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/backend/base.py b/src/rhosocial/activerecord/backend/impl/postgres/backend/base.py
index 56ae2ca3..4e3707a7 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/backend/base.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/backend/base.py
@@ -5,7 +5,7 @@
containing methods that are shared between sync and async backends.
"""
-from typing import Dict, Optional, Tuple, Type, TYPE_CHECKING
+from typing import Dict, List, Optional, Tuple, Type, TYPE_CHECKING
import logging
from psycopg.errors import (
@@ -260,13 +260,18 @@ def _register_postgres_adapters(self):
- BOTH: Register both adapters, with custom taking precedence
- multirange_adapter_mode: Same for Multirange types (PG 14+ only)
- Note: The following adapters are NOT registered by default due to str->str
- type mapping conflicts with existing string handling:
- - PostgresXMLAdapter: XML type
- - PostgresBitStringAdapter: bit/varbit types
- - PostgresJsonPathAdapter: jsonpath type
-
- Users should specify these explicitly when working with such columns.
+ Note: every backend-named value type this package defines has its
+ adapter registered here. Those adapters key on their own wrapper
+ types (``PostgresXML``, ``PostgresJsonPath``, ``PostgresBitString``,
+ ``PostgresGeometry``, ``PostgresVector``, ``PostgresHstore``) rather
+ than on ``str``, so registering them cannot shadow the core string
+ handling -- an earlier note here described an older shape of these
+ adapters and no longer applies.
+
+ ``PostgresHstoreAdapter`` is registered for its own type only. It also
+ accepts a plain ``dict``, but ``(dict, str)`` in this registry would
+ take every dict in the backend away from the JSON adapter, and a
+ backend covers its own types without displacing the core ones.
"""
from ..adapters import (
PostgresListAdapter,
@@ -275,6 +280,11 @@ def _register_postgres_adapters(self):
PostgresEnumAdapter,
PostgresRangeAdapter,
PostgresMultirangeAdapter,
+ PostgresNeutralBitStringAdapter,
+ PostgresNeutralGeometryAdapter,
+ PostgresNeutralMacAddressAdapter,
+ PostgresNeutralRangeAdapter,
+ PostgresNeutralVectorAdapter,
)
from ..adapters.geometric import PostgresGeometryAdapter
from ..adapters.monetary import PostgresMoneyAdapter
@@ -283,6 +293,13 @@ def _register_postgres_adapters(self):
from ..adapters.uuid import PostgresUUIDAdapter
from ..adapters.pg_lsn import PostgresLsnAdapter
from ..adapters.text_search import PostgresTsVectorAdapter, PostgresTsQueryAdapter
+ from ..adapters.xml import PostgresXMLAdapter
+ from ..adapters.json import PostgresJsonPathAdapter
+ from ..adapters.bit_string import PostgresBitStringAdapter
+ from ..adapters.hstore import PostgresHstoreAdapter
+ from ..adapters.postgis import PostgresPostGISAdapter
+ from ..adapters.pgvector import PostgresVectorAdapter
+ from ..type_values.hstore import PostgresHstore
from ..config import RangeAdapterMode
pg_adapters = [
@@ -305,9 +322,13 @@ def _register_postgres_adapters(self):
# PostgresJsonPathAdapter it claims no str->str mapping, so it
# cannot shadow the default string handling.
PostgresUUIDAdapter(),
- # PostgresJsonPathAdapter(), # Not registered: str->str conflict
- # PostgresXMLAdapter is NOT registered by default
- # due to str->str type pair conflict
+ # The backend's own value types: each keys on its wrapper type,
+ # so none of them can shadow a core Python type.
+ PostgresXMLAdapter(),
+ PostgresJsonPathAdapter(),
+ PostgresBitStringAdapter(),
+ PostgresPostGISAdapter(),
+ PostgresVectorAdapter(),
]
for adapter in pg_adapters:
@@ -317,6 +338,28 @@ def _register_postgres_adapters(self):
adapter, py_type, db_type, allow_override=True
)
+ # hstore is registered for its own type only: the adapter also accepts
+ # a plain ``dict`` as a convenience, and that pair would displace the
+ # JSON adapter for every dict in this backend.
+ self.adapter_registry.register(
+ PostgresHstoreAdapter(), PostgresHstore, str, allow_override=True
+ )
+
+ # Neutral value adapters are keyed by the core neutral Python types
+ # (Geometry, Vector, ...), so they never collide with the backend
+ # wrapper adapters above and are always available to the catalogue.
+ neutral_adapters = [
+ PostgresNeutralGeometryAdapter(),
+ PostgresNeutralVectorAdapter(),
+ PostgresNeutralBitStringAdapter(),
+ PostgresNeutralRangeAdapter(),
+ PostgresNeutralMacAddressAdapter(),
+ ]
+ for adapter in neutral_adapters:
+ for py_type, db_types in adapter.supported_types.items():
+ for db_type in db_types:
+ self.adapter_registry.register(adapter, py_type, db_type, allow_override=True)
+
# Register Range adapters based on configuration
range_mode = getattr(self.config, "range_adapter_mode", RangeAdapterMode.NATIVE)
if range_mode in (RangeAdapterMode.CUSTOM, RangeAdapterMode.BOTH):
@@ -340,6 +383,25 @@ def _register_postgres_adapters(self):
self.log(logging.DEBUG, "Registered PostgreSQL-specific type adapters")
+ def get_type_adapters(self) -> List["SQLTypeAdapter"]:
+ """Return the adapter instances this backend provides.
+
+ This is a plain inventory: it says which adapters exist for this backend.
+ It carries no suggestion/default/priority semantics; the caller decides.
+
+ The inventory is deduplicated by adapter class (module + qualname) and
+ sorted by ``(module, qualname)``, so the order is deterministic and a
+ fresh list is returned on every call.
+ """
+ adapters: List["SQLTypeAdapter"] = list(self.adapter_registry.get_all_adapters().values())
+
+ unique: Dict[Tuple[str, str], "SQLTypeAdapter"] = {}
+ for adapter in adapters:
+ adapter_class = type(adapter)
+ unique.setdefault((adapter_class.__module__, adapter_class.__qualname__), adapter)
+
+ return [unique[key] for key in sorted(unique)]
+
def _is_connection_error(self, error: Exception) -> bool:
"""Check if an error indicates a connection loss.
@@ -439,7 +501,7 @@ def get_default_adapter_suggestions(self) -> Dict[Type, Tuple["SQLTypeAdapter",
mapping conflicts with the base string handling. Users must explicitly
specify adapters for these types when needed.
"""
- suggestions: Dict[Type, Tuple["SQLTypeAdapter", Type]] = {}
+ base = super().get_default_adapter_suggestions()
# Define a list of desired Python type to DB driver type mappings.
# This list reflects types seen in test fixtures and common usage,
@@ -461,6 +523,14 @@ def get_default_adapter_suggestions(self) -> Dict[Type, Tuple["SQLTypeAdapter",
# Import PostgreSQL-specific types
from ..type_values.range import PostgresRange, PostgresMultirange
from ..type_values.geometric import Point, Line, LineSegment, Box, Path, Polygon, Circle
+ from rhosocial.activerecord.backend.adapters.bitstring import BitString
+ from rhosocial.activerecord.backend.adapters.geometry import Geometry
+ from rhosocial.activerecord.backend.adapters.network import MacAddress
+ from rhosocial.activerecord.backend.adapters.range import Multirange, Range
+ from rhosocial.activerecord.backend.adapters.vector import Vector
+ from rhosocial.activerecord.backend.base.type_adaption import (
+ merge_adapter_suggestions,
+ )
from ..type_values.text_search import PostgresTsVector, PostgresTsQuery
from ..type_values.monetary import PostgresMoney
from ..type_values.network_address import PostgresMacaddr, PostgresMacaddr8
@@ -541,18 +611,23 @@ def get_default_adapter_suggestions(self) -> Dict[Type, Tuple["SQLTypeAdapter",
(CID, int), # Command identifier
# === PostgreSQL Tuple Identifier ===
(TID, str), # Tuple identifier (block number, offset)
+ # === Neutral families (text/wire forms in this backend's adapters) ===
+ (Geometry, str), # WKT/EWKT text (covers the seven concrete shapes)
+ (Vector, str), # pgvector text input, e.g. ``[1.0,2.0]``
+ (BitString, str), # ``bit``/``varbit`` binary-digit text
+ (Range, str), # PostgreSQL range literal
+ (Multirange, str), # PostgreSQL multirange literal
+ (MacAddress, str), # canonical lowercase colon text
# Note: PostgresXML and PostgresBitString are NOT included here
# because they both map to str, which conflicts with base string handling.
# Users must explicitly specify adapters for these types.
]
- # Iterate through the defined mappings and retrieve adapters from the registry.
+ suggestions = merge_adapter_suggestions(base, type_mappings, self.adapter_registry)
+
+ # Report any mapping this backend's registry cannot satisfy.
for py_type, db_type in type_mappings:
- adapter = self.adapter_registry.get_adapter(py_type, db_type)
- if adapter:
- suggestions[py_type] = (adapter, db_type)
- else:
- # Log a debug message if a specific adapter is expected but not found.
+ if py_type not in suggestions:
self.log(
logging.DEBUG,
f"No adapter found for ({py_type.__name__}, {db_type.__name__}). "
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/column_types.py b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py
new file mode 100644
index 00000000..12cab93d
--- /dev/null
+++ b/src/rhosocial/activerecord/backend/impl/postgres/column_types.py
@@ -0,0 +1,461 @@
+# src/rhosocial/activerecord/backend/impl/postgres/column_types.py
+"""PostgreSQL's own column classes.
+
+A column class is an *operation surface*: it says what a value held in a column
+can be asked to do. Core narrows by the Python type (``str`` -> StringColumn,
+``dict`` -> JSONColumn), and those classes deliberately promise only what every
+backend can execute. PostgreSQL carries value families the framework does not
+have a core class for -- text search, ``jsonpath``, hstore, LSN, the object
+identifiers -- and richer spellings for the ones it does (PostGIS, the range
+operators, ``macaddr``).
+
+This module is where those names live, so a model can choose one explicitly::
+
+ Annotated[Point, UseColumnType(PostgresGeometryColumn())]
+
+Each class inherits the core class that already carries the right operation
+floor (``PostgresGeometryColumn(GeometryColumn)``), or ``ColumnBase`` when the
+family has no core class at all (text search, hstore, LSN). The server's own
+operations -- ``ST_Distance``, ``@>``, ``justify_hours`` -- are added here as
+they are measured; until then the class states the same floor the core class
+does, which is the honest minimum rather than a promise the server refuses.
+
+``POSTGRES_EXTRA_COLUMN_TYPES`` in :mod:`.mixins.column_type` keys these by the
+value class they answer for, so a field annotated with one of PostgreSQL's own
+value types resolves without a declaration.
+"""
+
+from typing import TYPE_CHECKING
+
+from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError
+from rhosocial.activerecord.backend.expression.column_types import (
+ BitStringColumn,
+ ColumnBase,
+ GeometryColumn,
+ IntegerColumn,
+ MacAddressColumn,
+ MultirangeColumn,
+ NumericColumn,
+ RangeColumn,
+ VectorColumn,
+ XMLColumn,
+)
+
+if TYPE_CHECKING: # pragma: no cover
+ from rhosocial.activerecord.backend.expression.operators import (
+ ArithmeticOperation,
+ BinaryExpression,
+ UnaryExpression,
+ )
+ from rhosocial.activerecord.backend.expression.functions import FunctionCall
+
+
+def _require(dialect, switch: str) -> None:
+ """Fail loudly, and by name, when the server does not answer a capability.
+
+ A column method must never render an operator the server has no switch
+ for: that would produce SQL which fails on the first query, with the error
+ pointing at the column instead of at the missing capability.
+ """
+ answer = getattr(dialect, switch, None)
+ if answer is None or not answer():
+ raise UnsupportedFeatureError(
+ type(dialect).__name__,
+ switch,
+ f"this operation needs the {switch}() capability",
+ )
+
+
+class PostgresGeometryColumn(GeometryColumn):
+ """A column holding a PostgreSQL geometric value (point, line, box, ...).
+
+ Seven server geometric types and the PostGIS ``geometry`` wrapper share one
+ operation surface here. ``ST_Distance`` and the overlap operators are the
+ server's own spellings and are added to this class as they are measured.
+ """
+
+ def distance_to(self, other) -> "BinaryExpression":
+ """``col <-> other``: the distance between two geometric values.
+
+ ``<->`` is the one geometric operator every native geometric type
+ answers (point, line, lseg, box, path, polygon, circle), so it is safe
+ on this shared class.
+ """
+ from .functions.geometric import geometry_distance
+
+ return geometry_distance(self._dialect, self, other)
+
+
+class PostgresAreaGeometryColumn(PostgresGeometryColumn):
+ """A geometry column whose value can contain and overlap another value.
+
+ ``@>`` / ``<@`` / ``&&`` exist for boxes, polygons and circles, not for
+ points, lines or segments. Keeping them on this narrower class means a
+ ``Point`` field cannot offer an operator the server would refuse.
+ """
+
+ def contains(self, other) -> "BinaryExpression":
+ """``col @> other``: whether this geometry contains the other."""
+ from .functions.geometric import geometry_contains
+
+ return geometry_contains(self._dialect, self, other)
+
+ def contained_by(self, other) -> "BinaryExpression":
+ """``col <@ other``: whether this geometry is contained by the other."""
+ from .functions.geometric import geometry_contained_by
+
+ return geometry_contained_by(self._dialect, self, other)
+
+ def overlaps(self, other) -> "BinaryExpression":
+ """``col && other``: whether the two geometries overlap."""
+ from .functions.geometric import geometry_overlaps
+
+ return geometry_overlaps(self._dialect, self, other)
+
+
+class PostgisGeometryColumn(PostgresGeometryColumn):
+ """A ``geometry`` column backed by the PostGIS extension.
+
+ The ``ST_*`` functions are an extension's surface, not the core server's,
+ so they live on this subclass and are gated on
+ ``supports_postgis_spatial_functions()``. A field annotated with the
+ PostGIS wrapper value class resolves here; a plain geometric type keeps
+ the built-in operators only.
+ """
+
+ def st_distance(self, other, use_spheroid: bool = False) -> "FunctionCall":
+ """``ST_Distance(col, other[, use_spheroid])``."""
+ _require(self._dialect, "supports_postgis_spatial_functions")
+ from .functions.postgis import st_distance
+
+ return st_distance(self._dialect, self, other, use_spheroid)
+
+ def st_contains(self, other) -> "FunctionCall":
+ """``ST_Contains(col, other)``."""
+ _require(self._dialect, "supports_postgis_spatial_functions")
+ from .functions.postgis import st_contains
+
+ return st_contains(self._dialect, self, other)
+
+ def st_within(self, other) -> "FunctionCall":
+ """``ST_Within(col, other)``."""
+ _require(self._dialect, "supports_postgis_spatial_functions")
+ from .functions.postgis import st_within
+
+ return st_within(self._dialect, self, other)
+
+ def st_intersects(self, other) -> "FunctionCall":
+ """``ST_Intersects(col, other)``."""
+ _require(self._dialect, "supports_postgis_spatial_functions")
+ from .functions.postgis import st_intersects
+
+ return st_intersects(self._dialect, self, other)
+
+ def st_area(self) -> "FunctionCall":
+ """``ST_Area(col)``."""
+ _require(self._dialect, "supports_postgis_spatial_functions")
+ from .functions.postgis import st_area
+
+ return st_area(self._dialect, self)
+
+ def st_length(self) -> "FunctionCall":
+ """``ST_Length(col)``."""
+ _require(self._dialect, "supports_postgis_spatial_functions")
+ from .functions.postgis import st_length
+
+ return st_length(self._dialect, self)
+
+
+class PostgresVectorColumn(VectorColumn):
+ """A column holding a pgvector value.
+
+ The ``<->`` / ``<=>`` / ``<#>`` distance operators belong here; the core
+ class states only the shared column surface until they are measured.
+ """
+
+ def l2_distance(self, other) -> "BinaryExpression":
+ """``col <-> other``: Euclidean distance."""
+ _require(self._dialect, "supports_pgvector_similarity_search")
+ from .functions.pgvector import vector_l2_distance
+
+ return vector_l2_distance(self._dialect, self, other)
+
+ def cosine_distance(self, other) -> "BinaryExpression":
+ """``col <=> other``: cosine distance."""
+ _require(self._dialect, "supports_pgvector_similarity_search")
+ from .functions.pgvector import vector_cosine_distance
+
+ return vector_cosine_distance(self._dialect, self, other)
+
+ def inner_product(self, other) -> "BinaryExpression":
+ """``col <#> other``: negative inner product."""
+ _require(self._dialect, "supports_pgvector_similarity_search")
+ from .functions.pgvector import vector_inner_product
+
+ return vector_inner_product(self._dialect, self, other)
+
+ def cosine_similarity(self, other) -> "ArithmeticOperation":
+ """``1 - (col <=> other)``: cosine similarity."""
+ _require(self._dialect, "supports_pgvector_similarity_search")
+ from .functions.pgvector import vector_cosine_similarity
+
+ return vector_cosine_similarity(self._dialect, self, other)
+
+
+class PostgresRangeColumn(RangeColumn):
+ """A column holding a native PostgreSQL range (``int4range``, ...).
+
+ ``@>`` / ``<@`` / ``&&`` and ``lower()`` / ``upper()`` are PostgreSQL's own;
+ they are added here as the range family is completed.
+ """
+
+ def contains(self, other) -> "BinaryExpression":
+ """``col @> other``: does the range contain the element or range?"""
+ _require(self._dialect, "supports_range_operators")
+ from .functions.range import range_contains
+
+ return range_contains(self._dialect, self, other)
+
+ def contained_by(self, other) -> "BinaryExpression":
+ """``col <@ other``."""
+ _require(self._dialect, "supports_range_operators")
+ from .functions.range import range_contained_by
+
+ return range_contained_by(self._dialect, self, other)
+
+ def overlaps(self, other) -> "BinaryExpression":
+ """``col && other``."""
+ _require(self._dialect, "supports_range_operators")
+ from .functions.range import range_overlaps
+
+ return range_overlaps(self._dialect, self, other)
+
+ def is_empty(self) -> "FunctionCall":
+ """``ISEMPTY(col)``."""
+ _require(self._dialect, "supports_range_functions")
+ from .functions.range import range_is_empty
+
+ return range_is_empty(self._dialect, self)
+
+ def lower(self) -> "FunctionCall":
+ """``LOWER(col)``."""
+ _require(self._dialect, "supports_range_functions")
+ from .functions.range import range_lower
+
+ return range_lower(self._dialect, self)
+
+ def upper(self) -> "FunctionCall":
+ """``UPPER(col)``."""
+ _require(self._dialect, "supports_range_functions")
+ from .functions.range import range_upper
+
+ return range_upper(self._dialect, self)
+
+
+class PostgresMultirangeColumn(MultirangeColumn):
+ """A column holding a native PostgreSQL multirange."""
+
+ def contains(self, other) -> "BinaryExpression":
+ """``col @> other``."""
+ _require(self._dialect, "supports_multirange")
+ from .functions.range import multirange_contains
+
+ return multirange_contains(self._dialect, self, other)
+
+ def contained_by(self, other) -> "BinaryExpression":
+ """``col <@ other``."""
+ _require(self._dialect, "supports_multirange")
+ from .functions.range import multirange_is_contained_by
+
+ return multirange_is_contained_by(self._dialect, self, other)
+
+ def overlaps(self, other) -> "BinaryExpression":
+ """``col && other``."""
+ _require(self._dialect, "supports_multirange")
+ from .functions.range import multirange_overlaps
+
+ return multirange_overlaps(self._dialect, self, other)
+
+
+class PostgresBitStringColumn(BitStringColumn):
+ """A column holding ``bit`` / ``varbit``.
+
+ PostgreSQL spells exclusive-or ``#`` where MySQL spells it ``^``, so the
+ bitwise family lives on this class rather than on the shared one.
+ """
+
+ def bit_and(self, other) -> "BinaryExpression":
+ """``col & other``."""
+ from .functions.bit_string import bit_and
+
+ return bit_and(self._dialect, self, other)
+
+ def bit_or(self, other) -> "BinaryExpression":
+ """``col | other``."""
+ from .functions.bit_string import bit_or
+
+ return bit_or(self._dialect, self, other)
+
+ def bit_xor(self, other) -> "BinaryExpression":
+ """``col # other`` -- PostgreSQL's spelling of bitwise XOR."""
+ from .functions.bit_string import bit_xor
+
+ return bit_xor(self._dialect, self, other)
+
+ def bit_not(self) -> "UnaryExpression":
+ """``~ col``."""
+ from .functions.bit_string import bit_not
+
+ return bit_not(self._dialect, self)
+
+ def bit_length(self) -> "FunctionCall":
+ """``BIT_LENGTH(col)``, not the generic ``LENGTH``."""
+ from .functions.bit_string import bit_length_func
+
+ return bit_length_func(self._dialect, self)
+
+ def bit_count(self) -> "FunctionCall":
+ """``BIT_COUNT(col)``: the number of set bits."""
+ from .functions.bit_string import bit_count
+
+ return bit_count(self._dialect, self)
+
+ def shift_left(self, n: int) -> "BinaryExpression":
+ """``col << n``."""
+ from .functions.bit_string import bit_shift_left
+
+ return bit_shift_left(self._dialect, self, n)
+
+ def shift_right(self, n: int) -> "BinaryExpression":
+ """``col >> n``."""
+ from .functions.bit_string import bit_shift_right
+
+ return bit_shift_right(self._dialect, self, n)
+
+
+class PostgresTextSearchColumn(ColumnBase):
+ """A column holding ``tsvector`` or ``tsquery``.
+
+ ``to_tsvector`` / ``to_tsquery`` / ``@@`` are PostgreSQL's; no core class
+ models a text-search value, so this class starts from the column surface.
+ """
+
+ def matches(self, query) -> "BinaryExpression":
+ """``col @@ query``: does the vector match the query?"""
+ from .functions.text_search import ts_matches
+
+ return ts_matches(self._dialect, self, query)
+
+ def rank(self, query, weights=None) -> "FunctionCall":
+ """``ts_rank(col, query[, weights])``: the relevance of the match."""
+ from .functions.text_search import ts_rank
+
+ return ts_rank(self._dialect, self, query, weights)
+
+ @property
+ def format_method(self) -> str:
+ """The dialect formatting method that renders this column."""
+ return "format_column"
+
+
+class PostgresJsonPathColumn(ColumnBase):
+ """A column holding ``jsonpath``.
+
+ The type has no core counterpart: it is a path expression, not a document,
+ so it neither navigates like JSON nor compares like text.
+ """
+
+ @property
+ def format_method(self) -> str:
+ """The dialect formatting method that renders this column."""
+ return "format_column"
+
+
+class PostgresHstoreColumn(ColumnBase):
+ """A column holding ``hstore``: a key/value map.
+
+ The ``->`` accessor and the ``@>`` containment operator belong here; the
+ class starts from the column surface.
+ """
+
+ def exist(self, key) -> "FunctionCall":
+ """``EXIST(col, key)``: whether the key is present, even with NULL."""
+ _require(self._dialect, "supports_hstore_operators")
+ from rhosocial.activerecord.backend.expression import Literal
+ from .functions.hstore import hstore_exist
+
+ return hstore_exist(self._dialect, self, Literal(self._dialect, key))
+
+ def defined(self, key) -> "FunctionCall":
+ """``DEFINED(col, key)``: whether the key is present and non-NULL."""
+ _require(self._dialect, "supports_hstore_operators")
+ from rhosocial.activerecord.backend.expression import Literal
+ from .functions.hstore import hstore_defined
+
+ return hstore_defined(self._dialect, self, Literal(self._dialect, key))
+
+ @property
+ def format_method(self) -> str:
+ """The dialect formatting method that renders this column."""
+ return "format_column"
+
+
+class PostgresXmlColumn(XMLColumn):
+ """A column holding PostgreSQL ``xml``.
+
+ Inherits the core XML surface: casting and null tests, but no comparison --
+ ``xml = xml`` is refused by this server too.
+ """
+
+
+class PostgresMacAddressColumn(MacAddressColumn):
+ """A column holding ``macaddr`` or ``macaddr8``."""
+
+
+class PostgresMoneyColumn(NumericColumn):
+ """A column holding ``money``.
+
+ It inherits the numeric surface, which is what the server gives it, and the
+ currency/locale facts stay with the DDL layer.
+ """
+
+
+class PostgresIdentifierColumn(IntegerColumn):
+ """A column holding an object identifier (``oid``, ``regclass``, ``xid``, ...).
+
+ The registry names are OID aliases, so they carry the whole-number surface
+ while the spelling of the declaration is the DDL layer's job.
+ """
+
+
+class PostgresLsnColumn(ColumnBase):
+ """A column holding ``pg_lsn``: a log sequence number.
+
+ The type compares and subtracts like a number, but it is a position in the
+ write-ahead log rather than a value to compute with, so no core numeric
+ surface is claimed here.
+ """
+
+ @property
+ def format_method(self) -> str:
+ """The dialect formatting method that renders this column."""
+ return "format_column"
+
+
+__all__ = [
+ "PostgresGeometryColumn",
+ "PostgresAreaGeometryColumn",
+ "PostgisGeometryColumn",
+ "PostgresVectorColumn",
+ "PostgresRangeColumn",
+ "PostgresMultirangeColumn",
+ "PostgresBitStringColumn",
+ "PostgresTextSearchColumn",
+ "PostgresJsonPathColumn",
+ "PostgresHstoreColumn",
+ "PostgresXmlColumn",
+ "PostgresMacAddressColumn",
+ "PostgresMoneyColumn",
+ "PostgresIdentifierColumn",
+ "PostgresLsnColumn",
+]
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/dialect.py b/src/rhosocial/activerecord/backend/impl/postgres/dialect.py
index aacaf9d5..093b703d 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/dialect.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/dialect.py
@@ -145,6 +145,7 @@
ILIKESupport,
IntrospectionSupport,
TransactionControlSupport,
+ TransactionalDDLSupport,
SQLFunctionSupport,
DDLTypeSupport,
)
@@ -170,6 +171,7 @@
PostgresLogicalReplicationMixin,
PostgresParallelQueryMixin,
PostgresColumnTypeMixin,
+ PostgresDataTypeSuggestionsMixin,
# Per-feature mixins
PostgresCTEMixin,
PostgresWindowMixin,
@@ -263,6 +265,7 @@
PostgresExpressionMixin,
PostgresFunctionMixin,
PostgresLiteralValueMixin,
+ PostgresIntegerAutoIncrementColumnSuggestionMixin,
)
from .protocols.ddl.type import PostgresTypeSupport
@@ -367,6 +370,8 @@
class PostgresDialect(
+ # Backend suggestion first: no core mixin may shadow its answer.
+ PostgresIntegerAutoIncrementColumnSuggestionMixin,
# The bases below come in bundles: a backend mixin, then the core bundle
# it stands in for. The backend's answer has to come first -- a mixin
# placed after the class it overrides never wins -- so a new mixin goes
@@ -522,6 +527,9 @@ class PostgresDialect(
PostgresVacuumMixin,
PostgresCopyMixin,
PostgresQueryOptimizationMixin,
+ # Suggested data types: the DDL half of the same answer. Ahead of the
+ # mixin that withholds the table, so this dialect's answers win.
+ PostgresDataTypeSuggestionsMixin,
PostgresDataTypeMixin,
PostgresLogicalReplicationMixin,
PostgresParallelQueryMixin,
@@ -668,6 +676,7 @@ class PostgresDialect(
IntrospectionSupport,
# Transaction control protocol
TransactionControlSupport,
+ TransactionalDDLSupport,
# PostgreSQL-specific protocols
PostgresExtensionSupport,
PostgresMaterializedViewSupport,
@@ -861,6 +870,27 @@ def get_server_version(self) -> Tuple[int, int, int]:
"""Return the PostgreSQL version this dialect is configured for."""
return self.version
+ def supports_transactional_ddl(self) -> bool:
+ """PostgreSQL DDL participates in transactions."""
+ return True
+
+ def supports_database_assigned_integer_column(self) -> bool:
+ """Whether an integer column's value comes from the database.
+
+ ``True``: SERIAL is a pseudo-type whose backing sequence supplies the
+ value, and its observable behaviour is the one a declaration asks
+ about -- omit the value on INSERT, the database supplies it, and the
+ row can return it. The spelling is not ``AUTO_INCREMENT``
+ (``supports_auto_increment_column`` stays ``False``), which is why the
+ capability and the mechanism are separate questions.
+
+ Not guaranteed: the MySQL counter behaviour. Inserting an explicit
+ value larger than the sequence's current one raises MySQL's counter to
+ ``max + 1``; a SERIAL column leaves its sequence untouched, so a later
+ generated value may collide.
+ """
+ return True
+
def supports_table_function(self) -> bool:
"""PostgreSQL reads a set-returning function as a row source.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/functions/pgvector.py b/src/rhosocial/activerecord/backend/impl/postgres/functions/pgvector.py
index 780340cb..0638ec21 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/functions/pgvector.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/functions/pgvector.py
@@ -27,6 +27,7 @@
from rhosocial.activerecord.backend.expression.operators import (
ArithmeticOperation,
BinaryExpression,
+ RawSQL,
)
from rhosocial.activerecord.backend.impl.postgres.type_values.pgvector import PostgresVector
from rhosocial.activerecord.backend.impl.postgres.expression.types import (
@@ -290,8 +291,15 @@ def vector_cosine_similarity(
>>> expr = vector_cosine_similarity(d, "embedding", [1.0, 2.0, 3.0])
"""
cosine_dist = vector_cosine_distance(dialect, column, query_vector)
+ # ``ArithmeticOperation`` only parenthesizes an ``ArithmeticOperation``
+ # operand; a ``BinaryExpression`` carrying ``<=>`` is not one, so without
+ # this wrapper it renders ``1 - col <=> x`` and the server reads that as
+ # ``(1 - col) <=> x``. The text is ours (a rendered expression, never user
+ # input) and the bind parameters are carried through unchanged.
+ dist_sql, dist_params = cosine_dist.to_sql()
+ grouped_dist = RawSQL(dialect, f"({dist_sql})", dist_params)
one = core.Literal(dialect, 1)
- return ArithmeticOperation(dialect, "sub", one, cosine_dist)
+ return ArithmeticOperation(dialect, "sub", one, grouped_dist)
# === Type Construction ===
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/__init__.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/__init__.py
index de2fcc3c..ef367094 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/__init__.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/__init__.py
@@ -11,6 +11,7 @@
- extensions: Extension mixins (pgvector, postgis, hstore, etc.)
"""
+from .integer_auto_increment_column_suggestion import PostgresIntegerAutoIncrementColumnSuggestionMixin
from .object_name import PostgresObjectNameMixin
from .extension import PostgresExtensionMixin
from .materialized_view import PostgresMaterializedViewMixin
@@ -98,6 +99,7 @@
from .query_optimization import PostgresQueryOptimizationMixin
from .data_type import PostgresDataTypeMixin
from .column_type import PostgresColumnTypeMixin
+from .data_type_suggestions import PostgresDataTypeSuggestionsMixin
from .logical_replication import PostgresLogicalReplicationMixin
from .parallel_query import PostgresParallelQueryMixin
from .property_graph_query import PostgresPropertyGraphQueryMixin
@@ -136,6 +138,7 @@
from .introspection import PostgresIntrospectionCapabilityMixin
__all__ = [
+ 'PostgresIntegerAutoIncrementColumnSuggestionMixin',
# Core mixins
"PostgresObjectNameMixin",
"PostgresExtensionMixin",
@@ -219,6 +222,7 @@
"PostgresQueryOptimizationMixin",
"PostgresDataTypeMixin",
"PostgresColumnTypeMixin",
+ "PostgresDataTypeSuggestionsMixin",
"PostgresLogicalReplicationMixin",
"PostgresParallelQueryMixin",
"PostgresPropertyGraphQueryMixin",
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/auto_increment.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/auto_increment.py
index ff55830c..3f8d06d0 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/auto_increment.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/auto_increment.py
@@ -21,8 +21,9 @@ def supports_auto_increment_column(self) -> bool:
Always ``False``: ``AUTO_INCREMENT`` is MySQL / MariaDB syntax and is
absent from the PostgreSQL grammar. The server-generated-value
- mechanisms PostgreSQL does have are the SQL-standard identity clause
- (:class:`~...mixins.identity_column.PostgresIdentityColumnMixin`) and
- the ``SERIAL`` type family.
+ mechanism PostgreSQL does have is the ``SERIAL`` type family; the
+ capability-level answer lives on the dialect
+ (``PostgresDialect.supports_database_assigned_integer_column``), which
+ is what a declaration asks for.
"""
return False
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py
index 2ec98ffc..0228c462 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/column_type.py
@@ -10,10 +10,15 @@
Every answer below is written out rather than inherited from a core-side
table, because a backend that owns its answer should be readable without a
-second file. The eighteen entries are the protocol's closed list, all of them
-answered, and exactly one of them is refused: ``datetime.timedelta``, which
-this server can spell as ``interval`` but which no core column class can
-answer for -- see the entry's own comment.
+second file. The twenty-four entries are the protocol's closed list, all of
+them answered: ``datetime.timedelta`` names ``IntervalColumn``, and the six
+complex families -- geometry, vector, bit string, range, multirange and MAC
+address -- name the core classes, which promise only the surface every column
+has. The DDL half of the six families is answered separately, in
+``data_type_suggestions.py``: this backend spells ``GEOMETRY`` / ``VARBIT`` /
+``MACADDR`` for three of them and refuses the three whose parameters a bare
+annotation does not carry. A column class and a storage entry answer
+separately, and neither one's answer implies the other's.
**What the answers are measured against.** The live probes in
``.claude/plan/2026-10-08/suggested-mappings.md`` §8 (≈90 server instances
@@ -51,21 +56,89 @@
import uuid
from typing import Any, Dict, Optional, Type
+from rhosocial.activerecord.backend.adapters import (
+ BitString,
+ Geometry,
+ MacAddress,
+ Multirange,
+ Range,
+ Vector,
+)
+
from rhosocial.activerecord.backend.dialect.mixins import ColumnTypeMixin
from rhosocial.activerecord.backend.expression.column_types import (
ArrayColumn,
BinaryColumn,
+ BitStringColumn,
BooleanColumn,
ColumnBase,
- TimestampColumn,
+ GeometryColumn,
IntegerColumn,
+ IntervalColumn,
JSONColumn,
+ MacAddressColumn,
+ MultirangeColumn,
NumericColumn,
+ RangeColumn,
StringColumn,
+ TimestampColumn,
UUIDColumn,
+ VectorColumn,
+)
+from ..column_types import (
+ PostgresAreaGeometryColumn,
+ PostgresBitStringColumn,
+ PostgisGeometryColumn,
+ PostgresGeometryColumn,
+ PostgresHstoreColumn,
+ PostgresIdentifierColumn,
+ PostgresJsonPathColumn,
+ PostgresLsnColumn,
+ PostgresMacAddressColumn,
+ PostgresMoneyColumn,
+ PostgresTextSearchColumn,
+ PostgresVectorColumn,
+ PostgresXmlColumn,
+)
+from ..type_values import (
+ Box,
+ Circle,
+ CID,
+ Line,
+ LineSegment,
+ OID,
+ Path,
+ Point,
+ Polygon,
+ PostgresBitString,
+ PostgresGeometry,
+ PostgresHstore,
+ PostgresJsonPath,
+ PostgresLsn,
+ PostgresMacaddr,
+ PostgresMacaddr8,
+ PostgresMoney,
+ PostgresTsQuery,
+ PostgresTsVector,
+ PostgresVector,
+ PostgresXML,
+ RegClass,
+ RegCollation,
+ RegConfig,
+ RegDictionary,
+ RegNamespace,
+ RegOper,
+ RegOperator,
+ RegProc,
+ RegProcedure,
+ RegRole,
+ RegType,
+ TID,
+ XID,
+ XID8,
)
-#: All eighteen protocol entries, in the protocol's reading order. Commented
+#: All twenty-four protocol entries, in the protocol's reading order. Commented
#: per group because the reasons are the content: the answer is a claim about
#: this server, and a claim without its evidence is decoration.
POSTGRES_COLUMN_TYPES: Dict[Any, Optional[Type[ColumnBase]]] = {
@@ -100,23 +173,18 @@
datetime.date: TimestampColumn,
datetime.time: TimestampColumn,
datetime.datetime: TimestampColumn,
- # THE ONE DELIBERATE `None`. PostgreSQL has a real `interval` type -- §1
- # spells it `INTERVAL` where eight backends have no answer at all -- and no
- # core column class answers for it (`IntervalColumn` is a core gap,
- # secondary-gaps 附录 D ①). `interval` is not a number: the server answers
- # `justify_hours`, `EXTRACT(... FROM interval)` and field qualifiers for
- # it, and refuses `sqrt(interval '1 day')` outright, so naming a number
- # class here would hand the caller operations the engine cannot execute.
- # `None` is the protocol's last resort and this is its last resort: the
- # value is carried (psycopg binds and reads back a `timedelta`), and the
- # storage is spelled by the `DataType` layer
- # (`format_data_type_interval`), but the *operations* have no class to
- # name. A field declared `timedelta` fails to resolve with a message
- # naming the fix -- declare one explicitly with
- # `UseColumnType(SomeColumn)`. When core grows an `IntervalColumn`, this
- # entry is where it goes (pinned by
- # `test_the_interval_entry_is_refused_until_core_grows_an_interval_column`).
- datetime.timedelta: None,
+ # PostgreSQL has a real `interval` type -- §1 spells it `INTERVAL` where
+ # eight backends have no answer at all -- and it is not a number:
+ # `justify_hours`, `EXTRACT(... FROM interval)` and the field qualifiers
+ # operate on it, while `sqrt(interval '1 day')` is refused outright. So
+ # `IntervalColumn` names the value and offers no arithmetic; the numeric
+ # operations stay with numbers. The storage is spelled by the `DataType`
+ # layer (`format_data_type_interval`).
+ #
+ # The backend's own interval operations (`justify_hours`, field extraction)
+ # belong to a PostgreSQL-named subclass; the core class states only the
+ # surface every column has.
+ datetime.timedelta: IntervalColumn,
# -- Value families --------------------------------------------------
uuid.UUID: UUIDColumn,
# `dict` → the JSON column class, on both `json` and `jsonb`. §12's
@@ -159,11 +227,78 @@
# class would put storage into the operation layer, which is the split
# this protocol exists to keep.
enum.Enum: StringColumn,
+ # -- Complex families ------------------------------------------------
+ # The six families now have core column classes. Those classes promise
+ # only the surface every column has -- alias, null tests, casting and
+ # collation -- because no distance, containment, overlap, bitwise or
+ # similarity operation is spelled the same way on every backend. The
+ # PostgreSQL operations live on backend-named subclasses (PostGIS is an
+ # extension, not the core server), which is where the richer spelling
+ # belongs. The storage stays answered in `data_type_suggestions.py`.
+ Geometry: GeometryColumn,
+ Vector: VectorColumn,
+ BitString: BitStringColumn,
+ Range: RangeColumn,
+ Multirange: MultirangeColumn,
+ MacAddress: MacAddressColumn,
+}
+
+
+#: PostgreSQL's own value classes -> the column class a bare field gets.
+#:
+#: The protocol's second table, and the backend-owned half: a Python type this
+#: server models and the framework does not. The keys mirror
+#: ``POSTGRES_EXTRA_DATA_TYPE_SUGGESTIONS``, with one deliberate omission --
+#: ``PostgresRange`` / ``PostgresMultirange`` -- for the reason recorded there:
+#: their adapters register only in the CUSTOM/BOTH range modes, so a default
+#: backend has no adapter for the value and a suggestion would build a column
+#: nothing can write. The column classes exist (``PostgresRangeColumn`` and
+#: ``PostgresMultirangeColumn``) and a field can name them explicitly with
+#: ``UseColumnType`` once its adapter is in place.
+POSTGRES_EXTRA_COLUMN_TYPES: Dict[Any, Type[ColumnBase]] = {
+ PostgresBitString: PostgresBitStringColumn,
+ PostgresGeometry: PostgisGeometryColumn,
+ Point: PostgresGeometryColumn,
+ Line: PostgresGeometryColumn,
+ LineSegment: PostgresGeometryColumn,
+ Path: PostgresGeometryColumn,
+ # @> / <@ / && exist for these three, not for the line-like types.
+ Box: PostgresAreaGeometryColumn,
+ Polygon: PostgresAreaGeometryColumn,
+ Circle: PostgresAreaGeometryColumn,
+ PostgresTsVector: PostgresTextSearchColumn,
+ PostgresTsQuery: PostgresTextSearchColumn,
+ PostgresJsonPath: PostgresJsonPathColumn,
+ PostgresHstore: PostgresHstoreColumn,
+ PostgresMacaddr: PostgresMacAddressColumn,
+ PostgresMacaddr8: PostgresMacAddressColumn,
+ PostgresMoney: PostgresMoneyColumn,
+ PostgresXML: PostgresXmlColumn,
+ PostgresLsn: PostgresLsnColumn,
+ PostgresVector: PostgresVectorColumn,
+ # Object identifiers: the registry names are OID aliases, so they share the
+ # whole-number surface and the DDL spelling differs per name.
+ OID: PostgresIdentifierColumn,
+ RegClass: PostgresIdentifierColumn,
+ RegType: PostgresIdentifierColumn,
+ RegProc: PostgresIdentifierColumn,
+ RegProcedure: PostgresIdentifierColumn,
+ RegOper: PostgresIdentifierColumn,
+ RegOperator: PostgresIdentifierColumn,
+ RegConfig: PostgresIdentifierColumn,
+ RegDictionary: PostgresIdentifierColumn,
+ RegNamespace: PostgresIdentifierColumn,
+ RegRole: PostgresIdentifierColumn,
+ RegCollation: PostgresIdentifierColumn,
+ XID: PostgresIdentifierColumn,
+ XID8: PostgresIdentifierColumn,
+ CID: PostgresIdentifierColumn,
+ TID: PostgresIdentifierColumn,
}
class PostgresColumnTypeMixin(ColumnTypeMixin):
- """The full common-Python-type → column-class table for PostgreSQL.
+ """The full framework-modelled-Python-type → column-class table for PostgreSQL.
Composed into :class:`~rhosocial.activerecord.backend.impl.postgres.dialect.PostgresDialect`
ahead of this backend's own mixins. Nothing else in the list can answer for
@@ -178,12 +313,21 @@ class PostgresColumnTypeMixin(ColumnTypeMixin):
operations, and it is pinned by the backend's own test file rather than
left to drift.
- **One entry is refused.** ``datetime.timedelta`` answers ``None`` because
- PostgreSQL's native ``interval`` has no core column class -- the gap this
- backend used to hide by naming ``NumericColumn`` and accepting that
- ``sqrt(interval '1 day')`` would be offered and would fail on the server.
- A refusal that reaches the model layer as a resolution error is the honest
- version of that gap, and the entry's comment says what closes it.
+ **No entry is refused.** ``datetime.timedelta`` used to answer ``None``
+ because PostgreSQL's native ``interval`` had no core column class; core
+ now has ``IntervalColumn``, so the value is named and the arithmetic it
+ does not promise stays where it belongs. The six complex families used to
+ answer ``None`` for the mirror-image reason -- no core class existed --
+ and now name their core classes, which promise only the surface every
+ column has. Their storage is answered here too -- ``GEOMETRY``,
+ ``VARBIT`` and ``MACADDR`` -- so a bare model builds the table and a
+ field resolves.
+
+ **A backend-named class is where richer operations go.** PostGIS
+ functions, range ``@>`` operators and `justify_hours` are each this
+ server's own; they belong to a subclass such as
+ ``PostgresGeometryColumn(GeometryColumn)`` in the extra table, not to
+ the core class that every backend derives from.
The table has no version branch because nothing in it moves with the
version: the one thing that does (``jsonb`` becoming available in 9.4)
@@ -193,5 +337,18 @@ class PostgresColumnTypeMixin(ColumnTypeMixin):
def suggested_column_types(self) -> Dict[Any, Optional[Type[ColumnBase]]]:
return dict(POSTGRES_COLUMN_TYPES)
+ def suggested_extra_column_types(self) -> Dict[Any, Type[ColumnBase]]:
+ """This server's own value classes -> their column classes.
+
+ A field annotated with a PostgreSQL value class (``Point``, ``PostgresXML``,
+ ``PostgresMoney``) resolves without a declaration. The range wrappers are
+ absent on purpose -- see :data:`POSTGRES_EXTRA_COLUMN_TYPES`.
+ """
+ return dict(POSTGRES_EXTRA_COLUMN_TYPES)
+
-__all__ = ["POSTGRES_COLUMN_TYPES", "PostgresColumnTypeMixin"]
+__all__ = [
+ "POSTGRES_COLUMN_TYPES",
+ "POSTGRES_EXTRA_COLUMN_TYPES",
+ "PostgresColumnTypeMixin",
+]
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py
new file mode 100644
index 00000000..57b3809b
--- /dev/null
+++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py
@@ -0,0 +1,260 @@
+# src/rhosocial/activerecord/backend/impl/postgres/mixins/data_type_suggestions.py
+"""PostgreSQL's **suggested data types**: what a bare field is declared as here.
+
+The DDL half of the type answer, separate from :mod:`.column_type` for the
+reason that file already states: a column class says what a value can *do*,
+this says what a column *is*.
+
+Three things about this server shape the answers:
+
+* **text is one tier, and it is unbounded.** PostgreSQL's ``TEXT`` has no size
+ cap (``TOAST`` moves large values out of the row automatically), so a declared
+ capacity is satisfied rather than rounded: ``TextType(length=N)``, ``JsonType``
+ and ``XmlType`` all spend the same ``TEXT``/``XML`` word here.
+* **a JSON document's natural home here is ``JSONB``.** The column table's own
+ comment explains why the operation surface is one class either way; this is
+ where the storage choice is made, and it is ``JSONB`` (indexable, and the only
+ one of the two with an equality operator).
+* **arrays are native.** ``dict``'s container siblings get real arrays, and the
+ element width is the shared default: a Python list is ``TEXT[]`` unless the
+ field declares otherwise.
+
+Three families carry a parameter a bare annotation does not say: ``Vector``
+needs a dimension, and ``Range`` / ``Multirange`` need an element type (the
+element decides the spelling, ``int4range`` / ``numrange`` / ``daterange``).
+A suggestion may not invent either, so it names the **text carrier** their
+neutral adapters already write -- pgvector's ``[1,2,3]`` and the range literal
+``[1,2)`` -- and a bare field round-trips. The field that wants the server's
+native type declares it with ``UseSqlType``; the alternative, answering
+``None``, would take the table away from the caller, which is not what a
+suggestion is for.
+
+Each call returns a **fresh dict** whose values are this module's read-only
+templates; the derivation binds a dialect on a copy of the single entry it uses.
+"""
+from __future__ import annotations
+
+import datetime
+import decimal
+import enum
+import uuid
+from typing import Any, Dict, Optional
+
+from rhosocial.activerecord.backend.adapters import (
+ BitString,
+ Geometry,
+ MacAddress,
+ Multirange,
+ Range,
+ Vector,
+)
+from rhosocial.activerecord.backend.expression.types import (
+ ArrayType,
+ BlobType,
+ BooleanType,
+ DateType,
+ DecimalType,
+ DoubleType,
+ IntegerType,
+ IntervalType,
+ JsonBType,
+ TextType,
+ TimeType,
+ XmlType,
+ TimestampType,
+ UUIDType,
+ VarCharType,
+)
+from rhosocial.activerecord.backend.impl.postgres.expression.types import (
+ PostgresBoxType,
+ PostgresCIDType,
+ PostgresCircleType,
+ PostgresGeometryType,
+ PostgresHstoreType,
+ PostgresJsonPathType,
+ PostgresLineSegmentType,
+ PostgresLineType,
+ PostgresMacAddr8Type,
+ PostgresMacAddrType,
+ PostgresMoneyType,
+ PostgresOIDType,
+ PostgresPathType,
+ PostgresPointType,
+ PostgresPolygonType,
+ PostgresRegClassType,
+ PostgresRegTypeType,
+ PostgresTIDType,
+ PostgresTSQueryType,
+ PostgresTSVectorType,
+ PostgresVarBitType,
+ PostgresXID8Type,
+ PostgresXIDType,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.bit_string import (
+ PostgresBitString,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.geometric import (
+ Box,
+ Circle,
+ Line,
+ LineSegment,
+ Path,
+ Point,
+ Polygon,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.hstore import (
+ PostgresHstore,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.json import (
+ PostgresJsonPath,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.monetary import (
+ PostgresMoney,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.network_address import (
+ PostgresMacaddr,
+ PostgresMacaddr8,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.object_identifier import (
+ CID,
+ OID,
+ TID,
+ XID,
+ XID8,
+ RegClass,
+ RegCollation,
+ RegConfig,
+ RegDictionary,
+ RegNamespace,
+ RegOper,
+ RegOperator,
+ RegProc,
+ RegProcedure,
+ RegRole,
+ RegType,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.pg_lsn import (
+ PostgresLsn,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.pgvector import (
+ PostgresVector,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.postgis import (
+ PostgresGeometry,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.range import (
+ PostgresMultirange,
+ PostgresRange,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.text_search import (
+ PostgresTsQuery,
+ PostgresTsVector,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values.xml import (
+ PostgresXML,
+)
+
+#: PostgreSQL's suggested declaration per framework-modelled Python type.
+POSTGRES_DATA_TYPE_SUGGESTIONS: Dict[Any, Optional[Any]] = {
+ bool: BooleanType(),
+ int: IntegerType(),
+ float: DoubleType(),
+ decimal.Decimal: DecimalType(),
+ str: TextType(),
+ bytes: BlobType(),
+ bytearray: BlobType(),
+ datetime.date: DateType(),
+ datetime.time: TimeType(),
+ datetime.datetime: TimestampType(precision=3),
+ datetime.timedelta: IntervalType(),
+ uuid.UUID: UUIDType(),
+ dict: JsonBType(),
+ list: ArrayType(element_type=VarCharType(length=255)),
+ tuple: ArrayType(element_type=VarCharType(length=255)),
+ set: ArrayType(element_type=VarCharType(length=255)),
+ frozenset: ArrayType(element_type=VarCharType(length=255)),
+ enum.Enum: VarCharType(length=255),
+ # -- Complex families ------------------------------------------------
+ # GEOMETRY untyped: point/line/polygon are the *shape* a value carries, and
+ # the column decides the shape and SRID it accepts.
+ Geometry: PostgresGeometryType(),
+ # No dimension to declare here; the neutral adapter's text is the carrier.
+ Vector: TextType(),
+ BitString: PostgresVarBitType(),
+ # The element type is the column's decision; the literal text round-trips.
+ Range: TextType(),
+ Multirange: TextType(),
+ MacAddress: PostgresMacAddrType(),
+}
+
+
+#: Declarations for PostgreSQL's **own** value classes -- the types the
+#: framework does not model. A field annotated with one of these is a Python
+#: type no portable reader knows, so the backend has to say what it stores.
+#: Entries whose native spelling needs a parameter (a vector's dimension, a
+#: range's subtype) name the text carrier their adapters write; the rest name
+#: the server's own type.
+POSTGRES_EXTRA_DATA_TYPE_SUGGESTIONS: Dict[Any, Optional[Any]] = {
+ # Bit string, text search, jsonpath and the PostGIS wrapper.
+ PostgresBitString: PostgresVarBitType(),
+ PostgresGeometry: PostgresGeometryType(),
+ PostgresTsVector: PostgresTSVectorType(),
+ PostgresTsQuery: PostgresTSQueryType(),
+ PostgresJsonPath: PostgresJsonPathType(),
+ # The server's own geometric family.
+ Point: PostgresPointType(),
+ Line: PostgresLineType(),
+ LineSegment: PostgresLineSegmentType(),
+ Box: PostgresBoxType(),
+ Path: PostgresPathType(),
+ Polygon: PostgresPolygonType(),
+ Circle: PostgresCircleType(),
+ # Network, money, hstore, xml and LSN.
+ PostgresMacaddr: PostgresMacAddrType(),
+ PostgresMacaddr8: PostgresMacAddr8Type(),
+ PostgresMoney: PostgresMoneyType(),
+ PostgresHstore: PostgresHstoreType(),
+ PostgresXML: XmlType(),
+ PostgresLsn: TextType(),
+ # Object identifiers: the wrapped ones have their own declaration; the
+ # registry names are OID aliases and are carried as text.
+ OID: PostgresOIDType(),
+ RegClass: PostgresRegClassType(),
+ RegType: PostgresRegTypeType(),
+ RegProc: TextType(),
+ RegProcedure: TextType(),
+ RegOper: TextType(),
+ RegOperator: TextType(),
+ RegConfig: TextType(),
+ RegDictionary: TextType(),
+ RegNamespace: TextType(),
+ RegRole: TextType(),
+ RegCollation: TextType(),
+ XID: PostgresXIDType(),
+ XID8: PostgresXID8Type(),
+ CID: PostgresCIDType(),
+ TID: PostgresTIDType(),
+ # Parameter-carrying wrapper: the text its adapter writes.
+ PostgresVector: TextType(),
+ # `PostgresRange` / `PostgresMultirange` are deliberately absent: their
+ # adapters are registered only in the CUSTOM/BOTH range modes, so a default
+ # backend has no adapter for those value classes. A suggestion without an
+ # adapter builds a column nothing can write.
+}
+
+
+class PostgresDataTypeSuggestionsMixin:
+ """PostgreSQL's answer to "what declaration does a bare field get here"."""
+
+ def suggested_data_types(self) -> Dict[Any, Optional[Any]]:
+ return dict(POSTGRES_DATA_TYPE_SUGGESTIONS)
+
+ def suggested_extra_data_types(self) -> Dict[Any, Optional[Any]]:
+ return dict(POSTGRES_EXTRA_DATA_TYPE_SUGGESTIONS)
+
+
+__all__ = [
+ "POSTGRES_DATA_TYPE_SUGGESTIONS",
+ "POSTGRES_EXTRA_DATA_TYPE_SUGGESTIONS",
+ "PostgresDataTypeSuggestionsMixin",
+]
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl/partition.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl/partition.py
index b6530102..f724892b 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl/partition.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl/partition.py
@@ -63,6 +63,19 @@ def supports_partitioned_table_creation(self) -> bool:
"""
return self.supports_table_partitioning()
+ def supports_partitioned_table_primary_key(self) -> bool:
+ """Check if a partitioned parent table can declare a primary key.
+
+ PostgreSQL 10 refused a PRIMARY KEY on a partitioned table unless
+ it included the partition key, so a parent declared with one fails
+ on 10 and works from 11 on -- a parent partitioned by created_at
+ with PRIMARY KEY (id, created_at) is the shape callers rely on.
+
+ Returns:
+ True if PostgreSQL version >= 11.
+ """
+ return self.version_at_least((11, 0, 0))
+
def supports_range_table_partitioning(self) -> bool:
"""Check if RANGE table partitioning is supported.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py
index c44ff5b9..b22d6bd9 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py
@@ -1,14 +1,54 @@
# src/rhosocial/activerecord/backend/impl/postgres/mixins/ddl_table.py
import re
-from typing import Any, List, Tuple
+from typing import Any, Dict, List, Tuple
from rhosocial.activerecord.backend.expression.objects import Table
-from rhosocial.activerecord.backend.expression.statements.ddl_table import ColumnPrimaryKeyConstraint, IdentityClause
+from rhosocial.activerecord.backend.expression.statements.ddl_table import ColumnPrimaryKeyConstraint
+from rhosocial.activerecord.backend.expression.types import (
+ BigIntType,
+ IntegerType,
+ SmallIntType,
+)
+
+#: An auto-increment column is a SERIAL pseudo-type, not a clause.
+#:
+#: PostgreSQL spells "the database assigns this integer" as a *type* whose
+#: backing sequence does the work. SERIAL has existed far longer than the
+#: SQL-standard identity clause, and its observable behaviour -- an omitted
+#: value is supplied and returned -- is what the declaration asks for, so it
+#: is the one spelling this dialect uses. The mapping covers exactly the three
+#: integer widths SERIAL has; anything else is refused rather than approximated.
+SERIAL_TYPES: Dict[type, str] = {
+ SmallIntType: "SMALLSERIAL",
+ IntegerType: "SERIAL",
+ BigIntType: "BIGSERIAL",
+}
class PostgresTableMixin:
"""PostgreSQL table extended features implementation."""
+ def _serial_type_sql(self, data_type: Any) -> str:
+ """The SERIAL pseudo-type for an auto-increment integer column.
+
+ Refuses a column outside the three widths SERIAL has rather than
+ approximating one: an auto-increment text column has no PostgreSQL
+ spelling, and silently choosing a type would decide for the caller.
+ """
+ for core_type, spelling in SERIAL_TYPES.items():
+ if isinstance(data_type, core_type):
+ return spelling
+ from rhosocial.activerecord.backend.dialect.exceptions import (
+ UnsupportedFeatureError,
+ )
+
+ raise UnsupportedFeatureError(
+ self.name,
+ "AUTO_INCREMENT column",
+ "SERIAL covers smallint, integer and bigint; "
+ f"{type(data_type).__name__} is none of them",
+ )
+
def supports_if_not_exists_table(self) -> bool:
"""CREATE TABLE IF NOT EXISTS is supported since PostgreSQL 9.5+."""
return self.version_at_least((9, 5, 0))
@@ -215,27 +255,7 @@ def format_column_definition(self, col_def) -> Tuple[str, tuple]:
attr_sql, attr_params = self.format_column_attributes(col_def)
col_sql += attr_sql
all_params.extend(attr_params)
- auto_identity_added = False
for constraint in col_def.constraints:
- if (
- not auto_identity_added
- and isinstance(constraint.branch, ColumnPrimaryKeyConstraint)
- and constraint.branch.is_auto_increment
- ):
- # An auto-increment constraint on PostgreSQL is the standard
- # identity clause in its default generation mode. Routing it
- # through the gated formatter keeps the version boundary in
- # one place: PostgreSQL 9 refuses here instead of rendering
- # a GENERATED clause its server rejects, and no silent
- # fallback to SERIAL is attempted. The flag lives on the
- # PRIMARY KEY branch since the two-level split, so it is read
- # there rather than probed off the clause.
- identity_sql, identity_params = self.format_identity_clause(
- IdentityClause(self, "BY DEFAULT")
- )
- col_sql += identity_sql
- all_params.extend(identity_params)
- auto_identity_added = True
suffix, params = self.format_column_constraint(constraint)
col_sql += suffix
all_params.extend(params)
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/function.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/function.py
index c280cccd..8b947810 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/function.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/function.py
@@ -101,3 +101,13 @@ def _check_function_support(self, func_name: str) -> "FunctionSupportInfo":
return FunctionSupportInfo(supported=False, reason="extension_version_insufficient")
return FunctionSupportInfo(supported=True)
+
+ def supports_bit_count(self) -> bool:
+ """Whether bit_count(bit) is supported.
+
+ Native function, PostgreSQL 14+. The bit-string function tables of
+ the 9.5 through 13 documentation carry no bit_count entry; it first
+ appears in 14.
+ https://www.postgresql.org/docs/current/functions-bitstring.html
+ """
+ return self.version_at_least((14, 0, 0))
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/integer_auto_increment_column_suggestion.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/integer_auto_increment_column_suggestion.py
new file mode 100644
index 00000000..2ce4e459
--- /dev/null
+++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/integer_auto_increment_column_suggestion.py
@@ -0,0 +1,48 @@
+# src/rhosocial/activerecord/backend/impl/postgres/mixins/integer_auto_increment_column_suggestion.py
+"""PostgresIntegerAutoIncrementColumnSuggestionMixin -- postgres's integer auto-increment column suggestion.
+
+The answer is the backend's own spelling, assembled from its capability
+probes where it has one. It is placed first in the dialect bases so no core
+mixin can shadow it, and it renders nothing itself -- the returned clause's
+formatter owns the SQL spelling.
+"""
+
+from typing import TYPE_CHECKING
+
+from ....expression.statements import IntegerAutoIncrementColumnSuggestion
+
+if TYPE_CHECKING: # pragma: no cover
+ from ....expression.types._base import DataType
+
+
+class PostgresIntegerAutoIncrementColumnSuggestionMixin:
+ """Suggest postgres's declaration for a generated integer key."""
+
+ def suggest_integer_auto_increment_column(
+ self, default_type: "DataType"
+ ) -> IntegerAutoIncrementColumnSuggestion:
+ from ....expression.types import BigIntType, IntegerType, SmallIntType
+ from ..expression.types import (
+ PostgresBigSerialType,
+ PostgresSerialType,
+ PostgresSmallSerialType,
+ )
+
+ # PostgreSQL has no column marker: the SERIAL pseudo-type carries the
+ # sequence, so auto_increment=False tells the framework to add no
+ # clause. The width mapping mirrors the engine's three serial types.
+ for core_type, serial_type in (
+ (SmallIntType, PostgresSmallSerialType),
+ (IntegerType, PostgresSerialType),
+ (BigIntType, PostgresBigSerialType),
+ ):
+ if isinstance(default_type, core_type):
+ return IntegerAutoIncrementColumnSuggestion(serial_type(self), False)
+ from ....dialect.exceptions import UnsupportedFeatureError
+
+ raise UnsupportedFeatureError(
+ self.name,
+ "AUTO_INCREMENT column",
+ "SERIAL covers smallint, integer and bigint; "
+ f"{type(default_type).__name__} is none of them",
+ )
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type.py
index d3aaafa0..f54b49b4 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type.py
@@ -88,6 +88,15 @@ def supports_xid8_type(self) -> bool:
"""
return self.version_at_least((13, 0, 0))
+ def supports_pg_lsn_addition(self) -> bool:
+ """Whether a pg_lsn value can be added to a numeric byte count.
+
+ Native feature, PostgreSQL 14+. The pg_lsn subtraction operator
+ predates it; only 14 introduced ``pg_lsn + numeric``.
+ https://www.postgresql.org/docs/current/datatype-pg-lsn.html#DATATYPE-PG-LSN
+ """
+ return self.version_at_least((14, 0, 0))
+
def format_create_range_type(
self,
expr: CreateTypeStatement,
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py b/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py
index d0c9e56f..ce666d77 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/mixins/types/data_type_formatting.py
@@ -679,6 +679,28 @@ def supports_data_type_postgres_smallserial(self) -> bool:
return True
def supports_data_type_postgres_serial(self) -> bool:
+ """Whether ``SERIAL`` exists, which is every PostgreSQL version.
+
+ SERIAL is the PostgreSQL spelling of "the database assigns this
+ integer", and it is a *pseudo-type*, not a column attribute: writing
+ ``id SERIAL`` creates an integer column with a default drawn from a
+ sequence the engine creates and owns. ``AUTO_INCREMENT`` is the MySQL
+ spelling of the same observable behaviour and differs in three ways:
+
+ * it is a column attribute, so the type stays ``INT`` and the marker
+ rides beside it; ``SERIAL`` replaces the type;
+ * it is a per-table counter, while ``SERIAL`` is backed by a sequence
+ object (visible in the catalogue, droppable, shareable);
+ * inserting an explicit value larger than the current one raises the
+ MySQL counter to ``max + 1``, while a ``SERIAL`` column leaves its
+ sequence untouched -- the one place where the two are not
+ operationally equivalent.
+
+ PostgreSQL also accepts the SQL-standard identity clause from 10 on
+ (``supports_identity_column``), which is a third spelling of the same
+ capability; ``supports_database_assigned_integer_column`` is the
+ capability-level answer.
+ """
return True
def supports_data_type_postgres_bigserial(self) -> bool:
@@ -812,7 +834,14 @@ def supports_data_type_postgres_tid(self) -> bool:
return True
def supports_data_type_postgres_pg_lsn(self) -> bool:
- return True
+ """pg_lsn arrived in PostgreSQL 9.4.
+
+ An unconditional True told every server it could have a pg_lsn
+ column, and a 9.3 server found out by executing the DDL ('type
+ "pg_lsn" does not exist'). The type is documented from 9.4 on:
+ https://www.postgresql.org/docs/9.4/datatype-pg-lsn.html
+ """
+ return self.version_at_least((9, 4, 0))
def supports_data_type_postgres_hstore(self) -> bool:
return True
@@ -967,7 +996,7 @@ def format_data_type_postgres_enum(self, data_type) -> Tuple[str, tuple]:
def supports_data_type_postgres_enum(self) -> bool:
return True
- def suggested_data_types(self) -> dict:
+ def substitute_data_types(self) -> dict:
"""Cross-backend type-consistency suggestion map.
PostgreSQL renders every core type it supports through its own
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/protocols/ddl/partition.py b/src/rhosocial/activerecord/backend/impl/postgres/protocols/ddl/partition.py
index e152392b..b32ed78e 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/protocols/ddl/partition.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/protocols/ddl/partition.py
@@ -33,6 +33,7 @@ class PostgresPartitionSupport(PartitionSupport, Protocol):
- Concurrent DETACH (PG 14+)
- Partition bounds expression (PG 12+)
- Partitionwise join/aggregate (PG 11+)
+ - Primary key on a partitioned table (PG 11+)
Official Documentation:
- Partitioning: https://www.postgresql.org/docs/current/ddl-partitioning.html
@@ -43,6 +44,7 @@ class PostgresPartitionSupport(PartitionSupport, Protocol):
- HASH partitioning: PostgreSQL 11+
- DEFAULT partition: PostgreSQL 11+
- Row movement: PostgreSQL 11+
+ - Primary key on a partitioned table: PostgreSQL 11+
- Concurrent DETACH: PostgreSQL 14+
- Partition bounds expression: PostgreSQL 12+
- Partitionwise join: PostgreSQL 11+
@@ -73,6 +75,15 @@ def supports_partition_key_update(self) -> bool:
"""
...
+ def supports_partitioned_table_primary_key(self) -> bool:
+ """Whether a partitioned parent table can declare a primary key.
+
+ Native feature, PostgreSQL 11+.
+ PostgreSQL 10 refuses a PRIMARY KEY on a partitioned table unless it
+ includes the partition key, so the constraint arrives with 11.
+ """
+ ...
+
def supports_concurrent_detach(self) -> bool:
"""Whether CONCURRENTLY DETACH PARTITION is supported.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/protocols/types/data_type.py b/src/rhosocial/activerecord/backend/impl/postgres/protocols/types/data_type.py
index 75dc1797..76ec879a 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/protocols/types/data_type.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/protocols/types/data_type.py
@@ -21,6 +21,7 @@ class PostgresDataTypeSupport(Protocol):
- Numeric Infinity (PG 14+)
- Nondeterministic ICU collation (PG 12+)
- xid8 type (PG 13+)
+ - pg_lsn addition (PG 14+)
Official Documentation:
- Multirange: https://www.postgresql.org/docs/current/rangetypes.html
@@ -37,6 +38,7 @@ class PostgresDataTypeSupport(Protocol):
- Multirange: PostgreSQL 14+
- JSONB subscript: PostgreSQL 14+
- Numeric Infinity: PostgreSQL 14+
+ - pg_lsn addition: PostgreSQL 14+
"""
def supports_multirange_type(self) -> bool:
@@ -95,6 +97,14 @@ def supports_xid8_type(self) -> bool:
"""
...
+ def supports_pg_lsn_addition(self) -> bool:
+ """Whether a pg_lsn value can be added to a numeric byte count.
+
+ Native feature, PostgreSQL 14+.
+ Enables ``pg_lsn + numeric`` arithmetic.
+ """
+ ...
+
def format_create_range_type(self, expr) -> Tuple[str, tuple]:
"""Format CREATE TYPE AS RANGE statement from expression object.
diff --git a/src/rhosocial/activerecord/backend/impl/postgres/transaction.py b/src/rhosocial/activerecord/backend/impl/postgres/transaction.py
index 701e36d8..7a7e46d9 100644
--- a/src/rhosocial/activerecord/backend/impl/postgres/transaction.py
+++ b/src/rhosocial/activerecord/backend/impl/postgres/transaction.py
@@ -306,3 +306,7 @@ async def rollback(self) -> None:
# Clear deferred constraints when outermost transaction rolls back
if self._transaction_level == 0:
self._deferred_constraints.clear()
+
+ async def supports_savepoint(self) -> bool:
+ """Async counterpart of the sync capability probe."""
+ return self._backend.dialect.supports_savepoint()
diff --git a/tests/benchmark/activerecord_bulk/test_bulk_create.py b/tests/benchmark/activerecord_bulk/test_bulk_create.py
index 8abfa754..4c1ce6f1 100644
--- a/tests/benchmark/activerecord_bulk/test_bulk_create.py
+++ b/tests/benchmark/activerecord_bulk/test_bulk_create.py
@@ -1,5 +1,2 @@
# Bridge file for bulk_create benchmark tests from the testsuite.
-from rhosocial.activerecord.testsuite.benchmark.crud.test_bulk_create import * # noqa: F401, F403
-from rhosocial.activerecord.testsuite.benchmark.crud.test_bulk_create_async import * # noqa: F403
-from rhosocial.activerecord.testsuite.benchmark.crud.test_bulk_create_async import * # noqa: F401, F403
-
+from rhosocial.activerecord.testsuite.benchmark.crud.core.test_bulk_create import * # noqa: F401, F403
diff --git a/tests/benchmark/activerecord_bulk/test_bulk_create_async.py b/tests/benchmark/activerecord_bulk/test_bulk_create_async.py
new file mode 100644
index 00000000..5e874a24
--- /dev/null
+++ b/tests/benchmark/activerecord_bulk/test_bulk_create_async.py
@@ -0,0 +1,2 @@
+from rhosocial.activerecord.testsuite.benchmark.crud.core.test_bulk_create_async import * # noqa: F403
+from rhosocial.activerecord.testsuite.benchmark.crud.core.test_bulk_create_async import * # noqa: F401, F403
diff --git a/tests/benchmark/backend/conftest.py b/tests/benchmark/backend/conftest.py
index a8371131..f5beac37 100644
--- a/tests/benchmark/backend/conftest.py
+++ b/tests/benchmark/backend/conftest.py
@@ -13,7 +13,7 @@
payload_count_for_size,
)
-from providers.scenarios import get_enabled_scenarios, get_scenario
+from support.postgres import get_enabled_scenarios, get_scenario
@dataclass
diff --git a/tests/benchmark/conftest.py b/tests/benchmark/conftest.py
new file mode 100644
index 00000000..0421d11a
--- /dev/null
+++ b/tests/benchmark/conftest.py
@@ -0,0 +1,9 @@
+# tests/benchmark/conftest.py
+"""Register PostgreSQL implementations for the shared benchmark contracts.
+
+Importing ``providers`` populates the testsuite's global ``benchmarks``
+registry before pytest collects the shared ``benchmark/*`` contract files.
+Without this import those contracts skip with "no implementation registered".
+"""
+
+from tests.benchmark import providers # noqa: F401
diff --git a/tests/benchmark/providers.py b/tests/benchmark/providers.py
new file mode 100644
index 00000000..c6602013
--- /dev/null
+++ b/tests/benchmark/providers.py
@@ -0,0 +1,230 @@
+# tests/benchmark/providers.py
+"""PostgreSQL benchmark implementations registered with the shared testsuite.
+
+The testsuite's ``benchmark/*`` contracts obtain a backend implementation from
+the global ``benchmarks`` registry. Registering here (at conftest import time)
+is what turns those contracts from "skip: no implementation" into real
+measurements. Direct ``StorageBackend.execute`` benchmarks stay backend-owned
+under ``tests/benchmark/backend/`` and do not use this registry.
+"""
+
+import uuid
+from typing import ClassVar, Optional
+
+from pydantic import EmailStr, Field
+
+from rhosocial.activerecord.backend.options import ExecutionOptions
+from rhosocial.activerecord.backend.schema import StatementType
+from rhosocial.activerecord.base.field_proxy import FieldProxy
+from rhosocial.activerecord.field import DefaultTimestampMixin, IntegerPKMixin
+from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord
+from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.data import (
+ make_user_payloads,
+ payload_count_for_size,
+)
+from rhosocial.activerecord.testsuite.benchmark.crud.interfaces import CrudBenchmarkContext
+from rhosocial.activerecord.testsuite.benchmark.mixin.interfaces import MixinBenchmarkContext
+from rhosocial.activerecord.testsuite.benchmark.query.interfaces import QueryBenchmarkContext
+from rhosocial.activerecord.testsuite.benchmark.registry import (
+ BenchmarkImplementation,
+ benchmarks,
+)
+from rhosocial.activerecord.testsuite.benchmark.transaction.interfaces import (
+ TransactionBenchmarkContext,
+)
+
+from support.postgres import SCENARIOS, scenario
+
+BACKEND_NAMESPACE = "rhosocial.activerecord.backend.impl.postgres"
+BACKEND_NAME = "postgres"
+
+
+# --------------------------------------------------------------------------- #
+# Minimal benchmark-only models. Each run uses a fresh database, so these are
+# declared locally instead of reusing feature fixtures. DDL is derived from
+# the model via the expression system (no hand-built SQL).
+# --------------------------------------------------------------------------- #
+class _BenchUserBase:
+ @classmethod
+ def table_name(cls):
+ return "benchmark_users"
+
+ c: ClassVar[FieldProxy] = FieldProxy()
+ id: Optional[int] = None
+ username: str
+ email: EmailStr
+ age: Optional[int] = Field(..., ge=0, le=120)
+ balance: float = 0.0
+ notes: Optional[str] = None
+ is_active: bool = True
+
+
+class BenchUser(IntegerPKMixin, DefaultTimestampMixin, _BenchUserBase, ActiveRecord):
+ pass
+
+
+class AsyncBenchUser(IntegerPKMixin, DefaultTimestampMixin, _BenchUserBase, AsyncActiveRecord):
+ pass
+
+
+def _config_for_scenario(scenario_name: str, tag: str):
+ """A fresh, scenario-derived config; each feature run gets its own database."""
+ sc = scenario(scenario_name)
+ # PostgreSQL is a server backend: each run needs its own logical database.
+ # Keep the name short enough to stay under the 63-byte identifier limit.
+ unique = f"bench_{tag}_{uuid.uuid4().hex}"
+ sc.reset_database(unique)
+ cfg = sc.make_config(unique)
+ return sc, cfg
+
+
+async def _seed_async(model, payloads):
+ ids = []
+ for payload in payloads:
+ obj = model(**payload)
+ await obj.save()
+ ids.append(obj.id)
+ return ids
+
+
+class CrudBenchmarkImpl(BenchmarkImplementation):
+ def __init__(self, tag="crud"):
+ self.tag = tag
+ self._backends = []
+
+ def scenarios(self):
+ return list(SCENARIOS)
+
+ def sync_setup(self, scenario_name, size):
+ sc, cfg = _config_for_scenario(scenario_name, self.tag)
+ BenchUser.configure(cfg, sc.backend_class)
+ backend = BenchUser.backend()
+ backend.execute(*BenchUser.create_table_statement(backend=backend).to_sql(), options=DDL)
+ self._backends.append(backend)
+ payloads = make_user_payloads(payload_count_for_size(size))
+ ids = []
+ for payload in payloads:
+ obj = BenchUser(**payload)
+ obj.save()
+ ids.append(obj.id)
+ return CrudBenchmarkContext(
+ scenario_name, size, BenchUser, payloads, ids, BACKEND_NAMESPACE, BACKEND_NAME
+ )
+
+ def sync_teardown(self, scenario_name, context):
+ for backend in self._backends:
+ backend.disconnect()
+ self._backends.clear()
+
+ async def async_setup(self, scenario_name, size, strategy="context"):
+ sc, cfg = _config_for_scenario(scenario_name, self.tag)
+ await AsyncBenchUser.configure(cfg, sc.async_backend_class)
+ backend = AsyncBenchUser.backend()
+ await backend.execute(
+ *AsyncBenchUser.create_table_statement(backend=backend).to_sql(), options=DDL
+ )
+ self._backends.append(backend)
+ payloads = make_user_payloads(payload_count_for_size(size))
+ ids = await _seed_async(AsyncBenchUser, payloads)
+ return CrudBenchmarkContext(
+ scenario_name, size, AsyncBenchUser, payloads, ids, BACKEND_NAMESPACE, BACKEND_NAME
+ )
+
+ async def async_teardown(self, scenario_name, context):
+ for backend in self._backends:
+ await backend.disconnect()
+ self._backends.clear()
+
+
+class QueryBenchmarkImpl(CrudBenchmarkImpl):
+ """Query benchmark shares the CRUD context shape."""
+
+ def sync_setup(self, scenario_name, size):
+ ctx = super().sync_setup(scenario_name, size)
+ return QueryBenchmarkContext(
+ ctx.scenario,
+ ctx.size,
+ ctx.model_class,
+ ctx.payloads,
+ ctx.record_ids,
+ ctx.backend_namespace,
+ ctx.backend_name,
+ )
+
+ async def async_setup(self, scenario_name, size, strategy="context"):
+ ctx = await super().async_setup(scenario_name, size, strategy)
+ return QueryBenchmarkContext(
+ ctx.scenario,
+ ctx.size,
+ ctx.model_class,
+ ctx.payloads,
+ ctx.record_ids,
+ ctx.backend_namespace,
+ ctx.backend_name,
+ )
+
+
+class TransactionBenchmarkImpl(CrudBenchmarkImpl):
+ def sync_setup(self, scenario_name, size):
+ ctx = super().sync_setup(scenario_name, size)
+ return TransactionBenchmarkContext(
+ ctx.scenario,
+ ctx.size,
+ ctx.model_class,
+ ctx.payloads,
+ ctx.record_ids,
+ ctx.backend_namespace,
+ ctx.backend_name,
+ )
+
+ async def async_setup(self, scenario_name, size, strategy="context"):
+ ctx = await super().async_setup(scenario_name, size, strategy)
+ return TransactionBenchmarkContext(
+ ctx.scenario,
+ ctx.size,
+ ctx.model_class,
+ ctx.payloads,
+ ctx.record_ids,
+ ctx.backend_namespace,
+ ctx.backend_name,
+ )
+
+
+class MixinBenchmarkImpl(CrudBenchmarkImpl):
+ def sync_setup(self, scenario_name, size):
+ ctx = super().sync_setup(scenario_name, size)
+ return MixinBenchmarkContext(
+ ctx.scenario,
+ ctx.size,
+ ctx.model_class,
+ ctx.payloads,
+ ctx.record_ids,
+ ctx.backend_namespace,
+ ctx.backend_name,
+ )
+
+ async def async_setup(self, scenario_name, size, strategy="context"):
+ ctx = await super().async_setup(scenario_name, size, strategy)
+ return MixinBenchmarkContext(
+ ctx.scenario,
+ ctx.size,
+ ctx.model_class,
+ ctx.payloads,
+ ctx.record_ids,
+ ctx.backend_namespace,
+ ctx.backend_name,
+ )
+
+
+# DDL options used by the derived statements.
+DDL = ExecutionOptions(stmt_type=StatementType.DDL)
+
+
+# --------------------------------------------------------------------------- #
+# Register. Imported as a pytest plugin (``-p tests.benchmark.providers``) so
+# registration happens before the shared contracts are collected.
+# --------------------------------------------------------------------------- #
+benchmarks.register("crud", CrudBenchmarkImpl("crud"))
+benchmarks.register("query", QueryBenchmarkImpl("query"))
+benchmarks.register("transaction", TransactionBenchmarkImpl("transaction"))
+benchmarks.register("mixin", MixinBenchmarkImpl("mixin"))
diff --git a/tests/benchmark/relation/conftest.py b/tests/benchmark/relation/conftest.py
index cce2ecbd..bac5082f 100644
--- a/tests/benchmark/relation/conftest.py
+++ b/tests/benchmark/relation/conftest.py
@@ -6,11 +6,17 @@
Redis benchmark support is not introduced in this release. The related
source snippets are kept as comments for follow-up external cache design.
"""
-
-from rhosocial.activerecord.testsuite.feature.relation.conftest import ( # noqa: F401
- user_post_comment_classes,
+from rhosocial.activerecord.testsuite.pytest_plugin import Declaration
+
+from rhosocial.activerecord.backend.options import ExecutionOptions
+from rhosocial.activerecord.backend.schema import StatementType
+from rhosocial.activerecord.testsuite.feature.query.relation.fixtures.definitions import (
+ CommentDefinition,
+ PostDefinition,
+ UserDefinition,
)
+
from dataclasses import dataclass
from typing import Any
@@ -22,6 +28,18 @@
# Not introduced in this release; keep snippets for follow-up external cache design.
# from rhosocial.activerecord.relation.cache_backends import CacheSerializer, RedisCache
+from rhosocial.activerecord.testsuite.feature.query.relation.conftest import ( # noqa: F401
+ user_post_comment_classes,
+)
+
+
+
+
+
+
+
+
+
pytestmark = [
pytest.mark.benchmark,
pytest.mark.benchmark_relation,
@@ -45,7 +63,18 @@ class RelationBenchmarkContext:
# Redis benchmark is not introduced in this release. Keep the fixture shape as
# comments for follow-up external cache design instead of deleting the source.
# ---------------------------------------------------------------------------
-# @pytest.fixture(scope="session")
+#
+
+# This directory owns a database shared by all its tests within a scenario;
+# pin them to one worker so setup/teardown never races on the same database.
+DECLARATION = Declaration(
+ # This scope opens a database; the plugin enforces this declaration.
+ uses_database=True,
+ parallel=True,
+ purpose="Directory-owned PostgreSQL database shared by this test group.",
+)
+
+@pytest.fixture(scope="session")
# def _redis_client():
# redis = pytest.importorskip("redis")
# try:
@@ -156,3 +185,40 @@ def relation_benchmark_env(cache_scenario, _raw_models):
)
finally:
InstanceCache.set_backend(original_backend)
+
+DDL = ExecutionOptions(stmt_type=StatementType.DDL)
+DEFINITIONS = (UserDefinition, PostDefinition, CommentDefinition)
+
+
+@pytest.fixture(scope="session")
+def database_config(backend_scenario):
+ """The scenario, its connection configuration, and the database name."""
+ name = "test_benchmark_relation"
+ return backend_scenario, backend_scenario.make_config(name), name
+
+
+@pytest.fixture(scope="session")
+def database(database_config):
+ """The benchmark directory's database, prepared once."""
+ scenario, config, name = database_config
+ scenario.reset_database(name)
+ backend = scenario.backend_class(connection_config=config)
+ backend.connect()
+ backend.introspect_and_adapt()
+ yield backend
+ backend.disconnect()
+
+
+@pytest.fixture(scope="module", autouse=True)
+def schema(database):
+ """Create the relation tables once per module.
+
+ Benchmarks measure query cost, not per-test isolation, so the exception to
+ the per-test drop+create rule applies here.
+ """
+ fixtures = [definition(database.dialect) for definition in DEFINITIONS]
+ for fixture in fixtures:
+ database.execute(*fixture.create_table.to_sql(), options=DDL)
+ yield
+ for fixture in reversed(fixtures):
+ database.execute(*fixture.drop_table.to_sql(), options=DDL)
diff --git a/tests/conftest.py b/tests/conftest.py
index cfd3b1c8..d73453a8 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,18 +1,21 @@
# tests/conftest.py
-"""
-This is the root pytest configuration file for the rhosocial-activerecord-postgres package's test suite.
+"""Root configuration for the PostgreSQL backend's test tree.
-Its primary responsibility is to configure the environment so that the external
-`rhosocial-activerecord-testsuite` can find and use the backend-specific
-implementations (Providers) defined within this project.
+The backend knows its own classes and how a scenario maps to a connection, so
+no declaration table is needed here: the scenario is exposed as a parameterized
+pytest fixture that the testsuite environment consumes.
"""
+
import asyncio
-import os
import selectors
import sys
import pytest
+import support.postgres
+
+_SCENARIOS = [support.postgres.scenario(name) for name in support.postgres.SCENARIOS]
+
if sys.platform == "win32":
@@ -34,176 +37,10 @@ def pytest_asyncio_loop_factories(config, item):
said. Elsewhere the default loop is already selector-based, and the
async tests' node ids stay exactly as they were.
"""
- return {
- "selector": lambda: asyncio.SelectorEventLoop(selectors.SelectSelector())
- }
-
-
-# Set the environment variable that the testsuite uses to locate the provider registry.
-# The testsuite is a generic package and doesn't know the specific location of the
-# provider implementations for this backend (postgres). This environment variable
-# acts as a bridge, pointing the testsuite to the correct import path.
-#
-# `setdefault` is used to ensure that this value is set only if it hasn't been
-# set already, allowing for overrides in different environments if needed.
-os.environ.setdefault(
- 'TESTSUITE_PROVIDER_REGISTRY',
- 'providers.registry:provider_registry'
-)
-
-# Early-parse --scenarios from sys.argv and set POSTGRES_ACTIVE_SCENARIOS env var.
-# This must happen before providers.scenarios is imported (it filters its
-# SCENARIO_MAP at import time).
-_argv_scenarios = None
-for _i, _arg in enumerate(sys.argv):
- if _arg.startswith('--scenarios='):
- _argv_scenarios = _arg.split('=', 1)[1]
- elif _arg == '--scenarios' and _i + 1 < len(sys.argv):
- _argv_scenarios = sys.argv[_i + 1]
-
-if _argv_scenarios:
- os.environ['POSTGRES_ACTIVE_SCENARIOS'] = _argv_scenarios
-
-# =============================================================================
-# Scenario Parallel Scheduling Plugin
-#
-# Usage:
-# pytest --scenario-parallel -n --dist=loadgroup tests/
-#
-# Design: All tests for the same scenario are pinned to the same xdist worker
-# (via nodeid @suffix), while tests for different scenarios run in
-# parallel. Behavior is unchanged without --scenario-parallel.
-# =============================================================================
-
-
-def _get_scenario_names():
- """Lazy import to avoid side effects during conftest loading."""
- try:
- from providers.scenarios import SCENARIO_MAP
- return set(SCENARIO_MAP.keys()), list(SCENARIO_MAP.keys())
- except Exception:
- return set(), []
-
-
-def _extract_scenario_from_item(item, scenario_name_set):
- """Extract scenario name from item's callspec.
-
- Returns:
- str: scenario name when exactly one scenario param is found
- None: no scenario params (not a scenario-parametrized test)
- list: multiple distinct scenario names (cross-scenario test)
- """
- callspec = getattr(item, 'callspec', None)
- if callspec is None:
- return None
- scenario_values = [
- v for v in callspec.params.values()
- if isinstance(v, str) and v in scenario_name_set
- ]
- if len(scenario_values) == 1:
- return scenario_values[0]
- if len(scenario_values) >= 2:
- return scenario_values # cross-scenario: caller checks isinstance(result, list)
- return None
-
-
-def _add_xdist_group_marker(item, group_name):
- """Append @group_name suffix to item._nodeid for loadgroup scheduling."""
- suffix = f"@{group_name}"
- if suffix not in item.nodeid:
- item._nodeid = item.nodeid + suffix
-
-
-def pytest_addoption(parser):
- parser.addoption(
- '--scenario-parallel',
- action='store_true',
- default=False,
- help='Scenario parallel mode: distribute scenarios across workers, keep each scenario on one worker.',
- )
- # The generic --scenarios option is registered by the testsuite conftest
- # (loaded via ``addopts``); register it here only when it is not already
- # present so the two conftests can coexist.
- try:
- parser.addoption(
- '--scenarios',
- default=None,
- help='Comma-separated list of scenario names to run (e.g., --scenarios=postgres_16,postgres_17). '
- 'Compatible with pytest -k "" as a native alternative.',
- )
- except ValueError:
- pass
-
-
-def pytest_configure(config):
- config.addinivalue_line(
- "markers",
- "xdist_group(name): specify the xdist group for a test (provided by pytest-xdist).",
- )
-
- # Propagate --scenarios to environment variable so that all conftest.py
- # instances (which load SCENARIO_MAP independently) can filter consistently.
- scenarios_opt = config.getoption('--scenarios', default=None)
- if scenarios_opt:
- os.environ['POSTGRES_ACTIVE_SCENARIOS'] = scenarios_opt
-
-
-def pytest_collection_modifyitems(config, items):
- if not config.getoption('--scenario-parallel', default=False):
- return
-
- scenario_name_set, scenario_name_list = _get_scenario_names()
- if not scenario_name_set:
- return
-
- scenario_items = []
- cross_scenario_items = []
- normal_items = []
-
- for item in items:
- result = _extract_scenario_from_item(item, scenario_name_set)
- if isinstance(result, list):
- item.add_marker(
- pytest.mark.skip(
- reason="Cross-scenario test skipped in --scenario-parallel mode. "
- "Run without --scenario-parallel for serial execution."
- )
- )
- cross_scenario_items.append(item)
- elif isinstance(result, str):
- _add_xdist_group_marker(item, result)
- scenario_items.append(item)
- else:
- normal_items.append(item)
-
- def sort_key(item):
- result = _extract_scenario_from_item(item, scenario_name_set)
- if not isinstance(result, str):
- return ('~', 0)
- try:
- scenario_idx = scenario_name_list.index(result)
- except ValueError:
- scenario_idx = 0
- base = item.nodeid.split('[')[0] if '[' in item.nodeid else item.nodeid
- return (base, scenario_idx)
-
- first_scenario = scenario_name_list[0]
- for item in normal_items:
- _add_xdist_group_marker(item, first_scenario)
- scenario_items.extend(normal_items)
- normal_items = []
-
- scenario_items.sort(key=sort_key)
- items[:] = scenario_items + normal_items + cross_scenario_items
+ return {"selector": lambda: asyncio.SelectorEventLoop(selectors.SelectSelector())}
- groups: dict = {}
- for item in scenario_items:
- sn = _extract_scenario_from_item(item, scenario_name_set)
- if isinstance(sn, str):
- base = item.nodeid.split('[')[0] if '[' in item.nodeid else item.nodeid
- groups.setdefault(base, set()).add(sn)
- print(f"\n[ScenarioParallel] {len(items)} items: {len(scenario_items)} scenario-param + "
- f"{len(normal_items)} normal + {len(cross_scenario_items)} cross-scenario (skipped)")
- print(f"[ScenarioParallel] {len(groups)} test methods, {len(scenario_name_list)} scenarios in parallel")
- print(f"[ScenarioParallel] Suggested: --dist=loadgroup -n {len(scenario_name_list)}")
+@pytest.fixture(scope="session", params=_SCENARIOS, ids=lambda scenario: scenario.name)
+def backend_scenario(request):
+ """Return the scenario the tests run against; its id is the scenario name."""
+ return request.param
diff --git a/tests/providers/basic.py b/tests/providers/basic.py
deleted file mode 100644
index 7547b1f4..00000000
--- a/tests/providers/basic.py
+++ /dev/null
@@ -1,514 +0,0 @@
-"""
-This file provides the concrete implementation of the `IBasicProvider` interface
-that is defined in the `rhosocial-activerecord-testsuite` package.
-
-Its main responsibilities are:
-1. Reporting which test scenarios (database configurations) are available.
-2. Setting up the database environment for a given test. This includes:
- - Getting the correct database configuration for the scenario.
- - Configuring the ActiveRecord model with a database connection.
- - Dropping any old tables and creating the necessary table schema.
-3. Cleaning up any resources after a test runs.
-"""
-import os
-import sys
-import logging
-from typing import Type, List, Tuple, Optional, Set # noqa: F401
-
-logger = logging.getLogger(__name__)
-
-from rhosocial.activerecord.model import ActiveRecord # noqa: E402
-from rhosocial.activerecord.backend.type_adapter import BaseSQLTypeAdapter # noqa: E402
-from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType # noqa: E402
-from rhosocial.activerecord.testsuite.feature.basic.interfaces import IBasicSyncProvider, IBasicAsyncProvider # noqa: E402
-from rhosocial.activerecord.testsuite.core.protocols import WorkerTestProtocol # noqa: E402
-
-# Import the fixture selector utility
-from rhosocial.activerecord.testsuite.utils import select_fixture # noqa: E402
-
-# Expression-based DDL fixtures
-from providers.fixtures._common import drop_table # noqa: E402
-from providers.fixtures.basic import TABLE_EXPRESSIONS as BASIC_TABLE_EXPRESSIONS # noqa: E402
-
-# Import base version models (Python 3.8+)
-from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( # noqa: E402
- User as UserBase, TypeCase as TypeCaseBase, ValidatedFieldUser as ValidatedFieldUserBase,
- TypeTestModel as TypeTestModelBase, ValidatedUser as ValidatedUserBase,
- TypeAdapterTest as TypeAdapterTestBase, YesOrNoBooleanAdapter,
- PydanticValidatedModel as PydanticValidatedModelBase,
- MappedUser as MappedUserBase, MappedPost as MappedPostBase, MappedComment as MappedCommentBase,
- ColumnMappingModel as ColumnMappingModelBase, MixedAnnotationModel as MixedAnnotationModelBase
-)
-from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( # noqa: E402
- BulkUser as BulkUserBase, AsyncBulkUser as AsyncBulkUserBase
-)
-# Import async base models
-from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( # noqa: E402
- AsyncUser as AsyncUserBase, AsyncTypeCase as AsyncTypeCaseBase,
- AsyncValidatedUser as AsyncValidatedUserBase, AsyncValidatedFieldUser as AsyncValidatedFieldUserBase,
- AsyncTypeTestModel as AsyncTypeTestModelBase, AsyncTypeAdapterTest as AsyncTypeAdapterTestBase,
- AsyncPydanticValidatedModel as AsyncPydanticValidatedModelBase,
- AsyncMappedUser as AsyncMappedUserBase, AsyncMappedPost as AsyncMappedPostBase,
- AsyncMappedComment as AsyncMappedCommentBase,
- AsyncColumnMappingModel as AsyncColumnMappingModelBase, AsyncMixedAnnotationModel as AsyncMixedAnnotationModelBase
-)
-
-# Conditionally import Python 3.10+ models
-User310 = TypeCase310 = ValidatedFieldUser310 = TypeTestModel310 = ValidatedUser310 = None
-TypeAdapterTest310 = PydanticValidatedModel310 = MappedUser310 = MappedPost310 = MappedComment310 = None
-ColumnMappingModel310 = MixedAnnotationModel310 = None
-AsyncUser310 = AsyncTypeCase310 = AsyncValidatedFieldUser310 = AsyncTypeTestModel310 = None
-AsyncValidatedUser310 = AsyncTypeAdapterTest310 = AsyncPydanticValidatedModel310 = AsyncMappedUser310 = AsyncMappedPost310 = None # noqa: E501
-AsyncMappedComment310 = AsyncColumnMappingModel310 = AsyncMixedAnnotationModel310 = None
-
-if sys.version_info >= (3, 10):
- try:
- from rhosocial.activerecord.testsuite.feature.basic.fixtures.models_py310 import (
- User as User310, TypeCase as TypeCase310, ValidatedFieldUser as ValidatedFieldUser310,
- TypeTestModel as TypeTestModel310, ValidatedUser as ValidatedUser310,
- TypeAdapterTest as TypeAdapterTest310, PydanticValidatedModel as PydanticValidatedModel310,
- MappedUser as MappedUser310, MappedPost as MappedPost310, MappedComment as MappedComment310,
- ColumnMappingModel as ColumnMappingModel310, MixedAnnotationModel as MixedAnnotationModel310
- )
- from rhosocial.activerecord.testsuite.feature.basic.fixtures.models_py310 import (
- AsyncUser as AsyncUser310, AsyncTypeCase as AsyncTypeCase310,
- AsyncValidatedUser as AsyncValidatedUser310, AsyncValidatedFieldUser as AsyncValidatedFieldUser310,
- AsyncTypeTestModel as AsyncTypeTestModel310, AsyncTypeAdapterTest as AsyncTypeAdapterTest310,
- AsyncPydanticValidatedModel as AsyncPydanticValidatedModel310,
- AsyncMappedUser as AsyncMappedUser310, AsyncMappedPost as AsyncMappedPost310,
- AsyncMappedComment as AsyncMappedComment310,
- AsyncColumnMappingModel as AsyncColumnMappingModel310, AsyncMixedAnnotationModel as AsyncMixedAnnotationModel310 # noqa: E501
- )
- except ImportError as e:
- logger.warning(f"Failed to import Python 3.10+ fixtures: {e}")
-
-# Conditionally import Python 3.11+ models
-User311 = TypeCase311 = ValidatedFieldUser311 = TypeTestModel311 = ValidatedUser311 = None
-TypeAdapterTest311 = PydanticValidatedModel311 = MappedUser311 = MappedPost311 = MappedComment311 = None
-ColumnMappingModel311 = MixedAnnotationModel311 = None
-AsyncUser311 = AsyncTypeCase311 = AsyncValidatedFieldUser311 = AsyncTypeTestModel311 = None
-AsyncValidatedUser311 = AsyncTypeAdapterTest311 = AsyncPydanticValidatedModel311 = AsyncMappedUser311 = AsyncMappedPost311 = None # noqa: E501
-AsyncMappedComment311 = AsyncColumnMappingModel311 = AsyncMixedAnnotationModel311 = None
-
-if sys.version_info >= (3, 11):
- try:
- from rhosocial.activerecord.testsuite.feature.basic.fixtures.models_py311 import (
- User as User311, TypeCase as TypeCase311, ValidatedFieldUser as ValidatedFieldUser311,
- TypeTestModel as TypeTestModel311, ValidatedUser as ValidatedUser311,
- TypeAdapterTest as TypeAdapterTest311, PydanticValidatedModel as PydanticValidatedModel311,
- MappedUser as MappedUser311, MappedPost as MappedPost311, MappedComment as MappedComment311,
- ColumnMappingModel as ColumnMappingModel311, MixedAnnotationModel as MixedAnnotationModel311
- )
- from rhosocial.activerecord.testsuite.feature.basic.fixtures.models_py311 import (
- AsyncUser as AsyncUser311, AsyncTypeCase as AsyncTypeCase311,
- AsyncValidatedUser as AsyncValidatedUser311, AsyncValidatedFieldUser as AsyncValidatedFieldUser311,
- AsyncTypeTestModel as AsyncTypeTestModel311, AsyncTypeAdapterTest as AsyncTypeAdapterTest311,
- AsyncPydanticValidatedModel as AsyncPydanticValidatedModel311,
- AsyncMappedUser as AsyncMappedUser311, AsyncMappedPost as AsyncMappedPost311,
- AsyncMappedComment as AsyncMappedComment311,
- AsyncColumnMappingModel as AsyncColumnMappingModel311, AsyncMixedAnnotationModel as AsyncMixedAnnotationModel311 # noqa: E501
- )
- except ImportError as e:
- logger.warning(f"Failed to import Python 3.11+ fixtures: {e}")
-
-# Conditionally import Python 3.12+ models
-User312 = TypeCase312 = ValidatedFieldUser312 = TypeTestModel312 = ValidatedUser312 = None
-TypeAdapterTest312 = PydanticValidatedModel312 = MappedUser312 = MappedPost312 = MappedComment312 = None
-ColumnMappingModel312 = MixedAnnotationModel312 = None
-AsyncUser312 = AsyncTypeCase312 = AsyncValidatedFieldUser312 = AsyncTypeTestModel312 = None
-AsyncValidatedUser312 = AsyncTypeAdapterTest312 = AsyncPydanticValidatedModel312 = AsyncMappedUser312 = AsyncMappedPost312 = None # noqa: E501
-AsyncMappedComment312 = AsyncColumnMappingModel312 = AsyncMixedAnnotationModel312 = None
-
-if sys.version_info >= (3, 12):
- try:
- from rhosocial.activerecord.testsuite.feature.basic.fixtures.models_py312 import (
- User as User312, TypeCase as TypeCase312, ValidatedFieldUser as ValidatedFieldUser312,
- TypeTestModel as TypeTestModel312, ValidatedUser as ValidatedUser312,
- TypeAdapterTest as TypeAdapterTest312, PydanticValidatedModel as PydanticValidatedModel312,
- MappedUser as MappedUser312, MappedPost as MappedPost312, MappedComment as MappedComment312,
- ColumnMappingModel as ColumnMappingModel312, MixedAnnotationModel as MixedAnnotationModel312
- )
- from rhosocial.activerecord.testsuite.feature.basic.fixtures.models_py312 import (
- AsyncUser as AsyncUser312, AsyncTypeCase as AsyncTypeCase312,
- AsyncValidatedUser as AsyncValidatedUser312, AsyncValidatedFieldUser as AsyncValidatedFieldUser312,
- AsyncTypeTestModel as AsyncTypeTestModel312, AsyncTypeAdapterTest as AsyncTypeAdapterTest312,
- AsyncPydanticValidatedModel as AsyncPydanticValidatedModel312,
- AsyncMappedUser as AsyncMappedUser312, AsyncMappedPost as AsyncMappedPost312,
- AsyncMappedComment as AsyncMappedComment312,
- AsyncColumnMappingModel as AsyncColumnMappingModel312, AsyncMixedAnnotationModel as AsyncMixedAnnotationModel312 # noqa: E501
- )
- except ImportError as e:
- logger.warning(f"Failed to import Python 3.12+ fixtures: {e}")
-
-
-# Select appropriate fixture classes based on Python version
-def _select_model_class(base_cls, py312_cls, py311_cls, py310_cls, model_name: str) -> Type:
- """Select the most appropriate model class for the current Python version."""
- candidates = [c for c in [py312_cls, py311_cls, py310_cls, base_cls] if c is not None]
- selected = select_fixture(*candidates)
- logger.info(f"Selected {model_name}: {selected.__name__} from {selected.__module__}")
- return selected
-
-
-# Select sync models
-User = _select_model_class(UserBase, User312, User311, User310, "User")
-TypeCase = _select_model_class(TypeCaseBase, TypeCase312, TypeCase311, TypeCase310, "TypeCase")
-ValidatedFieldUser = _select_model_class(ValidatedFieldUserBase, ValidatedFieldUser312, ValidatedFieldUser311, ValidatedFieldUser310, "ValidatedFieldUser") # noqa: E501
-TypeTestModel = _select_model_class(TypeTestModelBase, TypeTestModel312, TypeTestModel311, TypeTestModel310, "TypeTestModel") # noqa: E501
-ValidatedUser = _select_model_class(ValidatedUserBase, ValidatedUser312, ValidatedUser311, ValidatedUser310, "ValidatedUser") # noqa: E501
-TypeAdapterTest = _select_model_class(TypeAdapterTestBase, TypeAdapterTest312, TypeAdapterTest311, TypeAdapterTest310, "TypeAdapterTest") # noqa: E501
-PydanticValidatedModel = _select_model_class(PydanticValidatedModelBase, PydanticValidatedModel312, PydanticValidatedModel311, PydanticValidatedModel310, "PydanticValidatedModel") # noqa: E501
-MappedUser = _select_model_class(MappedUserBase, MappedUser312, MappedUser311, MappedUser310, "MappedUser")
-MappedPost = _select_model_class(MappedPostBase, MappedPost312, MappedPost311, MappedPost310, "MappedPost")
-MappedComment = _select_model_class(MappedCommentBase, MappedComment312, MappedComment311, MappedComment310, "MappedComment") # noqa: E501
-ColumnMappingModel = _select_model_class(ColumnMappingModelBase, ColumnMappingModel312, ColumnMappingModel311, ColumnMappingModel310, "ColumnMappingModel") # noqa: E501
-MixedAnnotationModel = _select_model_class(MixedAnnotationModelBase, MixedAnnotationModel312, MixedAnnotationModel311, MixedAnnotationModel310, "MixedAnnotationModel") # noqa: E501
-
-# Select async models
-AsyncUser = _select_model_class(AsyncUserBase, AsyncUser312, AsyncUser311, AsyncUser310, "AsyncUser")
-AsyncTypeCase = _select_model_class(AsyncTypeCaseBase, AsyncTypeCase312, AsyncTypeCase311, AsyncTypeCase310, "AsyncTypeCase") # noqa: E501
-AsyncValidatedFieldUser = _select_model_class(AsyncValidatedFieldUserBase, AsyncValidatedFieldUser312, AsyncValidatedFieldUser311, AsyncValidatedFieldUser310, "AsyncValidatedFieldUser") # noqa: E501
-AsyncTypeTestModel = _select_model_class(AsyncTypeTestModelBase, AsyncTypeTestModel312, AsyncTypeTestModel311, AsyncTypeTestModel310, "AsyncTypeTestModel") # noqa: E501
-AsyncValidatedUser = _select_model_class(AsyncValidatedUserBase, AsyncValidatedUser312, AsyncValidatedUser311, AsyncValidatedUser310, "AsyncValidatedUser") # noqa: E501
-AsyncTypeAdapterTest = _select_model_class(AsyncTypeAdapterTestBase, AsyncTypeAdapterTest312, AsyncTypeAdapterTest311, AsyncTypeAdapterTest310, "AsyncTypeAdapterTest") # noqa: E501
-AsyncPydanticValidatedModel = _select_model_class(AsyncPydanticValidatedModelBase, AsyncPydanticValidatedModel312, AsyncPydanticValidatedModel311, AsyncPydanticValidatedModel310, "AsyncPydanticValidatedModel") # noqa: E501
-AsyncMappedUser = _select_model_class(AsyncMappedUserBase, AsyncMappedUser312, AsyncMappedUser311, AsyncMappedUser310, "AsyncMappedUser") # noqa: E501
-AsyncMappedPost = _select_model_class(AsyncMappedPostBase, AsyncMappedPost312, AsyncMappedPost311, AsyncMappedPost310, "AsyncMappedPost") # noqa: E501
-AsyncMappedComment = _select_model_class(AsyncMappedCommentBase, AsyncMappedComment312, AsyncMappedComment311, AsyncMappedComment310, "AsyncMappedComment") # noqa: E501
-AsyncColumnMappingModel = _select_model_class(AsyncColumnMappingModelBase, AsyncColumnMappingModel312, AsyncColumnMappingModel311, AsyncColumnMappingModel310, "AsyncColumnMappingModel") # noqa: E501
-AsyncMixedAnnotationModel = _select_model_class(AsyncMixedAnnotationModelBase, AsyncMixedAnnotationModel312, AsyncMixedAnnotationModel311, AsyncMixedAnnotationModel310, "AsyncMixedAnnotationModel") # noqa: E501
-BulkUser = BulkUserBase
-AsyncBulkUser = AsyncBulkUserBase
-
-# ...and the scenarios are defined specifically for this backend.
-from .scenarios import get_enabled_scenarios, get_scenario # noqa: E402
-
-
-class BasicProviderBase:
- def __init__(self):
- self._scenario_db_files = {}
- self._created_tables: Set[str] = set()
-
- def get_test_scenarios(self) -> List[str]:
- return list(get_enabled_scenarios().keys())
-
- def get_yes_no_adapter(self) -> 'BaseSQLTypeAdapter':
- return YesOrNoBooleanAdapter()
-
- def get_dialect(self, scenario_name: str = "default"):
- """Return a bare, fully-constructed PostgreSQL dialect instance.
-
- Used by the ``feature/basic/ddl`` subtopic (expression/dialect
- contract). ``(16, 0, 0)`` advertises support for all three
- ``IF [NOT] EXISTS`` modifiers (available since PG 9.6).
- """
- from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect
-
- return PostgresDialect(version=(16, 0, 0))
-
- def _track_backend(self, backend_instance, collection) -> None:
- if backend_instance not in collection:
- collection.append(backend_instance)
-
- def _load_postgres_schema(self, filename: str) -> str:
- schema_dir = os.path.join(
- os.path.dirname(__file__), "..", "rhosocial", "activerecord_postgres_test", "feature", "basic", "schema"
- )
- schema_path = os.path.join(schema_dir, filename)
- with open(schema_path, 'r', encoding='utf-8') as f:
- return f.read()
-
-
-class BasicSyncProvider(BasicProviderBase, IBasicSyncProvider, WorkerTestProtocol):
-
- def __init__(self):
- super().__init__()
- self._active_backends = []
-
- def _setup_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]:
- backend_class, config = get_scenario(scenario_name)
- model_class.configure(config, backend_class)
- backend_instance = model_class.__backend__
- self._track_backend(backend_instance, self._active_backends)
- self._reset_table_sync(model_class, table_name)
- self._created_tables.add(table_name)
- return model_class
-
- def _reset_table_sync(self, model_class: Type[ActiveRecord], table_name: str) -> None:
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- try:
- sql, params = drop_table(model_class.__backend__.dialect, table_name).to_sql()
- model_class.__backend__.execute(sql, params, options=opts)
- except Exception as e:
- print(f"Could not drop table {table_name}: {e}")
- if fn := BASIC_TABLE_EXPRESSIONS.get(table_name):
- create_expr = fn(model_class.__backend__.dialect, table_name)
- sql, params = create_expr.to_sql()
- model_class.__backend__.execute(sql, params, options=opts)
-
- def _initialize_model_schema(self, model_class: Type[ActiveRecord], table_name: str) -> None:
- self._reset_table_sync(model_class, table_name)
-
- def _setup_multiple_models(self, model_classes: List[Tuple[Type[ActiveRecord], str]], scenario_name: str) -> Tuple[Type[ActiveRecord], ...]:
- if not model_classes:
- return tuple()
- first_model_class, first_table_name = model_classes[0]
- first_model = self._setup_model(first_model_class, scenario_name, first_table_name)
- shared_backend = first_model.__backend__
- result = [first_model]
- for model_class, table_name in model_classes[1:]:
- model_class.__connection_config__ = first_model.__connection_config__
- model_class.__backend_class__ = first_model.__backend_class__
- model_class.__backend__ = shared_backend
- self._track_backend(shared_backend, self._active_backends)
- self._initialize_model_schema(model_class, table_name)
- self._created_tables.add(table_name)
- result.append(model_class)
- return tuple(result)
-
- def setup_user_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(User, scenario_name, "users")
-
- def setup_type_case_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(TypeCase, scenario_name, "type_cases")
-
- def setup_type_test_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(TypeTestModel, scenario_name, "type_tests")
-
- def setup_validated_field_user_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(ValidatedFieldUser, scenario_name, "validated_field_users")
-
- def setup_validated_user_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(ValidatedUser, scenario_name, "validated_users")
-
- def setup_pydantic_validated_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(PydanticValidatedModel, scenario_name, "pydantic_validated_models")
-
- def setup_mapped_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- return self._setup_multiple_models([
- (MappedUser, "users"),
- (MappedPost, "posts"),
- (MappedComment, "comments")
- ], scenario_name)
-
- def setup_mixed_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]:
- from rhosocial.activerecord_postgres_test.feature.basic.fixtures.models import PostgresMixedAnnotationModel
- return self._setup_multiple_models([
- (ColumnMappingModel, "column_mapping_items"),
- (PostgresMixedAnnotationModel, "mixed_annotation_items")
- ], scenario_name)
-
- def setup_type_adapter_model_and_schema(self, scenario_name: str = None) -> Type[ActiveRecord]:
- if scenario_name is None:
- scenario_name = self.get_test_scenarios()[0] if self.get_test_scenarios() else "default"
- return self._setup_model(TypeAdapterTest, scenario_name, "type_adapter_tests")
-
- def setup_bulk_user_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(BulkUser, scenario_name, "bulk_users")
-
- def setup_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- def setup_order_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- def setup_mapped_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- def setup_product_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- def setup_product_form_a_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- def setup_product_with_proxy_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- def setup_product_with_column_and_adapter_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- def get_worker_connection_params(self, scenario_name: str, fixture_type: str = None) -> dict:
- from .scenarios import SCENARIO_MAP
- is_async = fixture_type and fixture_type.startswith('async_')
- backend_class_name = 'AsyncPostgresBackend' if is_async else 'PostgresBackend'
- table_name = 'users'
- if fixture_type:
- base_type = fixture_type.replace('async_', '')
- table_map = {
- 'user': 'users',
- 'type_case': 'type_cases',
- 'type_test': 'type_tests',
- 'validated_field_user': 'validated_field_users',
- 'validated_user': 'validated_users',
- 'pydantic_validated_model': 'pydantic_validated_models',
- 'type_adapter_test': 'type_adapter_tests',
- }
- table_name = table_map.get(base_type, 'users')
- if scenario_name not in SCENARIO_MAP:
- if SCENARIO_MAP:
- scenario_name = next(iter(SCENARIO_MAP))
- else:
- raise ValueError("No scenarios registered")
- config_dict = SCENARIO_MAP[scenario_name]
- from .pooling import resolve_database_name
-
- pooled_db = resolve_database_name(scenario_name)
- if pooled_db:
- config_dict = {**config_dict, "database": pooled_db}
- return {
- 'backend_module': 'rhosocial.activerecord.backend.impl.postgres.backend',
- 'backend_class_name': backend_class_name,
- 'config_class_module': 'rhosocial.activerecord.backend.impl.postgres.config',
- 'config_class_name': 'PostgresConnectionConfig',
- 'config_kwargs': config_dict,
- 'schema_sql': self._load_postgres_schema(f'{table_name}.sql'),
- }
-
- def get_worker_schema_sql(self, scenario_name: str, table_name: str) -> str:
- return self._load_postgres_schema(f'{table_name}.sql')
-
- def cleanup_after_test(self, scenario_name: str):
- for backend_instance in self._active_backends:
- try:
- for table_name in list(self._created_tables):
- try:
- backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE')
- except Exception:
- pass
- finally:
- try:
- backend_instance.disconnect()
- except Exception:
- pass
- self._active_backends.clear()
- self._created_tables.clear()
-
-
-class BasicAsyncProvider(BasicProviderBase, IBasicAsyncProvider):
-
- def __init__(self):
- super().__init__()
- self._active_async_backends = []
-
- async def get_dialect(self, scenario_name: str = "default"):
- """Async mirror of ``BasicProviderBase.get_dialect``."""
- return super().get_dialect(scenario_name)
-
- async def _setup_async_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]:
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
- _, config = get_scenario(scenario_name)
- await model_class.configure(config, AsyncPostgresBackend)
- backend_instance = model_class.__backend__
- self._track_backend(backend_instance, self._active_async_backends)
- await self._reset_table_async(model_class, table_name)
- self._created_tables.add(table_name)
- return model_class
-
- async def _reset_table_async(self, model_class: Type[ActiveRecord], table_name: str) -> None:
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- try:
- sql, params = drop_table(model_class.__backend__.dialect, table_name).to_sql()
- await model_class.__backend__.execute(sql, params, options=opts)
- except Exception as e:
- print(f"Could not drop table {table_name}: {e}")
- if fn := BASIC_TABLE_EXPRESSIONS.get(table_name):
- create_expr = fn(model_class.__backend__.dialect, table_name)
- sql, params = create_expr.to_sql()
- await model_class.__backend__.execute(sql, params, options=opts)
-
- async def _initialize_async_model_schema(self, model_class: Type[ActiveRecord], table_name: str) -> None:
- await self._reset_table_async(model_class, table_name)
-
- async def _setup_multiple_models_async(self, model_classes: List[Tuple[Type[ActiveRecord], str]], scenario_name: str) -> Tuple[Type[ActiveRecord], ...]:
- if not model_classes:
- return tuple()
- first_model_class, first_table_name = model_classes[0]
- first_model = await self._setup_async_model(first_model_class, scenario_name, first_table_name)
- shared_backend = first_model.__backend__
- result = [first_model]
- for model_class, table_name in model_classes[1:]:
- model_class.__connection_config__ = first_model.__connection_config__
- model_class.__backend_class__ = first_model.__backend_class__
- model_class.__backend__ = shared_backend
- self._track_backend(shared_backend, self._active_async_backends)
- await self._initialize_async_model_schema(model_class, table_name)
- self._created_tables.add(table_name)
- result.append(model_class)
- return tuple(result)
-
- async def setup_user_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncUser, scenario_name, "users")
-
- async def setup_type_case_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncTypeCase, scenario_name, "type_cases")
-
- async def setup_type_test_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncTypeTestModel, scenario_name, "type_tests")
-
- async def setup_validated_field_user_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncValidatedFieldUser, scenario_name, "validated_field_users")
-
- async def setup_validated_user_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncValidatedUser, scenario_name, "validated_users")
-
- async def setup_pydantic_validated_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncPydanticValidatedModel, scenario_name, "pydantic_validated_models")
-
- async def setup_mapped_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- return await self._setup_multiple_models_async([
- (AsyncMappedUser, "users"),
- (AsyncMappedPost, "posts"),
- (AsyncMappedComment, "comments")
- ], scenario_name)
-
- async def setup_mixed_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]:
- from rhosocial.activerecord_postgres_test.feature.basic.fixtures.models import AsyncPostgresMixedAnnotationModel
- return await self._setup_multiple_models_async([
- (AsyncColumnMappingModel, "column_mapping_items"),
- (AsyncPostgresMixedAnnotationModel, "mixed_annotation_items")
- ], scenario_name)
-
- async def setup_type_adapter_model_and_schema(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncTypeAdapterTest, scenario_name, "type_adapter_tests")
-
- async def setup_bulk_user_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncBulkUser, scenario_name, "bulk_users")
-
- async def setup_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- async def setup_order_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- async def setup_mapped_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- async def setup_product_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- async def setup_product_form_a_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- async def setup_product_with_proxy_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- async def setup_product_with_column_and_adapter_model(self, scenario_name: str) -> Type[ActiveRecord]:
- raise NotImplementedError
-
- async def cleanup_after_test(self, scenario_name: str):
- for backend_instance in self._active_async_backends:
- try:
- for table_name in list(self._created_tables):
- try:
- await backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE')
- except Exception:
- pass
- finally:
- try:
- await backend_instance.disconnect()
- except Exception:
- pass
- self._active_async_backends.clear()
- self._created_tables.clear()
diff --git a/tests/providers/basic_connection.py b/tests/providers/basic_connection.py
deleted file mode 100644
index c57443c5..00000000
--- a/tests/providers/basic_connection.py
+++ /dev/null
@@ -1,183 +0,0 @@
-# tests/providers/basic_connection.py
-"""
-Concrete implementation of IBasicConnectionProvider for PostgreSQL backend.
-
-This provider sets up connection pools and models for testing
-ActiveRecord context awareness.
-"""
-from typing import Type, Tuple, Optional, List
-
-from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord
-from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
-from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig # noqa: F401
-from rhosocial.activerecord.connection.pool import BackendPool, AsyncBackendPool, PoolConfig
-from rhosocial.activerecord.backend.options import ExecutionOptions
-from rhosocial.activerecord.backend.schema import StatementType
-
-from rhosocial.activerecord.testsuite.feature.basic.connection.interfaces import IBasicConnectionProvider
-from .scenarios import get_scenario, get_enabled_scenarios
-
-
-class SyncTestUser(ActiveRecord):
- """Sync test user model for connection pool tests."""
- @classmethod
- def table_name(cls):
- return "test_users"
-
- id: Optional[int] = None
- name: str
- email: str
-
-
-class AsyncTestUser(AsyncActiveRecord):
- """Async test user model for connection pool tests."""
- @classmethod
- def table_name(cls):
- return "test_users"
-
- id: Optional[int] = None
- name: str
- email: str
-
-
-class BasicConnectionProvider(IBasicConnectionProvider):
- """
- PostgreSQL backend implementation for basic connection pool context tests.
- """
-
- def __init__(self):
- self._active_backends: List = []
- self._active_async_backends: List = []
-
- def get_test_scenarios(self) -> list:
- """Returns available test scenarios."""
- return list(get_enabled_scenarios().keys())
-
- def _create_test_table(self, backend):
- """Create the test_users table."""
- try:
- backend.execute("DROP TABLE IF EXISTS test_users", options=ExecutionOptions(stmt_type=StatementType.DDL))
- except Exception:
- pass
-
- backend.execute("""
- CREATE TABLE test_users (
- id SERIAL PRIMARY KEY,
- name VARCHAR(255) NOT NULL,
- email VARCHAR(255) NOT NULL
- )
- """, options=ExecutionOptions(stmt_type=StatementType.DDL))
-
- async def _create_test_table_async(self, backend):
- """Create the test_users table asynchronously."""
- try:
- await backend.execute("DROP TABLE IF EXISTS test_users", options=ExecutionOptions(stmt_type=StatementType.DDL)) # noqa: E501
- except Exception:
- pass
-
- await backend.execute("""
- CREATE TABLE test_users (
- id SERIAL PRIMARY KEY,
- name VARCHAR(255) NOT NULL,
- email VARCHAR(255) NOT NULL
- )
- """, options=ExecutionOptions(stmt_type=StatementType.DDL))
-
- def setup_sync_pool_and_model(self, scenario_name: str) -> Tuple[BackendPool, Type[ActiveRecord]]:
- """Setup sync connection pool and model for context tests."""
- _, config = get_scenario(scenario_name)
-
- # Create connection pool
- pool_config = PoolConfig(
- min_size=1,
- max_size=5,
- backend_factory=lambda: PostgresBackend(connection_config=config)
- )
- pool = BackendPool.create(pool_config)
-
- # Create table
- with pool.connection() as backend:
- self._create_test_table(backend)
- self._active_backends.append(backend)
-
- # Configure model to use a separate backend (not pool backend)
- # This tests that model.backend() returns pool context backend
- SyncTestUser.configure(config, PostgresBackend)
- self._active_backends.append(SyncTestUser.__backend__)
-
- return pool, SyncTestUser
-
- async def setup_async_pool_and_model(self, scenario_name: str) -> Tuple[AsyncBackendPool, Type[AsyncActiveRecord]]:
- """Setup async connection pool and model for context tests."""
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
-
- _, config = get_scenario(scenario_name)
-
- # Create connection pool
- pool_config = PoolConfig(
- min_size=1,
- max_size=5,
- backend_factory=lambda: AsyncPostgresBackend(connection_config=config)
- )
-
- # Create pool
- pool = await AsyncBackendPool.create(pool_config)
-
- # Create table
- async with pool.connection() as backend:
- await self._create_test_table_async(backend)
- self._active_async_backends.append(backend)
-
- # Configure model
- await AsyncTestUser.configure(config, AsyncPostgresBackend)
- self._active_async_backends.append(AsyncTestUser.__backend__)
-
- return pool, AsyncTestUser
-
- def cleanup_sync(self, scenario_name: str, pool: BackendPool):
- """Cleanup after sync tests."""
- try:
- pool.close(timeout=1.0, force=True)
- except Exception:
- pass
-
- # Disconnect backends
- for backend in self._active_backends:
- try:
- backend.execute("DROP TABLE IF EXISTS test_users CASCADE")
- except Exception:
- pass
- try:
- backend.disconnect()
- except Exception:
- pass
- self._active_backends.clear()
-
- async def cleanup_async(self, scenario_name: str, pool: AsyncBackendPool):
- """Cleanup after async tests."""
- try:
- await pool.close(timeout=1.0, force=True)
- except Exception:
- pass
-
- # Disconnect backends
- for backend in self._active_async_backends:
- try:
- await backend.execute("DROP TABLE IF EXISTS test_users CASCADE")
- except Exception:
- pass
- try:
- await backend.disconnect()
- except Exception:
- pass
- self._active_async_backends.clear()
-
- def setup_sync_pool_for_crud(self, scenario_name: str) -> Tuple[BackendPool, Type[ActiveRecord]]:
- """Setup sync connection pool for CRUD tests."""
- return self.setup_sync_pool_and_model(scenario_name)
-
- async def setup_async_pool_for_crud(self, scenario_name: str) -> Tuple[AsyncBackendPool, Type[AsyncActiveRecord]]:
- """Setup async connection pool for CRUD tests."""
- return await self.setup_async_pool_and_model(scenario_name)
diff --git a/tests/providers/crud_benchmark.py b/tests/providers/crud_benchmark.py
deleted file mode 100644
index bfc77fdd..00000000
--- a/tests/providers/crud_benchmark.py
+++ /dev/null
@@ -1,189 +0,0 @@
-"""PostgreSQL provider for CRUD benchmark tests."""
-
-import sys
-from typing import Type
-
-from rhosocial.activerecord.backend.options import ExecutionOptions
-from rhosocial.activerecord.backend.schema import StatementType
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.data import (
- make_user_payloads,
- payload_count_for_size,
-)
-from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models import (
- AsyncBenchmarkUser as AsyncBenchmarkUserBase,
- BenchmarkUser as BenchmarkUserBase,
-)
-from rhosocial.activerecord.testsuite.benchmark.crud.interfaces import CrudBenchmarkContext
-from rhosocial.activerecord.testsuite.utils import select_fixture
-
-from .scenarios import get_enabled_scenarios, get_scenario
-
-BenchmarkUser310 = AsyncBenchmarkUser310 = None
-BenchmarkUser311 = AsyncBenchmarkUser311 = None
-BenchmarkUser312 = AsyncBenchmarkUser312 = None
-
-if sys.version_info >= (3, 10):
- from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models_py310 import (
- AsyncBenchmarkUser as AsyncBenchmarkUser310,
- BenchmarkUser as BenchmarkUser310,
- )
-
-if sys.version_info >= (3, 11):
- from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models_py311 import (
- AsyncBenchmarkUser as AsyncBenchmarkUser311,
- BenchmarkUser as BenchmarkUser311,
- )
-
-if sys.version_info >= (3, 12):
- from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models_py312 import (
- AsyncBenchmarkUser as AsyncBenchmarkUser312,
- BenchmarkUser as BenchmarkUser312,
- )
-
-
-BenchmarkUser = select_fixture(
- *[
- candidate
- for candidate in (BenchmarkUser312, BenchmarkUser311, BenchmarkUser310, BenchmarkUserBase)
- if candidate
- ]
-)
-AsyncBenchmarkUser = select_fixture(
- *[
- candidate
- for candidate in (
- AsyncBenchmarkUser312,
- AsyncBenchmarkUser311,
- AsyncBenchmarkUser310,
- AsyncBenchmarkUserBase,
- )
- if candidate
- ]
-)
-
-
-class CrudBenchmarkProvider:
- def __init__(self):
- self._active_backends = []
- self._active_async_backends = []
-
- def get_benchmark_scenarios(self):
- return list(get_enabled_scenarios().keys())
-
- def setup_benchmark_sync(self, scenario: str, size: str):
- model_class = self._setup_model(BenchmarkUser, scenario)
- payloads = make_user_payloads(payload_count_for_size(size))
- record_ids = []
- for payload in payloads:
- instance = model_class(**payload)
- rows = instance.save()
- if rows != 1 or instance.id is None:
- raise AssertionError("failed to seed sync CRUD benchmark row")
- record_ids.append(instance.id)
- return CrudBenchmarkContext(
- scenario=scenario,
- size=size,
- model_class=model_class,
- payloads=payloads,
- record_ids=record_ids,
- backend_namespace="rhosocial.activerecord.backend.impl.postgres",
- backend_name="postgres",
- )
-
- def teardown_benchmark_sync(self, scenario: str, context: CrudBenchmarkContext) -> None:
- self._cleanup_sync()
-
- async def setup_benchmark_async(self, scenario: str, size: str):
- model_class = await self._setup_async_model(AsyncBenchmarkUser, scenario)
- payloads = make_user_payloads(payload_count_for_size(size))
- record_ids = []
- for payload in payloads:
- instance = model_class(**payload)
- rows = await instance.save()
- if rows != 1 or instance.id is None:
- raise AssertionError("failed to seed async CRUD benchmark row")
- record_ids.append(instance.id)
- return CrudBenchmarkContext(
- scenario=scenario,
- size=size,
- model_class=model_class,
- payloads=payloads,
- record_ids=record_ids,
- backend_namespace="rhosocial.activerecord.backend.impl.postgres",
- backend_name="postgres",
- )
-
- async def teardown_benchmark_async(self, scenario: str, context: CrudBenchmarkContext) -> None:
- await self._cleanup_async()
-
- def _setup_model(self, model_class: Type[ActiveRecord], scenario: str) -> Type[ActiveRecord]:
- backend_class, config = get_scenario(scenario)
- model_class.configure(config, backend_class)
- self._initialize_schema(model_class.__backend__)
- if model_class.__backend__ not in self._active_backends:
- self._active_backends.append(model_class.__backend__)
- return model_class
-
- async def _setup_async_model(
- self, model_class: Type[ActiveRecord], scenario: str
- ) -> Type[ActiveRecord]:
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
-
- _, config = get_scenario(scenario)
- await model_class.configure(config, AsyncPostgresBackend)
- await self._initialize_schema_async(model_class.__backend__)
- if model_class.__backend__ not in self._active_async_backends:
- self._active_async_backends.append(model_class.__backend__)
- return model_class
-
- def _initialize_schema(self, backend):
- options = ExecutionOptions(stmt_type=StatementType.DDL)
- backend.execute("DROP TABLE IF EXISTS benchmark_users", options=options)
- backend.execute(self._schema_sql(), options=options)
-
- async def _initialize_schema_async(self, backend):
- options = ExecutionOptions(stmt_type=StatementType.DDL)
- await backend.execute("DROP TABLE IF EXISTS benchmark_users", options=options)
- await backend.execute(self._schema_sql(), options=options)
-
- def _schema_sql(self):
- return """
-CREATE TABLE benchmark_users (
- id SERIAL PRIMARY KEY,
- username VARCHAR(255) NOT NULL,
- email VARCHAR(255) NOT NULL,
- age INTEGER,
- balance DOUBLE PRECISION NOT NULL DEFAULT 0.0,
- notes TEXT,
- is_active BOOLEAN NOT NULL DEFAULT TRUE,
- created_at TIMESTAMP,
- updated_at TIMESTAMP
-)
-"""
-
- def _cleanup_sync(self):
- for backend in self._active_backends:
- try:
- backend.execute("DROP TABLE IF EXISTS benchmark_users CASCADE")
- except Exception:
- pass
- try:
- backend.disconnect()
- except Exception:
- pass
- self._active_backends.clear()
-
- async def _cleanup_async(self):
- for backend in self._active_async_backends:
- try:
- await backend.execute("DROP TABLE IF EXISTS benchmark_users CASCADE")
- except Exception:
- pass
- try:
- await backend.disconnect()
- except Exception:
- pass
- self._active_async_backends.clear()
diff --git a/tests/providers/events.py b/tests/providers/events.py
deleted file mode 100644
index f20be52f..00000000
--- a/tests/providers/events.py
+++ /dev/null
@@ -1,201 +0,0 @@
-"""
-This file provides the concrete implementation of the `IEventsProvider` interface
-that is defined in the `rhosocial-activerecord-testsuite` package.
-
-Its main responsibilities are:
-1. Reporting which test scenarios (database configurations) are available.
-2. Setting up the database environment for a given test. This includes:
- - Getting the correct database configuration for the scenario.
- - Configuring the ActiveRecord model with a database connection.
- - Dropping any old tables and creating the necessary table schema.
-3. Cleaning up any resources after a test runs.
-"""
-import os
-import sys
-import logging
-from typing import Type, List
-
-from rhosocial.activerecord.model import ActiveRecord
-
-# Setup logging for fixture selection debugging
-logger = logging.getLogger(__name__)
-
-# Import the fixture selector utility
-from rhosocial.activerecord.testsuite.utils import select_fixture # noqa: E402
-
-# Import base version models (Python 3.8+)
-from rhosocial.activerecord.testsuite.feature.events.fixtures.models import ( # noqa: E402
- EventTestModel as EventTestModelBase,
- EventTrackingModel as EventTrackingModelBase,
- AsyncEventTestModel as AsyncEventTestModelBase,
-)
-
-# Conditionally import Python 3.10+ models
-EventTestModel310 = EventTrackingModel310 = None
-
-if sys.version_info >= (3, 10):
- try:
- from rhosocial.activerecord.testsuite.feature.events.fixtures.models_py310 import (
- EventTestModel as EventTestModel310,
- EventTrackingModel as EventTrackingModel310
- )
- except ImportError as e:
- logger.warning(f"Failed to import Python 3.10+ fixtures: {e}")
-
-# Conditionally import Python 3.11+ models
-EventTestModel311 = EventTrackingModel311 = None
-
-if sys.version_info >= (3, 11):
- try:
- from rhosocial.activerecord.testsuite.feature.events.fixtures.models_py311 import (
- EventTestModel as EventTestModel311,
- EventTrackingModel as EventTrackingModel311
- )
- except ImportError as e:
- logger.warning(f"Failed to import Python 3.11+ fixtures: {e}")
-
-# Conditionally import Python 3.12+ models
-EventTestModel312 = EventTrackingModel312 = None
-
-if sys.version_info >= (3, 12):
- try:
- from rhosocial.activerecord.testsuite.feature.events.fixtures.models_py312 import (
- EventTestModel as EventTestModel312,
- EventTrackingModel as EventTrackingModel312
- )
- except ImportError as e:
- logger.warning(f"Failed to import Python 3.12+ fixtures: {e}")
-
-
-# Select appropriate fixture classes based on Python version
-def _select_model_class(base_cls, py312_cls, py311_cls, py310_cls, model_name: str) -> Type:
- """Select the most appropriate model class for the current Python version."""
- candidates = [c for c in [py312_cls, py311_cls, py310_cls, base_cls] if c is not None]
- selected = select_fixture(*candidates)
- logger.info(f"Selected {model_name}: {selected.__name__} from {selected.__module__}")
- return selected
-
-
-# Select models
-EventTestModel = _select_model_class(EventTestModelBase, EventTestModel312, EventTestModel311, EventTestModel310, "EventTestModel") # noqa: E501
-EventTrackingModel = _select_model_class(EventTrackingModelBase, EventTrackingModel312, EventTrackingModel311, EventTrackingModel310, "EventTrackingModel") # noqa: E501
-AsyncEventTestModel = AsyncEventTestModelBase
-
-from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType # noqa: E402
-from rhosocial.activerecord.testsuite.feature.events.interfaces import IEventsSyncProvider, IEventsAsyncProvider # noqa: E402
-# ...and the scenarios are defined specifically for this backend.
-from .scenarios import get_enabled_scenarios, get_scenario # noqa: E402
-
-# Expression-based DDL fixtures
-from .fixtures._common import drop_table # noqa: E402
-from .fixtures.events import TABLE_EXPRESSIONS as EVENTS_TABLE_EXPRESSIONS # noqa: E402
-
-
-class EventsProviderBase:
- def __init__(self):
- self._active_backends = []
-
- def get_test_scenarios(self) -> List[str]:
- return list(get_enabled_scenarios().keys())
-
- def _load_postgres_schema(self, filename: str) -> str:
- schema_dir = os.path.join(
- os.path.dirname(__file__), "..", "rhosocial", "activerecord_postgres_test", "feature", "events", "schema"
- )
- schema_path = os.path.join(schema_dir, filename)
- with open(schema_path, 'r', encoding='utf-8') as f:
- return f.read()
-
-
-class EventsSyncProvider(EventsProviderBase, IEventsSyncProvider):
-
- def __init__(self):
- super().__init__()
-
- def _setup_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]:
- backend_class, config = get_scenario(scenario_name)
- model_class.configure(config, backend_class)
- backend_instance = model_class.__backend__
- if backend_instance not in self._active_backends:
- self._active_backends.append(backend_instance)
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- try:
- sql, params = drop_table(backend_instance.dialect, table_name).to_sql()
- backend_instance.execute(sql, params, options=opts)
- except Exception as e:
- print(f"Could not drop table {table_name}: {e}")
- if fn := EVENTS_TABLE_EXPRESSIONS.get(table_name):
- create_expr = fn(backend_instance.dialect, table_name)
- sql, params = create_expr.to_sql()
- backend_instance.execute(sql, params, options=opts)
- return model_class
-
- def setup_event_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(EventTestModel, scenario_name, "event_tests")
-
- def setup_event_tracking_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(EventTrackingModel, scenario_name, "event_tracking_models")
-
- def cleanup_after_test(self, scenario_name: str):
- for backend_instance in self._active_backends:
- try:
- for table_name in ['event_tests', 'event_tracking_models']:
- try:
- backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE')
- except Exception:
- pass
- finally:
- try:
- backend_instance.disconnect()
- except Exception:
- pass
- self._active_backends.clear()
-
-
-class EventsAsyncProvider(EventsProviderBase, IEventsAsyncProvider):
-
- def __init__(self):
- super().__init__()
- self._active_async_backends = []
-
- async def _setup_async_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]:
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
- _, config = get_scenario(scenario_name)
- await model_class.configure(config, AsyncPostgresBackend)
- backend_instance = model_class.__backend__
- if backend_instance not in self._active_async_backends:
- self._active_async_backends.append(backend_instance)
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- try:
- sql, params = drop_table(backend_instance.dialect, table_name).to_sql()
- await backend_instance.execute(sql, params, options=opts)
- except Exception as e:
- print(f"Could not drop table {table_name}: {e}")
- if fn := EVENTS_TABLE_EXPRESSIONS.get(table_name):
- create_expr = fn(backend_instance.dialect, table_name)
- sql, params = create_expr.to_sql()
- await backend_instance.execute(sql, params, options=opts)
- return model_class
-
- async def setup_event_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncEventTestModel, scenario_name, "event_tests")
-
- async def setup_event_tracking_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(EventTrackingModel, scenario_name, "event_tracking_models")
-
- async def cleanup_after_test(self, scenario_name: str):
- for backend_instance in self._active_async_backends:
- try:
- for table_name in ['event_tests', 'event_tracking_models']:
- try:
- await backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE')
- except Exception:
- pass
- finally:
- try:
- await backend_instance.disconnect()
- except Exception:
- pass
- self._active_async_backends.clear()
diff --git a/tests/providers/fastapi_benchmark.py b/tests/providers/fastapi_benchmark.py
deleted file mode 100644
index 3ebdcba6..00000000
--- a/tests/providers/fastapi_benchmark.py
+++ /dev/null
@@ -1,242 +0,0 @@
-"""PostgreSQL provider for FastAPI benchmark tests."""
-
-import sys
-from contextlib import asynccontextmanager
-from typing import Type
-
-from rhosocial.activerecord.backend.options import ExecutionOptions
-from rhosocial.activerecord.backend.schema import StatementType
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.data import (
- make_user_payloads,
- payload_count_for_size,
-)
-from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models import (
- AsyncBenchmarkUser as AsyncBenchmarkUserBase,
-)
-from rhosocial.activerecord.testsuite.benchmark.fastapi.interfaces import (
- FASTAPI_CONNECTION_STRATEGIES,
- FASTAPI_CONTEXT_STRATEGY,
- FASTAPI_RUNTIME_CONFIGS,
- FastAPIBenchmarkContext,
-)
-from rhosocial.activerecord.testsuite.utils import select_fixture
-
-from .scenarios import get_enabled_scenarios, get_scenario
-
-AsyncBenchmarkUser310 = None
-AsyncBenchmarkUser311 = None
-AsyncBenchmarkUser312 = None
-
-if sys.version_info >= (3, 10):
- from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models_py310 import (
- AsyncBenchmarkUser as AsyncBenchmarkUser310,
- )
-
-if sys.version_info >= (3, 11):
- from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models_py311 import (
- AsyncBenchmarkUser as AsyncBenchmarkUser311,
- )
-
-if sys.version_info >= (3, 12):
- from rhosocial.activerecord.testsuite.benchmark.crud.fixtures.models_py312 import (
- AsyncBenchmarkUser as AsyncBenchmarkUser312,
- )
-
-AsyncBenchmarkUser = select_fixture(
- *[
- candidate
- for candidate in (
- AsyncBenchmarkUser312,
- AsyncBenchmarkUser311,
- AsyncBenchmarkUser310,
- AsyncBenchmarkUserBase,
- )
- if candidate
- ]
-)
-
-
-class FastAPIBenchmarkProvider:
- def __init__(self):
- self._active_async_backends = []
- self._active_async_pools = []
- self._active_clients = []
-
- def get_benchmark_scenarios(self):
- return list(get_enabled_scenarios().keys())
-
- def get_connection_strategies(self):
- return FASTAPI_CONNECTION_STRATEGIES
-
- async def setup_benchmark_async(
- self,
- scenario: str,
- size: str,
- connection_strategy: str = "context",
- ):
- import httpx
- from rhosocial.activerecord.testsuite.benchmark.fastapi.app import (
- create_fastapi_benchmark_app,
- )
-
- model_class, config = await self._setup_async_model(AsyncBenchmarkUser, scenario)
- payloads = make_user_payloads(payload_count_for_size(size))
- record_ids = []
- async with model_class.__backend__.context():
- for payload in payloads:
- instance = model_class(**payload)
- rows = await instance.save()
- if rows != 1 or instance.id is None:
- raise AssertionError("failed to seed async FastAPI benchmark row")
- record_ids.append(instance.id)
-
- runtime_config = self._fastapi_runtime_config(connection_strategy)
- pool = None
- pool_config = None
- backend_context_factory = self._create_async_context_factory(config)
- if connection_strategy != FASTAPI_CONTEXT_STRATEGY:
- pool, pool_config = await self._create_async_pool(config, runtime_config)
- backend_context_factory = pool.connection
-
- app = create_fastapi_benchmark_app(
- model_class=model_class,
- backend_context_factory=backend_context_factory,
- backend_name="postgres",
- scenario=scenario,
- )
- transport = httpx.ASGITransport(app=app)
- client = httpx.AsyncClient(transport=transport, base_url="http://testserver")
- self._active_clients.append(client)
-
- return FastAPIBenchmarkContext(
- scenario=scenario,
- size=size,
- app=app,
- client=client,
- model_class=model_class,
- payloads=payloads,
- record_ids=record_ids,
- backend_namespace="rhosocial.activerecord.backend.impl.postgres",
- backend_name="postgres",
- connection_strategy=connection_strategy,
- concurrency=runtime_config["concurrency"],
- repeat=runtime_config["repeat"],
- pool_config={
- "min_size": pool_config.min_size,
- "max_size": pool_config.max_size,
- "connection_mode": pool_config.connection_mode,
- }
- if pool_config
- else None,
- pool_connection_mode=pool.connection_mode if pool else None,
- pool_stats=pool.get_stats if pool else None,
- )
-
- async def teardown_benchmark_async(
- self,
- scenario: str,
- context: FastAPIBenchmarkContext,
- ) -> None:
- await self._cleanup_async()
-
- async def _setup_async_model(
- self, model_class: Type[ActiveRecord], scenario: str
- ) -> Type[ActiveRecord]:
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
-
- _, config = get_scenario(scenario)
- await model_class.configure(config, AsyncPostgresBackend)
- await self._initialize_schema_async(model_class.__backend__)
- if model_class.__backend__ not in self._active_async_backends:
- self._active_async_backends.append(model_class.__backend__)
- return model_class, config
-
- async def _initialize_schema_async(self, backend):
- options = ExecutionOptions(stmt_type=StatementType.DDL)
- await self._drop_benchmark_table(backend, options)
- await backend.execute(self._schema_sql(), options=options)
-
- def _create_async_context_factory(self, config):
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
-
- @asynccontextmanager
- async def context_factory():
- backend = AsyncPostgresBackend(connection_config=config)
- async with backend.context():
- yield backend
-
- return context_factory
-
- def _fastapi_runtime_config(self, connection_strategy):
- try:
- return FASTAPI_RUNTIME_CONFIGS[connection_strategy]
- except KeyError as exc:
- raise ValueError(
- f"unsupported FastAPI benchmark connection strategy: {connection_strategy}"
- ) from exc
-
- async def _create_async_pool(self, config, runtime_config):
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
- from rhosocial.activerecord.connection.pool import AsyncBackendPool, PoolConfig
-
- pool_config = PoolConfig(
- min_size=runtime_config["pool_min_size"],
- max_size=runtime_config["pool_max_size"],
- connection_mode="auto",
- backend_factory=lambda: AsyncPostgresBackend(connection_config=config),
- )
- pool = await AsyncBackendPool.create(pool_config)
- self._active_async_pools.append(pool)
- return pool, pool_config
-
- def _schema_sql(self):
- return """
-CREATE TABLE benchmark_users (
- id SERIAL PRIMARY KEY,
- username VARCHAR(255) NOT NULL,
- email VARCHAR(255) NOT NULL,
- age INTEGER,
- balance DOUBLE PRECISION NOT NULL DEFAULT 0.0,
- notes TEXT,
- is_active BOOLEAN NOT NULL DEFAULT TRUE,
- created_at TIMESTAMP,
- updated_at TIMESTAMP
-)
-"""
-
- async def _cleanup_async(self):
- for client in self._active_clients:
- try:
- await client.aclose()
- except Exception:
- pass
- self._active_clients.clear()
-
- for pool in self._active_async_pools:
- try:
- await pool.close(force=True)
- except Exception:
- pass
- self._active_async_pools.clear()
-
- for backend in self._active_async_backends:
- try:
- options = ExecutionOptions(stmt_type=StatementType.DDL)
- await self._drop_benchmark_table(backend, options)
- except Exception:
- pass
- try:
- await backend.disconnect()
- except Exception:
- pass
- self._active_async_backends.clear()
-
- async def _drop_benchmark_table(self, backend, options):
- await backend.execute('DROP TABLE IF EXISTS "benchmark_users" CASCADE', options=options)
diff --git a/tests/providers/fixtures/__init__.py b/tests/providers/fixtures/__init__.py
deleted file mode 100644
index cd640fd9..00000000
--- a/tests/providers/fixtures/__init__.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# tests/providers/fixtures/__init__.py
-"""PostgreSQL-specific DDL expression fixtures for the testsuite providers.
-
-Each module in this package exposes a ``TABLE_EXPRESSIONS`` mapping of
-table name -> factory callable ``Callable[[DialectLike, str], CreateTableStatement]``.
-
-The factory functions build :class:`CreateTableStatement` instances that emit
-PostgreSQL-compatible DDL (SERIAL / UUID / JSONB / BYTEA / TIMESTAMPTZ / BOOLEAN /
-DECIMAL / VARCHAR / TEXT / FK constraints / CHECK / UNIQUE / NOT NULL / DEFAULT).
-The pre-existing ``.sql`` schema files under
-``tests/rhosocial/activerecord_postgres_test/feature//schema/``
-remain as the authoritative reference for what the expressions here must
-produce; they are simply no longer read at runtime by the providers.
-"""
diff --git a/tests/providers/fixtures/_common.py b/tests/providers/fixtures/_common.py
deleted file mode 100644
index 2af3a52b..00000000
--- a/tests/providers/fixtures/_common.py
+++ /dev/null
@@ -1,34 +0,0 @@
-# tests/providers/fixtures/_common.py
-"""Shared helpers for the PostgreSQL DDL expression fixtures.
-
-Provides the ``drop_table`` helper used by all feature providers.
-"""
-
-from __future__ import annotations
-
-from typing import Tuple
-
-from rhosocial.activerecord.backend.expression import (
- CreateTableStatement,
- DropTableStatement,
-)
-from rhosocial.activerecord.backend.expression.objects import Table
-
-
-def drop_table(dialect, table_name: str) -> DropTableStatement:
- """Build a ``DROP TABLE IF EXISTS table_name CASCADE`` expression."""
- return DropTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_exists=True,
- )
-
-
-def create_table_sql(expr: CreateTableStatement) -> Tuple[str, tuple]:
- """Generate canonical PostgreSQL DDL for a :class:`CreateTableStatement`.
-
- For PostgreSQL no post-processing is required (unlike MySQL where storage
- option quotes must be stripped). This pass-through wrapper exists so the
- call site is the same as the MySQL counterpart.
- """
- return expr.to_sql()
diff --git a/tests/providers/fixtures/basic.py b/tests/providers/fixtures/basic.py
deleted file mode 100644
index f55ce340..00000000
--- a/tests/providers/fixtures/basic.py
+++ /dev/null
@@ -1,498 +0,0 @@
-# tests/providers/fixtures/basic.py
-"""DDL expressions for the ``feature/basic`` table group (PostgreSQL).
-
-Each factory builds a :class:`CreateTableStatement` whose generated DDL is
-semantically equivalent to the reference ``.sql`` schema files under
-``tests/rhosocial/activerecord_postgres_test/feature/basic/schema/``. Those
-``.sql`` files are kept as the authoritative reference and are no longer
-loaded at runtime.
-"""
-
-from typing import Callable, Dict
-
-from rhosocial.activerecord.backend.expression import (
- CreateTableStatement,
- ColumnDefaultConstraint,
- ColumnNotNullConstraint,
- ColumnPrimaryKeyConstraint,
- TablePrimaryKeyConstraint,
-)
-from rhosocial.activerecord.backend.expression.statements import (
- ColumnDefinition,
- ColumnConstraint,
- ForeignKeyConstraint,
- TableConstraint,
- ReferentialAction,
-)
-from rhosocial.activerecord.backend.expression.types import (
- ArrayType,
- BigIntType,
- BooleanType,
- DateType,
- DecimalType,
- DoubleType,
- FloatType,
- IntegerType,
- JsonBType,
- SmallIntType,
- TextType,
- TimeTzType,
- TimestampTzType,
- VarCharType,
- BlobType,
- UUIDType,
-)
-from rhosocial.activerecord.backend.expression.objects import Table
-from rhosocial.activerecord.backend.impl.postgres.expression import (
- PostgresSerialType,
-)
-
-_CASCADE = ReferentialAction.CASCADE
-
-
-# ---------------------------------------------------------------------------
-# basic/users.sql
-# ---------------------------------------------------------------------------
-
-def create_users_table(dialect, table_name: str = "users") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "username", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "age", IntegerType(dialect=dialect)),
- ColumnDefinition(dialect, "balance", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]),
- ColumnDefinition(dialect, "is_active", BooleanType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, True))]),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# basic/type_cases.sql
-# ---------------------------------------------------------------------------
-
-def create_type_cases_table(dialect, table_name: str = "type_cases") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", UUIDType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "username", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "tiny_int", SmallIntType(dialect=dialect)),
- ColumnDefinition(dialect, "small_int", SmallIntType(dialect=dialect)),
- ColumnDefinition(dialect, "big_int", BigIntType(dialect=dialect)),
- ColumnDefinition(dialect, "float_val", FloatType(dialect=dialect)),
- ColumnDefinition(dialect, "double_val", DoubleType(dialect=dialect)),
- ColumnDefinition(dialect, "decimal_val", DecimalType(precision=10, scale=4, dialect=dialect)),
- ColumnDefinition(dialect, "char_val", VarCharType(length=255, dialect=dialect)),
- ColumnDefinition(dialect, "varchar_val", VarCharType(length=255, dialect=dialect)),
- ColumnDefinition(dialect, "text_val", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "date_val", DateType(dialect=dialect)),
- ColumnDefinition(dialect, "time_val", TimeTzType(dialect=dialect)),
- ColumnDefinition(dialect, "timestamp_val", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "blob_val", BlobType(dialect=dialect)),
- ColumnDefinition(dialect, "json_val", JsonBType(dialect=dialect)),
- ColumnDefinition(dialect, "array_val", ArrayType(element_type=IntegerType(dialect=dialect), dialect=dialect)),
- ColumnDefinition(dialect, "is_active", BooleanType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, True))]),
- ],
- table_constraints=[
- TableConstraint(dialect, branch=TablePrimaryKeyConstraint(dialect, ["id"])),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# basic/type_tests.sql
-# ---------------------------------------------------------------------------
-
-def create_type_tests_table(dialect, table_name: str = "type_tests") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", UUIDType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "string_field", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "int_field", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "float_field", FloatType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "decimal_field", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "bool_field", BooleanType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "datetime_field", TimestampTzType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "json_field", JsonBType(dialect=dialect)),
- ColumnDefinition(dialect, "nullable_field", VarCharType(length=255, dialect=dialect)),
- ],
- table_constraints=[
- TableConstraint(dialect, branch=TablePrimaryKeyConstraint(dialect, ["id"])),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# basic/validated_field_users.sql
-# ---------------------------------------------------------------------------
-
-def create_validated_field_users_table(dialect, table_name: str = "validated_field_users") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "username", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "age", IntegerType(dialect=dialect)),
- ColumnDefinition(dialect, "balance", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "credit_score", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 300))]),
- ColumnDefinition(dialect, "status", VarCharType(length=50, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "active"))]),
- ColumnDefinition(dialect, "is_active", BooleanType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, True))]),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# basic/validated_users.sql
-# ---------------------------------------------------------------------------
-
-def create_validated_users_table(dialect, table_name: str = "validated_users") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "username", VarCharType(length=50, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "age", IntegerType(dialect=dialect)),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# basic/pydantic_validated_models.sql
-# ---------------------------------------------------------------------------
-
-def create_pydantic_validated_models_table(dialect, table_name: str = "pydantic_validated_models") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "code", VarCharType(length=32, dialect=dialect)),
- ColumnDefinition(dialect, "quantity", IntegerType(dialect=dialect)),
- ColumnDefinition(dialect, "step_count", IntegerType(dialect=dialect)),
- ColumnDefinition(dialect, "price", DecimalType(precision=10, scale=2, dialect=dialect)),
- ColumnDefinition(dialect, "start_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "end_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "status", VarCharType(length=32, dialect=dialect)),
- ColumnDefinition(dialect, "normalized_name", VarCharType(length=50, dialect=dialect)),
- ColumnDefinition(dialect, "created_token", VarCharType(length=255, dialect=dialect)),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# basic/bulk_users.sql
-# ---------------------------------------------------------------------------
-
-def create_bulk_users_table(dialect, table_name: str = "bulk_users") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "age", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0))]),
- ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, ""))]),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# basic/posts.sql
-# ---------------------------------------------------------------------------
-
-def create_posts_table(dialect, table_name: str = "posts") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "author", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "title", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "content", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "published_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "published", BooleanType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, False))]),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- table_constraints=[
- ForeignKeyConstraint(dialect, columns=["author"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"],
- on_delete=_CASCADE),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# basic/comments.sql
-# ---------------------------------------------------------------------------
-
-def create_comments_table(dialect, table_name: str = "comments") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "post_ref", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "author", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "text", TextType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "approved", BooleanType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, False))]),
- ],
- table_constraints=[
- ForeignKeyConstraint(dialect, columns=["post_ref"], foreign_key_table=Table(dialect, 'posts'), foreign_key_columns=["id"],
- on_delete=_CASCADE),
- ForeignKeyConstraint(dialect, columns=["author"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"],
- on_delete=_CASCADE),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# basic/column_mapping_items.sql
-# ---------------------------------------------------------------------------
-
-def create_column_mapping_items_table(dialect, table_name: str = "column_mapping_items") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "item_total", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "remarks", IntegerType(dialect=dialect)),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# basic/mixed_annotation_items.sql
-# ---------------------------------------------------------------------------
-
-def create_mixed_annotation_items_table(dialect, table_name: str = "mixed_annotation_items") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "tags", ArrayType(element_type=TextType(dialect=dialect), dialect=dialect)),
- ColumnDefinition(dialect, "meta", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "description", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "status", TextType(dialect=dialect)),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# basic/type_adapter_tests.sql
-# ---------------------------------------------------------------------------
-
-def create_type_adapter_tests_table(dialect, table_name: str = "type_adapter_tests") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=True,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "optional_name", VarCharType(length=255, dialect=dialect)),
- ColumnDefinition(dialect, "optional_age", IntegerType(dialect=dialect)),
- ColumnDefinition(dialect, "last_login", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "is_premium", BooleanType(dialect=dialect)),
- ColumnDefinition(dialect, "unsupported_union", VarCharType(length=255, dialect=dialect)),
- ColumnDefinition(dialect, "custom_bool", VarCharType(length=10, dialect=dialect)),
- ColumnDefinition(dialect, "optional_custom_bool", VarCharType(length=10, dialect=dialect)),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# composite_pk/order_items.sql (composite PK)
-# ---------------------------------------------------------------------------
-
-def create_composite_pk_order_items_table(dialect, table_name: str = "order_items") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "order_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "product_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "quantity", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]),
- ColumnDefinition(dialect, "unit_price", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ],
- table_constraints=[
- TableConstraint(dialect, branch=TablePrimaryKeyConstraint(dialect, ["order_id", "product_id"])),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# composite_pk/store_inventory.sql (composite PK, no FK)
-# ---------------------------------------------------------------------------
-
-def create_store_inventory_table(dialect, table_name: str = "store_inventory") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "store_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "product_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "batch_id", VarCharType(length=64, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "stock", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0))]),
- ],
- table_constraints=[
- TableConstraint(dialect, branch=TablePrimaryKeyConstraint(dialect, ["store_id", "product_id", "batch_id"])),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# derived_field/orders.sql (single PK)
-# ---------------------------------------------------------------------------
-
-def create_orders_table(dialect, table_name: str = "orders") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "total", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "created_at", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TextType(dialect=dialect)),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# derived_field/product.sql (single PK)
-# ---------------------------------------------------------------------------
-
-def create_product_table(dialect, table_name: str = "product") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=True,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "name", TextType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "price", FloatType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "quantity", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ],
- )
-
-
-TABLE_EXPRESSIONS: Dict[str, Callable] = {
- "users": create_users_table,
- "type_cases": create_type_cases_table,
- "type_tests": create_type_tests_table,
- "validated_field_users": create_validated_field_users_table,
- "validated_users": create_validated_users_table,
- "pydantic_validated_models": create_pydantic_validated_models_table,
- "bulk_users": create_bulk_users_table,
- "posts": create_posts_table,
- "comments": create_comments_table,
- "column_mapping_items": create_column_mapping_items_table,
- "mixed_annotation_items": create_mixed_annotation_items_table,
- "type_adapter_tests": create_type_adapter_tests_table,
- "order_items": create_composite_pk_order_items_table,
- "store_inventory": create_store_inventory_table,
- "orders": create_orders_table,
- "product": create_product_table,
-}
diff --git a/tests/providers/fixtures/events.py b/tests/providers/fixtures/events.py
deleted file mode 100644
index 3c3e626a..00000000
--- a/tests/providers/fixtures/events.py
+++ /dev/null
@@ -1,84 +0,0 @@
-# tests/providers/fixtures/events.py
-"""DDL expressions for the ``feature/events`` table group (PostgreSQL).
-
-Reference: ``tests/rhosocial/activerecord_postgres_test/feature/events/schema/``.
-"""
-
-from typing import Callable, Dict
-
-from rhosocial.activerecord.backend.expression import (
- CreateTableStatement,
- ColumnDefaultConstraint,
- ColumnNotNullConstraint,
- ColumnNullableConstraint,
- ColumnPrimaryKeyConstraint,
-)
-from rhosocial.activerecord.backend.expression.statements import (
- ColumnDefinition,
- ColumnConstraint,
-)
-from rhosocial.activerecord.backend.expression.types import (
- IntegerType,
- TextType,
- TimestampTzType,
- VarCharType,
-)
-from rhosocial.activerecord.backend.impl.postgres.expression import PostgresSerialType
-from rhosocial.activerecord.backend.expression.objects import Table
-
-
-# ---------------------------------------------------------------------------
-# events/event_tests.sql
-# ---------------------------------------------------------------------------
-
-def create_event_tests_table(dialect, table_name: str = "event_tests") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "status", VarCharType(length=50, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "draft"))]),
- ColumnDefinition(dialect, "revision", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]),
- ColumnDefinition(dialect, "content", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# events/event_tracking_models.sql
-# ---------------------------------------------------------------------------
-
-def create_event_tracking_models_table(dialect, table_name: str = "event_tracking_models") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "title", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "content", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "view_count", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0))]),
- ColumnDefinition(dialect, "last_viewed_at", TimestampTzType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNullableConstraint(dialect))]),
- ],
- )
-
-
-TABLE_EXPRESSIONS: Dict[str, Callable] = {
- "event_tests": create_event_tests_table,
- "event_tracking_models": create_event_tracking_models_table,
-}
diff --git a/tests/providers/fixtures/mixins.py b/tests/providers/fixtures/mixins.py
deleted file mode 100644
index c2892334..00000000
--- a/tests/providers/fixtures/mixins.py
+++ /dev/null
@@ -1,134 +0,0 @@
-# tests/providers/fixtures/mixins.py
-"""DDL expressions for the ``feature/mixins`` table group (PostgreSQL).
-
-Reference: ``tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/``.
-"""
-
-from typing import Callable, Dict
-
-from rhosocial.activerecord.backend.expression import (
- CreateTableStatement,
- ColumnDefaultConstraint,
- ColumnNotNullConstraint,
- ColumnNullableConstraint,
- ColumnPrimaryKeyConstraint,
-)
-from rhosocial.activerecord.backend.expression.statements import (
- ColumnDefinition,
- ColumnConstraint,
-)
-from rhosocial.activerecord.backend.expression.types import (
- BooleanType,
- DecimalType,
- IntegerType,
- TextType,
- TimestampTzType,
- VarCharType,
-)
-from rhosocial.activerecord.backend.impl.postgres.expression import PostgresSerialType
-from rhosocial.activerecord.backend.expression.objects import Table
-
-
-# ---------------------------------------------------------------------------
-# mixins/combined_articles.sql
-# ---------------------------------------------------------------------------
-
-def create_combined_articles_table(dialect, table_name: str = "combined_articles") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "title", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "content", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "status", VarCharType(length=50, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "draft"))]),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "version", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]),
- ColumnDefinition(dialect, "deleted_at", TimestampTzType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNullableConstraint(dialect))]),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# mixins/tasks.sql
-# ---------------------------------------------------------------------------
-
-def create_tasks_table(dialect, table_name: str = "tasks") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "title", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "is_completed", BooleanType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, False))]),
- ColumnDefinition(dialect, "deleted_at", TimestampTzType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNullableConstraint(dialect))]),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# mixins/timestamped_posts.sql
-# ---------------------------------------------------------------------------
-
-def create_timestamped_posts_table(dialect, table_name: str = "timestamped_posts") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "title", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "content", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# mixins/versioned_products.sql
-# ---------------------------------------------------------------------------
-
-def create_versioned_products_table(dialect, table_name: str = "versioned_products") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "price", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]),
- ColumnDefinition(dialect, "version", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]),
- ],
- )
-
-
-TABLE_EXPRESSIONS: Dict[str, Callable] = {
- "combined_articles": create_combined_articles_table,
- "tasks": create_tasks_table,
- "timestamped_posts": create_timestamped_posts_table,
- "versioned_products": create_versioned_products_table,
-}
diff --git a/tests/providers/fixtures/query.py b/tests/providers/fixtures/query.py
deleted file mode 100644
index 25d052cb..00000000
--- a/tests/providers/fixtures/query.py
+++ /dev/null
@@ -1,385 +0,0 @@
-# tests/providers/fixtures/query.py
-"""DDL expressions for the ``feature/query`` table group (PostgreSQL).
-
-Reference: ``tests/rhosocial/activerecord_postgres_test/feature/query/schema/``.
-"""
-
-from typing import Callable, Dict
-
-from rhosocial.activerecord.backend.expression import (
- CreateTableStatement,
- ColumnDefaultConstraint,
- ColumnNotNullConstraint,
- ColumnNullableConstraint,
- ColumnPrimaryKeyConstraint,
-)
-from rhosocial.activerecord.backend.expression.statements import (
- ColumnDefinition,
- ColumnConstraint,
- ForeignKeyConstraint,
- ReferentialAction,
-)
-from rhosocial.activerecord.backend.expression.types import (
- BooleanType,
- DecimalType,
- IntegerType,
- JsonBType,
- TextType,
- TimestampTzType,
- VarCharType,
-)
-from rhosocial.activerecord.backend.impl.postgres.expression import PostgresSerialType
-from rhosocial.activerecord.backend.expression.objects import Table
-
-_CASCADE = ReferentialAction.CASCADE
-
-
-# ---------------------------------------------------------------------------
-# query/users.sql
-# ---------------------------------------------------------------------------
-
-def create_users_table(dialect, table_name: str = "users") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "username", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "age", IntegerType(dialect=dialect)),
- ColumnDefinition(dialect, "balance", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]),
- ColumnDefinition(dialect, "is_active", BooleanType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, True))]),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# query/posts.sql
-# ---------------------------------------------------------------------------
-
-def create_posts_table(dialect, table_name: str = "posts") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "user_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "title", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "content", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "status", VarCharType(length=50, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "published"))]),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- table_constraints=[
- ForeignKeyConstraint(dialect, columns=["user_id"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"],
- on_delete=_CASCADE),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# query/comments.sql
-# ---------------------------------------------------------------------------
-
-def create_comments_table(dialect, table_name: str = "comments") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "user_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "post_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "content", TextType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "is_hidden", BooleanType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, False))]),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- table_constraints=[
- ForeignKeyConstraint(dialect, columns=["user_id"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"],
- on_delete=_CASCADE),
- ForeignKeyConstraint(dialect, columns=["post_id"], foreign_key_table=Table(dialect, 'posts'), foreign_key_columns=["id"],
- on_delete=_CASCADE),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# query/orders.sql
-# ---------------------------------------------------------------------------
-
-def create_orders_table(dialect, table_name: str = "orders") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "user_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "order_number", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "total_amount", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]),
- ColumnDefinition(dialect, "status", VarCharType(length=50, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "pending"))]),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- table_constraints=[
- ForeignKeyConstraint(dialect, columns=["user_id"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"]),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# query/order_items.sql
-# ---------------------------------------------------------------------------
-
-def create_order_items_table(dialect, table_name: str = "order_items") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "order_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "product_name", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "quantity", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]),
- ColumnDefinition(dialect, "unit_price", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "subtotal", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- table_constraints=[
- ForeignKeyConstraint(dialect, columns=["order_id"], foreign_key_table=Table(dialect, 'orders'), foreign_key_columns=["id"],
- on_delete=_CASCADE),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# query/profiles.sql
-# ---------------------------------------------------------------------------
-
-def create_profiles_table(dialect, table_name: str = "profiles") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "user_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "bio", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "avatar_url", VarCharType(length=512, dialect=dialect)),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- table_constraints=[
- ForeignKeyConstraint(dialect, columns=["user_id"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"]),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# query/json_users.sql
-# ---------------------------------------------------------------------------
-
-def create_json_users_table(dialect, table_name: str = "json_users") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "username", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "email", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "age", IntegerType(dialect=dialect)),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "settings", JsonBType(dialect=dialect)),
- ColumnDefinition(dialect, "tags", JsonBType(dialect=dialect)),
- ColumnDefinition(dialect, "profile", JsonBType(dialect=dialect)),
- ColumnDefinition(dialect, "roles", JsonBType(dialect=dialect)),
- ColumnDefinition(dialect, "scores", JsonBType(dialect=dialect)),
- ColumnDefinition(dialect, "subscription", JsonBType(dialect=dialect)),
- ColumnDefinition(dialect, "preferences", JsonBType(dialect=dialect)),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# query/nodes.sql (self-referential FK)
-# ---------------------------------------------------------------------------
-
-def create_nodes_table(dialect, table_name: str = "nodes") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "parent_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNullableConstraint(dialect))]),
- ColumnDefinition(dialect, "value", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- table_constraints=[
- ForeignKeyConstraint(dialect, columns=["parent_id"], foreign_key_table=Table(dialect, 'nodes'), foreign_key_columns=["id"],
- on_delete=_CASCADE),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# query/searchable_items.sql
-# ---------------------------------------------------------------------------
-
-def create_searchable_items_table(dialect, table_name: str = "searchable_items") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "name", VarCharType(length=255, dialect=dialect)),
- ColumnDefinition(dialect, "tags", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# query/extended_orders.sql
-# ---------------------------------------------------------------------------
-
-def create_extended_orders_table(dialect, table_name: str = "extended_orders") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "user_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "order_number", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "total_amount", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.00))]),
- ColumnDefinition(dialect, "status", VarCharType(length=50, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "pending"))]),
- ColumnDefinition(dialect, "priority", VarCharType(length=50, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "medium"))]),
- ColumnDefinition(dialect, "region", VarCharType(length=50, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "default"))]),
- ColumnDefinition(dialect, "category", VarCharType(length=255, dialect=dialect)),
- ColumnDefinition(dialect, "product", VarCharType(length=255, dialect=dialect)),
- ColumnDefinition(dialect, "department", VarCharType(length=255, dialect=dialect)),
- ColumnDefinition(dialect, "year", VarCharType(length=10, dialect=dialect)),
- ColumnDefinition(dialect, "quarter", VarCharType(length=10, dialect=dialect)),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- table_constraints=[
- ForeignKeyConstraint(dialect, columns=["user_id"], foreign_key_table=Table(dialect, 'users'), foreign_key_columns=["id"],
- on_delete=_CASCADE),
- ],
- )
-
-
-# ---------------------------------------------------------------------------
-# query/extended_order_items.sql
-# ---------------------------------------------------------------------------
-
-def create_extended_order_items_table(dialect, table_name: str = "extended_order_items") -> CreateTableStatement:
- return CreateTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_not_exists=False,
- columns=[
- ColumnDefinition(dialect, "id", PostgresSerialType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]),
- ColumnDefinition(dialect, "order_id", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "product_name", VarCharType(length=255, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "quantity", IntegerType(dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
- ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]),
- ColumnDefinition(dialect, "price", DecimalType(precision=10, scale=2, dialect=dialect),
- constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "category", VarCharType(length=255, dialect=dialect)),
- ColumnDefinition(dialect, "region", VarCharType(length=50, dialect=dialect)),
- ColumnDefinition(dialect, "created_at", TimestampTzType(dialect=dialect)),
- ColumnDefinition(dialect, "updated_at", TimestampTzType(dialect=dialect)),
- ],
- table_constraints=[
- ForeignKeyConstraint(dialect, columns=["order_id"], foreign_key_table=Table(dialect, 'extended_orders'), foreign_key_columns=["id"],
- on_delete=_CASCADE),
- ],
- )
-
-
-TABLE_EXPRESSIONS: Dict[str, Callable] = {
- "users": create_users_table,
- "posts": create_posts_table,
- "comments": create_comments_table,
- "orders": create_orders_table,
- "order_items": create_order_items_table,
- "profiles": create_profiles_table,
- "json_users": create_json_users_table,
- "nodes": create_nodes_table,
- "searchable_items": create_searchable_items_table,
- "extended_orders": create_extended_orders_table,
- "extended_order_items": create_extended_order_items_table,
-}
diff --git a/tests/providers/mixin_benchmark.py b/tests/providers/mixin_benchmark.py
deleted file mode 100644
index 0e47555e..00000000
--- a/tests/providers/mixin_benchmark.py
+++ /dev/null
@@ -1,15 +0,0 @@
-"""PostgreSQL provider for mixin benchmark tests."""
-
-from rhosocial.activerecord.testsuite.benchmark.mixin.interfaces import MixinBenchmarkContext
-
-from .crud_benchmark import CrudBenchmarkProvider
-
-
-class MixinBenchmarkProvider(CrudBenchmarkProvider):
- def setup_benchmark_sync(self, scenario: str, size: str):
- context = super().setup_benchmark_sync(scenario, size)
- return MixinBenchmarkContext(**context.__dict__)
-
- async def setup_benchmark_async(self, scenario: str, size: str):
- context = await super().setup_benchmark_async(scenario, size)
- return MixinBenchmarkContext(**context.__dict__)
diff --git a/tests/providers/mixins.py b/tests/providers/mixins.py
deleted file mode 100644
index 42f844c1..00000000
--- a/tests/providers/mixins.py
+++ /dev/null
@@ -1,232 +0,0 @@
-"""
-This file provides the concrete implementation of the `IMixinsProvider` interface
-that is defined in the `rhosocial-activerecord-testsuite` package.
-
-Its main responsibilities are:
-1. Reporting which test scenarios (database configurations) are available.
-2. Setting up the database environment for a given test. This includes:
- - Getting the correct database configuration for the scenario.
- - Configuring the ActiveRecord model with a database connection.
- - Dropping any old tables and creating the necessary table schema.
-3. Cleaning up any resources after a test runs.
-"""
-import os
-import sys
-import logging
-from typing import Type, List
-
-from rhosocial.activerecord.model import ActiveRecord
-
-# Setup logging for fixture selection debugging
-logger = logging.getLogger(__name__)
-
-# Import the fixture selector utility
-from rhosocial.activerecord.testsuite.utils import select_fixture # noqa: E402
-
-# Import base version models (Python 3.8+)
-from rhosocial.activerecord.testsuite.feature.mixins.fixtures.models import ( # noqa: E402
- TimestampedPost as TimestampedPostBase,
- VersionedProduct as VersionedProductBase,
- Task as TaskBase,
- CombinedArticle as CombinedArticleBase,
- AsyncTimestampedPost as AsyncTimestampedPostBase,
- AsyncVersionedProduct as AsyncVersionedProductBase,
- AsyncTask as AsyncTaskBase,
- AsyncCombinedArticle as AsyncCombinedArticleBase,
-)
-
-# Conditionally import Python 3.10+ models
-TimestampedPost310 = VersionedProduct310 = Task310 = CombinedArticle310 = None
-
-if sys.version_info >= (3, 10):
- try:
- from rhosocial.activerecord.testsuite.feature.mixins.fixtures.models_py310 import (
- TimestampedPost as TimestampedPost310,
- VersionedProduct as VersionedProduct310,
- Task as Task310,
- CombinedArticle as CombinedArticle310
- )
- except ImportError as e:
- logger.warning(f"Failed to import Python 3.10+ fixtures: {e}")
-
-# Conditionally import Python 3.11+ models
-TimestampedPost311 = VersionedProduct311 = Task311 = CombinedArticle311 = None
-
-if sys.version_info >= (3, 11):
- try:
- from rhosocial.activerecord.testsuite.feature.mixins.fixtures.models_py311 import (
- TimestampedPost as TimestampedPost311,
- VersionedProduct as VersionedProduct311,
- Task as Task311,
- CombinedArticle as CombinedArticle311
- )
- except ImportError as e:
- logger.warning(f"Failed to import Python 3.11+ fixtures: {e}")
-
-# Conditionally import Python 3.12+ models
-TimestampedPost312 = VersionedProduct312 = Task312 = CombinedArticle312 = None
-
-if sys.version_info >= (3, 12):
- try:
- from rhosocial.activerecord.testsuite.feature.mixins.fixtures.models_py312 import (
- TimestampedPost as TimestampedPost312,
- VersionedProduct as VersionedProduct312,
- Task as Task312,
- CombinedArticle as CombinedArticle312
- )
- except ImportError as e:
- logger.warning(f"Failed to import Python 3.12+ fixtures: {e}")
-
-
-# Select appropriate fixture classes based on Python version
-def _select_model_class(base_cls, py312_cls, py311_cls, py310_cls, model_name: str) -> Type:
- """Select the most appropriate model class for the current Python version."""
- candidates = [c for c in [py312_cls, py311_cls, py310_cls, base_cls] if c is not None]
- selected = select_fixture(*candidates)
- logger.info(f"Selected {model_name}: {selected.__name__} from {selected.__module__}")
- return selected
-
-
-# Select models
-TimestampedPost = _select_model_class(TimestampedPostBase, TimestampedPost312, TimestampedPost311, TimestampedPost310, "TimestampedPost") # noqa: E501
-VersionedProduct = _select_model_class(VersionedProductBase, VersionedProduct312, VersionedProduct311, VersionedProduct310, "VersionedProduct") # noqa: E501
-Task = _select_model_class(TaskBase, Task312, Task311, Task310, "Task")
-CombinedArticle = _select_model_class(CombinedArticleBase, CombinedArticle312, CombinedArticle311, CombinedArticle310, "CombinedArticle") # noqa: E501
-
-AsyncTimestampedPost = AsyncTimestampedPostBase
-AsyncVersionedProduct = AsyncVersionedProductBase
-AsyncTask = AsyncTaskBase
-AsyncCombinedArticle = AsyncCombinedArticleBase
-
-from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType # noqa: E402
-from rhosocial.activerecord.testsuite.feature.mixins.interfaces import IMixinsSyncProvider, IMixinsAsyncProvider # noqa: E402
-# ...and the scenarios are defined specifically for this backend.
-from .scenarios import get_enabled_scenarios, get_scenario # noqa: E402
-
-# Expression-based DDL fixtures
-from .fixtures._common import drop_table # noqa: E402
-from .fixtures.mixins import TABLE_EXPRESSIONS as MIXINS_TABLE_EXPRESSIONS # noqa: E402
-
-
-class MixinsProviderBase:
- def __init__(self):
- self._active_backends = []
-
- def get_test_scenarios(self) -> List[str]:
- return list(get_enabled_scenarios().keys())
-
- def _load_postgres_schema(self, filename: str) -> str:
- schema_dir = os.path.join(
- os.path.dirname(__file__), "..", "rhosocial", "activerecord_postgres_test", "feature", "mixins", "schema"
- )
- schema_path = os.path.join(schema_dir, filename)
- with open(schema_path, 'r', encoding='utf-8') as f:
- return f.read()
-
-
-class MixinsSyncProvider(MixinsProviderBase, IMixinsSyncProvider):
-
- def __init__(self):
- super().__init__()
-
- def _setup_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]:
- backend_class, config = get_scenario(scenario_name)
- model_class.configure(config, backend_class)
- backend_instance = model_class.__backend__
- if backend_instance not in self._active_backends:
- self._active_backends.append(backend_instance)
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- try:
- sql, params = drop_table(backend_instance.dialect, table_name).to_sql()
- backend_instance.execute(sql, params, options=opts)
- except Exception as e:
- print(f"Could not drop table {table_name}: {e}")
- if fn := MIXINS_TABLE_EXPRESSIONS.get(table_name):
- create_expr = fn(backend_instance.dialect, table_name)
- sql, params = create_expr.to_sql()
- backend_instance.execute(sql, params, options=opts)
- return model_class
-
- def setup_timestamped_post_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(TimestampedPost, scenario_name, "timestamped_posts")
-
- def setup_versioned_product_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(VersionedProduct, scenario_name, "versioned_products")
-
- def setup_task_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(Task, scenario_name, "tasks")
-
- def setup_combined_article_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return self._setup_model(CombinedArticle, scenario_name, "combined_articles")
-
- def cleanup_after_test(self, scenario_name: str):
- for backend_instance in self._active_backends:
- try:
- for table_name in ['timestamped_posts', 'versioned_products', 'tasks',
- 'combined_articles']:
- try:
- backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE')
- except Exception:
- pass
- finally:
- try:
- backend_instance.disconnect()
- except Exception:
- pass
- self._active_backends.clear()
-
-
-class MixinsAsyncProvider(MixinsProviderBase, IMixinsAsyncProvider):
-
- def __init__(self):
- super().__init__()
- self._active_async_backends = []
-
- async def _setup_async_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]:
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
- _, config = get_scenario(scenario_name)
- await model_class.configure(config, AsyncPostgresBackend)
- backend_instance = model_class.__backend__
- if backend_instance not in self._active_async_backends:
- self._active_async_backends.append(backend_instance)
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- try:
- sql, params = drop_table(backend_instance.dialect, table_name).to_sql()
- await backend_instance.execute(sql, params, options=opts)
- except Exception as e:
- print(f"Could not drop table {table_name}: {e}")
- if fn := MIXINS_TABLE_EXPRESSIONS.get(table_name):
- create_expr = fn(backend_instance.dialect, table_name)
- sql, params = create_expr.to_sql()
- await backend_instance.execute(sql, params, options=opts)
- return model_class
-
- async def setup_timestamped_post_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncTimestampedPost, scenario_name, "timestamped_posts")
-
- async def setup_versioned_product_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncVersionedProduct, scenario_name, "versioned_products")
-
- async def setup_task_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncTask, scenario_name, "tasks")
-
- async def setup_combined_article_model(self, scenario_name: str) -> Type[ActiveRecord]:
- return await self._setup_async_model(AsyncCombinedArticle, scenario_name, "combined_articles")
-
- async def cleanup_after_test(self, scenario_name: str):
- for backend_instance in self._active_async_backends:
- try:
- for table_name in ['timestamped_posts', 'versioned_products', 'tasks',
- 'combined_articles']:
- try:
- await backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE')
- except Exception:
- pass
- finally:
- try:
- await backend_instance.disconnect()
- except Exception:
- pass
- self._active_async_backends.clear()
diff --git a/tests/providers/partition.py b/tests/providers/partition.py
deleted file mode 100644
index 3a630c16..00000000
--- a/tests/providers/partition.py
+++ /dev/null
@@ -1,381 +0,0 @@
-"""PostgreSQL provider for shared partition testsuite scenarios."""
-from __future__ import annotations
-
-from datetime import datetime
-from decimal import Decimal
-from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type
-
-from rhosocial.activerecord.base.field_proxy import FieldProxy
-from rhosocial.activerecord.base import IdentityAttribute
-from rhosocial.activerecord.backend.expression import Column
-from rhosocial.activerecord.backend.expression.statements import (
- ColumnDefinition,
- CreateTableStatement,
- DropTableStatement,
- PartitionClause,
- PartitionStrategy,
- TruncateStatement,
- ColumnNotNullConstraint,
-)
-from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import AsyncPostgresBackend
-from rhosocial.activerecord.backend.impl.postgres.expression import (
- PostgresAttachPartitionStatement,
- PostgresColumnDefinition,
- PostgresCreatePartitionStatement,
- PostgresDetachPartitionStatement,
- PostgresPartitionMetadataQueryStatement,
-)
-from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord
-from rhosocial.activerecord.testsuite.feature.partition.interfaces import IPartitionProvider
-
-from rhosocial.activerecord.backend.expression.types import (
- BigIntType, IntegerType, TextType, TimestampType, DecimalType,
-)
-from rhosocial.activerecord.backend.expression.statements import (
- ColumnConstraint,
-)
-
-from .scenarios import get_enabled_scenarios, get_scenario
-from rhosocial.activerecord.backend.expression.objects import Table
-
-
-class PartitionProvider(IPartitionProvider):
- """Concrete partition provider backed by real PostgreSQL scenarios."""
-
- TABLE_NAME = "ar_testsuite_partition_events"
- PARTITIONS = {
- "p2026_01": ("ar_testsuite_partition_events_p2026_01", "2026-01-01", "2026-02-01"),
- "p2026_02": ("ar_testsuite_partition_events_p2026_02", "2026-02-01", "2026-03-01"),
- "p2026_03": ("ar_testsuite_partition_events_p2026_03", "2026-03-01", "2026-04-01"),
- }
-
- def __init__(self):
- self._active_backends = []
- self._active_async_backends = []
-
- def get_test_scenarios(self) -> List[str]:
- """Return PostgreSQL scenarios configured for real backend tests."""
- return list(get_enabled_scenarios().keys())
-
- def get_partition_capabilities(self, scenario_name: str) -> Dict[str, bool]:
- backend = self._ensure_backend(scenario_name)
- return self._capabilities(backend)
-
- async def async_get_partition_capabilities(self, scenario_name: str) -> Dict[str, bool]:
- backend = await self._ensure_async_backend(scenario_name)
- return self._capabilities(backend)
-
- def setup_range_partitioned_event_fixtures(
- self,
- scenario_name: str,
- ) -> Tuple[Type[ActiveRecord], ...]:
- backend = self._ensure_backend(scenario_name)
- self._reset_partition_table(backend)
- Event = self._event_model(backend)
- return (Event,)
-
- async def setup_async_range_partitioned_event_fixtures(
- self,
- scenario_name: str,
- ) -> Tuple[Type[ActiveRecord], ...]:
- backend = await self._ensure_async_backend(scenario_name)
- await self._reset_partition_table_async(backend)
- Event = self._async_event_model(backend)
- return (Event,)
-
- def add_future_range_partition(self, scenario_name: str) -> None:
- backend = self._ensure_backend(scenario_name)
- name, from_value, to_value = self.PARTITIONS["p2026_03"]
- sql, params = self._create_range_partition_sql(backend.dialect, name, from_value, to_value)
- backend.execute(sql, params)
-
- async def async_add_future_range_partition(self, scenario_name: str) -> None:
- backend = await self._ensure_async_backend(scenario_name)
- name, from_value, to_value = self.PARTITIONS["p2026_03"]
- sql, params = self._create_range_partition_sql(backend.dialect, name, from_value, to_value)
- await backend.execute(sql, params)
-
- def truncate_partition(self, scenario_name: str, partition_key: str) -> None:
- backend = self._ensure_backend(scenario_name)
- sql, params = self._truncate_partition_sql(backend.dialect, self._partition_name(partition_key))
- backend.execute(sql, params)
-
- async def async_truncate_partition(self, scenario_name: str, partition_key: str) -> None:
- backend = await self._ensure_async_backend(scenario_name)
- sql, params = self._truncate_partition_sql(backend.dialect, self._partition_name(partition_key))
- await backend.execute(sql, params)
-
- def detach_partition(self, scenario_name: str, partition_key: str) -> None:
- backend = self._ensure_backend(scenario_name)
- sql, params = self._detach_partition_sql(backend.dialect, self._partition_name(partition_key))
- backend.execute(sql, params)
-
- async def async_detach_partition(self, scenario_name: str, partition_key: str) -> None:
- backend = await self._ensure_async_backend(scenario_name)
- sql, params = self._detach_partition_sql(backend.dialect, self._partition_name(partition_key))
- await backend.execute(sql, params)
-
- def attach_partition(self, scenario_name: str, partition_key: str) -> None:
- backend = self._ensure_backend(scenario_name)
- name, from_value, to_value = self.PARTITIONS[partition_key]
- sql, params = self._attach_partition_sql(backend.dialect, name, from_value, to_value)
- backend.execute(sql, params)
-
- async def async_attach_partition(self, scenario_name: str, partition_key: str) -> None:
- backend = await self._ensure_async_backend(scenario_name)
- name, from_value, to_value = self.PARTITIONS[partition_key]
- sql, params = self._attach_partition_sql(backend.dialect, name, from_value, to_value)
- await backend.execute(sql, params)
-
- def get_partition_metadata(self, scenario_name: str) -> Dict[str, Any]:
- backend = self._ensure_backend(scenario_name)
- return self._metadata(backend)
-
- async def async_get_partition_metadata(self, scenario_name: str) -> Dict[str, Any]:
- backend = await self._ensure_async_backend(scenario_name)
- return await self._metadata_async(backend)
-
- def create_valid_unique_constraint(self, scenario_name: str) -> None:
- backend = self._ensure_backend(scenario_name)
- backend.execute(
- f'CREATE UNIQUE INDEX IF NOT EXISTS "{self.TABLE_NAME}_id_created_at_uq" '
- f'ON "{self.TABLE_NAME}" (id, created_at)'
- )
-
- async def async_create_valid_unique_constraint(self, scenario_name: str) -> None:
- backend = await self._ensure_async_backend(scenario_name)
- await backend.execute(
- f'CREATE UNIQUE INDEX IF NOT EXISTS "{self.TABLE_NAME}_id_created_at_uq" '
- f'ON "{self.TABLE_NAME}" (id, created_at)'
- )
-
- def create_invalid_unique_constraint(self, scenario_name: str) -> None:
- backend = self._ensure_backend(scenario_name)
- backend.execute(
- f'CREATE UNIQUE INDEX "{self.TABLE_NAME}_id_only_uq" '
- f'ON "{self.TABLE_NAME}" (id)'
- )
-
- async def async_create_invalid_unique_constraint(self, scenario_name: str) -> None:
- backend = await self._ensure_async_backend(scenario_name)
- await backend.execute(
- f'CREATE UNIQUE INDEX "{self.TABLE_NAME}_id_only_uq" '
- f'ON "{self.TABLE_NAME}" (id)'
- )
-
- def cleanup_after_test(self, scenario_name: str) -> None:
- """Drop partition test tables and disconnect sync backends."""
- for backend in self._active_backends:
- try:
- self._drop_partition_tables(backend)
- finally:
- backend.disconnect()
- self._active_backends.clear()
-
- async def cleanup_after_test_async(self, scenario_name: str) -> None:
- """Drop partition test tables and disconnect async backends."""
- for backend in self._active_async_backends:
- try:
- await self._drop_partition_tables_async(backend)
- finally:
- await backend.disconnect()
- self._active_async_backends.clear()
-
- def _ensure_backend(self, scenario_name: str):
- if self._active_backends:
- return self._active_backends[0]
- backend_class, config = get_scenario(scenario_name)
- backend = backend_class(connection_config=config)
- backend.connect()
- backend.introspect_and_adapt()
- self._active_backends.append(backend)
- return backend
-
- async def _ensure_async_backend(self, scenario_name: str):
- if self._active_async_backends:
- return self._active_async_backends[0]
- _, config = get_scenario(scenario_name)
- backend = AsyncPostgresBackend(connection_config=config)
- await backend.connect()
- await backend.introspect_and_adapt()
- self._active_async_backends.append(backend)
- return backend
-
- def _capabilities(self, backend) -> Dict[str, bool]:
- dialect = backend.dialect
- supports_creation = dialect.supports_partitioned_table_creation()
- supports_pg11 = dialect.version >= (11, 0, 0)
- return {
- "range_partitioning": supports_creation and dialect.supports_range_table_partitioning(),
- "add_partition": dialect.supports_add_partition(),
- "truncate_partition": dialect.supports_truncate_partition(),
- "detach_partition": dialect.supports_detach_partition(),
- "attach_partition": dialect.supports_attach_partition(),
- "partition_introspection": dialect.supports_partition_metadata_introspection(),
- "partition_bounds": dialect.supports_partition_bounds_expression(),
- "partitioned_unique_constraint": supports_creation and supports_pg11,
- "unique_requires_partition_key": supports_creation and supports_pg11,
- }
-
- def _reset_partition_table(self, backend) -> None:
- self._drop_partition_tables(backend)
- sql, params = self._create_parent_sql(backend.dialect)
- backend.execute(sql, params)
- for key in ("p2026_01", "p2026_02"):
- name, from_value, to_value = self.PARTITIONS[key]
- sql, params = self._create_range_partition_sql(backend.dialect, name, from_value, to_value)
- backend.execute(sql, params)
-
- async def _reset_partition_table_async(self, backend) -> None:
- await self._drop_partition_tables_async(backend)
- sql, params = self._create_parent_sql(backend.dialect)
- await backend.execute(sql, params)
- for key in ("p2026_01", "p2026_02"):
- name, from_value, to_value = self.PARTITIONS[key]
- sql, params = self._create_range_partition_sql(backend.dialect, name, from_value, to_value)
- await backend.execute(sql, params)
-
- def _drop_partition_tables(self, backend) -> None:
- for table_name in self._all_table_names():
- sql, params = self._drop_partition_sql(backend.dialect, table_name)
- backend.execute(sql, params)
-
- async def _drop_partition_tables_async(self, backend) -> None:
- for table_name in self._all_table_names():
- sql, params = self._drop_partition_sql(backend.dialect, table_name)
- await backend.execute(sql, params)
-
- def _all_table_names(self) -> Tuple[str, ...]:
- return tuple(partition[0] for partition in self.PARTITIONS.values()) + (self.TABLE_NAME,)
-
- def _partition_name(self, partition_key: str) -> str:
- return self.PARTITIONS[partition_key][0]
-
- def _create_parent_sql(self, dialect):
- expr = CreateTableStatement(
- dialect=dialect,
- table=self.TABLE_NAME,
- columns=[
- PostgresColumnDefinition(dialect, "id", BigIntType(dialect=dialect), attributes=[IdentityAttribute(generation="BY DEFAULT")]),
- ColumnDefinition(dialect, "created_at", TimestampType(dialect=dialect), constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "tenant_id", IntegerType(dialect=dialect), constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
- ColumnDefinition(dialect, "payload", TextType(dialect=dialect)),
- ColumnDefinition(dialect, "amount", DecimalType(precision=12, scale=2, dialect=dialect)),
- ],
- partition=PartitionClause(
- dialect=dialect,
- method=PartitionStrategy.RANGE,
- keys=[Column(dialect, "created_at")],
- ),
- )
- return expr.to_sql()
-
- def _create_range_partition_sql(self, dialect, partition_name: str, from_value: str, to_value: str):
- expr = PostgresCreatePartitionStatement(
- dialect=dialect,
- partition_name=partition_name,
- parent_table=self.TABLE_NAME,
- partition_type="RANGE",
- partition_values={"from": from_value, "to": to_value},
- )
- return expr.to_sql()
-
- def _detach_partition_sql(self, dialect, partition_name: str):
- expr = PostgresDetachPartitionStatement(
- dialect=dialect,
- partition_name=partition_name,
- parent_table=self.TABLE_NAME,
- )
- return expr.to_sql()
-
- def _attach_partition_sql(self, dialect, partition_name: str, from_value: str, to_value: str):
- expr = PostgresAttachPartitionStatement(
- dialect=dialect,
- partition_name=partition_name,
- parent_table=self.TABLE_NAME,
- partition_type="RANGE",
- partition_values={"from": from_value, "to": to_value},
- )
- return expr.to_sql()
-
- def _truncate_partition_sql(self, dialect, partition_name: str):
- expr = TruncateStatement(dialect=dialect, table=Table(dialect, partition_name))
- return expr.to_sql()
-
- def _drop_partition_sql(self, dialect, table_name: str):
- expr = DropTableStatement(
- dialect=dialect,
- table=Table(dialect, table_name),
- if_exists=True,
- cascade=True,
- )
- return expr.to_sql()
-
- def _partition_metadata_sql(self, dialect):
- expr = PostgresPartitionMetadataQueryStatement(
- dialect=dialect,
- parent_table=self.TABLE_NAME,
- )
- return expr.to_sql()
-
- def _event_model(self, backend):
- table_name = self.TABLE_NAME
-
- class PartitionEvent(ActiveRecord):
- @classmethod
- def table_name(cls):
- return table_name
-
- __backend__ = backend
- c: ClassVar[FieldProxy] = FieldProxy()
-
- id: Optional[int] = None
- created_at: datetime
- tenant_id: int
- payload: Optional[str] = None
- amount: Optional[Decimal] = None
-
- return PartitionEvent
-
- def _async_event_model(self, backend):
- table_name = self.TABLE_NAME
-
- class AsyncPartitionEvent(AsyncActiveRecord):
- @classmethod
- def table_name(cls):
- return table_name
-
- __backend__ = backend
- c: ClassVar[FieldProxy] = FieldProxy()
-
- id: Optional[int] = None
- created_at: datetime
- tenant_id: int
- payload: Optional[str] = None
- amount: Optional[Decimal] = None
-
- return AsyncPartitionEvent
-
- def _metadata(self, backend) -> Dict[str, Any]:
- sql, params = self._partition_metadata_sql(backend.dialect)
- rows = backend.fetch_all(sql, params)
- return self._metadata_dict(rows)
-
- async def _metadata_async(self, backend) -> Dict[str, Any]:
- sql, params = self._partition_metadata_sql(backend.dialect)
- rows = await backend.fetch_all(sql, params)
- return self._metadata_dict(rows)
-
- def _metadata_dict(self, rows) -> Dict[str, Any]:
- first = rows[0] if rows else None
- partition_key = first["partition_key"] if first else ""
- return {
- "is_partitioned": bool(partition_key),
- "strategy": "range" if partition_key.upper().startswith("RANGE") else "unknown",
- "key_columns": ["created_at"] if "created_at" in partition_key.lower() else [],
- "partitions": [
- {"name": row["name"], "bound": row["bound"]}
- for row in rows
- if row["name"] is not None
- ],
- }
diff --git a/tests/providers/pooling.py b/tests/providers/pooling.py
deleted file mode 100644
index 40186779..00000000
--- a/tests/providers/pooling.py
+++ /dev/null
@@ -1,132 +0,0 @@
-# tests/providers/pooling.py
-"""Database pooling helpers for the PostgreSQL test providers.
-
-Under parallel (pytest-xdist) runs with a positive pool size the providers
-reuse a per-worker pooled database ``{database}_{index}`` on the scenario's
-PostgreSQL server instead of the shared scenario ``database`` schema, so
-scenario variants of the same test can run concurrently on different workers
-without conflicting. The pool name prefix is derived from the scenario's
-configured ``database`` (the YAML ``database`` field), so e.g.
-``database: test_db`` produces pooled databases ``test_db_0``, ``test_db_1``,
-... Serial runs (no ``-n``) keep the previous behaviour: the provider connects
-to the scenario's configured ``database``.
-
-The scenario name selects the server (host/port); the pool index selects the
-database name. The two are deliberately unrelated.
-"""
-
-import psycopg
-
-from rhosocial.activerecord.testsuite.core.pool import (
- pooled_database_name,
- register_base_database,
- register_pool_reset_handler,
-)
-
-from .scenarios import SCENARIO_MAP, get_scenario_raw
-
-# Derive each scenario's pooled-database base name from its configured
-# ``database`` (YAML ``database`` field). Registered at import time so any
-# caller of pooled_database_name() / resolve_database_name() resolves names
-# consistent with the scenario configuration.
-for _scenario_name, _scenario_config in SCENARIO_MAP.items():
- register_base_database(_scenario_name, _scenario_config["database"])
-
-
-def resolve_database_name(scenario_name: str):
- """
- Return the pooled database name (e.g. ``test_db_3``) used by a test for
- the given scenario, or ``None`` when pooling is inactive (callers then fall
- back to the scenario's configured database).
- """
- return pooled_database_name(scenario_name)
-
-
-def _escape_identifier(name: str) -> str:
- """Escape a PostgreSQL identifier for use inside double quotes."""
- return name.replace('"', '""')
-
-
-def _connect_maintenance(config) -> psycopg.Connection:
- """Connect to a maintenance database (``postgres`` or the configured one)."""
- for dbname in ("postgres", config.database):
- try:
- return psycopg.connect(
- host=config.host,
- port=config.port,
- dbname=dbname,
- user=config.username,
- password=config.password,
- connect_timeout=10,
- autocommit=True,
- )
- except psycopg.Error:
- continue
- return None
-
-
-def _reset_postgres_database(scenario_name: str, db_name: str) -> None:
- """Ensure the pooled database exists and is empty on the scenario's server.
-
- Connects to the server selected by ``scenario_name``, creates the pooled
- ``db_name`` database if missing, and drops all leftover non-extension
- tables so the test starts from a clean state. Extension-owned tables are
- preserved (e.g. PostGIS metadata). Errors are swallowed: a failed reset
- must not hide the underlying test failure.
- """
- if scenario_name not in SCENARIO_MAP:
- return
- _, config = get_scenario_raw(scenario_name)
- try:
- admin_conn = _connect_maintenance(config)
- if admin_conn is None:
- return
- try:
- with admin_conn.cursor() as cursor:
- cursor.execute("SELECT 1 FROM pg_database WHERE datname = %s", (db_name,))
- if cursor.fetchone() is None:
- cursor.execute(f'CREATE DATABASE "{_escape_identifier(db_name)}"')
- finally:
- admin_conn.close()
- except Exception:
- return
-
- try:
- conn = psycopg.connect(
- host=config.host,
- port=config.port,
- dbname=db_name,
- user=config.username,
- password=config.password,
- connect_timeout=10,
- autocommit=True,
- )
- try:
- with conn.cursor() as cursor:
- cursor.execute(
- """
- SELECT n.nspname, c.relname
- FROM pg_class c
- JOIN pg_namespace n ON n.oid = c.relnamespace
- WHERE c.relkind IN ('r', 'p', 'm')
- AND n.nspname NOT IN ('pg_catalog', 'information_schema')
- AND NOT EXISTS (
- SELECT 1 FROM pg_depend d
- JOIN pg_extension e ON d.refobjid = e.oid
- WHERE d.classid = 'pg_class'::regclass
- AND d.objid = c.oid
- AND d.deptype = 'e'
- )
- """
- )
- for schema, table in cursor.fetchall():
- cursor.execute(
- f'DROP TABLE IF EXISTS "{_escape_identifier(schema)}"."{_escape_identifier(table)}" CASCADE'
- )
- finally:
- conn.close()
- except Exception:
- pass
-
-
-register_pool_reset_handler(_reset_postgres_database)
diff --git a/tests/providers/query.py b/tests/providers/query.py
deleted file mode 100644
index 142790bc..00000000
--- a/tests/providers/query.py
+++ /dev/null
@@ -1,694 +0,0 @@
-"""
-This file provides the concrete implementation of the `IQueryProvider` interface
-that is defined in the `rhosocial-activerecord-testsuite` package.
-
-Its main responsibilities are:
-1. Reporting which test scenarios (database configurations) are available.
-2. Setting up the database environment for a given test. This includes:
- - Getting the correct database configuration for the scenario.
- - Configuring the ActiveRecord model with a database connection.
- - Dropping any old tables and creating the necessary table schema.
-3. Cleaning up any resources (like temporary database files) after a test runs.
-"""
-import os
-import sys
-import logging
-from typing import Set, Type, List, Tuple
-
-from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord
-
-# Setup logging for fixture selection debugging
-logger = logging.getLogger(__name__)
-
-# Import the fixture selector utility
-from rhosocial.activerecord.testsuite.utils import select_fixture # noqa: E402
-
-# Import base version models (Python 3.8+)
-from rhosocial.activerecord.testsuite.feature.query.fixtures.models import ( # noqa: E402
- User as UserBase, JsonUser as JsonUserBase,
- Order as OrderBase, OrderItem as OrderItemBase,
- Post as PostBase, Comment as CommentBase,
- Profile as ProfileBase,
- MappedUser as MappedUserBase, MappedPost as MappedPostBase, MappedComment as MappedCommentBase
-)
-from rhosocial.activerecord.testsuite.feature.query.fixtures.cte_models import Node # noqa: E402
-from rhosocial.activerecord.testsuite.feature.query.fixtures.extended_models import ExtendedOrder, ExtendedOrderItem # noqa: E402
-
-# Conditionally import Python 3.10+ models
-User310 = JsonUser310 = Order310 = OrderItem310 = Post310 = Comment310 = Profile310 = None
-MappedUser310 = MappedPost310 = MappedComment310 = None
-
-if sys.version_info >= (3, 10):
- try:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.models_py310 import (
- User as User310, JsonUser as JsonUser310,
- Order as Order310, OrderItem as OrderItem310,
- Post as Post310, Comment as Comment310,
- Profile as Profile310,
- MappedUser as MappedUser310, MappedPost as MappedPost310, MappedComment as MappedComment310
- )
- except ImportError as e:
- logger.warning(f"Failed to import Python 3.10+ fixtures: {e}")
-
-# Conditionally import Python 3.11+ models
-User311 = JsonUser311 = Order311 = OrderItem311 = Post311 = Comment311 = Profile311 = None
-MappedUser311 = MappedPost311 = MappedComment311 = None
-
-if sys.version_info >= (3, 11):
- try:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.models_py311 import (
- User as User311, JsonUser as JsonUser311,
- Order as Order311, OrderItem as OrderItem311,
- Post as Post311, Comment as Comment311,
- Profile as Profile311,
- MappedUser as MappedUser311, MappedPost as MappedPost311, MappedComment as MappedComment311
- )
- except ImportError as e:
- logger.warning(f"Failed to import Python 3.11+ fixtures: {e}")
-
-# Conditionally import Python 3.12+ models
-User312 = JsonUser312 = Order312 = OrderItem312 = Post312 = Comment312 = Profile312 = None
-MappedUser312 = MappedPost312 = MappedComment312 = None
-
-if sys.version_info >= (3, 12):
- try:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.models_py312 import (
- User as User312, JsonUser as JsonUser312,
- Order as Order312, OrderItem as OrderItem312,
- Post as Post312, Comment as Comment312,
- Profile as Profile312,
- MappedUser as MappedUser312, MappedPost as MappedPost312, MappedComment as MappedComment312
- )
- except ImportError as e:
- logger.warning(f"Failed to import Python 3.12+ fixtures: {e}")
-
-
-# Select appropriate fixture classes based on Python version
-def _select_model_class(base_cls, py312_cls, py311_cls, py310_cls, model_name: str) -> Type:
- """Select the most appropriate model class for the current Python version."""
- candidates = [c for c in [py312_cls, py311_cls, py310_cls, base_cls] if c is not None]
- selected = select_fixture(*candidates)
- logger.info(f"Selected {model_name}: {selected.__name__} from {selected.__module__}")
- return selected
-
-
-# Select sync models
-User = _select_model_class(UserBase, User312, User311, User310, "User")
-JsonUser = _select_model_class(JsonUserBase, JsonUser312, JsonUser311, JsonUser310, "JsonUser")
-Order = _select_model_class(OrderBase, Order312, Order311, Order310, "Order")
-OrderItem = _select_model_class(OrderItemBase, OrderItem312, OrderItem311, OrderItem310, "OrderItem")
-Post = _select_model_class(PostBase, Post312, Post311, Post310, "Post")
-Comment = _select_model_class(CommentBase, Comment312, Comment311, Comment310, "Comment")
-MappedUser = _select_model_class(MappedUserBase, MappedUser312, MappedUser311, MappedUser310, "MappedUser")
-MappedPost = _select_model_class(MappedPostBase, MappedPost312, MappedPost311, MappedPost310, "MappedPost")
-MappedComment = _select_model_class(MappedCommentBase, MappedComment312, MappedComment311, MappedComment310, "MappedComment") # noqa: E501
-Profile = _select_model_class(ProfileBase, Profile312, Profile311, Profile310, "Profile")
-
-from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType # noqa: E402
-from rhosocial.activerecord.testsuite.feature.query.interfaces import IQuerySyncProvider, IQueryAsyncProvider # noqa: E402
-from rhosocial.activerecord.testsuite.core.protocols import WorkerTestProtocol # noqa: E402
-
-# Composite-PK model classes used by setup_order_item_model.
-from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( # noqa: E402
- OrderItem as CompositeOrderItemBase,
- AsyncOrderItem as AsyncCompositeOrderItemBase,
-)
-
-# Expression-based DDL fixtures
-from providers.fixtures._common import drop_table # noqa: E402
-from providers.fixtures.query import TABLE_EXPRESSIONS as QUERY_TABLE_EXPRESSIONS # noqa: E402
-
-# The scenarios are defined specifically for this backend.
-from .scenarios import get_enabled_scenarios, get_scenario # noqa: E402
-
-
-class QueryProviderBase:
- def __init__(self):
- self._active_backends = []
- self._created_tables: Set[str] = set()
- self._created_schemas: Set[str] = set()
- self._mixed_schema_provisioned = False
-
- def supports_schema(self) -> bool:
- """PostgreSQL models named schema namespaces natively."""
- return True
-
- def get_test_scenarios(self) -> List[str]:
- return list(get_enabled_scenarios().keys())
-
- def _provision_cross_schema(self, backend_instance) -> None:
- """Create the two cross-schema fixture namespaces, tables and seeds."""
- from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import (
- SCHEMA_A,
- SCHEMA_B,
- )
-
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- statements = []
- for schema in (SCHEMA_A, SCHEMA_B):
- statements.append(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE')
- statements.append(f'CREATE SCHEMA "{schema}"')
- statements.append(
- f'CREATE TABLE "{SCHEMA_A}".customers '
- f'(id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL)'
- )
- statements.append(
- f'CREATE TABLE "{SCHEMA_B}".orders '
- f'(id SERIAL PRIMARY KEY, customer_id INTEGER NOT NULL, amount INTEGER NOT NULL)'
- )
- for sql in statements:
- backend_instance.execute(sql, options=opts)
- self._created_schemas.update((SCHEMA_A, SCHEMA_B))
-
- def _provision_mixed_schema_sync(self, backend_instance) -> None:
- """Provision an identical orders table in SCHEMA_A (default stays untouched)."""
- from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import (
- SCHEMA_A,
- )
-
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- statements = [
- f'DROP SCHEMA IF EXISTS "{SCHEMA_A}" CASCADE',
- f'CREATE SCHEMA "{SCHEMA_A}"',
- f'CREATE TABLE "{SCHEMA_A}".orders ('
- "id SERIAL PRIMARY KEY, user_id INTEGER NOT NULL, "
- "order_number VARCHAR(255) NOT NULL, "
- "total_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00, "
- "status VARCHAR(50) NOT NULL DEFAULT 'pending', "
- "created_at TIMESTAMP WITH TIME ZONE, updated_at TIMESTAMP WITH TIME ZONE)",
- ]
- for sql in statements:
- backend_instance.execute(sql, options=opts)
- self._mixed_schema_provisioned = True
-
- async def _provision_mixed_schema_async(self, backend_instance) -> None:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import (
- SCHEMA_A,
- )
-
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- statements = [
- f'DROP SCHEMA IF EXISTS "{SCHEMA_A}" CASCADE',
- f'CREATE SCHEMA "{SCHEMA_A}"',
- f'CREATE TABLE "{SCHEMA_A}".orders ('
- "id SERIAL PRIMARY KEY, user_id INTEGER NOT NULL, "
- "order_number VARCHAR(255) NOT NULL, "
- "total_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00, "
- "status VARCHAR(50) NOT NULL DEFAULT 'pending', "
- "created_at TIMESTAMP WITH TIME ZONE, updated_at TIMESTAMP WITH TIME ZONE)",
- ]
- for sql in statements:
- await backend_instance.execute(sql, options=opts)
- self._mixed_schema_provisioned = True
-
- def _track_backend(self, backend_instance, collection):
- if backend_instance not in collection:
- collection.append(backend_instance)
-
- def _load_postgres_schema(self, filename: str) -> str:
- schema_dir = os.path.join(
- os.path.dirname(__file__), "..", "rhosocial", "activerecord_postgres_test", "feature", "query", "schema"
- )
- schema_path = os.path.join(schema_dir, filename)
- with open(schema_path, 'r', encoding='utf-8') as f:
- return f.read()
-
-
-class QuerySyncProvider(QueryProviderBase, IQuerySyncProvider, WorkerTestProtocol):
-
- def __init__(self):
- super().__init__()
- self._active_backends = []
-
- def _setup_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str, shared_backend=None) -> Type[ActiveRecord]:
- backend_class, config = get_scenario(scenario_name)
- if shared_backend is None:
- model_class.configure(config, backend_class)
- else:
- model_class.__connection_config__ = config
- model_class.__backend_class__ = backend_class
- model_class.__backend__ = shared_backend
- backend_instance = model_class.__backend__
- self._track_backend(backend_instance, self._active_backends)
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- try:
- sql, params = drop_table(backend_instance.dialect, table_name).to_sql()
- backend_instance.execute(sql, params, options=opts)
- except Exception:
- pass
- if fn := QUERY_TABLE_EXPRESSIONS.get(table_name):
- create_expr = fn(backend_instance.dialect, table_name)
- sql, params = create_expr.to_sql()
- backend_instance.execute(sql, params, options=opts)
- self._created_tables.add(table_name)
- return model_class
-
- def _setup_multiple_models(self, models_and_tables: List[Tuple[Type[ActiveRecord], str]], scenario_name: str) -> Tuple[Type[ActiveRecord], ...]:
- result = []
- shared_backend = None
- for i, (model_class, table_name) in enumerate(models_and_tables):
- if i == 0:
- configured_model = self._setup_model(model_class, scenario_name, table_name)
- shared_backend = configured_model.__backend__
- else:
- configured_model = self._setup_model(model_class, scenario_name, table_name, shared_backend=shared_backend)
- result.append(configured_model)
- return tuple(result)
-
- def setup_order_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- models_and_tables = [
- (User, "users"),
- (Order, "orders"),
- (OrderItem, "order_items")
- ]
- return self._setup_multiple_models(models_and_tables, scenario_name)
-
- def setup_blog_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- models_and_tables = [
- (User, "users"),
- (Post, "posts"),
- (Comment, "comments")
- ]
- return self._setup_multiple_models(models_and_tables, scenario_name)
-
- def setup_json_user_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]:
- from rhosocial.activerecord.backend.impl.postgres.adapters import PostgresJSONBAdapter
- jsonb_adapter = PostgresJSONBAdapter()
- json_fields = ["settings", "tags", "profile", "roles", "scores", "subscription", "preferences"]
- for field_name in json_fields:
- if field_name not in JsonUser.__field_adapters__:
- JsonUser.__field_adapters__[field_name] = (jsonb_adapter, str)
- models_and_tables = [
- (JsonUser, "json_users"),
- ]
- return self._setup_multiple_models(models_and_tables, scenario_name)
-
- def setup_tree_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]:
- models_and_tables = [
- (Node, "nodes"),
- ]
- return self._setup_multiple_models(models_and_tables, scenario_name)
-
- def setup_extended_order_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- models_and_tables = [
- (User, "users"),
- (ExtendedOrder, "extended_orders"),
- (ExtendedOrderItem, "extended_order_items")
- ]
- return self._setup_multiple_models(models_and_tables, scenario_name)
-
- def setup_combined_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- models_and_tables = [
- (User, "users"),
- (Order, "orders"),
- (OrderItem, "order_items"),
- (Post, "posts"),
- (Comment, "comments")
- ]
- return self._setup_multiple_models(models_and_tables, scenario_name)
-
- def setup_annotated_query_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.annotated_adapter_models import SearchableItem
- return self._setup_multiple_models([
- (SearchableItem, "searchable_items"),
- ], scenario_name)
-
- def setup_mapped_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- return self._setup_multiple_models([
- (MappedUser, "users"),
- (MappedPost, "posts"),
- (MappedComment, "comments")
- ], scenario_name)
-
- def setup_profile_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord]]:
- return self._setup_multiple_models([
- (User, "users"),
- (Profile, "profiles"),
- ], scenario_name)
-
- def setup_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]:
- """Set up the composite-PK OrderItem model for the query feature tests."""
- from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType
- from providers.fixtures._common import drop_table
- from providers.fixtures.basic import TABLE_EXPRESSIONS as BASIC_EXPRS
-
- backend_class, config = get_scenario(scenario_name)
- CompositeOrderItemBase.configure(config, backend_class)
- backend_instance = CompositeOrderItemBase.__backend__
- self._track_backend(backend_instance, self._active_backends)
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- try:
- sql, params = drop_table(backend_instance.dialect, "order_items").to_sql()
- backend_instance.execute(sql, params, options=opts)
- except Exception:
- pass
- if fn := BASIC_EXPRS.get("order_items"):
- create_expr = fn(backend_instance.dialect, "order_items")
- sql, params = create_expr.to_sql()
- backend_instance.execute(sql, params, options=opts)
- self._created_tables.add("order_items")
- return CompositeOrderItemBase
-
- def setup_schema_fixtures(self, scenario_name: str):
- """Two models in two distinct schemas (see testsuite schema_models)."""
- from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import (
- SchemaCustomer,
- SchemaOrder,
- )
-
- backend_class, config = get_scenario(scenario_name)
- SchemaCustomer.configure(config, backend_class)
- SchemaOrder.configure(config, backend_class)
- shared_backend = SchemaCustomer.__backend__
- self._track_backend(shared_backend, self._active_backends)
- self._provision_cross_schema(shared_backend)
- return SchemaCustomer, SchemaOrder
-
- def setup_mixed_schema_fixtures(self, scenario_name: str):
- """(User, Order, MixedSchemaOrder): default users/orders plus orders in SCHEMA_A."""
- from rhosocial.activerecord.testsuite.feature.query.cross_schema.mixed_schema_models import (
- MixedSchemaOrder,
- )
- from rhosocial.activerecord.testsuite.feature.query.fixtures.models import Order, User
-
- user_model = self._setup_model(User, scenario_name, "users")
- shared_backend = user_model.__backend__
- order_model = self._setup_model(Order, scenario_name, "orders", shared_backend)
-
- backend_class, config = get_scenario(scenario_name)
- MixedSchemaOrder.__connection_config__ = config
- MixedSchemaOrder.__backend_class__ = backend_class
- MixedSchemaOrder.__backend__ = shared_backend
- self._track_backend(shared_backend, self._active_backends)
- self._provision_mixed_schema_sync(shared_backend)
- return user_model, order_model, MixedSchemaOrder
-
- def _get_schema_sql_for_fixture_type(self, fixture_type: str) -> dict:
- schemas = {}
- if fixture_type == 'order':
- tables = ['users', 'orders', 'order_items']
- elif fixture_type == 'blog':
- tables = ['users', 'posts', 'comments']
- elif fixture_type == 'user':
- tables = ['users']
- elif fixture_type == 'combined':
- tables = ['users', 'orders', 'order_items', 'posts', 'comments']
- else:
- tables = ['users']
- for table in tables:
- schemas[table] = self._load_postgres_schema(f'{table}.sql')
- return schemas
-
- def get_worker_connection_params(self, scenario_name: str, fixture_type: str = 'order') -> dict:
- from .scenarios import SCENARIO_MAP
- is_async = fixture_type and fixture_type.startswith('async_')
- backend_class_name = 'AsyncPostgresBackend' if is_async else 'PostgresBackend'
- base_fixture_type = fixture_type.replace('async_', '') if fixture_type else 'order'
- schema_sql = self._get_schema_sql_for_fixture_type(base_fixture_type)
- if scenario_name not in SCENARIO_MAP:
- if SCENARIO_MAP:
- scenario_name = next(iter(SCENARIO_MAP))
- else:
- raise ValueError("No scenarios registered")
- config_dict = SCENARIO_MAP[scenario_name]
- from .pooling import resolve_database_name
-
- pooled_db = resolve_database_name(scenario_name)
- if pooled_db:
- config_dict = {**config_dict, "database": pooled_db}
- return {
- 'backend_module': 'rhosocial.activerecord.backend.impl.postgres.backend',
- 'backend_class_name': backend_class_name,
- 'config_class_module': 'rhosocial.activerecord.backend.impl.postgres.config',
- 'config_class_name': 'PostgresConnectionConfig',
- 'config_kwargs': config_dict,
- 'schema_sql': schema_sql,
- }
-
- def get_worker_schema_sql(self, scenario_name: str, table_name: str) -> str:
- return self._load_postgres_schema(f'{table_name}.sql')
-
- def cleanup_after_test(self, scenario_name: str):
- for backend_instance in self._active_backends:
- try:
- for table_name in list(self._created_tables):
- try:
- backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE')
- except Exception:
- pass
- finally:
- try:
- backend_instance.disconnect()
- except Exception:
- pass
- for schema_name in list(self._created_schemas):
- try:
- backend_instance.execute(f'DROP SCHEMA IF EXISTS "{schema_name}" CASCADE')
- except Exception:
- pass
- if self._mixed_schema_provisioned:
- try:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import (
- SCHEMA_A,
- )
-
- backend_instance.execute(f'DROP SCHEMA IF EXISTS "{SCHEMA_A}" CASCADE')
- except Exception:
- pass
- self._mixed_schema_provisioned = False
- self._active_backends.clear()
- self._created_tables.clear()
- self._created_schemas.clear()
-
-
-class QueryAsyncProvider(QueryProviderBase, IQueryAsyncProvider):
-
- def __init__(self):
- super().__init__()
- self._active_async_backends = []
-
- async def _setup_async_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str, shared_backend=None) -> Type[ActiveRecord]:
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
- _, config = get_scenario(scenario_name)
- if shared_backend is None:
- await model_class.configure(config, AsyncPostgresBackend)
- else:
- model_class.__connection_config__ = config
- model_class.__backend_class__ = AsyncPostgresBackend
- model_class.__backend__ = shared_backend
- backend_instance = model_class.__backend__
- self._track_backend(backend_instance, self._active_async_backends)
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- try:
- sql, params = drop_table(backend_instance.dialect, table_name).to_sql()
- await backend_instance.execute(sql, params, options=opts)
- except Exception:
- pass
- if fn := QUERY_TABLE_EXPRESSIONS.get(table_name):
- create_expr = fn(backend_instance.dialect, table_name)
- sql, params = create_expr.to_sql()
- await backend_instance.execute(sql, params, options=opts)
- self._created_tables.add(table_name)
- return model_class
-
- async def _setup_multiple_models_async(self, models_and_tables: List[Tuple[Type[ActiveRecord], str]], scenario_name: str) -> Tuple[Type[ActiveRecord], ...]:
- result = []
- shared_backend = None
- for i, (model_class, table_name) in enumerate(models_and_tables):
- if i == 0:
- configured_model = await self._setup_async_model(model_class, scenario_name, table_name)
- shared_backend = configured_model.__backend__
- else:
- configured_model = await self._setup_async_model(model_class, scenario_name, table_name, shared_backend=shared_backend)
- result.append(configured_model)
- return tuple(result)
-
- async def setup_order_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.async_models import AsyncUser, AsyncOrder, AsyncOrderItem
- return await self._setup_multiple_models_async([
- (AsyncUser, "users"),
- (AsyncOrder, "orders"),
- (AsyncOrderItem, "order_items")
- ], scenario_name)
-
- async def setup_blog_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.async_models import AsyncUser
- from rhosocial.activerecord.testsuite.feature.query.fixtures.async_blog_models import AsyncPost, AsyncComment
- return await self._setup_multiple_models_async([
- (AsyncUser, "users"),
- (AsyncPost, "posts"),
- (AsyncComment, "comments")
- ], scenario_name)
-
- async def setup_json_user_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.async_json_models import AsyncJsonUser
- from rhosocial.activerecord.backend.impl.postgres.adapters import PostgresJSONBAdapter
- jsonb_adapter = PostgresJSONBAdapter()
- json_fields = ["settings", "tags", "profile", "roles", "scores", "subscription", "preferences"]
- for field_name in json_fields:
- if field_name not in AsyncJsonUser.__field_adapters__:
- AsyncJsonUser.__field_adapters__[field_name] = (jsonb_adapter, str)
- return await self._setup_multiple_models_async([
- (AsyncJsonUser, "json_users"),
- ], scenario_name)
-
- async def setup_tree_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.async_cte_models import AsyncNode
- return await self._setup_multiple_models_async([
- (AsyncNode, "nodes"),
- ], scenario_name)
-
- async def setup_extended_order_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.async_extended_models import AsyncUser, AsyncExtendedOrder, AsyncExtendedOrderItem
- return await self._setup_multiple_models_async([
- (AsyncUser, "users"),
- (AsyncExtendedOrder, "extended_orders"),
- (AsyncExtendedOrderItem, "extended_order_items")
- ], scenario_name)
-
- async def setup_combined_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.async_models import AsyncUser, AsyncOrder, AsyncOrderItem
- from rhosocial.activerecord.testsuite.feature.query.fixtures.async_blog_models import AsyncPost, AsyncComment
- return await self._setup_multiple_models_async([
- (AsyncUser, "users"),
- (AsyncOrder, "orders"),
- (AsyncOrderItem, "order_items"),
- (AsyncPost, "posts"),
- (AsyncComment, "comments")
- ], scenario_name)
-
- async def setup_annotated_query_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.async_annotated_adapter_models import AsyncSearchableItem
- return await self._setup_multiple_models_async([
- (AsyncSearchableItem, "searchable_items"),
- ], scenario_name)
-
- async def setup_mapped_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import AsyncMappedUser, AsyncMappedPost, AsyncMappedComment
- return await self._setup_multiple_models_async([
- (AsyncMappedUser, "users"),
- (AsyncMappedPost, "posts"),
- (AsyncMappedComment, "comments")
- ], scenario_name)
-
- async def setup_profile_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], Type[ActiveRecord]]:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.async_models import AsyncUser, AsyncProfile
- return await self._setup_multiple_models_async([
- (AsyncUser, "users"),
- (AsyncProfile, "profiles"),
- ], scenario_name)
-
- async def setup_order_item_model(self, scenario_name: str) -> Type[AsyncActiveRecord]:
- """Set up the composite-PK AsyncOrderItem model for the query feature tests."""
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
- from rhosocial.activerecord.backend.options import ExecutionOptions, StatementType
- from providers.fixtures._common import drop_table
- from providers.fixtures.basic import TABLE_EXPRESSIONS as BASIC_EXPRS
-
- _, config = get_scenario(scenario_name)
- await AsyncCompositeOrderItemBase.configure(config, AsyncPostgresBackend)
- backend_instance = AsyncCompositeOrderItemBase.__backend__
- self._track_backend(backend_instance, self._active_async_backends)
- opts = ExecutionOptions(stmt_type=StatementType.DDL)
- try:
- sql, params = drop_table(backend_instance.dialect, "order_items").to_sql()
- await backend_instance.execute(sql, params, options=opts)
- except Exception:
- pass
- if fn := BASIC_EXPRS.get("order_items"):
- create_expr = fn(backend_instance.dialect, "order_items")
- sql, params = create_expr.to_sql()
- await backend_instance.execute(sql, params, options=opts)
- self._created_tables.add("order_items")
- return AsyncCompositeOrderItemBase
-
- async def setup_schema_fixtures(self, scenario_name: str):
- """Two async models in two distinct schemas."""
- from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import (
- AsyncSchemaCustomer,
- AsyncSchemaOrder,
- )
-
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
- from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
-
- _, config = get_scenario(scenario_name)
-
- # Provision DDL through a short-lived synchronous connection.
- ddl_backend = PostgresBackend(connection_config=config)
- ddl_backend.connect()
- try:
- self._provision_cross_schema(ddl_backend)
- finally:
- ddl_backend.disconnect()
-
- await AsyncSchemaCustomer.configure(config, AsyncPostgresBackend)
- await AsyncSchemaOrder.configure(config, AsyncPostgresBackend)
- shared_backend = AsyncSchemaCustomer.__backend__
- self._track_backend(shared_backend, self._active_async_backends)
- return AsyncSchemaCustomer, AsyncSchemaOrder
-
- async def cleanup_after_test(self, scenario_name: str):
- for backend_instance in self._active_async_backends:
- try:
- for table_name in list(self._created_tables):
- try:
- await backend_instance.execute(f'DROP TABLE IF EXISTS "{table_name}" CASCADE')
- except Exception:
- pass
- finally:
- try:
- await backend_instance.disconnect()
- except Exception:
- pass
- for schema_name in list(self._created_schemas):
- try:
- await backend_instance.execute(
- f'DROP SCHEMA IF EXISTS "{schema_name}" CASCADE')
- except Exception:
- pass
- if self._mixed_schema_provisioned:
- try:
- from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import (
- SCHEMA_A,
- )
-
- await backend_instance.execute(f'DROP SCHEMA IF EXISTS "{SCHEMA_A}" CASCADE')
- except Exception:
- pass
- self._mixed_schema_provisioned = False
- self._active_async_backends.clear()
- self._created_tables.clear()
- self._created_schemas.clear()
-
- async def setup_mixed_schema_fixtures(self, scenario_name: str):
- """(AsyncUser, AsyncOrder, AsyncMixedSchemaOrder) with orders also in SCHEMA_A."""
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
- from rhosocial.activerecord.testsuite.feature.query.cross_schema.mixed_schema_models import (
- AsyncMixedSchemaOrder,
- )
- from rhosocial.activerecord.testsuite.feature.query.fixtures.async_models import (
- AsyncOrder,
- AsyncUser,
- )
-
- _, config = get_scenario(scenario_name)
- user_model = await self._setup_async_model(AsyncUser, scenario_name, "users")
- shared_backend = user_model.__backend__
- self._track_backend(shared_backend, self._active_async_backends)
- order_model = await self._setup_async_model(AsyncOrder, scenario_name, "orders", shared_backend)
-
- AsyncMixedSchemaOrder.__connection_config__ = config
- AsyncMixedSchemaOrder.__backend_class__ = AsyncPostgresBackend
- AsyncMixedSchemaOrder.__backend__ = shared_backend
- self._track_backend(shared_backend, self._active_async_backends)
- await self._provision_mixed_schema_async(shared_backend)
- return AsyncUser, order_model, AsyncMixedSchemaOrder
diff --git a/tests/providers/query_benchmark.py b/tests/providers/query_benchmark.py
deleted file mode 100644
index cca4f5c6..00000000
--- a/tests/providers/query_benchmark.py
+++ /dev/null
@@ -1,15 +0,0 @@
-"""PostgreSQL provider for query benchmark tests."""
-
-from rhosocial.activerecord.testsuite.benchmark.query.interfaces import QueryBenchmarkContext
-
-from .crud_benchmark import CrudBenchmarkProvider
-
-
-class QueryBenchmarkProvider(CrudBenchmarkProvider):
- def setup_benchmark_sync(self, scenario: str, size: str):
- context = super().setup_benchmark_sync(scenario, size)
- return QueryBenchmarkContext(**context.__dict__)
-
- async def setup_benchmark_async(self, scenario: str, size: str):
- context = await super().setup_benchmark_async(scenario, size)
- return QueryBenchmarkContext(**context.__dict__)
diff --git a/tests/providers/query_connection.py b/tests/providers/query_connection.py
deleted file mode 100644
index d0c01c3f..00000000
--- a/tests/providers/query_connection.py
+++ /dev/null
@@ -1,169 +0,0 @@
-# tests/providers/query_connection.py
-"""
-Concrete implementation of IQueryConnectionProvider for PostgreSQL backend.
-
-This provider sets up connection pools and models for testing
-query classes context awareness (ActiveQuery, CTEQuery, SetOperationQuery).
-"""
-from typing import Type, Tuple, Optional, List
-
-from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord
-from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
-from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig # noqa: F401
-from rhosocial.activerecord.connection.pool import BackendPool, AsyncBackendPool, PoolConfig
-from rhosocial.activerecord.backend.options import ExecutionOptions
-from rhosocial.activerecord.backend.schema import StatementType
-
-from rhosocial.activerecord.testsuite.feature.query.connection.interfaces import IQueryConnectionProvider
-from .scenarios import get_scenario, get_enabled_scenarios
-
-
-class SyncQueryTestUser(ActiveRecord):
- """Sync test user model for query connection pool tests."""
- @classmethod
- def table_name(cls):
- return "test_users"
-
- id: Optional[int] = None
- name: str
- email: str
-
-
-class AsyncQueryTestUser(AsyncActiveRecord):
- """Async test user model for query connection pool tests."""
- @classmethod
- def table_name(cls):
- return "test_users"
-
- id: Optional[int] = None
- name: str
- email: str
-
-
-class QueryConnectionProvider(IQueryConnectionProvider):
- """
- PostgreSQL backend implementation for query connection pool context tests.
- """
-
- def __init__(self):
- self._active_backends: List = []
- self._active_async_backends: List = []
-
- def get_test_scenarios(self) -> list:
- """Returns available test scenarios."""
- return list(get_enabled_scenarios().keys())
-
- def _create_test_table(self, backend):
- """Create the test_users table."""
- try:
- backend.execute("DROP TABLE IF EXISTS test_users", options=ExecutionOptions(stmt_type=StatementType.DDL))
- except Exception:
- pass
-
- backend.execute("""
- CREATE TABLE test_users (
- id SERIAL PRIMARY KEY,
- name VARCHAR(255) NOT NULL,
- email VARCHAR(255) NOT NULL
- )
- """, options=ExecutionOptions(stmt_type=StatementType.DDL))
-
- async def _create_test_table_async(self, backend):
- """Create the test_users table asynchronously."""
- try:
- await backend.execute("DROP TABLE IF EXISTS test_users", options=ExecutionOptions(stmt_type=StatementType.DDL)) # noqa: E501
- except Exception:
- pass
-
- await backend.execute("""
- CREATE TABLE test_users (
- id SERIAL PRIMARY KEY,
- name VARCHAR(255) NOT NULL,
- email VARCHAR(255) NOT NULL
- )
- """, options=ExecutionOptions(stmt_type=StatementType.DDL))
-
- def setup_sync_pool_and_model(self, scenario_name: str) -> Tuple[BackendPool, Type[ActiveRecord]]:
- """Setup sync connection pool and model for query context tests."""
- _, config = get_scenario(scenario_name)
-
- # Create connection pool
- pool_config = PoolConfig(
- min_size=1,
- max_size=5,
- backend_factory=lambda: PostgresBackend(connection_config=config)
- )
- pool = BackendPool.create(pool_config)
-
- # Create table
- with pool.connection() as backend:
- self._create_test_table(backend)
- self._active_backends.append(backend)
-
- # Configure model to use a separate backend (not pool backend)
- # This tests that model.backend() returns pool context backend
- SyncQueryTestUser.configure(config, PostgresBackend)
- self._active_backends.append(SyncQueryTestUser.__backend__)
-
- return pool, SyncQueryTestUser
-
- async def setup_async_pool_and_model(self, scenario_name: str) -> Tuple[AsyncBackendPool, Type[AsyncActiveRecord]]:
- """Setup async connection pool and model for query context tests."""
- from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
- AsyncPostgresBackend,
- )
-
- _, config = get_scenario(scenario_name)
-
- # Create connection pool
- pool_config = PoolConfig(
- min_size=1,
- max_size=5,
- backend_factory=lambda: AsyncPostgresBackend(connection_config=config)
- )
-
- # Create pool
- pool = await AsyncBackendPool.create(pool_config)
-
- # Create table
- async with pool.connection() as backend:
- await self._create_test_table_async(backend)
- self._active_async_backends.append(backend)
-
- # Configure model
- await AsyncQueryTestUser.configure(config, AsyncPostgresBackend)
- self._active_async_backends.append(AsyncQueryTestUser.__backend__)
-
- return pool, AsyncQueryTestUser
-
- def cleanup_sync(self, scenario_name: str, pool: BackendPool):
- """Cleanup after sync tests."""
- pool.close(timeout=1.0)
-
- # Disconnect backends
- for backend in self._active_backends:
- try:
- backend.execute("DROP TABLE IF EXISTS test_users CASCADE")
- except Exception:
- pass
- try:
- backend.disconnect()
- except Exception:
- pass
- self._active_backends.clear()
-
- async def cleanup_async(self, scenario_name: str, pool: AsyncBackendPool):
- """Cleanup after async tests."""
- await pool.close(timeout=1.0)
-
- # Disconnect backends
- for backend in self._active_async_backends:
- try:
- await backend.execute("DROP TABLE IF EXISTS test_users CASCADE")
- except Exception:
- pass
- try:
- await backend.disconnect()
- except Exception:
- pass
- self._active_async_backends.clear()
diff --git a/tests/providers/registry.py b/tests/providers/registry.py
deleted file mode 100644
index 2375942b..00000000
--- a/tests/providers/registry.py
+++ /dev/null
@@ -1,77 +0,0 @@
-# tests/providers/registry.py
-"""
-Test Provider Registry for postgres Backend
-
-This module registers the concrete implementations of the test suite provider
-interfaces for the postgres backend.
-"""
-from rhosocial.activerecord.testsuite.core.registry import ProviderRegistry
-from rhosocial.activerecord.testsuite.feature.cli.providers import (
- GenericAsyncCLIProvider,
- GenericSyncCLIProvider,
-)
-from .basic import BasicSyncProvider, BasicAsyncProvider
-from .events import EventsSyncProvider, EventsAsyncProvider
-from .mixins import MixinsSyncProvider, MixinsAsyncProvider
-from .query import QuerySyncProvider, QueryAsyncProvider
-from .relation import RelationSyncProvider, RelationAsyncProvider
-from .basic_connection import BasicConnectionProvider
-from .query_connection import QueryConnectionProvider
-from .crud_benchmark import CrudBenchmarkProvider
-from .fastapi_benchmark import FastAPIBenchmarkProvider
-from .mixin_benchmark import MixinBenchmarkProvider
-from .query_benchmark import QueryBenchmarkProvider
-from .transaction_benchmark import TransactionBenchmarkProvider
-
-# Importing the pooling module registers the PostgreSQL-specific pool reset
-# handler (a side effect of the import), mirroring MySQL's tests/providers/pooling.py.
-from . import pooling # noqa: F401
-
-# Create a single, global instance of the ProviderRegistry for this backend.
-provider_registry = ProviderRegistry()
-
-# Register the concrete implementations as the providers for the
-# interfaces defined in the testsuite.
-provider_registry.register("feature.basic.IBasicProvider", BasicSyncProvider)
-provider_registry.register("feature.basic.IBasicSyncProvider", BasicSyncProvider)
-provider_registry.register("feature.basic.IBasicAsyncProvider", BasicAsyncProvider)
-
-provider_registry.register("feature.events.IEventsProvider", EventsSyncProvider)
-provider_registry.register("feature.events.IEventsSyncProvider", EventsSyncProvider)
-provider_registry.register("feature.events.IEventsAsyncProvider", EventsAsyncProvider)
-
-provider_registry.register("feature.mixins.IMixinsProvider", MixinsSyncProvider)
-provider_registry.register("feature.mixins.IMixinsSyncProvider", MixinsSyncProvider)
-provider_registry.register("feature.mixins.IMixinsAsyncProvider", MixinsAsyncProvider)
-
-provider_registry.register("feature.query.IQueryProvider", QuerySyncProvider)
-provider_registry.register("feature.query.IQuerySyncProvider", QuerySyncProvider)
-provider_registry.register("feature.query.IQueryAsyncProvider", QueryAsyncProvider)
-
-provider_registry.register("feature.relation.IRelationProvider", RelationSyncProvider)
-provider_registry.register("feature.relation.IRelationSyncProvider", RelationSyncProvider)
-provider_registry.register("feature.relation.IRelationAsyncProvider", RelationAsyncProvider)
-
-# Register connection pool context awareness providers
-provider_registry.register(
- "feature.basic.connection.IBasicConnectionProvider",
- BasicConnectionProvider,
-)
-provider_registry.register(
- "feature.query.connection.IQueryConnectionProvider",
- QueryConnectionProvider,
-)
-
-# Register benchmark providers.
-provider_registry.register("benchmark.crud.ICrudBenchmarkProvider", CrudBenchmarkProvider)
-provider_registry.register("benchmark.query.IQueryBenchmarkProvider", QueryBenchmarkProvider)
-provider_registry.register(
- "benchmark.transaction.ITransactionBenchmarkProvider",
- TransactionBenchmarkProvider,
-)
-provider_registry.register("benchmark.mixin.IMixinBenchmarkProvider", MixinBenchmarkProvider)
-provider_registry.register("benchmark.fastapi.IFastAPIBenchmarkProvider", FastAPIBenchmarkProvider)
-
-# Register CLI providers, assembled from the basic and mixins providers above.
-provider_registry.register("feature.cli.ICLISyncProvider", GenericSyncCLIProvider)
-provider_registry.register("feature.cli.ICLIAsyncProvider", GenericAsyncCLIProvider)
diff --git a/tests/providers/relation.py b/tests/providers/relation.py
deleted file mode 100644
index 2ec56c93..00000000
--- a/tests/providers/relation.py
+++ /dev/null
@@ -1,459 +0,0 @@
-# tests/providers/relation.py
-from typing import Dict, List, Tuple, Type, Set
-
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import AsyncPostgresBackend
-from rhosocial.activerecord.backend.impl.postgres.adapters.json import PostgresJSONBAdapter
-from rhosocial.activerecord.testsuite.feature.relation.interfaces import IRelationSyncProvider, IRelationAsyncProvider
-from rhosocial.activerecord.testsuite.feature.relation.fixtures.models import (
- Employee, Department, Author, Book, Chapter, Profile,
- User, Post, Comment,
- AsyncUser, AsyncPost, AsyncComment,
- BoundaryOwner, BoundaryProfile, BoundaryPost,
- AsyncBoundaryOwner, AsyncBoundaryProfile, AsyncBoundaryPost,
-)
-from .scenarios import get_enabled_scenarios, get_scenario
-
-
-EMPLOYEE_DEPARTMENT_SCHEMA = """
- DROP TABLE IF EXISTS employees CASCADE;
- DROP TABLE IF EXISTS departments CASCADE;
- CREATE TABLE departments (
- id SERIAL PRIMARY KEY,
- name TEXT NOT NULL,
- description TEXT DEFAULT ''
- );
- CREATE TABLE employees (
- id SERIAL PRIMARY KEY,
- username TEXT NOT NULL,
- department_id INTEGER NOT NULL
- );
-"""
-
-AUTHOR_BOOK_SCHEMA = """
- DROP TABLE IF EXISTS chapters CASCADE;
- DROP TABLE IF EXISTS books CASCADE;
- DROP TABLE IF EXISTS profiles CASCADE;
- DROP TABLE IF EXISTS authors CASCADE;
- CREATE TABLE authors (
- id SERIAL PRIMARY KEY,
- name TEXT NOT NULL
- );
- CREATE TABLE books (
- id SERIAL PRIMARY KEY,
- title TEXT NOT NULL,
- author_id INTEGER NOT NULL
- );
- CREATE TABLE chapters (
- id SERIAL PRIMARY KEY,
- title TEXT NOT NULL,
- book_id INTEGER NOT NULL
- );
- CREATE TABLE profiles (
- id SERIAL PRIMARY KEY,
- bio TEXT NOT NULL,
- author_id INTEGER NOT NULL
- );
-"""
-
-USER_POST_COMMENT_SCHEMA = """
- DROP TABLE IF EXISTS comments CASCADE;
- DROP TABLE IF EXISTS posts CASCADE;
- DROP TABLE IF EXISTS users CASCADE;
- CREATE TABLE users (
- id SERIAL PRIMARY KEY,
- name TEXT NOT NULL,
- email TEXT,
- settings JSONB
- );
- CREATE TABLE posts (
- id SERIAL PRIMARY KEY,
- title TEXT NOT NULL,
- body TEXT NOT NULL,
- user_id INTEGER NOT NULL,
- view_count INTEGER NOT NULL DEFAULT 0,
- metadata JSONB
- );
- CREATE TABLE comments (
- id SERIAL PRIMARY KEY,
- body TEXT NOT NULL,
- post_id INTEGER NOT NULL,
- meta JSONB
- );
-"""
-
-RELATION_BOUNDARY_SCHEMA = """
- DROP TABLE IF EXISTS relation_boundary_posts CASCADE;
- DROP TABLE IF EXISTS relation_boundary_profiles CASCADE;
- DROP TABLE IF EXISTS relation_boundary_owners CASCADE;
- CREATE TABLE relation_boundary_owners (
- id SERIAL PRIMARY KEY,
- name TEXT NOT NULL
- );
- CREATE TABLE relation_boundary_profiles (
- id SERIAL PRIMARY KEY,
- bio TEXT NOT NULL,
- owner_id INTEGER NULL
- );
- CREATE TABLE relation_boundary_posts (
- id SERIAL PRIMARY KEY,
- title TEXT NOT NULL,
- owner_id INTEGER NULL
- );
-"""
-
-
-class RelationProviderBase:
- def __init__(self):
- self._sync_user_post_comment_setup = False
- self._async_user_post_comment_setup = False
- self._sync_relation_boundary_setup = False
- self._async_relation_boundary_setup = False
- self._created_tables: Set[str] = set()
-
- def get_test_scenarios(self) -> List[str]:
- return list(get_enabled_scenarios().keys())
-
- def _configure_with_shared_backend(self, model_class, config, backend_class, backend):
- model_class.__connection_config__ = config
- model_class.__backend_class__ = backend_class
- model_class.__backend__ = backend
-
- def _configure_json_field_adapters(self):
- adapter = PostgresJSONBAdapter()
- User.__field_adapters__["settings"] = (adapter, str)
- Post.__field_adapters__["metadata"] = (adapter, str)
- Comment.__field_adapters__["meta"] = (adapter, str)
- AsyncUser.__field_adapters__["settings"] = (adapter, str)
- AsyncPost.__field_adapters__["metadata"] = (adapter, str)
- AsyncComment.__field_adapters__["meta"] = (adapter, str)
-
- def _reset_setup_state(self):
- self._sync_user_post_comment_setup = False
- self._async_user_post_comment_setup = False
- self._sync_relation_boundary_setup = False
- self._async_relation_boundary_setup = False
-
-
-class RelationSyncProvider(RelationProviderBase, IRelationSyncProvider):
-
- def __init__(self):
- super().__init__()
- self._active_backends = []
-
- def _execute_script(self, backend, sql: str):
- for statement in sql.split(";"):
- statement = statement.strip()
- if statement:
- backend.execute(statement)
-
- def _setup_employee_department(self, scenario_name):
- backend_class, config = get_scenario(scenario_name)
- Employee.configure(config, backend_class)
- backend = Employee.backend()
- backend.connect()
- backend.introspect_and_adapt()
- self._active_backends.append(backend)
- self._execute_script(backend, EMPLOYEE_DEPARTMENT_SCHEMA)
- self._configure_with_shared_backend(Department, config, backend_class, backend)
- return Employee, Department
-
- def _setup_author_book(self, scenario_name):
- backend_class, config = get_scenario(scenario_name)
- Author.configure(config, backend_class)
- backend = Author.backend()
- backend.connect()
- backend.introspect_and_adapt()
- self._active_backends.append(backend)
- self._execute_script(backend, AUTHOR_BOOK_SCHEMA)
- self._configure_with_shared_backend(Book, config, backend_class, backend)
- self._configure_with_shared_backend(Chapter, config, backend_class, backend)
- self._configure_with_shared_backend(Profile, config, backend_class, backend)
- return Author, Book, Chapter, Profile
-
- def _setup_user_post_comment_sync(self, scenario_name):
- if not self._sync_user_post_comment_setup:
- self._configure_json_field_adapters()
- backend_class, config = get_scenario(scenario_name)
- User.configure(config, backend_class)
- backend = User.backend()
- backend.connect()
- backend.introspect_and_adapt()
- self._active_backends.append(backend)
- self._execute_script(backend, USER_POST_COMMENT_SCHEMA)
- self._configure_with_shared_backend(Post, config, backend_class, backend)
- self._configure_with_shared_backend(Comment, config, backend_class, backend)
- self._sync_user_post_comment_setup = True
-
- def _setup_relation_boundary_sync(self, scenario_name):
- if not self._sync_relation_boundary_setup:
- backend_class, config = get_scenario(scenario_name)
- BoundaryOwner.configure(config, backend_class)
- backend = BoundaryOwner.backend()
- backend.connect()
- backend.introspect_and_adapt()
- self._active_backends.append(backend)
- self._execute_script(backend, RELATION_BOUNDARY_SCHEMA)
- self._configure_with_shared_backend(
- BoundaryProfile, config, backend_class, backend,
- )
- self._configure_with_shared_backend(
- BoundaryPost, config, backend_class, backend,
- )
- self._sync_relation_boundary_setup = True
-
- def setup_employee_department_fixtures(
- self,
- scenario_name: str,
- ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord]]:
- return self._setup_employee_department(scenario_name)
-
- def setup_author_book_fixtures(
- self,
- scenario_name: str,
- ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- return self._setup_author_book(scenario_name)
-
- def setup_user_model(self, scenario_name: str) -> Type[ActiveRecord]:
- self._setup_user_post_comment_sync(scenario_name)
- return User
-
- def setup_post_model(self, scenario_name: str) -> Type[ActiveRecord]:
- self._setup_user_post_comment_sync(scenario_name)
- return Post
-
- def setup_comment_model(self, scenario_name: str) -> Type[ActiveRecord]:
- self._setup_user_post_comment_sync(scenario_name)
- return Comment
-
- def setup_relation_boundary_fixtures(
- self,
- scenario_name: str,
- ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- self._setup_relation_boundary_sync(scenario_name)
- return BoundaryOwner, BoundaryProfile, BoundaryPost
-
- def load_relation_boundary_dataset(self, scenario_name: str, dataset_name: str) -> Dict[str, int]:
- self._setup_relation_boundary_sync(scenario_name)
- return self._load_relation_boundary_dataset(dataset_name)
-
- def _load_relation_boundary_dataset(self, dataset_name):
- if dataset_name == "null_foreign_key":
- profile = BoundaryProfile(bio="No owner", owner_id=None)
- profile.save()
- return {"profile_id": profile.id}
-
- if dataset_name == "orphan_foreign_key":
- missing_owner_id = 999999
- post = BoundaryPost(title="Orphan post", owner_id=missing_owner_id)
- post.save()
- return {"post_id": post.id, "missing_owner_id": missing_owner_id}
-
- if dataset_name == "owner_without_children":
- owner = BoundaryOwner(name="Owner without children")
- owner.save()
- return {"owner_id": owner.id}
-
- if dataset_name == "multiple_has_one_matches":
- owner = BoundaryOwner(name="Owner with duplicate profiles")
- owner.save()
- first = BoundaryProfile(bio="First profile", owner_id=owner.id)
- first.save()
- second = BoundaryProfile(bio="Second profile", owner_id=owner.id)
- second.save()
- return {
- "owner_id": owner.id,
- "first_profile_id": first.id,
- "second_profile_id": second.id,
- }
-
- raise ValueError(f"Unknown relation boundary dataset: {dataset_name}")
-
- def cleanup_after_test(self, scenario_name: str) -> None:
- tables_to_drop = [
- 'employees', 'departments',
- 'authors', 'books', 'chapters', 'profiles',
- 'users', 'posts', 'comments',
- 'relation_boundary_owners', 'relation_boundary_profiles', 'relation_boundary_posts',
- ]
- for backend in self._active_backends:
- try:
- for table in tables_to_drop:
- try:
- backend.execute(f'DROP TABLE IF EXISTS "{table}" CASCADE')
- except Exception:
- pass
- finally:
- try:
- backend.disconnect()
- except Exception:
- pass
- self._active_backends.clear()
- self._reset_setup_state()
-
-
-class RelationAsyncProvider(RelationProviderBase, IRelationAsyncProvider):
-
- def __init__(self):
- super().__init__()
- self._active_async_backends = []
-
- def _configure_async_model_without_connection(self, model_class, config, backend=None):
- if backend is None:
- backend = AsyncPostgresBackend(connection_config=config)
- model_class.__connection_config__ = config
- model_class.__backend_class__ = AsyncPostgresBackend
- model_class.__backend__ = backend
- return backend
-
- async def _execute_script_async(self, backend, sql: str):
- for statement in sql.split(";"):
- statement = statement.strip()
- if statement:
- await backend.execute(statement)
-
- async def _setup_employee_department_fixtures_async(self, scenario_name):
- _, config = get_scenario(scenario_name)
- await Employee.configure(config, AsyncPostgresBackend)
- backend = Employee.backend()
- await backend.connect()
- await backend.introspect_and_adapt()
- self._active_async_backends.append(backend)
- await self._execute_script_async(backend, EMPLOYEE_DEPARTMENT_SCHEMA)
- self._configure_with_shared_backend(Department, config, AsyncPostgresBackend, backend)
- return Employee, Department
-
- async def _setup_author_book_fixtures_async(self, scenario_name):
- _, config = get_scenario(scenario_name)
- await Author.configure(config, AsyncPostgresBackend)
- backend = Author.backend()
- await backend.connect()
- await backend.introspect_and_adapt()
- self._active_async_backends.append(backend)
- await self._execute_script_async(backend, AUTHOR_BOOK_SCHEMA)
- self._configure_with_shared_backend(Book, config, AsyncPostgresBackend, backend)
- self._configure_with_shared_backend(Chapter, config, AsyncPostgresBackend, backend)
- self._configure_with_shared_backend(Profile, config, AsyncPostgresBackend, backend)
- return Author, Book, Chapter, Profile
-
- async def _setup_user_post_comment_async(self, scenario_name):
- if not self._async_user_post_comment_setup:
- self._configure_json_field_adapters()
- _, config = get_scenario(scenario_name)
- backend = self._configure_async_model_without_connection(AsyncUser, config)
- self._configure_async_model_without_connection(AsyncPost, config, backend)
- self._configure_async_model_without_connection(AsyncComment, config, backend)
- self._active_async_backends.append(backend)
- await backend.introspect_and_adapt()
- await self._execute_script_async(backend, USER_POST_COMMENT_SCHEMA)
- self._async_user_post_comment_setup = True
-
- async def _setup_relation_boundary_async(self, scenario_name):
- if not self._async_relation_boundary_setup:
- _, config = get_scenario(scenario_name)
- backend = self._configure_async_model_without_connection(
- AsyncBoundaryOwner, config,
- )
- self._configure_async_model_without_connection(
- AsyncBoundaryProfile, config, backend,
- )
- self._configure_async_model_without_connection(
- AsyncBoundaryPost, config, backend,
- )
- self._active_async_backends.append(backend)
- await backend.introspect_and_adapt()
- await self._execute_script_async(backend, RELATION_BOUNDARY_SCHEMA)
- self._async_relation_boundary_setup = True
-
- async def setup_employee_department_fixtures(
- self,
- scenario_name: str,
- ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord]]:
- return await self._setup_employee_department_fixtures_async(scenario_name)
-
- async def setup_author_book_fixtures(
- self,
- scenario_name: str,
- ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- return await self._setup_author_book_fixtures_async(scenario_name)
-
- async def setup_user_model(self, scenario_name: str) -> Type[ActiveRecord]:
- await self._setup_user_post_comment_async(scenario_name)
- return AsyncUser
-
- async def setup_post_model(self, scenario_name: str) -> Type[ActiveRecord]:
- await self._setup_user_post_comment_async(scenario_name)
- return AsyncPost
-
- async def setup_comment_model(self, scenario_name: str) -> Type[ActiveRecord]:
- await self._setup_user_post_comment_async(scenario_name)
- return AsyncComment
-
- async def setup_relation_boundary_fixtures(
- self,
- scenario_name: str,
- ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]:
- await self._setup_relation_boundary_async(scenario_name)
- return AsyncBoundaryOwner, AsyncBoundaryProfile, AsyncBoundaryPost
-
- async def load_relation_boundary_dataset(
- self,
- scenario_name: str,
- dataset_name: str,
- ) -> Dict[str, int]:
- await self._setup_relation_boundary_async(scenario_name)
- return await self._load_async_relation_boundary_dataset(dataset_name)
-
- async def _load_async_relation_boundary_dataset(self, dataset_name):
- if dataset_name == "null_foreign_key":
- profile = AsyncBoundaryProfile(bio="No owner", owner_id=None)
- await profile.save()
- return {"profile_id": profile.id}
-
- if dataset_name == "orphan_foreign_key":
- missing_owner_id = 999999
- post = AsyncBoundaryPost(title="Orphan post", owner_id=missing_owner_id)
- await post.save()
- return {"post_id": post.id, "missing_owner_id": missing_owner_id}
-
- if dataset_name == "owner_without_children":
- owner = AsyncBoundaryOwner(name="Owner without children")
- await owner.save()
- return {"owner_id": owner.id}
-
- if dataset_name == "multiple_has_one_matches":
- owner = AsyncBoundaryOwner(name="Owner with duplicate profiles")
- await owner.save()
- first = AsyncBoundaryProfile(bio="First profile", owner_id=owner.id)
- await first.save()
- second = AsyncBoundaryProfile(bio="Second profile", owner_id=owner.id)
- await second.save()
- return {
- "owner_id": owner.id,
- "first_profile_id": first.id,
- "second_profile_id": second.id,
- }
-
- raise ValueError(f"Unknown relation boundary dataset: {dataset_name}")
-
- async def cleanup_after_test(self, scenario_name: str):
- tables_to_drop = [
- 'employees', 'departments',
- 'authors', 'books', 'chapters', 'profiles',
- 'users', 'posts', 'comments',
- 'relation_boundary_owners', 'relation_boundary_profiles', 'relation_boundary_posts',
- ]
- for backend in self._active_async_backends:
- try:
- for table in tables_to_drop:
- try:
- await backend.execute(f'DROP TABLE IF EXISTS "{table}" CASCADE')
- except Exception:
- pass
- finally:
- try:
- await backend.disconnect()
- except Exception:
- pass
- self._active_async_backends.clear()
- self._reset_setup_state()
diff --git a/tests/providers/scenarios.py b/tests/providers/scenarios.py
deleted file mode 100644
index 621b6677..00000000
--- a/tests/providers/scenarios.py
+++ /dev/null
@@ -1,142 +0,0 @@
-# tests/providers/scenarios.py
-"""postgres backend test scenario configuration mapping table"""
-
-import os
-from dataclasses import replace
-from typing import Dict, Any, Tuple, Type
-from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
-from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig
-from rhosocial.activerecord.testsuite.core.pool import pooled_database_name
-
-# Scenario name -> configuration dictionary mapping table (postgres only)
-SCENARIO_MAP: Dict[str, Dict[str, Any]] = {}
-
-
-def register_scenario(name: str, config: Dict[str, Any]):
- """Register postgres test scenario"""
- SCENARIO_MAP[name] = config
-
-
-def get_scenario_raw(name: str) -> Tuple[Type[PostgresBackend], PostgresConnectionConfig]:
- """Return the backend class and connection config for a scenario.
-
- The config uses the scenario's configured ``database``; no pool override is
- applied. Used by the pool reset handler, which must reach the server
- regardless of whether a pooled database exists yet.
- """
- if name not in SCENARIO_MAP:
- # If the specified scenario is not found, use the first available one as a fallback
- if SCENARIO_MAP:
- name = next(iter(SCENARIO_MAP))
- else:
- raise ValueError("No scenarios registered")
-
- # Unpack the configuration dictionary into the dataclass constructor.
- config = PostgresConnectionConfig(**SCENARIO_MAP[name])
- return PostgresBackend, config
-
-
-def get_scenario(name: str) -> Tuple[Type[PostgresBackend], PostgresConnectionConfig]:
- """
- Retrieves the backend class and a connection configuration object for a given
- scenario name. This is called by the provider to set up the database for a test.
-
- Under an active database pool the config's ``database`` is replaced by the
- worker's pooled database name (``{database}_{index}``) so concurrent workers
- never share a schema. Serial runs keep the scenario's configured database.
- """
- backend_class, config = get_scenario_raw(name)
- pooled_db = pooled_database_name(name)
- if pooled_db:
- config = replace(config, database=pooled_db)
- return backend_class, config
-
-
-def get_enabled_scenarios() -> Dict[str, Any]:
- """
- Returns the map of all currently enabled scenarios. The testsuite's conftest
- uses this to parameterize the tests, causing them to run for each scenario.
- """
- return SCENARIO_MAP
-
-
-def _load_scenarios_from_config():
- """
- Load scenarios from a configuration file with the following priority:
- 1. Environment variable specified path (highest priority)
- 2. Default path tests/config/postgres_scenarios.yaml (lowest priority)
- If no valid configuration file is found, terminate with an error.
- """
- try:
- import yaml
- except ImportError:
- raise ImportError("PyYAML is required to load postgres scenario configuration files. Please install it.") # noqa: B904
-
- # First, try to load from path specified in environment variable
- env_config_path = os.getenv("POSTGRES_SCENARIOS_CONFIG_PATH")
- if env_config_path and os.path.exists(env_config_path):
- print(f"Loading postgres scenarios from environment-specified path: {env_config_path}")
- config_path = env_config_path
- else:
- # Default path with lowest priority
- # Note: The path is relative to this file's location.
- config_path = os.path.join(os.path.dirname(__file__), "..", "config", "postgres_scenarios.yaml")
- if not os.path.exists(config_path):
- raise FileNotFoundError(
- "No postgres scenarios configuration file found. "
- "Either set POSTGRES_SCENARIOS_CONFIG_PATH environment variable to point to a valid YAML file "
- f"or place postgres_scenarios.yaml in the {os.path.dirname(config_path)} directory."
- )
- print(f"Loading postgres scenarios from default path: {config_path}")
-
- try:
- with open(config_path, 'r', encoding='utf-8') as f:
- config_data = yaml.safe_load(f)
-
- if 'scenarios' not in config_data:
- raise ValueError(f"Configuration file {config_path} does not contain 'scenarios' key")
-
- for scenario_name, config in config_data['scenarios'].items():
- register_scenario(scenario_name, config)
-
- _apply_scenario_filter()
-
- except Exception as e:
- raise RuntimeError(f"Failed to load or parse scenario configuration file {config_path}: {e}") # noqa: B904
-
-
-def _apply_scenario_filter():
- """Filter SCENARIO_MAP based on the active scenarios env var.
-
- The env var is set either by the --scenarios pytest option in the
- testsuite's root conftest (TESTSUITE_ACTIVE_SCENARIOS) or by a backend
- local override (POSTGRES_ACTIVE_SCENARIOS). It contains comma-separated
- full scenario names (e.g., "postgres_16,postgres_17").
- """
- filter_str = os.getenv("POSTGRES_ACTIVE_SCENARIOS") or os.getenv("TESTSUITE_ACTIVE_SCENARIOS")
- if not filter_str:
- return
-
- allowed = set(s.strip() for s in filter_str.split(',') if s.strip())
- if not allowed:
- return
-
- to_remove = [name for name in SCENARIO_MAP if name not in allowed]
- for name in to_remove:
- del SCENARIO_MAP[name]
-
- if to_remove:
- print(f"Filtered scenarios: kept {list(SCENARIO_MAP.keys())}, "
- f"removed {to_remove} (--scenarios={filter_str})")
-
-
-def _register_default_scenarios():
- """
- Registers the scenarios loaded from an external configuration file.
- No hardcoded scenarios are registered in the code itself.
- """
- _load_scenarios_from_config()
-
-
-# Register default scenarios during initialization
-_register_default_scenarios()
diff --git a/tests/providers/transaction_benchmark.py b/tests/providers/transaction_benchmark.py
deleted file mode 100644
index 3330de2e..00000000
--- a/tests/providers/transaction_benchmark.py
+++ /dev/null
@@ -1,17 +0,0 @@
-"""PostgreSQL provider for transaction benchmark tests."""
-
-from rhosocial.activerecord.testsuite.benchmark.transaction.interfaces import (
- TransactionBenchmarkContext,
-)
-
-from .crud_benchmark import CrudBenchmarkProvider
-
-
-class TransactionBenchmarkProvider(CrudBenchmarkProvider):
- def setup_benchmark_sync(self, scenario: str, size: str):
- context = super().setup_benchmark_sync(scenario, size)
- return TransactionBenchmarkContext(**context.__dict__)
-
- async def setup_benchmark_async(self, scenario: str, size: str):
- context = await super().setup_benchmark_async(scenario, size)
- return TransactionBenchmarkContext(**context.__dict__)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py
new file mode 100644
index 00000000..8b0f95c4
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/adapters/conftest.py
+"""Bridge to the shared ``adapters`` contract."""
+from rhosocial.activerecord.testsuite.feature.adapters.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py
new file mode 100644
index 00000000..881817ab
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/adapters/test_json_codec.py
+"""Bridge to the shared ``adapters`` contract."""
+from rhosocial.activerecord.testsuite.feature.adapters.test_json_codec import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py
new file mode 100644
index 00000000..e294ba71
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types.py
+"""Bridge to the shared ``adapters`` contract."""
+from rhosocial.activerecord.testsuite.feature.adapters.test_neutral_types import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py
new file mode 100644
index 00000000..f0f2a7b9
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/adapters/test_neutral_types_async.py
+"""Bridge to the shared ``adapters`` contract."""
+from rhosocial.activerecord.testsuite.feature.adapters.test_neutral_types_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/SHARDS.md b/tests/rhosocial/activerecord_postgres_test/feature/backend/SHARDS.md
new file mode 100644
index 00000000..b5784f2d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/SHARDS.md
@@ -0,0 +1,130 @@
+# Directory-bound database shards
+
+Every directory under `execute/` that holds tests declares exactly one
+database in its own `conftest.py`:
+
+```python
+from pathlib import Path
+
+from providers.shards import register
+
+register(Path(__file__).parent, "test_db_")
+```
+
+The rules behind the map:
+
+- **One leaf directory = one database.** A directory that only groups
+ capabilities (e.g. `execute/postgres/extension/`, `execute/postgres/types/`)
+ holds no test files and declares no shard; only its leaf subdirectories do.
+- Shared, cross-backend features use the fixed numbers `test_db_1` …
+ `test_db_23`; `test_db_24` is reserved for the backend namespace root
+ (`execute/postgres/`), and backend-unique leaves start at `test_db_25` with
+ no upper limit.
+- A sharded directory's tests stay on one xdist worker
+ (`xdist_group("db:")`) and share that database: directories run
+ serially, different directories run in parallel. Construct tests carry no
+ group and no database.
+- `resolve_database_name()` prefers the directory shard over worker-slot
+ pooling, so serial runs use the directory's database too.
+- Worker-slot pooling uses the `test_db_pool_` base (see
+ `tests/providers/pooling.py`), so pool slots never collide with
+ `test_db_` shards.
+- All registered shards are created and cleared once per session by the
+ autouse session fixture in `tests/conftest.py`; they are not dropped at the
+ end of the session.
+- When a leaf is added or moved, update this table and allocate the next free
+ number.
+
+## Shared leaves (fixed 1..23)
+
+| Leaf directory | Database | Test modules |
+|---|---|---|
+| `execute/connection/` | `test_db_1` | 8 |
+| `execute/crud/` | `test_db_2` | 4 |
+| `execute/query/` | `test_db_3` | 5 |
+| `execute/join/` | `test_db_4` | 1 |
+| `execute/transaction/` | `test_db_5` | 8 |
+| `execute/ddl_table/` | `test_db_6` | 1 |
+| `execute/ddl_column/` | `test_db_7` | 0 (placeholder `.gitkeep`) |
+| `execute/ddl_constraint/` | `test_db_8` | 0 (placeholder `.gitkeep`) |
+| `execute/ddl_index/` | `test_db_9` | 0 (placeholder `.gitkeep`) |
+| `execute/ddl_view/` | `test_db_10` | 2 |
+| `execute/dml_insert/` | `test_db_11` | 2 |
+| `execute/dml_update_delete/` | `test_db_12` | 1 |
+| `execute/json/` | `test_db_13` | 1 |
+| `execute/partition/` | `test_db_14` | 4 |
+| `execute/introspection/` | `test_db_15` | 19 |
+| `execute/errors/` | `test_db_16` | 3 |
+| `execute/concurrency/` | `test_db_17` | 2 |
+| `execute/cli/` | `test_db_18` | 4 |
+| `execute/functions/` | `test_db_19` | 2 |
+| `execute/sequence_identity/` | `test_db_20` | 1 |
+| `execute/fulltext_spatial/` | `test_db_21` | 0 (placeholder `.gitkeep`; PostgreSQL full-text/spatial extensions live under `execute/postgres/extension/`) |
+| `execute/show_admin/` | `test_db_22` | 0 (placeholder `.gitkeep`) |
+| `execute/routine_domain/` | `test_db_23` | 0 (placeholder `.gitkeep`) |
+
+## Backend namespace root
+
+| Directory | Database | Test modules |
+|---|---|---|
+| `execute/postgres/` | `test_db_24` | 0 (namespace only; leaf subdirectories carry their own shards) |
+
+## PostgreSQL-unique leaves (25+)
+
+### `execute/postgres/extension//`
+
+| Leaf directory | Database | Test modules |
+|---|---|---|
+| `execute/postgres/extension/address_standardizer/` | `test_db_25` | 1 |
+| `execute/postgres/extension/bloom/` | `test_db_26` | 1 |
+| `execute/postgres/extension/btree_gin/` | `test_db_27` | 1 |
+| `execute/postgres/extension/btree_gist/` | `test_db_28` | 1 |
+| `execute/postgres/extension/citext/` | `test_db_29` | 1 |
+| `execute/postgres/extension/cube/` | `test_db_30` | 1 |
+| `execute/postgres/extension/fuzzystrmatch/` | `test_db_31` | 1 |
+| `execute/postgres/extension/hstore/` | `test_db_32` | 1 |
+| `execute/postgres/extension/hypopg/` | `test_db_33` | 1 |
+| `execute/postgres/extension/intarray/` | `test_db_34` | 1 |
+| `execute/postgres/extension/orafce/` | `test_db_35` | 1 |
+| `execute/postgres/extension/pg_cron/` | `test_db_36` | 1 |
+| `execute/postgres/extension/pg_partman/` | `test_db_37` | 1 |
+| `execute/postgres/extension/pg_repack/` | `test_db_38` | 1 |
+| `execute/postgres/extension/pg_stat_statements/` | `test_db_39` | 1 |
+| `execute/postgres/extension/pg_surgery/` | `test_db_40` | 1 |
+| `execute/postgres/extension/pg_walinspect/` | `test_db_41` | 1 |
+| `execute/postgres/extension/pgaudit/` | `test_db_42` | 1 |
+| `execute/postgres/extension/pgcrypto/` | `test_db_43` | 1 |
+| `execute/postgres/extension/pglogical/` | `test_db_44` | 1 |
+| `execute/postgres/extension/tablefunc/` | `test_db_45` | 1 |
+| `execute/postgres/extension/uuid_ossp/` | `test_db_46` | 1 |
+| `execute/postgres/extension/earthdistance/` | `test_db_47` | 1 |
+| `execute/postgres/extension/ltree/` | `test_db_48` | 1 |
+| `execute/postgres/extension/pg_trgm/` | `test_db_49` | 1 |
+| `execute/postgres/extension/pgrouting/` | `test_db_50` | 1 |
+| `execute/postgres/extension/pgvector/` | `test_db_51` | 1 |
+| `execute/postgres/extension/postgis/` | `test_db_52` | 1 |
+| `execute/postgres/extension/postgis_raster/` | `test_db_53` | 1 |
+| `execute/postgres/extension/ddl/` | `test_db_54` | 1 (CREATE/DROP EXTENSION execution) |
+
+### `execute/postgres/types//`
+
+| Leaf directory | Database | Test modules |
+|---|---|---|
+| `execute/postgres/types/bitstring/` | `test_db_55` | 1 |
+| `execute/postgres/types/cast/` | `test_db_56` | 1 |
+| `execute/postgres/types/enum/` | `test_db_57` | 1 |
+| `execute/postgres/types/extension_types/` | `test_db_58` | 1 |
+| `execute/postgres/types/literal/` | `test_db_59` | 1 |
+| `execute/postgres/types/lsn/` | `test_db_60` | 1 |
+| `execute/postgres/types/money/` | `test_db_61` | 1 |
+| `execute/postgres/types/network/` | `test_db_62` | 1 |
+| `execute/postgres/types/oid/` | `test_db_63` | 1 |
+| `execute/postgres/types/range/` | `test_db_64` | 1 |
+| `execute/postgres/types/xml/` | `test_db_65` | 1 |
+
+### Other PostgreSQL-unique leaves
+
+| Leaf directory | Database | Test modules |
+|---|---|---|
+| `execute/postgres/dialect_security/` | `test_db_66` | 1 |
+| `execute/postgres/capability_probe/` | `test_db_67` | 1 |
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py
new file mode 100644
index 00000000..311f75aa
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py
@@ -0,0 +1,126 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/conftest.py
+"""Fixtures for the PostgreSQL native type tests.
+
+The directory owns one logical database (``test_backend_adapters_native``),
+so a test class opens one connection and creates its tables once. Each module
+declares the tables it needs in ``TABLES``; only those ``CREATE TABLE``
+statements are executed from ``schema/native_types.sql``. That keeps a
+targeted run inside the remote-latency budget and keeps the statements shared
+between modules in one visible place.
+
+Extension tables live in ``schema/extension_types.sql`` and are only created
+by a class fixture that has already established the extension exists.
+"""
+from rhosocial.activerecord.testsuite.pytest_plugin import Declaration
+
+import re
+from pathlib import Path
+
+import pytest
+
+
+DECLARATION = Declaration(
+ uses_database=True,
+ parallel=True,
+ purpose="PostgreSQL native type tests (native) against the directory-owned database.",
+ passes_means="the live-database contract of this directory holds on PostgreSQL",
+ fails_means="the directory-owned database is corrupted or a backend behavior is wrong",
+)
+
+SCHEMA_DIR = Path(__file__).parent / "schema"
+BUILTIN_SCHEMA = SCHEMA_DIR / "native_types.sql"
+EXTENSION_SCHEMA = SCHEMA_DIR / "extension_types.sql"
+
+
+def _statements(path):
+ """Return the non-empty statements of a small SQL script."""
+ text = path.read_text(encoding="utf-8")
+ text = re.sub(r"--[^\n]*", "", text)
+ return [part.strip() for part in text.split(";") if part.strip()]
+
+
+def _create_tables(backend, path, names):
+ """Execute only the ``CREATE TABLE`` statements whose table is in ``names``."""
+ for statement in _statements(path):
+ for name in names:
+ pattern = r"CREATE TABLE\s+(?:IF NOT EXISTS\s+)?{}\s*\(".format(
+ re.escape(name)
+ )
+ if re.search(pattern, statement, re.IGNORECASE):
+ backend.execute(statement)
+ break
+
+
+def _require_extension(backend, name):
+ """Skip with the exact missing extension name when the server lacks it."""
+ if backend.dialect.is_extension_installed(name):
+ return
+ available = "yes" if backend.dialect.is_extension_available(name) else "no"
+ pytest.skip(
+ "extension '{}' is not installed (pg_extension); "
+ "pg_available_extensions says available: {}".format(name, available)
+ )
+
+
+#: The dialect's own support switches for the column types these native tables
+#: need. The conftest never inspects a server version itself: it asks the
+#: dialect, and the dialect answers per version and per capability.
+_TABLE_TYPE_SWITCHES = (
+ ("native_ranges", "supports_multirange_type", "multirange"),
+ ("native_multiranges", "supports_multirange_type", "multirange"),
+ ("native_wrapped_scalars", "supports_xid8_type", "xid8"),
+ ("native_json_xml", "supports_data_type_postgres_jsonpath", "jsonpath"),
+ ("native_network", "supports_data_type_postgres_macaddr8", "macaddr8"),
+)
+
+
+@pytest.fixture(scope="class")
+def native_backend(postgres_backend_class, request):
+ """The class's backend, with the class's built-in tables created."""
+ backend = postgres_backend_class
+ names = tuple(getattr(request.cls, "TABLES", ()))
+ for table, probe, concept in _TABLE_TYPE_SWITCHES:
+ if table in names and not getattr(backend.dialect, probe)():
+ pytest.skip(
+ f"this dialect does not support {concept} "
+ f"({probe} is False)"
+ )
+ if names:
+ _create_tables(backend, BUILTIN_SCHEMA, names)
+ return backend
+
+
+@pytest.fixture(scope="class")
+def postgis_backend(postgres_backend_class):
+ """Backend with the PostGIS table; skips when PostGIS is absent."""
+ backend = postgres_backend_class
+ _require_extension(backend, "postgis")
+ _create_tables(backend, EXTENSION_SCHEMA, ("native_ext_postgis",))
+ return backend
+
+
+@pytest.fixture(scope="class")
+def vector_backend(postgres_backend_class):
+ """Backend with the pgvector table; skips when pgvector is absent."""
+ backend = postgres_backend_class
+ _require_extension(backend, "vector")
+ _create_tables(backend, EXTENSION_SCHEMA, ("native_ext_pgvector",))
+ return backend
+
+
+@pytest.fixture(scope="class")
+def hstore_backend(postgres_backend_class):
+ """Backend with hstore installed and its table created.
+
+ hstore is a contrib extension, so it can be created when the server lists
+ it in ``pg_available_extensions``; the skip only happens when neither is
+ true.
+ """
+ from rhosocial.activerecord_postgres_test.feature.backend.utils import (
+ ensure_extension_installed,
+ )
+
+ backend = postgres_backend_class
+ ensure_extension_installed(backend, "hstore")
+ _create_tables(backend, EXTENSION_SCHEMA, ("native_ext_hstore",))
+ return backend
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/helpers.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/helpers.py
new file mode 100644
index 00000000..8f7be9a5
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/helpers.py
@@ -0,0 +1,70 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/helpers.py
+"""Small SQL helpers shared by the native type test modules."""
+
+from rhosocial.activerecord.backend.options import ExecutionOptions
+from rhosocial.activerecord.backend.schema import StatementType
+
+#: INSERT ... RETURNING must ask for result processing explicitly: a DML
+#: statement does not run the result pipeline by default.
+RETURNING_OPTIONS = ExecutionOptions(
+ stmt_type=StatementType.DML,
+ process_result_set=True,
+)
+
+
+def insert_row(backend, table, values, casts=None):
+ """Insert one row and return its ``id``.
+
+ ``values`` keeps its insertion order, so callers can line the columns up
+ with the SQL they assert against. ``casts`` maps a column name to the
+ PostgreSQL cast appended to its placeholder, for the few types whose text
+ form is the only unambiguous input (``xid``, ``bit(n)``, ...).
+ """
+ casts = casts or {}
+ columns = ", ".join(values)
+ placeholders = ", ".join(
+ "%s" + ("::" + casts[name] if name in casts else "") for name in values
+ )
+ sql = "INSERT INTO {} ({}) VALUES ({}) RETURNING id".format(
+ table, columns, placeholders
+ )
+ result = backend.execute(sql, tuple(values.values()), options=RETURNING_OPTIONS)
+ return result.data[0]["id"]
+
+
+def insert_sql(backend, sql):
+ """Run a native ``INSERT ... RETURNING id`` and return the new row id.
+
+ Used by the S3 cases, which deliberately bypass the adapter.
+ """
+ result = backend.execute(sql, options=RETURNING_OPTIONS)
+ return result.data[0]["id"]
+
+
+def read_raw(backend, table, column, row_id, expression=None):
+ """Read the server's own text for one column of one row."""
+ if expression is None:
+ expression = "{}::text".format(column)
+ row = backend.fetch_one(
+ "SELECT {} AS raw FROM {} WHERE id = %s".format(expression, table),
+ (row_id,),
+ )
+ return row["raw"]
+
+
+def read_value(backend, table, column, row_id):
+ """Read the driver-decoded value for one column of one row."""
+ row = backend.fetch_one(
+ "SELECT {} AS value FROM {} WHERE id = %s".format(column, table),
+ (row_id,),
+ )
+ return row["value"]
+
+
+def update_cell(backend, table, column, row_id, value, cast=None):
+ """Write one column, optionally through an explicit PostgreSQL cast."""
+ suffix = "" if cast is None else "::" + cast
+ backend.execute(
+ "UPDATE {} SET {} = %s{} WHERE id = %s".format(table, column, suffix),
+ (value, row_id),
+ )
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/extension_types.sql b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/extension_types.sql
new file mode 100644
index 00000000..b21de2de
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/extension_types.sql
@@ -0,0 +1,17 @@
+-- tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/extension_types.sql
+-- Need per database the grouped statement; create extension before running this.
+CREATE TABLE IF NOT EXISTS native_ext_postgis (
+ id serial PRIMARY KEY,
+ geom geometry(Point, 4326),
+ geog geography(Point, 4326)
+);
+
+CREATE TABLE IF NOT EXISTS native_ext_pgvector (
+ id serial PRIMARY KEY,
+ embedding vector(3)
+);
+
+CREATE TABLE IF NOT EXISTS native_ext_hstore (
+ id serial PRIMARY KEY,
+ attrs hstore
+);
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/native_types.sql b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/native_types.sql
new file mode 100644
index 00000000..0e6ab99e
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/native_types.sql
@@ -0,0 +1,91 @@
+-- tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/schema/native_types.sql
+-- Built-in PostgreSQL types only: every statement is safe on a stock server.
+-- Tables are grouped by family; a module enables only the tables it names.
+
+CREATE TABLE IF NOT EXISTS native_wrapped_scalars (
+ id serial PRIMARY KEY,
+ amount money,
+ oid_value oid,
+ regclass_value regclass,
+ regtype_value regtype,
+ regproc_value regproc,
+ regconfig_value regconfig,
+ regnamespace_value regnamespace,
+ xid_value xid,
+ xid8_value xid8,
+ cid_value cid,
+ tid_value tid,
+ lsn_value pg_lsn
+);
+
+CREATE TABLE IF NOT EXISTS native_network (
+ id serial PRIMARY KEY,
+ inet_value inet,
+ cidr_value cidr,
+ mac_value macaddr,
+ mac8_value macaddr8
+);
+
+CREATE TABLE IF NOT EXISTS native_bits (
+ id serial PRIMARY KEY,
+ fixed_bits bit(8),
+ var_bits varbit,
+ five_bits bit(5)
+);
+
+CREATE TABLE IF NOT EXISTS native_full_text (
+ id serial PRIMARY KEY,
+ vector_value tsvector,
+ query_value tsquery
+);
+
+CREATE TABLE IF NOT EXISTS native_geometric (
+ id serial PRIMARY KEY,
+ point_value point,
+ line_value line,
+ lseg_value lseg,
+ box_value box,
+ path_value path,
+ polygon_value polygon,
+ circle_value circle
+);
+
+CREATE TABLE IF NOT EXISTS native_arrays (
+ id serial PRIMARY KEY,
+ ints int[],
+ texts text[]
+);
+
+CREATE TABLE IF NOT EXISTS native_ranges (
+ id serial PRIMARY KEY,
+ i4 int4range,
+ i8 int8range,
+ num numrange,
+ ts tsrange,
+ tstz tstzrange,
+ dt daterange
+);
+
+CREATE TABLE IF NOT EXISTS native_multiranges (
+ id serial PRIMARY KEY,
+ i4 int4multirange,
+ i8 int8multirange,
+ num nummultirange,
+ ts tsmultirange,
+ tstz tstzmultirange,
+ dt datemultirange
+);
+
+CREATE TABLE IF NOT EXISTS native_json_xml (
+ id serial PRIMARY KEY,
+ payload_json json,
+ payload_jsonb jsonb,
+ path_value jsonpath,
+ doc xml
+);
+
+CREATE TABLE IF NOT EXISTS native_remaining (
+ id serial PRIMARY KEY,
+ payload bytea,
+ span interval
+);
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_arrays.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_arrays.py
new file mode 100644
index 00000000..974c6729
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_arrays.py
@@ -0,0 +1,105 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_arrays.py
+"""Native tests for PostgreSQL ``T[]`` arrays.
+
+The registered suggestion for ``list`` must stay the native
+``PostgresListAdapter`` (list -> list), never the JSON text adapter. Arrays
+are asserted three ways: the server's ``{...}`` text, the driver's decoded
+list, and a native ``{1,2}`` literal written without the adapter.
+"""
+
+import pytest
+
+from rhosocial.activerecord.backend.errors import DatabaseError
+from rhosocial.activerecord.backend.impl.postgres.adapters.base import (
+ PostgresListAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.adapters.json import (
+ PostgresJSONBAdapter,
+)
+from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import (
+ insert_row,
+ insert_sql,
+ read_raw,
+ read_value,
+ update_cell,
+)
+
+TABLE = "native_arrays"
+
+ARRAY = PostgresListAdapter()
+
+
+class TestArrays:
+ TABLES = (TABLE,)
+
+ def test_native_int_and_text_arrays_round_trip(self, native_backend):
+ """S1/S2: bound lists stay lists and their server text is ``{...}``."""
+ backend = native_backend
+ ints = [1, 2, 3]
+ texts = ["a", "b"]
+ row_id = insert_row(
+ backend,
+ TABLE,
+ {
+ "ints": ARRAY.to_database(ints, list),
+ "texts": ARRAY.to_database(texts, list),
+ },
+ {"ints": "int[]", "texts": "text[]"},
+ )
+
+ assert read_raw(backend, TABLE, "ints", row_id) == "{1,2,3}"
+ assert read_raw(backend, TABLE, "texts", row_id) == "{a,b}"
+ assert read_value(backend, TABLE, "ints", row_id) == ints
+ assert read_value(backend, TABLE, "texts", row_id) == texts
+
+ assert ARRAY.from_database(read_value(backend, TABLE, "ints", row_id), list) == ints
+ assert ARRAY.from_database(read_value(backend, TABLE, "texts", row_id), list) == texts
+
+ update_cell(
+ backend, TABLE, "ints", row_id,
+ ARRAY.to_database(ARRAY.from_database(ints, list), list), "int[]",
+ )
+ assert read_raw(backend, TABLE, "ints", row_id) == "{1,2,3}"
+
+ def test_empty_list_is_distinct_from_null(self, native_backend):
+ """An empty list stores ``{}``, while NULL remains NULL."""
+ backend = native_backend
+ empty_row = insert_row(
+ backend, TABLE, {"ints": ARRAY.to_database([], list)}, {"ints": "int[]"}
+ )
+ null_row = insert_row(backend, TABLE, {"ints": None}, {"ints": "int[]"})
+
+ assert read_raw(backend, TABLE, "ints", empty_row) == "{}"
+ assert read_value(backend, TABLE, "ints", empty_row) == []
+ assert read_value(backend, TABLE, "ints", null_row) is None
+
+ def test_native_array_literal_reads_back_as_a_list(self, native_backend):
+ """S3: postgres-written ``{4,5}`` and ``{x,y}`` are plain lists."""
+ backend = native_backend
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (ints, texts) VALUES "
+ "('{{4,5}}'::int[], '{{x,y}}'::text[]) RETURNING id".format(TABLE),
+ )
+ assert read_raw(backend, TABLE, "ints", row_id) == "{4,5}"
+ assert read_raw(backend, TABLE, "texts", row_id) == "{x,y}"
+ assert read_value(backend, TABLE, "ints", row_id) == [4, 5]
+ assert read_value(backend, TABLE, "texts", row_id) == ["x", "y"]
+ assert ARRAY.from_database([4, 5], list) == [4, 5]
+
+ def test_array_suggestion_is_native_and_not_json(self, native_backend):
+ """J9 guard: ``list`` resolves to the array adapter, not JSON text."""
+ suggestions = native_backend.get_default_adapter_suggestions()
+ adapter, target = suggestions[list]
+ assert target is list
+ assert isinstance(adapter, PostgresListAdapter)
+ assert not isinstance(adapter, PostgresJSONBAdapter)
+ # The write-side value is handed to psycopg unchanged.
+ assert adapter.to_database([1, 2], list) == [1, 2]
+
+ def test_wrong_element_type_is_rejected_by_the_server(self, native_backend):
+ """The array's element type is enforced by PostgreSQL."""
+ with pytest.raises(DatabaseError):
+ native_backend.execute(
+ "SELECT %s::int[]", (ARRAY.to_database(["not-an-int"], list),)
+ )
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_bit_strings.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_bit_strings.py
new file mode 100644
index 00000000..1f4293a8
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_bit_strings.py
@@ -0,0 +1,128 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_bit_strings.py
+"""Native tests for PostgreSQL ``bit(n)`` and ``varbit``.
+
+The neutral ``BitString`` adapter binds the bare binary digits; ``bit(n)``
+right-pads them exactly as PostgreSQL does. The wrapper
+``PostgresBitStringAdapter`` emits the SQL literal ``B'1010'`` instead, which
+is used inline for the wrapper path. The bit length is asserted separately
+from the bytes.
+"""
+
+import pytest
+
+from rhosocial.activerecord.backend.adapters import BitString
+from rhosocial.activerecord.backend.errors import TypeConversionError
+from rhosocial.activerecord.backend.impl.postgres.adapters.bit_string import (
+ PostgresBitStringAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.adapters.neutral import (
+ PostgresNeutralBitStringAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values import (
+ PostgresBitString,
+)
+from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import (
+ insert_row,
+ insert_sql,
+ read_raw,
+ update_cell,
+)
+
+TABLE = "native_bits"
+
+WRAPPER = PostgresBitStringAdapter()
+NEUTRAL = PostgresNeutralBitStringAdapter()
+
+
+class TestBitStrings:
+ TABLES = (TABLE,)
+
+ def test_bit8_pads_on_the_right_and_stays_stable(self, native_backend):
+ """S2: a short input into bit(8) is padded, and re-writing is a no-op."""
+ backend = native_backend
+ value = BitString.from_bits("1010")
+ bound = NEUTRAL.to_database(value, str)
+ assert bound == "1010"
+
+ row_id = insert_row(backend, TABLE, {"fixed_bits": bound}, {"fixed_bits": "bit(8)"})
+ raw = read_raw(backend, TABLE, "fixed_bits", row_id)
+ assert raw == "10100000"
+
+ decoded = NEUTRAL.from_database(raw, BitString)
+ assert decoded.to_bits() == "10100000"
+ assert decoded.bit_length == 8
+
+ update_cell(
+ backend, TABLE, "fixed_bits", row_id,
+ NEUTRAL.to_database(decoded, str), "bit(8)",
+ )
+ assert read_raw(backend, TABLE, "fixed_bits", row_id) == raw
+
+ def test_varbit_preserves_non_byte_aligned_lengths(self, native_backend):
+ """S1/S2: five bits stay five bits in both varbit and bit(5)."""
+ backend = native_backend
+ value = BitString.from_bits("10101")
+ row_id = insert_row(
+ backend,
+ TABLE,
+ {
+ "var_bits": NEUTRAL.to_database(value, str),
+ "five_bits": NEUTRAL.to_database(value, str),
+ },
+ {"var_bits": "varbit", "five_bits": "bit(5)"},
+ )
+
+ assert read_raw(backend, TABLE, "var_bits", row_id) == "10101"
+ assert read_raw(backend, TABLE, "five_bits", row_id) == "10101"
+
+ decoded = NEUTRAL.from_database("10101", BitString)
+ assert decoded == value
+ assert decoded.bit_length == 5
+
+ update_cell(backend, TABLE, "var_bits", row_id, "10101", "varbit")
+ assert read_raw(backend, TABLE, "var_bits", row_id) == "10101"
+
+ def test_declared_length_option_pads_external_text(self):
+ """S1: an explicit bit length restores the leading zeros in text."""
+ padded = NEUTRAL.from_database("1010", BitString, {"bit_length": 8})
+ assert padded.to_bits() == "10100000"
+ assert padded.bit_length == 8
+
+ def test_wrapper_adapter_emits_an_sql_literal(self, native_backend):
+ """The wrapper adapter's wire form is ``B'...'``, used inline."""
+ backend = native_backend
+ value = PostgresBitString("1010")
+ literal = WRAPPER.to_database(value, str)
+ assert literal == "B'1010'"
+
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (five_bits) VALUES ({}::bit(5)) RETURNING id".format(
+ TABLE, literal
+ ),
+ )
+ raw = read_raw(backend, TABLE, "five_bits", row_id)
+ assert raw == "10100"
+ decoded = WRAPPER.from_database(raw, PostgresBitString)
+ assert decoded == PostgresBitString("10100")
+
+ def test_external_bit_literal_is_accepted(self, native_backend):
+ """S3: ``B'101'`` written by native SQL reads back as three bits."""
+ backend = native_backend
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (var_bits) VALUES (B'101'::varbit) RETURNING id".format(
+ TABLE
+ ),
+ )
+ raw = read_raw(backend, TABLE, "var_bits", row_id)
+ assert raw == "101"
+ decoded = NEUTRAL.from_database(raw, BitString)
+ assert decoded == BitString.from_bits("101")
+ assert decoded.bit_length == 3
+
+ def test_invalid_bit_text_is_wrapped(self):
+ """Non-binary text is rejected by the adapter, not passed to the driver."""
+ for text in ("102", "", "B'101"):
+ with pytest.raises(TypeConversionError):
+ NEUTRAL.from_database(text, BitString)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_extensions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_extensions.py
new file mode 100644
index 00000000..9fc5cca8
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_extensions.py
@@ -0,0 +1,169 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_extensions.py
+"""Native tests for extension-provided types.
+
+The extension existence is established before any table is created, so a
+server without the extension reports a skip naming exactly that extension.
+On the shared test server only ``hstore`` is available; ``postgis`` and
+``pgvector`` are listed in ``pg_available_extensions`` as absent and their
+classes skip accordingly.
+"""
+
+import pytest
+
+from rhosocial.activerecord.backend.adapters import Geometry, Vector
+from rhosocial.activerecord.backend.errors import DatabaseError, TypeConversionError
+from rhosocial.activerecord.backend.impl.postgres.adapters.hstore import (
+ PostgresHstoreAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.adapters.neutral import (
+ PostgresNeutralGeometryAdapter,
+ PostgresNeutralVectorAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values import (
+ PostgresHstore,
+)
+from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import (
+ insert_row,
+ insert_sql,
+ read_raw,
+ update_cell,
+)
+
+POSTGIS_TABLE = "native_ext_postgis"
+VECTOR_TABLE = "native_ext_pgvector"
+HSTORE_TABLE = "native_ext_hstore"
+
+GEOMETRY = PostgresNeutralGeometryAdapter()
+VECTOR = PostgresNeutralVectorAdapter()
+HSTORE = PostgresHstoreAdapter()
+
+
+class TestPostgis:
+ """PostGIS geometry/geography; skipped when the extension is absent."""
+
+ def test_geometry_ewkt_round_trip_and_srid(self, postgis_backend):
+ backend = postgis_backend
+ value = Geometry.from_wkt("POINT (1 2)", srid=4326)
+ bound = GEOMETRY.to_database(value, str)
+ assert bound == "SRID=4326;POINT (1.0 2.0)"
+
+ row_id = insert_row(
+ backend, POSTGIS_TABLE, {"geom": bound}, {"geom": "geometry"}
+ )
+ ewkt = read_raw(backend, POSTGIS_TABLE, "geom", row_id, "ST_AsEWKT(geom)")
+ assert ewkt.startswith("SRID=4326;POINT")
+ assert read_raw(backend, POSTGIS_TABLE, "geom", row_id, "ST_SRID(geom)") == 4326
+
+ decoded = GEOMETRY.from_database(ewkt, Geometry)
+ assert decoded.srid == 4326
+ assert decoded.to_wkt().startswith("POINT")
+
+ update_cell(backend, POSTGIS_TABLE, "geom", row_id, ewkt, "geometry")
+ assert read_raw(backend, POSTGIS_TABLE, "geom", row_id, "ST_AsEWKT(geom)") == ewkt
+
+ def test_geography_keeps_its_default_srid(self, postgis_backend):
+ backend = postgis_backend
+ value = Geometry.from_wkt("POINT (1 2)", srid=4326)
+ bound = GEOMETRY.to_database(value, str)
+ row_id = insert_row(
+ backend, POSTGIS_TABLE, {"geog": bound}, {"geog": "geography"}
+ )
+ assert read_raw(backend, POSTGIS_TABLE, "geog", row_id, "ST_SRID(geog)") == 4326
+ ewkt = read_raw(backend, POSTGIS_TABLE, "geog", row_id, "ST_AsEWKT(geog)")
+ assert ewkt.startswith("SRID=4326;POINT")
+ assert GEOMETRY.from_database(ewkt, Geometry).srid == 4326
+
+ def test_default_geometry_text_is_hex_ewkb_and_rejected(self, postgis_backend):
+ """PostGIS's default output is EWKB hex; the adapter refuses to guess."""
+ backend = postgis_backend
+ row_id = insert_row(
+ backend,
+ POSTGIS_TABLE,
+ {"geom": GEOMETRY.to_database(Geometry.from_wkt("POINT (1 2)", srid=4326), str)},
+ {"geom": "geometry"},
+ )
+ hex_ewkb = read_raw(backend, POSTGIS_TABLE, "geom", row_id, "geom::text")
+ assert hex_ewkb[:2].lower() == "01"
+ with pytest.raises(TypeConversionError) as excinfo:
+ GEOMETRY.from_database(hex_ewkb, Geometry)
+ assert "EWKB" in str(excinfo.value)
+
+ def test_external_ewkt_literal_reads_back(self, postgis_backend):
+ backend = postgis_backend
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (geom) VALUES "
+ "(ST_GeomFromEWKT('SRID=4326;POINT(1 2)')) RETURNING id".format(
+ POSTGIS_TABLE
+ ),
+ )
+ ewkt = read_raw(backend, POSTGIS_TABLE, "geom", row_id, "ST_AsEWKT(geom)")
+ assert ewkt == "SRID=4326;POINT(1 2)"
+ assert GEOMETRY.from_database(ewkt, Geometry).srid == 4326
+
+
+class TestPgVector:
+ """pgvector ``vector``; skipped when the extension is absent."""
+
+ def test_vector_text_round_trip(self, vector_backend):
+ backend = vector_backend
+ value = Vector((1.0, 2.0, 3.0))
+ bound = VECTOR.to_database(value, str)
+ assert bound == "[1.0,2.0,3.0]"
+
+ row_id = insert_row(
+ backend, VECTOR_TABLE, {"embedding": bound}, {"embedding": "vector(3)"}
+ )
+ raw = read_raw(backend, VECTOR_TABLE, "embedding", row_id)
+ assert raw == "[1,2,3]"
+ assert read_raw(
+ backend, VECTOR_TABLE, "embedding", row_id, "vector_dims(embedding)"
+ ) == 3
+ assert VECTOR.from_database(raw, Vector) == value
+
+ update_cell(
+ backend, VECTOR_TABLE, "embedding", row_id,
+ VECTOR.to_database(VECTOR.from_database(raw, Vector), str), "vector(3)",
+ )
+ assert read_raw(backend, VECTOR_TABLE, "embedding", row_id) == raw
+
+ def test_vector_dimension_mismatch_is_rejected(self, vector_backend):
+ backend = vector_backend
+ with pytest.raises(DatabaseError):
+ backend.execute(
+ "SELECT %s::vector(3)", (VECTOR.to_database(Vector((1.0, 2.0)), str),)
+ )
+
+
+class TestHstore:
+ """hstore key/value pairs; installed from contrib when available."""
+
+ def test_hstore_dict_round_trip_and_raw_text(self, hstore_backend):
+ backend = hstore_backend
+ value = {"a": "1", "b": "2"}
+ bound = HSTORE.to_database(value, str)
+ assert bound == '"a"=>"1", "b"=>"2"'
+
+ row_id = insert_row(
+ backend, HSTORE_TABLE, {"attrs": bound}, {"attrs": "hstore"}
+ )
+ raw = read_raw(backend, HSTORE_TABLE, "attrs", row_id)
+ assert raw == '"a"=>"1", "b"=>"2"'
+ decoded = HSTORE.from_database(raw, PostgresHstore)
+ assert decoded.data == value
+
+ update_cell(backend, HSTORE_TABLE, "attrs", row_id, raw, "hstore")
+ assert read_raw(backend, HSTORE_TABLE, "attrs", row_id) == raw
+
+ def test_external_hstore_literal_including_null(self, hstore_backend):
+ backend = hstore_backend
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (attrs) VALUES ('a=>1, b=>NULL'::hstore) RETURNING id".format(
+ HSTORE_TABLE
+ ),
+ )
+ raw = read_raw(backend, HSTORE_TABLE, "attrs", row_id)
+ assert raw == '"a"=>"1", "b"=>NULL'
+ decoded = HSTORE.from_database(raw, PostgresHstore)
+ assert decoded.data == {"a": "1", "b": None}
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_full_text.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_full_text.py
new file mode 100644
index 00000000..b6862a44
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_full_text.py
@@ -0,0 +1,110 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_full_text.py
+"""Native tests for PostgreSQL ``tsvector`` and ``tsquery``.
+
+Both types are asserted through ``col::text``, which is PostgreSQL's own
+lexeme serialisation, and then decoded with the backend wrappers. A second
+write must reproduce the same text (S2), and native literals written by SQL
+must read back (S3).
+"""
+
+import pytest
+
+from rhosocial.activerecord.backend.impl.postgres.adapters.text_search import (
+ PostgresTsQueryAdapter,
+ PostgresTsVectorAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values import (
+ PostgresTsQuery,
+ PostgresTsVector,
+)
+from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import (
+ insert_row,
+ insert_sql,
+ read_raw,
+ update_cell,
+)
+
+TABLE = "native_full_text"
+
+TSVECTOR = PostgresTsVectorAdapter()
+TSQUERY = PostgresTsQueryAdapter()
+
+
+class TestFullText:
+ TABLES = (TABLE,)
+
+ def test_tsvector_keeps_positions_and_weights(self, native_backend):
+ """S1/S2: sorted lexemes with positions/weights survive a rewrite."""
+ backend = native_backend
+ value = PostgresTsVector.from_string("'hello':1A 'world':2B")
+ bound = TSVECTOR.to_database(value, str)
+ assert bound == "'hello':1A 'world':2B"
+
+ row_id = insert_row(
+ backend, TABLE, {"vector_value": bound}, {"vector_value": "tsvector"}
+ )
+ raw = read_raw(backend, TABLE, "vector_value", row_id)
+ assert raw == "'hello':1A 'world':2B"
+
+ decoded = TSVECTOR.from_database(raw, PostgresTsVector)
+ assert decoded == value
+ assert decoded.get_positions("hello") == [(1, "A")]
+
+ update_cell(
+ backend, TABLE, "vector_value", row_id,
+ TSVECTOR.to_database(decoded, str), "tsvector",
+ )
+ assert read_raw(backend, TABLE, "vector_value", row_id) == raw
+
+ def test_tsquery_keeps_boolean_structure(self, native_backend):
+ """S1/S2: the AND structure and its text stay stable."""
+ backend = native_backend
+ value = PostgresTsQuery.parse("hello & world")
+ bound = TSQUERY.to_database(value, str)
+ assert bound == "'hello' & 'world'"
+
+ row_id = insert_row(
+ backend, TABLE, {"query_value": bound}, {"query_value": "tsquery"}
+ )
+ raw = read_raw(backend, TABLE, "query_value", row_id)
+ assert raw == "'hello' & 'world'"
+
+ decoded = TSQUERY.from_database(raw, PostgresTsQuery)
+ assert decoded == value
+
+ update_cell(
+ backend, TABLE, "query_value", row_id,
+ TSQUERY.to_database(decoded, str), "tsquery",
+ )
+ assert read_raw(backend, TABLE, "query_value", row_id) == raw
+
+ def test_external_full_text_literals_are_parsed(self, native_backend):
+ """S3: native text forms produced by SQL read back as wrappers."""
+ backend = native_backend
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (vector_value, query_value) VALUES "
+ "(to_tsvector('simple', 'cat dog'), "
+ "to_tsquery('simple', 'cat & dog')) RETURNING id".format(TABLE),
+ )
+
+ raw_vector = read_raw(backend, TABLE, "vector_value", row_id)
+ raw_query = read_raw(backend, TABLE, "query_value", row_id)
+ assert raw_vector == "'cat':1 'dog':2"
+ assert raw_query == "'cat' & 'dog'"
+
+ vector = TSVECTOR.from_database(raw_vector, PostgresTsVector)
+ query = TSQUERY.from_database(raw_query, PostgresTsQuery)
+ assert vector.get_lexemes() == ["cat", "dog"]
+ assert vector.get_positions("dog") == [(2, None)]
+ assert query == PostgresTsQuery.parse("cat & dog")
+
+ def test_invalid_tsquery_text_raises_value_error(self):
+ """The legacy wrapper adapter raises ValueError, not TypeConversionError.
+
+ The family-based adapters wrap failures, but ``PostgresTsQueryAdapter``
+ predates that base class and surfaces the parser's ValueError directly.
+ Recording it here keeps the contract explicit instead of guessing.
+ """
+ with pytest.raises(ValueError):
+ TSQUERY.from_database("hello &", PostgresTsQuery)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_geometric.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_geometric.py
new file mode 100644
index 00000000..da80fcec
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_geometric.py
@@ -0,0 +1,183 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_geometric.py
+"""Native tests for PostgreSQL's built-in geometric types.
+
+The seven wrapper types are checked together: each column is read through
+``col::text`` in one SELECT, which is the server's canonical geometric text
+(and which drops trailing ``.0`` components). Decoding happens with the
+wrapper's own target class; re-writing server text must not change it.
+"""
+
+import pytest
+
+from rhosocial.activerecord.backend.impl.postgres.adapters.geometric import (
+ PostgresGeometryAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values import (
+ Box,
+ Circle,
+ Line,
+ LineSegment,
+ Path,
+ Point,
+ Polygon,
+)
+from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import (
+ insert_row,
+ insert_sql,
+ read_raw,
+ update_cell,
+)
+
+TABLE = "native_geometric"
+
+WRAPPER = PostgresGeometryAdapter()
+
+_RAW_COLUMNS = (
+ "point_value",
+ "line_value",
+ "lseg_value",
+ "box_value",
+ "path_value",
+ "polygon_value",
+ "circle_value",
+)
+
+
+class TestGeometric:
+ TABLES = (TABLE,)
+
+ def test_seven_shapes_round_trip_and_raw_text(self, native_backend):
+ """S1: all seven shapes decode, and their text has the documented form."""
+ backend = native_backend
+ values = {
+ "point_value": WRAPPER.to_database(Point(1.5, 2.5), str),
+ "line_value": WRAPPER.to_database(Line(1.0, -1.0, 0.0), str),
+ "lseg_value": WRAPPER.to_database(
+ LineSegment(Point(0.0, 0.0), Point(1.5, 1.5)), str
+ ),
+ "box_value": WRAPPER.to_database(
+ Box(Point(1.5, 1.5), Point(0.0, 0.0)), str
+ ),
+ "path_value": WRAPPER.to_database(
+ Path([Point(0.5, 0.0), Point(1.5, 1.0), Point(2.5, 0.0)]), str
+ ),
+ "polygon_value": WRAPPER.to_database(
+ Polygon(
+ [
+ Point(0.5, 0.5),
+ Point(10.5, 0.5),
+ Point(10.5, 10.5),
+ Point(0.5, 0.5),
+ ]
+ ),
+ str,
+ ),
+ "circle_value": WRAPPER.to_database(Circle(Point(1.5, 2.5), 3.5), str),
+ }
+ casts = {name: name[: -len("_value")] for name in values}
+ row_id = insert_row(backend, TABLE, values, casts)
+
+ select = ", ".join(
+ "{}::text AS {}".format(name, name) for name in _RAW_COLUMNS
+ )
+ row = backend.fetch_one(
+ "SELECT {} FROM {} WHERE id = %s".format(select, TABLE), (row_id,)
+ )
+ assert row["point_value"] == "(1.5,2.5)"
+ assert row["line_value"] == "{1,-1,0}"
+ assert row["lseg_value"] == "[(0,0),(1.5,1.5)]"
+ assert row["box_value"] == "(1.5,1.5),(0,0)"
+ assert row["path_value"] == "[(0.5,0),(1.5,1),(2.5,0)]"
+ assert row["polygon_value"] == (
+ "((0.5,0.5),(10.5,0.5),(10.5,10.5),(0.5,0.5))"
+ )
+ assert row["circle_value"] == "<(1.5,2.5),3.5>"
+
+ assert WRAPPER.from_database(row["point_value"], Point) == Point(1.5, 2.5)
+ assert WRAPPER.from_database(row["line_value"], Line) == Line(1.0, -1.0, 0.0)
+ assert WRAPPER.from_database(row["lseg_value"], LineSegment) == LineSegment(
+ Point(0.0, 0.0), Point(1.5, 1.5)
+ )
+ assert WRAPPER.from_database(row["box_value"], Box) == Box(
+ Point(1.5, 1.5), Point(0.0, 0.0)
+ )
+ assert WRAPPER.from_database(row["path_value"], Path) == Path(
+ [Point(0.5, 0.0), Point(1.5, 1.0), Point(2.5, 0.0)]
+ )
+ assert WRAPPER.from_database(row["polygon_value"], Polygon) == Polygon(
+ [
+ Point(0.5, 0.5),
+ Point(10.5, 0.5),
+ Point(10.5, 10.5),
+ Point(0.5, 0.5),
+ ]
+ )
+ assert WRAPPER.from_database(row["circle_value"], Circle) == Circle(
+ Point(1.5, 2.5), 3.5
+ )
+
+ def test_open_and_closed_paths_keep_their_brackets(self, native_backend):
+ """The path's bracket form is data, not formatting."""
+ backend = native_backend
+ open_value = Path([Point(0.5, 0.0), Point(1.5, 1.0)], is_closed=False)
+ closed_value = Path([Point(0.5, 0.0), Point(1.5, 1.0)], is_closed=True)
+
+ open_row = insert_row(
+ backend,
+ TABLE,
+ {"path_value": WRAPPER.to_database(open_value, str)},
+ {"path_value": "path"},
+ )
+ closed_row = insert_row(
+ backend,
+ TABLE,
+ {"path_value": WRAPPER.to_database(closed_value, str)},
+ {"path_value": "path"},
+ )
+ assert read_raw(backend, TABLE, "path_value", open_row) == "[(0.5,0),(1.5,1)]"
+ assert read_raw(backend, TABLE, "path_value", closed_row) == "((0.5,0),(1.5,1))"
+ assert WRAPPER.from_database(
+ read_raw(backend, TABLE, "path_value", closed_row), Path
+ ).is_closed
+
+ def test_rewriting_server_text_does_not_drift(self, native_backend):
+ """S2: the server canonical text is stable across a write/read/write."""
+ backend = native_backend
+ value = Box(Point(1.5, 1.5), Point(0.0, 0.0))
+ row_id = insert_row(
+ backend,
+ TABLE,
+ {"box_value": WRAPPER.to_database(value, str)},
+ {"box_value": "box"},
+ )
+ raw = read_raw(backend, TABLE, "box_value", row_id)
+ decoded = WRAPPER.from_database(raw, Box)
+ assert decoded == value
+
+ update_cell(
+ backend, TABLE, "box_value", row_id,
+ WRAPPER.to_database(decoded, str), "box",
+ )
+ assert read_raw(backend, TABLE, "box_value", row_id) == raw
+
+ def test_external_geometric_literals_are_parsed(self, native_backend):
+ """S3: native SQL literals read back through the wrapper adapter."""
+ backend = native_backend
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (point_value, circle_value, polygon_value) VALUES "
+ "('(1,2)'::point, '<(1,2),3>'::circle, "
+ "'((0,0),(1,0),(1,1),(0,0))'::polygon) RETURNING id".format(TABLE),
+ )
+ assert read_raw(backend, TABLE, "point_value", row_id) == "(1,2)"
+ assert read_raw(backend, TABLE, "circle_value", row_id) == "<(1,2),3>"
+ assert read_raw(backend, TABLE, "polygon_value", row_id) == (
+ "((0,0),(1,0),(1,1),(0,0))"
+ )
+ assert WRAPPER.from_database("(1,2)", Point) == Point(1.0, 2.0)
+ assert WRAPPER.from_database("<(1,2),3>", Circle) == Circle(Point(1.0, 2.0), 3.0)
+
+ def test_malformed_geometric_text_raises(self):
+ """The legacy wrapper adapter surfaces malformed text as ValueError."""
+ with pytest.raises(ValueError):
+ WRAPPER.from_database("(1)", Point)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_json_xml.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_json_xml.py
new file mode 100644
index 00000000..82fdb9d1
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_json_xml.py
@@ -0,0 +1,157 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_json_xml.py
+"""Native tests for PostgreSQL ``json``/``jsonb``/``jsonpath`` and ``xml``.
+
+psycopg decodes ``json`` and ``jsonb`` to ``dict``/``list`` before the
+adapter sees them, so ``from_database`` must pass the decoded document
+through instead of calling ``json.loads`` again. ``jsonpath`` and ``xml``
+have text wire forms and are asserted through ``col::text``.
+"""
+
+import json
+
+import pytest
+
+from rhosocial.activerecord.backend.errors import DatabaseError
+from rhosocial.activerecord.backend.impl.postgres.adapters.base import (
+ PostgresJSONBAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.adapters.json import (
+ PostgresJsonPathAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.adapters.xml import (
+ PostgresXMLAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values import (
+ PostgresJsonPath,
+ PostgresXML,
+)
+from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import (
+ insert_row,
+ insert_sql,
+ read_raw,
+ read_value,
+ update_cell,
+)
+
+TABLE = "native_json_xml"
+
+JSON_ADAPTER = PostgresJSONBAdapter()
+JSONPATH = PostgresJsonPathAdapter()
+XML = PostgresXMLAdapter()
+
+
+class TestJsonXml:
+ TABLES = (TABLE,)
+
+ def test_json_and_jsonb_pass_decoded_documents_through(self, native_backend):
+ """S1: psycopg returns dicts, and the adapter does not re-decode them."""
+ backend = native_backend
+ value = {"a": 1, "b": [1, 2]}
+ bound = JSON_ADAPTER.to_database(value, dict)
+ row_id = insert_row(
+ backend,
+ TABLE,
+ {"payload_json": bound, "payload_jsonb": bound},
+ {"payload_json": "json", "payload_jsonb": "jsonb"},
+ )
+
+ # Both forms are serialised by the same dumper; jsonb canonicalises
+ # the whitespace, json keeps the dumped compact shape.
+ assert read_raw(backend, TABLE, "payload_json", row_id) == '{"a": 1, "b": [1, 2]}'
+ assert read_raw(backend, TABLE, "payload_jsonb", row_id) == '{"a": 1, "b": [1, 2]}'
+
+ for column in ("payload_json", "payload_jsonb"):
+ driver_value = read_value(backend, TABLE, column, row_id)
+ assert isinstance(driver_value, dict)
+ assert driver_value == value
+ assert JSON_ADAPTER.from_database(driver_value, dict) == value
+
+ update_cell(backend, TABLE, "payload_jsonb", row_id, bound, "jsonb")
+ assert read_raw(backend, TABLE, "payload_jsonb", row_id) == (
+ '{"a": 1, "b": [1, 2]}'
+ )
+
+ def test_jsonpath_canonicalises_the_path_text(self, native_backend):
+ """S1/S2: ``$.a`` is stored as ``$."a"`` and remains stable."""
+ backend = native_backend
+ value = PostgresJsonPath("$.a")
+ bound = JSONPATH.to_database(value, str)
+ assert bound == "$.a"
+
+ row_id = insert_row(
+ backend, TABLE, {"path_value": bound}, {"path_value": "jsonpath"}
+ )
+ raw = read_raw(backend, TABLE, "path_value", row_id)
+ assert raw == '$."a"'
+ decoded = JSONPATH.from_database(raw, PostgresJsonPath)
+ assert decoded == PostgresJsonPath('$."a"')
+ assert JSONPATH.to_database(decoded, str) == raw
+
+ update_cell(backend, TABLE, "path_value", row_id, raw, "jsonpath")
+ assert read_raw(backend, TABLE, "path_value", row_id) == raw
+
+ def test_xml_text_round_trips(self, native_backend):
+ """S1/S2: XML content is preserved verbatim and remains stable."""
+ backend = native_backend
+ value = PostgresXML("1")
+ bound = XML.to_database(value, str)
+ row_id = insert_row(backend, TABLE, {"doc": bound}, {"doc": "xml"})
+ raw = read_raw(backend, TABLE, "doc", row_id)
+ assert raw == "1"
+ assert XML.from_database(raw, PostgresXML) == value
+
+ update_cell(backend, TABLE, "doc", row_id, raw, "xml")
+ assert read_raw(backend, TABLE, "doc", row_id) == raw
+
+ def test_external_json_jsonpath_and_xml_literals(self, native_backend):
+ """S3: native SQL text is decoded into the same Python shapes."""
+ backend = native_backend
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (payload_json, payload_jsonb, path_value, doc) VALUES "
+ "('{{\"k\": \"v\"}}'::json, '{{\"k\":\"v\"}}'::jsonb, "
+ "'$.a'::jsonpath, '1'::xml) RETURNING id".format(TABLE),
+ )
+
+ assert read_raw(backend, TABLE, "payload_json", row_id) == '{"k": "v"}'
+ assert read_raw(backend, TABLE, "payload_jsonb", row_id) == '{"k": "v"}'
+ assert read_raw(backend, TABLE, "path_value", row_id) == '$."a"'
+ assert read_raw(backend, TABLE, "doc", row_id) == "1"
+
+ for column in ("payload_json", "payload_jsonb"):
+ driver_value = read_value(backend, TABLE, column, row_id)
+ assert driver_value == {"k": "v"}
+ assert JSON_ADAPTER.from_database(driver_value, dict) == {"k": "v"}
+
+ assert JSONPATH.from_database('$."a"', PostgresJsonPath) == PostgresJsonPath(
+ '$."a"'
+ )
+ assert XML.from_database("1", PostgresXML) == PostgresXML(
+ "1"
+ )
+
+ def test_malformed_xml_is_rejected_by_the_server(self, native_backend):
+ """PostgreSQL validates XML on input."""
+ with pytest.raises(DatabaseError):
+ native_backend.execute("SELECT %s::xml", ("",))
+
+ def test_jsonpath_requires_a_root_marker(self):
+ """The adapter rejects a path that is not rooted at ``$``."""
+ with pytest.raises(ValueError):
+ JSONPATH.to_database("a", str)
+ with pytest.raises(ValueError):
+ JSONPATH.from_database("a", PostgresJsonPath)
+
+ def test_json_document_is_never_double_encoded(self, native_backend):
+ """S2 guard: a dict read back stays a dict, not a JSON string."""
+ backend = native_backend
+ value = {"nested": {"n": 1}}
+ bound = JSON_ADAPTER.to_database(value, dict)
+ row_id = insert_row(
+ backend, TABLE, {"payload_jsonb": bound}, {"payload_jsonb": "jsonb"}
+ )
+ driver_value = read_value(backend, TABLE, "payload_jsonb", row_id)
+ decoded = JSON_ADAPTER.from_database(driver_value, dict)
+ assert decoded == value
+ assert not isinstance(decoded, str)
+ assert json.dumps(decoded, sort_keys=True) == json.dumps(value, sort_keys=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_network.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_network.py
new file mode 100644
index 00000000..47b6ad10
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_network.py
@@ -0,0 +1,169 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_network.py
+"""Native tests for PostgreSQL network address types.
+
+``inet``/``cidr`` use ``ipaddress`` objects, with ``host()`` and ``col::text``
+as the authoritative server expressions. ``macaddr``/``macaddr8`` must
+normalise uppercase, hyphenated and compact input to the lowercase
+colon-separated form.
+"""
+
+import ipaddress
+
+import pytest
+
+from rhosocial.activerecord.backend.errors import DatabaseError
+from rhosocial.activerecord.backend.impl.postgres.adapters.network_address import (
+ PostgresMacaddr8Adapter,
+ PostgresMacaddrAdapter,
+ PostgresNetworkAddressAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values import (
+ PostgresMacaddr,
+ PostgresMacaddr8,
+)
+from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import (
+ insert_row,
+ insert_sql,
+ read_raw,
+ read_value,
+ update_cell,
+)
+
+TABLE = "native_network"
+
+NETWORK = PostgresNetworkAddressAdapter()
+MACADDR = PostgresMacaddrAdapter()
+MACADDR8 = PostgresMacaddr8Adapter()
+
+
+class TestNetwork:
+ TABLES = (TABLE,)
+
+ def test_inet_address_and_interface_read_back(self, native_backend):
+ """S1/S2: host and netmask survive, and ``host()`` strips the mask."""
+ backend = native_backend
+ values = {
+ "inet_value": NETWORK.to_database(ipaddress.ip_address("192.168.1.5"), str),
+ }
+ row_id = insert_row(backend, TABLE, values, {"inet_value": "inet"})
+
+ assert read_raw(backend, TABLE, "inet_value", row_id) == "192.168.1.5/32"
+ assert read_raw(backend, TABLE, "inet_value", row_id, "host(inet_value)") == (
+ "192.168.1.5"
+ )
+ decoded = NETWORK.from_database(
+ read_value(backend, TABLE, "inet_value", row_id), str
+ )
+ assert decoded == ipaddress.ip_address("192.168.1.5")
+
+ update_cell(backend, TABLE, "inet_value", row_id, "192.168.1.5/32", "inet")
+ assert read_raw(backend, TABLE, "inet_value", row_id) == "192.168.1.5/32"
+
+ # An interface keeps the host bits and the mask together.
+ interface = ipaddress.ip_interface("192.168.1.5/24")
+ row_id = insert_row(
+ backend,
+ TABLE,
+ {"inet_value": NETWORK.to_database(interface, str)},
+ {"inet_value": "inet"},
+ )
+ assert read_raw(backend, TABLE, "inet_value", row_id) == "192.168.1.5/24"
+ assert read_raw(backend, TABLE, "inet_value", row_id, "host(inet_value)") == (
+ "192.168.1.5"
+ )
+ assert read_raw(backend, TABLE, "inet_value", row_id, "network(inet_value)::text") == (
+ "192.168.1.0/24"
+ )
+ decoded = NETWORK.from_database(
+ read_value(backend, TABLE, "inet_value", row_id), str
+ )
+ assert decoded == interface
+
+ def test_cidr_network_is_returned_as_a_network_object(self, native_backend):
+ """S1/S2: cidr binds as text and psycopg returns an IPv4Network."""
+ backend = native_backend
+ network = ipaddress.ip_network("192.168.1.0/24")
+ row_id = insert_row(
+ backend,
+ TABLE,
+ {"cidr_value": NETWORK.to_database(network, str)},
+ {"cidr_value": "cidr"},
+ )
+
+ assert read_raw(backend, TABLE, "cidr_value", row_id) == "192.168.1.0/24"
+ driver_value = read_value(backend, TABLE, "cidr_value", row_id)
+ assert isinstance(driver_value, ipaddress.IPv4Network)
+ assert NETWORK.from_database(driver_value, str) == network
+
+ update_cell(backend, TABLE, "cidr_value", row_id, "192.168.1.0/24", "cidr")
+ assert read_raw(backend, TABLE, "cidr_value", row_id) == "192.168.1.0/24"
+
+ def test_macaddr_normalises_uppercase_and_hyphenated_input(self, native_backend):
+ """S1/S2: the adapter and the server agree on the canonical form."""
+ backend = native_backend
+ value = PostgresMacaddr("08-00-2B-01-02-03")
+ assert MACADDR.to_database(value, str) == "08:00:2b:01:02:03"
+
+ row_id = insert_row(
+ backend,
+ TABLE,
+ {"mac_value": MACADDR.to_database(value, str)},
+ {"mac_value": "macaddr"},
+ )
+ raw = read_raw(backend, TABLE, "mac_value", row_id)
+ assert raw == "08:00:2b:01:02:03"
+ decoded = MACADDR.from_database(raw, PostgresMacaddr)
+ assert decoded == value
+ assert MACADDR.to_database(decoded, str) == raw
+
+ update_cell(backend, TABLE, "mac_value", row_id, raw, "macaddr")
+ assert read_raw(backend, TABLE, "mac_value", row_id) == raw
+
+ def test_macaddr8_expands_a_six_octet_address(self, native_backend):
+ """S1/S2: an EUI-48 input becomes the EUI-64 ``ff:fe`` form."""
+ backend = native_backend
+ value = PostgresMacaddr8("08002B010203")
+ assert MACADDR8.to_database(value, str) == "08:00:2b:ff:fe:01:02:03"
+
+ row_id = insert_row(
+ backend,
+ TABLE,
+ {"mac8_value": MACADDR8.to_database(value, str)},
+ {"mac8_value": "macaddr8"},
+ )
+ raw = read_raw(backend, TABLE, "mac8_value", row_id)
+ assert raw == "08:00:2b:ff:fe:01:02:03"
+ decoded = MACADDR8.from_database(raw, PostgresMacaddr8)
+ assert decoded == value
+ assert MACADDR8.to_database(decoded, str) == raw
+
+ def test_external_network_literals_are_parsed(self, native_backend):
+ """S3: native SQL text is accepted without an adapter write."""
+ backend = native_backend
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (inet_value, mac_value) VALUES "
+ "('10.0.0.1'::inet, '08002B010203'::macaddr) RETURNING id".format(TABLE),
+ )
+
+ assert read_raw(backend, TABLE, "inet_value", row_id) == "10.0.0.1/32"
+ assert read_raw(backend, TABLE, "mac_value", row_id) == "08:00:2b:01:02:03"
+ # Plain text carries the /32 mask, so the adapter's fallback decodes a
+ # /32 network rather than a bare host; the driver path above returns
+ # IPv4Address because psycopg already narrowed it. This is the
+ # documented limitation of parsing external inet text without a hint.
+ external = NETWORK.from_database("10.0.0.1/32", str)
+ assert isinstance(external, ipaddress.IPv4Network)
+ assert str(external) == "10.0.0.1/32"
+ assert MACADDR.from_database(
+ "08:00:2b:01:02:03", PostgresMacaddr
+ ) == PostgresMacaddr("08:00:2b:01:02:03")
+
+ def test_invalid_values_are_rejected(self, native_backend):
+ """Invalid input fails before SQL or at the server, never silently."""
+ with pytest.raises(ValueError):
+ PostgresMacaddr("08:00:2b:01:02")
+ with pytest.raises(ValueError):
+ PostgresMacaddr("08:00:2b:01:02:zz")
+ with pytest.raises(DatabaseError):
+ native_backend.execute("SELECT %s::inet", ("not-an-address",))
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py
new file mode 100644
index 00000000..f38c200a
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py
@@ -0,0 +1,278 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_ranges.py
+"""Native tests for PostgreSQL range and multirange types.
+
+Discrete ranges are normalised by the server (``[1,3]`` becomes ``[1,4)``),
+so the assertions compare canonical values rather than the input object.
+Text parsing cannot recover an element type on its own: without an
+``element_type``/``range_type`` hint, a quoted ``"2024-01-01"`` stays a
+``str``. That limitation is asserted explicitly, and the hinted form is
+asserted next to it.
+"""
+
+from datetime import date, datetime, timezone
+from decimal import Decimal
+
+import pytest
+
+from rhosocial.activerecord.backend.adapters import Multirange, Range
+from rhosocial.activerecord.backend.errors import TypeConversionError
+from rhosocial.activerecord.backend.impl.postgres.adapters.neutral import (
+ PostgresNeutralRangeAdapter,
+)
+from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import (
+ insert_row,
+ insert_sql,
+ read_raw,
+ update_cell,
+)
+
+RANGE_TABLE = "native_ranges"
+MULTIRANGE_TABLE = "native_multiranges"
+
+RANGE = PostgresNeutralRangeAdapter()
+
+
+def _require_multirange(backend):
+ if not backend.dialect.supports_multirange():
+ pytest.skip("multirange requires PostgreSQL 14+ per supports_multirange")
+
+
+def _read_range_columns(backend, table, row_id, columns):
+ select = ", ".join("{}::text AS {}".format(name, name) for name in columns)
+ return backend.fetch_one(
+ "SELECT {} FROM {} WHERE id = %s".format(select, table), (row_id,)
+ )
+
+
+class TestRanges:
+ TABLES = (RANGE_TABLE, MULTIRANGE_TABLE)
+
+ def test_six_range_types_bind_and_read_canonically(self, native_backend):
+ """S1: all six range types store and print their canonical text."""
+ backend = native_backend
+ backend.execute("SET TIME ZONE 'UTC'")
+ values = {
+ "i4": RANGE.to_database(Range(1, 3, "[]"), str),
+ "i8": RANGE.to_database(Range(2**40, 2**40 + 10, "[)"), str),
+ "num": RANGE.to_database(Range(Decimal("1.5"), Decimal("2.5"), "(]"), str),
+ "ts": RANGE.to_database(
+ Range(datetime(2024, 1, 1, 12, 0), datetime(2024, 1, 2, 12, 0), "[)"),
+ str,
+ ),
+ "tstz": RANGE.to_database(
+ Range(
+ datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc),
+ datetime(2024, 1, 2, 12, 0, tzinfo=timezone.utc),
+ "[)",
+ ),
+ str,
+ ),
+ "dt": RANGE.to_database(
+ Range(date(2024, 1, 1), date(2024, 1, 2), "[)"), str
+ ),
+ }
+ casts = {
+ "i4": "int4range",
+ "i8": "int8range",
+ "num": "numrange",
+ "ts": "tsrange",
+ "tstz": "tstzrange",
+ "dt": "daterange",
+ }
+ row_id = insert_row(backend, RANGE_TABLE, values, casts)
+ row = _read_range_columns(backend, RANGE_TABLE, row_id, values)
+
+ assert row["i4"] == "[1,4)"
+ assert row["i8"] == "[1099511627776,1099511627786)"
+ assert row["num"] == "(1.5,2.5]"
+ assert row["ts"] == '["2024-01-01 12:00:00","2024-01-02 12:00:00")'
+ assert row["tstz"] == '["2024-01-01 12:00:00+00","2024-01-02 12:00:00+00")'
+ assert row["dt"] == "[2024-01-01,2024-01-02)"
+
+ assert RANGE.from_database(row["i4"], Range, {"range_type": "int4range"}) == (
+ Range(1, 4, "[)")
+ )
+ assert RANGE.from_database(row["i8"], Range, {"range_type": "int8range"}) == (
+ Range(2**40, 2**40 + 10, "[)")
+ )
+ assert RANGE.from_database(row["num"], Range, {"element_type": "decimal"}) == (
+ Range(Decimal("1.5"), Decimal("2.5"), "(]")
+ )
+ assert RANGE.from_database(row["ts"], Range, {"element_type": "datetime"}) == (
+ Range(datetime(2024, 1, 1, 12, 0), datetime(2024, 1, 2, 12, 0), "[)")
+ )
+ assert RANGE.from_database(row["tstz"], Range, {"range_type": "tstzrange"}) == (
+ Range(
+ datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc),
+ datetime(2024, 1, 2, 12, 0, tzinfo=timezone.utc),
+ "[)",
+ )
+ )
+ assert RANGE.from_database(row["dt"], Range, {"range_type": "daterange"}) == (
+ Range(date(2024, 1, 1), date(2024, 1, 2), "[)")
+ )
+
+ def test_without_an_element_hint_quoted_bounds_stay_strings(self, native_backend):
+ """The documented limitation: text alone cannot infer date/datetime."""
+ backend = native_backend
+ backend.execute("SET TIME ZONE 'UTC'")
+ values = {"dt": RANGE.to_database(Range(date(2024, 1, 1), date(2024, 1, 2)), str)}
+ row_id = insert_row(backend, RANGE_TABLE, values, {"dt": "daterange"})
+ raw = read_raw(backend, RANGE_TABLE, "dt", row_id)
+
+ unhinted = RANGE.from_database(raw, Range)
+ assert unhinted.lower == "2024-01-01"
+ assert isinstance(unhinted.lower, str)
+ assert isinstance(unhinted.upper, str)
+
+ hinted = RANGE.from_database(raw, Range, {"element_type": "date"})
+ assert hinted.lower == date(2024, 1, 1)
+ assert hinted.upper == date(2024, 1, 2)
+
+ by_range_type = RANGE.from_database(raw, Range, {"range_type": "daterange"})
+ assert by_range_type == hinted
+
+ def test_empty_and_unbounded_ranges_are_normalised(self, native_backend):
+ """S2: empty stays empty; ``,5]`` canonicalises to ``(,6)``."""
+ backend = native_backend
+ backend.execute("SET TIME ZONE 'UTC'")
+ empty_row = insert_row(
+ backend,
+ RANGE_TABLE,
+ {"i4": RANGE.to_database(Range(empty=True), str)},
+ {"i4": "int4range"},
+ )
+ assert read_raw(backend, RANGE_TABLE, "i4", empty_row) == "empty"
+ empty = RANGE.from_database("empty", Range)
+ assert empty == Range(empty=True)
+ assert RANGE.to_database(empty, str) == "empty"
+
+ unbounded = Range(None, 5, "(]")
+ row_id = insert_row(
+ backend,
+ RANGE_TABLE,
+ {"i4": RANGE.to_database(unbounded, str)},
+ {"i4": "int4range"},
+ )
+ raw = read_raw(backend, RANGE_TABLE, "i4", row_id)
+ assert raw == "(,6)"
+ decoded = RANGE.from_database(raw, Range, {"range_type": "int4range"})
+ assert decoded == Range(None, 6, "()")
+
+ update_cell(
+ backend, RANGE_TABLE, "i4", row_id,
+ RANGE.to_database(decoded, str), "int4range",
+ )
+ assert read_raw(backend, RANGE_TABLE, "i4", row_id) == "(,6)"
+
+ def test_six_multirange_types_round_trip(self, native_backend):
+ """S1: all six multirange types keep their canonical segment list."""
+ backend = native_backend
+ _require_multirange(backend)
+ backend.execute("SET TIME ZONE 'UTC'")
+ values = {
+ "i4": RANGE.to_database(Multirange((Range(1, 5), Range(10, 15))), str),
+ "i8": RANGE.to_database(Multirange((Range(2**40, 2**40 + 5),)), str),
+ "num": RANGE.to_database(
+ Multirange((Range(Decimal("1.5"), Decimal("2.5")),)), str
+ ),
+ "ts": RANGE.to_database(
+ Multirange(
+ (Range(datetime(2024, 1, 1, 12, 0), datetime(2024, 1, 2, 12, 0)),)
+ ),
+ str,
+ ),
+ "tstz": RANGE.to_database(
+ Multirange(
+ (
+ Range(
+ datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc),
+ datetime(2024, 1, 2, 12, 0, tzinfo=timezone.utc),
+ ),
+ )
+ ),
+ str,
+ ),
+ "dt": RANGE.to_database(
+ Multirange((Range(date(2024, 1, 1), date(2024, 1, 2)),)), str
+ ),
+ }
+ casts = {
+ "i4": "int4multirange",
+ "i8": "int8multirange",
+ "num": "nummultirange",
+ "ts": "tsmultirange",
+ "tstz": "tstzmultirange",
+ "dt": "datemultirange",
+ }
+ row_id = insert_row(backend, MULTIRANGE_TABLE, values, casts)
+ row = _read_range_columns(backend, MULTIRANGE_TABLE, row_id, values)
+
+ assert row["i4"] == "{[1,5),[10,15)}"
+ assert row["i8"] == "{[1099511627776,1099511627781)}"
+ assert row["num"] == "{[1.5,2.5)}"
+ assert row["ts"] == '{["2024-01-01 12:00:00","2024-01-02 12:00:00")}'
+ assert row["tstz"] == '{["2024-01-01 12:00:00+00","2024-01-02 12:00:00+00")}'
+ assert row["dt"] == "{[2024-01-01,2024-01-02)}"
+
+ assert RANGE.from_database(row["i4"], Multirange, {"range_type": "int4range"}) == (
+ Multirange((Range(1, 5), Range(10, 15)))
+ )
+ assert RANGE.from_database(row["num"], Multirange, {"element_type": "decimal"}) == (
+ Multirange((Range(Decimal("1.5"), Decimal("2.5")),))
+ )
+ assert RANGE.from_database(row["dt"], Multirange, {"range_type": "daterange"}) == (
+ Multirange((Range(date(2024, 1, 1), date(2024, 1, 2)),))
+ )
+
+ def test_multirange_merges_overlap_and_sorts(self, native_backend):
+ """S2: unsorted/touching input becomes one sorted canonical list."""
+ backend = native_backend
+ _require_multirange(backend)
+ value = Multirange((Range(20, 25), Range(1, 5), Range(5, 10)))
+ assert RANGE.to_database(value, str) == "{[1,10),[20,25)}"
+
+ row_id = insert_row(
+ backend,
+ MULTIRANGE_TABLE,
+ {"i4": RANGE.to_database(value, str)},
+ {"i4": "int4multirange"},
+ )
+ raw = read_raw(backend, MULTIRANGE_TABLE, "i4", row_id)
+ assert raw == "{[1,10),[20,25)}"
+ decoded = RANGE.from_database(raw, Multirange, {"range_type": "int4range"})
+ assert decoded == Multirange((Range(1, 10), Range(20, 25)))
+
+ def test_external_range_and_multirange_literals(self, native_backend):
+ """S3: native SQL range literals read back as neutral values."""
+ backend = native_backend
+ _require_multirange(backend)
+ backend.execute("SET TIME ZONE 'UTC'")
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (i4, dt) VALUES "
+ "('[1,10)'::int4range, '[2024-01-01,2024-01-02)'::daterange) "
+ "RETURNING id".format(RANGE_TABLE),
+ )
+ multi_id = insert_sql(
+ backend,
+ "INSERT INTO {} (i4) VALUES "
+ "('{{[1,5),[10,15)}}'::int4multirange) RETURNING id".format(
+ MULTIRANGE_TABLE
+ ),
+ )
+
+ assert read_raw(backend, RANGE_TABLE, "i4", row_id) == "[1,10)"
+ assert read_raw(backend, RANGE_TABLE, "dt", row_id) == "[2024-01-01,2024-01-02)"
+ assert RANGE.from_database("[1,10)", Range, {"range_type": "int4range"}) == (
+ Range(1, 10, "[)")
+ )
+ assert read_raw(backend, MULTIRANGE_TABLE, "i4", multi_id) == "{[1,5),[10,15)}"
+ assert RANGE.from_database(
+ "{[1,5),[10,15)}", Multirange, {"range_type": "int4range"}
+ ) == Multirange((Range(1, 5), Range(10, 15)))
+
+ def test_unknown_element_hint_is_wrapped(self):
+ """A hint the adapter does not know is a conversion error."""
+ with pytest.raises(TypeConversionError):
+ RANGE.from_database("[1,2)", Range, {"element_type": "uuid"})
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_remaining.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_remaining.py
new file mode 100644
index 00000000..8a11ce5f
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_remaining.py
@@ -0,0 +1,89 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_remaining.py
+"""Native tests for ``bytea`` and ``interval``: the two pending gaps.
+
+Neither type has an adapter registered by this backend: ``bytes`` and
+``timedelta`` are absent from ``get_default_adapter_suggestions()`` and from
+the adapter registry. psycopg still round-trips both natively, so the tests
+pin that pass-through and record the missing adapter as a Phase 3b gap
+instead of inventing an adapter here.
+"""
+
+from datetime import timedelta
+
+from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import (
+ insert_row,
+ insert_sql,
+ read_raw,
+ read_value,
+ update_cell,
+)
+
+TABLE = "native_remaining"
+
+
+def _adapter_keys(backend, py_type):
+ return [
+ key
+ for key in backend.adapter_registry.get_all_adapters()
+ if key[0] is py_type
+ ]
+
+
+class TestRemainingTypes:
+ TABLES = (TABLE,)
+
+ def test_bytea_has_no_adapter_and_passes_through(self, native_backend):
+ """Gap: bytes has no adapter; psycopg binds and returns it unchanged."""
+ backend = native_backend
+ suggestions = backend.get_default_adapter_suggestions()
+ assert suggestions.get(bytes) is None
+ assert _adapter_keys(backend, bytes) == []
+
+ value = b"\x00\x01\xff"
+ row_id = insert_row(backend, TABLE, {"payload": value}, {"payload": "bytea"})
+ assert read_raw(backend, TABLE, "payload", row_id) == "\\x0001ff"
+ assert read_value(backend, TABLE, "payload", row_id) == value
+
+ update_cell(backend, TABLE, "payload", row_id, value, "bytea")
+ assert read_value(backend, TABLE, "payload", row_id) == value
+
+ def test_bytea_external_hex_literal_reads_back(self, native_backend):
+ """S3: the server's own hex form decodes to the same bytes."""
+ backend = native_backend
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (payload) VALUES ('\\x0001ff'::bytea) RETURNING id".format(
+ TABLE
+ ),
+ )
+ assert read_raw(backend, TABLE, "payload", row_id) == "\\x0001ff"
+ assert read_value(backend, TABLE, "payload", row_id) == b"\x00\x01\xff"
+
+ def test_interval_has_no_adapter_and_passes_through(self, native_backend):
+ """Gap: timedelta has no adapter; the driver handles interval natively."""
+ backend = native_backend
+ suggestions = backend.get_default_adapter_suggestions()
+ assert suggestions.get(timedelta) is None
+ assert _adapter_keys(backend, timedelta) == []
+
+ value = timedelta(days=1, seconds=7384)
+ row_id = insert_row(backend, TABLE, {"span": value}, {"span": "interval"})
+ assert read_raw(backend, TABLE, "span", row_id) == "1 day 02:03:04"
+ assert read_value(backend, TABLE, "span", row_id) == value
+
+ update_cell(backend, TABLE, "span", row_id, read_value(backend, TABLE, "span", row_id), "interval")
+ assert read_raw(backend, TABLE, "span", row_id) == "1 day 02:03:04"
+
+ def test_interval_external_literal_reads_back(self, native_backend):
+ """S3: a server-written interval text decodes to a timedelta."""
+ backend = native_backend
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (span) VALUES ('1 day 02:03:04'::interval) RETURNING id".format(
+ TABLE
+ ),
+ )
+ assert read_raw(backend, TABLE, "span", row_id) == "1 day 02:03:04"
+ assert read_value(backend, TABLE, "span", row_id) == timedelta(
+ days=1, seconds=7384
+ )
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_wrapped_scalars.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_wrapped_scalars.py
new file mode 100644
index 00000000..0c490eaa
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_wrapped_scalars.py
@@ -0,0 +1,242 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/native/test_native_wrapped_scalars.py
+"""Native tests for PostgreSQL's wrapped scalar types.
+
+``money``, ``oid``, the ``reg*`` family, ``xid``/``xid8``/``cid``, ``tid`` and
+``pg_lsn`` all have a wrapper class and an adapter in this backend. Reads
+assert the server's own text (``col::text`` or ``col::numeric`` for money, so
+the locale-formatted money output is never the truth), not the adapter's
+re-serialisation.
+"""
+
+from decimal import Decimal
+
+import pytest
+
+from rhosocial.activerecord.backend.impl.postgres.adapters.monetary import (
+ PostgresMoneyAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.adapters.object_identifier import (
+ PostgresOidAdapter,
+ PostgresTidAdapter,
+ PostgresXidAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.adapters.pg_lsn import (
+ PostgresLsnAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values import (
+ CID,
+ OID,
+ TID,
+ XID,
+ XID8,
+ PostgresLsn,
+ PostgresMoney,
+ RegClass,
+ RegConfig,
+ RegNamespace,
+ RegProc,
+ RegType,
+)
+from rhosocial.activerecord_postgres_test.feature.backend.adapters.native.helpers import (
+ insert_row,
+ insert_sql,
+ read_raw,
+ update_cell,
+)
+
+TABLE = "native_wrapped_scalars"
+
+MONEY = PostgresMoneyAdapter()
+OID_ADAPTER = PostgresOidAdapter()
+XID_ADAPTER = PostgresXidAdapter()
+TID_ADAPTER = PostgresTidAdapter()
+LSN_ADAPTER = PostgresLsnAdapter()
+
+
+class TestWrappedScalars:
+ TABLES = (TABLE,)
+
+ # --- S1, without a server -------------------------------------------------
+
+ def test_every_wrapper_round_trips_at_the_adapter_level(self):
+ """S1: to_database then from_database returns the same semantic value."""
+ cases = [
+ (MONEY, PostgresMoney(Decimal("1234.56")), PostgresMoney),
+ (OID_ADAPTER, OID(16384), OID),
+ (OID_ADAPTER, RegClass("pg_class"), RegClass),
+ (OID_ADAPTER, RegType("integer"), RegType),
+ (OID_ADAPTER, RegProc("now"), RegProc),
+ (OID_ADAPTER, RegConfig("english"), RegConfig),
+ (OID_ADAPTER, RegNamespace("public"), RegNamespace),
+ (XID_ADAPTER, XID(42), XID),
+ (XID_ADAPTER, XID8(42), XID8),
+ (XID_ADAPTER, CID(7), CID),
+ (TID_ADAPTER, TID(3, 5), TID),
+ (LSN_ADAPTER, PostgresLsn.from_string("16/B374D848"), PostgresLsn),
+ ]
+ for adapter, value, target in cases:
+ database_value = adapter.to_database(value, str)
+ decoded = adapter.from_database(database_value, target)
+ assert decoded == value
+ assert adapter.to_database(decoded, str) == database_value
+
+ # --- money ----------------------------------------------------------------
+
+ def test_money_records_numeric_truth_and_stays_stable(self, native_backend):
+ """S2: the numeric column value survives a read/rewrite unchanged."""
+ backend = native_backend
+ value = PostgresMoney(Decimal("1234.56"))
+ bound = MONEY.to_database(value, str)
+ assert bound == "1234.56"
+
+ row_id = insert_row(backend, TABLE, {"amount": bound}, {"amount": "money"})
+ numeric = read_raw(backend, TABLE, "amount", row_id, "amount::numeric::text")
+ assert numeric == "1234.56"
+
+ # The raw money text is locale formatted; the adapter must parse it.
+ raw_text = read_raw(backend, TABLE, "amount", row_id)
+ assert raw_text.startswith("$")
+ decoded = MONEY.from_database(raw_text, PostgresMoney)
+ assert decoded.amount == Decimal("1234.56")
+
+ # Writing the decoded value again must not change the stored amount.
+ update_cell(backend, TABLE, "amount", row_id, MONEY.to_database(decoded, str), "money")
+ assert read_raw(backend, TABLE, "amount", row_id, "amount::numeric::text") == numeric
+
+ # --- oid and the reg* family ----------------------------------------------
+
+ def test_oid_and_registry_names_read_back_as_wrappers(self, native_backend):
+ """S1/S2: reg* columns resolve names and the adapters rebuild wrappers."""
+ backend = native_backend
+ values = {
+ "oid_value": OID_ADAPTER.to_database(OID(16384), int),
+ "regclass_value": OID_ADAPTER.to_database(RegClass("pg_class"), str),
+ "regtype_value": OID_ADAPTER.to_database(RegType("integer"), str),
+ "regproc_value": OID_ADAPTER.to_database(RegProc("now"), str),
+ "regconfig_value": OID_ADAPTER.to_database(RegConfig("english"), str),
+ "regnamespace_value": OID_ADAPTER.to_database(RegNamespace("public"), str),
+ }
+ casts = {
+ "oid_value": "oid",
+ "regclass_value": "regclass",
+ "regtype_value": "regtype",
+ "regproc_value": "regproc",
+ "regconfig_value": "regconfig",
+ "regnamespace_value": "regnamespace",
+ }
+ row_id = insert_row(backend, TABLE, values, casts)
+
+ assert read_raw(backend, TABLE, "oid_value", row_id) == "16384"
+ assert read_raw(backend, TABLE, "regclass_value", row_id) == "pg_class"
+ assert read_raw(backend, TABLE, "regtype_value", row_id) == "integer"
+ assert read_raw(backend, TABLE, "regproc_value", row_id) == "now"
+ assert read_raw(backend, TABLE, "regconfig_value", row_id) == "english"
+ assert read_raw(backend, TABLE, "regnamespace_value", row_id) == "public"
+
+ assert OID_ADAPTER.from_database("16384", OID) == OID(16384)
+ assert OID_ADAPTER.from_database("pg_class", RegClass) == RegClass("pg_class")
+ assert OID_ADAPTER.from_database("integer", RegType) == RegType("integer")
+ assert OID_ADAPTER.from_database("now", RegProc) == RegProc("now")
+ assert OID_ADAPTER.from_database("english", RegConfig) == RegConfig("english")
+ assert OID_ADAPTER.from_database("public", RegNamespace) == RegNamespace("public")
+
+ # S2: rewrite the canonical text the adapter produces.
+ update_cell(
+ backend, TABLE, "regclass_value", row_id,
+ OID_ADAPTER.to_database(RegClass("pg_class"), str), "regclass",
+ )
+ assert read_raw(backend, TABLE, "regclass_value", row_id) == "pg_class"
+
+ # --- transaction and command identifiers ----------------------------------
+
+ def test_xid_xid8_and_cid_keep_their_decimal_text(self, native_backend):
+ """S1/S2: xid/xid8/cid bind as integer, but the server text is decimal."""
+ backend = native_backend
+ values = {
+ "xid_value": XID_ADAPTER.to_database(XID(42), int),
+ "xid8_value": XID_ADAPTER.to_database(XID8(42), int),
+ "cid_value": XID_ADAPTER.to_database(CID(7), int),
+ }
+ casts = {
+ "xid_value": "text::xid",
+ "xid8_value": "text::xid8",
+ "cid_value": "text::cid",
+ }
+ row_id = insert_row(backend, TABLE, values, casts)
+
+ assert read_raw(backend, TABLE, "xid_value", row_id) == "42"
+ assert read_raw(backend, TABLE, "xid8_value", row_id) == "42"
+ assert read_raw(backend, TABLE, "cid_value", row_id) == "7"
+
+ assert XID_ADAPTER.from_database("42", XID) == XID(42)
+ assert XID_ADAPTER.from_database("42", XID8) == XID8(42)
+ assert XID_ADAPTER.from_database("7", CID) == CID(7)
+
+ update_cell(
+ backend, TABLE, "xid_value", row_id,
+ XID_ADAPTER.to_database(XID(42), int), "text::xid",
+ )
+ assert read_raw(backend, TABLE, "xid_value", row_id) == "42"
+
+ # --- tid and pg_lsn -------------------------------------------------------
+
+ def test_tid_and_lsn_use_their_native_text_forms(self, native_backend):
+ """S1/S2: tid prints as ``(block,offset)`` and pg_lsn as ``HI/LO``."""
+ backend = native_backend
+ xid_bits = LSN_ADAPTER.to_database(
+ PostgresLsn.from_string("16/b374d848"), str
+ )
+ assert xid_bits == "16/B374D848" # the adapter canonicalises to upper case
+ values = {
+ "tid_value": TID_ADAPTER.to_database(TID(3, 5), str),
+ "lsn_value": xid_bits,
+ }
+ casts = {"tid_value": "tid", "lsn_value": "pg_lsn"}
+ row_id = insert_row(backend, TABLE, values, casts)
+
+ assert read_raw(backend, TABLE, "tid_value", row_id) == "(3,5)"
+ assert read_raw(backend, TABLE, "lsn_value", row_id) == "16/B374D848"
+
+ assert TID_ADAPTER.from_database("(3,5)", TID) == TID(3, 5)
+ assert LSN_ADAPTER.from_database("16/B374D848", PostgresLsn) == (
+ PostgresLsn.from_string("16/B374D848")
+ )
+
+ update_cell(
+ backend, TABLE, "lsn_value", row_id,
+ LSN_ADAPTER.to_database(
+ LSN_ADAPTER.from_database("16/B374D848", PostgresLsn), str
+ ), "pg_lsn",
+ )
+ assert read_raw(backend, TABLE, "lsn_value", row_id) == "16/B374D848"
+
+ # --- S3, external literals ------------------------------------------------
+
+ def test_external_money_oid_and_regclass_literals_are_parsed(self, native_backend):
+ """S3: values written by native SQL (no adapter) read back correctly."""
+ backend = native_backend
+ row_id = insert_sql(
+ backend,
+ "INSERT INTO {} (amount, oid_value, regclass_value) "
+ "VALUES ('9876.54'::money, 20000::oid, 'pg_class'::regclass) "
+ "RETURNING id".format(TABLE),
+ )
+
+ assert read_raw(backend, TABLE, "amount", row_id, "amount::numeric::text") == "9876.54"
+ assert read_raw(backend, TABLE, "oid_value", row_id) == "20000"
+ assert read_raw(backend, TABLE, "regclass_value", row_id) == "pg_class"
+
+ money = MONEY.from_database(read_raw(backend, TABLE, "amount", row_id), PostgresMoney)
+ assert money.amount == Decimal("9876.54")
+ assert OID_ADAPTER.from_database("20000", OID) == OID(20000)
+
+ # --- invalid input --------------------------------------------------------
+
+ def test_out_of_range_and_malformed_wrappers_raise(self):
+ """The adapter rejects values PostgreSQL could never store."""
+ with pytest.raises(ValueError):
+ OID_ADAPTER.to_database(4294967296, int)
+ with pytest.raises(ValueError):
+ TID_ADAPTER.to_database((0, 70000), str)
+ with pytest.raises(ValueError):
+ LSN_ADAPTER.to_database("not-an-lsn", str)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_json_adapters.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_json_adapters.py
new file mode 100644
index 00000000..10eaae54
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_json_adapters.py
@@ -0,0 +1,175 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_json_adapters.py
+"""Database-free coverage for the JSON/JSONB adapter hooks.
+
+Both definitions of ``PostgresJSONBAdapter`` are exercised: the one exported
+by ``adapters`` (and registered on the backend) and the copy in
+``adapters.json`` that offline tests import.
+"""
+
+import json
+from decimal import Decimal
+
+import pytest
+from psycopg.types.json import Jsonb, JsonbDumper
+
+from rhosocial.activerecord.backend.impl.postgres.adapters.base import (
+ PostgresJSONBAdapter as BaseJSONBAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.adapters.json import (
+ PostgresJSONBAdapter as JsonModuleJSONBAdapter,
+)
+
+ADAPTER_CLASSES = [
+ pytest.param(BaseJSONBAdapter, id="adapters.base"),
+ pytest.param(JsonModuleJSONBAdapter, id="adapters.json"),
+]
+
+
+class _Tagged:
+ """Marker returned by the sample object hook."""
+
+ def __init__(self, type_name, payload):
+ self.type_name = type_name
+ self.payload = payload
+
+
+def _object_hook(mapping):
+ if "__type__" in mapping:
+ return _Tagged(mapping["__type__"], mapping.get("payload"))
+ return mapping
+
+
+def _dumped_json(wrapper):
+ """Run the value through psycopg's own JSONB dumper, without a database."""
+ return json.loads(JsonbDumper(Jsonb).dump(wrapper))
+
+
+@pytest.mark.parametrize("adapter_cls", ADAPTER_CLASSES)
+class TestJSONBNoHooks:
+ def test_constructor_defaults(self, adapter_cls):
+ adapter = adapter_cls()
+ assert adapter.default is None
+ assert adapter.object_hook is None
+
+ def test_supported_types_unchanged(self, adapter_cls):
+ adapter = adapter_cls()
+ assert adapter.supported_types == {dict: {Jsonb}}
+
+ def test_to_database_returns_jsonb(self, adapter_cls):
+ adapter = adapter_cls()
+ result = adapter.to_database({"k": 1, "v": [2, 3]}, dict)
+ assert isinstance(result, Jsonb)
+ assert result.obj == {"k": 1, "v": [2, 3]}
+ assert _dumped_json(result) == {"k": 1, "v": [2, 3]}
+
+ def test_to_database_none(self, adapter_cls):
+ assert adapter_cls().to_database(None, dict) is None
+
+ def test_from_database_dict_and_list_passthrough(self, adapter_cls):
+ adapter = adapter_cls()
+ payload = {"a": 1, "nested": {"b": 2}}
+ decoded_list = [1, "two", {"three": 3}]
+ assert adapter.from_database(payload, dict) == payload
+ assert adapter.from_database(decoded_list, list) == decoded_list
+
+ def test_from_database_string_is_parsed(self, adapter_cls):
+ adapter = adapter_cls()
+ assert adapter.from_database('{"a": 1}', dict) == {"a": 1}
+ assert adapter.from_database("[1, 2, 3]", list) == [1, 2, 3]
+
+ def test_from_database_str_target_keeps_json_text(self, adapter_cls):
+ adapter = adapter_cls()
+ payload = {"title": "\u4e2d\u6587"}
+ assert adapter.from_database(payload, str) == json.dumps(payload, ensure_ascii=False)
+ assert adapter.from_database("raw text", str) == "raw text"
+
+ def test_unserialisable_value_raises_without_default(self, adapter_cls):
+ adapter = adapter_cls()
+ wrapper = adapter.to_database({"amount": Decimal("1.5")}, dict)
+ with pytest.raises(TypeError):
+ JsonbDumper(Jsonb).dump(wrapper)
+
+
+@pytest.mark.parametrize("adapter_cls", ADAPTER_CLASSES)
+class TestJSONBDefaultHook:
+ def test_default_is_applied_by_the_dumper(self, adapter_cls):
+ adapter = adapter_cls(default=str)
+ wrapper = adapter.to_database({"amount": Decimal("1.5")}, dict)
+ payload = _dumped_json(wrapper)
+ assert payload == {"amount": "1.5"}
+
+ def test_default_is_wired_into_the_jsonb_wrapper(self, adapter_cls):
+ adapter = adapter_cls(default=lambda value: "")
+ wrapper = adapter.to_database({"when": object()}, dict)
+ assert wrapper.dumps is not None
+ assert _dumped_json(wrapper) == {"when": ""}
+
+ def test_default_none_uses_psycopg_global_dumps(self, adapter_cls):
+ adapter = adapter_cls()
+ wrapper = adapter.to_database({"a": 1}, dict)
+ assert wrapper.dumps is None
+
+ def test_default_applies_to_str_target_serialisation(self, adapter_cls):
+ adapter = adapter_cls(default=str)
+ # psycopg already decoded the value; serialising back to str must
+ # route through the same ``default`` instead of raising.
+ assert adapter.from_database({"amount": Decimal("1.5")}, str) == '{"amount": "1.5"}'
+
+ def test_default_applies_to_batch(self, adapter_cls):
+ adapter = adapter_cls(default=str)
+ wrappers = adapter.to_database_batch([{"amount": Decimal("2.5")}, None], dict)
+ assert wrappers[1] is None
+ assert _dumped_json(wrappers[0]) == {"amount": "2.5"}
+
+
+@pytest.mark.parametrize("adapter_cls", ADAPTER_CLASSES)
+class TestJSONBObjectHook:
+ def test_hook_runs_over_already_decoded_dict(self, adapter_cls):
+ """psycopg decodes JSONB before the adapter; the hook still applies."""
+ adapter = adapter_cls(object_hook=_object_hook)
+ decoded = adapter.from_database({"__type__": "user", "payload": {"name": "ann"}}, dict)
+ assert isinstance(decoded, _Tagged)
+ assert decoded.type_name == "user"
+ assert decoded.payload == {"name": "ann"}
+
+ def test_hook_runs_over_nested_objects(self, adapter_cls):
+ adapter = adapter_cls(object_hook=_object_hook)
+ decoded = adapter.from_database(
+ {"outer": {"__type__": "inner", "payload": 1}, "plain": 2}, dict
+ )
+ assert decoded["plain"] == 2
+ assert isinstance(decoded["outer"], _Tagged)
+ assert decoded["outer"].payload == 1
+
+ def test_hook_runs_over_decoded_list(self, adapter_cls):
+ adapter = adapter_cls(object_hook=_object_hook)
+ decoded = adapter.from_database([{"__type__": "a", "payload": 1}, {"b": 2}], list)
+ assert isinstance(decoded[0], _Tagged)
+ assert decoded[1] == {"b": 2}
+
+ def test_hook_runs_over_json_string(self, adapter_cls):
+ adapter = adapter_cls(object_hook=_object_hook)
+ decoded = adapter.from_database('{"__type__": "user", "payload": {"name": "ann"}}', dict)
+ assert isinstance(decoded, _Tagged)
+ assert decoded.payload == {"name": "ann"}
+
+ def test_hook_is_not_applied_for_str_target(self, adapter_cls):
+ adapter = adapter_cls(object_hook=_object_hook)
+ assert adapter.from_database({"__type__": "user"}, str) == '{"__type__": "user"}'
+
+ def test_plain_decode_without_hook_matches_dict(self, adapter_cls):
+ adapter = adapter_cls()
+ assert adapter.from_database({"__type__": "user"}, dict) == {"__type__": "user"}
+
+ def test_default_and_object_hook_together(self, adapter_cls):
+ adapter = adapter_cls(default=str, object_hook=_object_hook)
+ wrapper = adapter.to_database({"__type__": "user", "amount": Decimal("1.5")}, dict)
+ assert _dumped_json(wrapper) == {"__type__": "user", "amount": "1.5"}
+ decoded = adapter.from_database({"__type__": "user", "payload": 1}, dict)
+ assert isinstance(decoded, _Tagged)
+
+ def test_batch_from_database_applies_hook(self, adapter_cls):
+ adapter = adapter_cls(object_hook=_object_hook)
+ decoded = adapter.from_database_batch([{"__type__": "user", "payload": 1}, None], dict)
+ assert isinstance(decoded[0], _Tagged)
+ assert decoded[1] is None
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py
new file mode 100644
index 00000000..4f5306f7
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py
@@ -0,0 +1,535 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/adapters/test_neutral_adapters.py
+"""DB-free contract tests for the PostgreSQL neutral value adapters.
+
+Every adapter here works on values only: no connection is opened and no server
+is needed. What is pinned is the wire form (WKT/EWKT, pgvector text, bit text,
+range literals and MAC text), the read path from the wrapper types and psycopg
+objects, the ``TypeConversionError`` wrapping, and the catalogue inventory.
+"""
+
+import math
+from datetime import date, datetime, time, timezone
+from decimal import Decimal
+
+import pytest
+
+from rhosocial.activerecord.backend.adapters import (
+ BitString,
+ Geometry,
+ GeometryCollection,
+ LineString,
+ MacAddress,
+ Multirange,
+ Point,
+ Polygon,
+ Range,
+ Vector,
+)
+from rhosocial.activerecord.backend.errors import TypeConversionError
+from rhosocial.activerecord.backend.impl.postgres.adapters.neutral import (
+ PostgresNeutralBitStringAdapter,
+ PostgresNeutralGeometryAdapter,
+ PostgresNeutralMacAddressAdapter,
+ PostgresNeutralRangeAdapter,
+ PostgresNeutralVectorAdapter,
+)
+from rhosocial.activerecord.backend.impl.postgres.backend import (
+ AsyncPostgresBackend,
+ PostgresBackend,
+)
+from rhosocial.activerecord.backend.impl.postgres.type_values import (
+ PostgresBitString,
+ PostgresGeometry,
+ PostgresMacaddr,
+ PostgresMacaddr8,
+ PostgresMultirange,
+ PostgresRange,
+ PostgresVector,
+)
+
+_NEUTRAL_CLASSES = (
+ PostgresNeutralBitStringAdapter,
+ PostgresNeutralGeometryAdapter,
+ PostgresNeutralMacAddressAdapter,
+ PostgresNeutralRangeAdapter,
+ PostgresNeutralVectorAdapter,
+)
+
+
+@pytest.fixture(params=[PostgresBackend, AsyncPostgresBackend])
+def backend(request):
+ """A constructed backend: neither branch opens a connection."""
+ return request.param(database="neutral_adapter_unit")
+
+
+def _class_key(adapter):
+ adapter_class = type(adapter)
+ return (adapter_class.__module__, adapter_class.__qualname__)
+
+
+class TestInventory:
+ def test_every_neutral_adapter_is_in_the_catalogue(self, backend):
+ names = {type(adapter).__name__ for adapter in backend.get_type_adapters()}
+ for adapter_class in _NEUTRAL_CLASSES:
+ assert adapter_class.__name__ in names
+
+ def test_neutral_classes_appear_once(self, backend):
+ keys = [_class_key(adapter) for adapter in backend.get_type_adapters()]
+ assert len(keys) == len(set(keys))
+
+ def test_inventory_is_deterministic(self, backend):
+ first = [_class_key(adapter) for adapter in backend.get_type_adapters()]
+ second = [_class_key(adapter) for adapter in backend.get_type_adapters()]
+ assert first == second
+ assert first == sorted(first)
+
+
+class TestGeometryAdapter:
+ def test_point_round_trip_without_srid(self):
+ adapter = PostgresNeutralGeometryAdapter()
+ point = Point(1, 2)
+ text = adapter.to_database(point, str)
+ assert text == "POINT (1.0 2.0)"
+ assert adapter.from_database(text, Geometry) == point
+
+ def test_point_round_trip_with_ewkt_srid(self):
+ adapter = PostgresNeutralGeometryAdapter()
+ point = Point(1, 2, srid=4326)
+ text = adapter.to_database(point, str)
+ assert text == "SRID=4326;POINT (1.0 2.0)"
+ decoded = adapter.from_database(text, Geometry)
+ assert decoded == point
+ assert decoded.srid == 4326
+
+ def test_srid_option_overrides_the_geometry(self):
+ adapter = PostgresNeutralGeometryAdapter()
+ assert adapter.to_database(Point(1, 2), str, {"srid": 3857}).startswith("SRID=3857;")
+
+ def test_polygon_and_collection_round_trip(self):
+ adapter = PostgresNeutralGeometryAdapter()
+ polygon = Polygon((((0, 0), (10, 0), (10, 10), (0, 0)),), srid=4326)
+ assert adapter.from_database(adapter.to_database(polygon, str), Geometry) == polygon
+ collection = GeometryCollection((Point(1, 2), LineString(((0, 0), (1, 1)))))
+ assert adapter.from_database(adapter.to_database(collection, str), Geometry) == collection
+
+ def test_decodes_the_backend_wrapper(self):
+ adapter = PostgresNeutralGeometryAdapter()
+ wrapper = PostgresGeometry.point(1.0, 2.0, srid=4326)
+ decoded = adapter.from_database(wrapper, Geometry)
+ assert decoded == Point(1.0, 2.0, srid=4326)
+
+ def test_hex_ewkb_is_rejected_instead_of_guessed(self):
+ adapter = PostgresNeutralGeometryAdapter()
+ with pytest.raises(TypeConversionError) as excinfo:
+ adapter.from_database("0101000020E6100000000000000000F03F", Geometry)
+ assert "EWKB" in str(excinfo.value)
+
+ def test_wrong_target_type_is_wrapped(self):
+ adapter = PostgresNeutralGeometryAdapter()
+ with pytest.raises(TypeConversionError) as excinfo:
+ adapter.to_database(Point(1, 2), bytes)
+ assert "Cannot convert Point to Geometry" in str(excinfo.value)
+
+ def test_invalid_wkt_is_wrapped(self):
+ adapter = PostgresNeutralGeometryAdapter()
+ with pytest.raises(TypeConversionError):
+ adapter.to_database("POINT (1 2", str)
+
+
+class TestVectorAdapter:
+ def test_text_round_trip(self):
+ adapter = PostgresNeutralVectorAdapter()
+ vector = Vector((1, 2.5, -3))
+ assert adapter.to_database(vector, str) == "[1,2.5,-3]"
+ assert adapter.from_database("[1,2.5,-3]", Vector) == vector
+
+ def test_decodes_a_plain_sequence_and_the_wrapper(self):
+ adapter = PostgresNeutralVectorAdapter()
+ assert adapter.from_database([1.0, 2.0], Vector) == Vector((1.0, 2.0))
+ assert adapter.from_database(PostgresVector([1.0, 2.0]), Vector) == Vector((1.0, 2.0))
+
+ def test_non_finite_components_use_the_pgvector_spellings(self):
+ adapter = PostgresNeutralVectorAdapter()
+ infinite = Vector((float("inf"), float("-inf")), allow_non_finite=True)
+ assert adapter.to_database(infinite, str) == "[Infinity,-Infinity]"
+ assert adapter.from_database("[Infinity,-Infinity]", Vector) == infinite
+
+ nan_vector = Vector((float("nan"),), allow_non_finite=True)
+ assert adapter.to_database(nan_vector, str) == "[NaN]"
+ decoded = adapter.from_database("[NaN]", Vector)
+ assert len(decoded.values) == 1
+ assert math.isnan(decoded.values[0])
+
+ def test_malformed_text_is_wrapped(self):
+ adapter = PostgresNeutralVectorAdapter()
+ for value in ("1,2", "[]", "[1,]", "[a]"):
+ with pytest.raises(TypeConversionError):
+ adapter.from_database(value, Vector)
+
+ def test_wrong_target_type_is_wrapped(self):
+ adapter = PostgresNeutralVectorAdapter()
+ with pytest.raises(TypeConversionError):
+ adapter.to_database(Vector((1.0,)), list)
+
+
+class TestBitStringAdapter:
+ def test_text_round_trip(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ bits = BitString.from_bits("1010")
+ assert adapter.to_database(bits, str) == "1010"
+ assert adapter.from_database("1010", BitString) == bits
+
+ def test_literal_option_emits_sql_literal(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ assert adapter.to_database(BitString.from_bits("1010"), str, {"literal": True}) == (
+ "B'1010'"
+ )
+
+ def test_declared_length_pads_on_the_right(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ decoded = adapter.from_database("1010", BitString, {"length": 8})
+ assert decoded.to_bits() == "10100000"
+ assert decoded.bit_length == 8
+
+ def test_declared_length_rejects_longer_text(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ with pytest.raises(TypeConversionError):
+ adapter.from_database("10101", BitString, {"length": 4})
+
+ def test_bytes_and_wrapper_decode(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ assert adapter.from_database(b"\xa0", BitString, {"bit_length": 4}) == (
+ BitString.from_bits("1010")
+ )
+ assert adapter.from_database(PostgresBitString("1010"), BitString) == (
+ BitString.from_bits("1010")
+ )
+
+ def test_invalid_text_is_wrapped(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ for value in ("102", "", "B'101'"[:-1]):
+ with pytest.raises(TypeConversionError):
+ adapter.from_database(value, BitString)
+
+
+class TestRangeAdapter:
+ def test_numeric_range_round_trip(self):
+ adapter = PostgresNeutralRangeAdapter()
+ value = Range(1, 10, "[)")
+ assert adapter.to_database(value, str) == "[1,10)"
+ assert adapter.from_database("[1,10)", Range) == value
+
+ def test_unbounded_bounds_are_normalized(self):
+ adapter = PostgresNeutralRangeAdapter()
+ decoded = adapter.from_database("(,5)", Range)
+ assert decoded == Range(None, 5, "()")
+ assert adapter.to_database(decoded, str) == "(,5)"
+ # A missing bound is forced to '('; the present upper bound keeps ']'.
+ assert adapter.from_database("[,5]", Range) == Range(None, 5, "(]")
+
+ def test_decimal_bounds_keep_their_precision(self):
+ adapter = PostgresNeutralRangeAdapter()
+ value = Range(Decimal("1.5"), Decimal("2.5"), "(]")
+ assert adapter.to_database(value, str) == "(1.5,2.5]"
+ assert adapter.from_database("(1.5,2.5]", Range) == value
+
+ def test_quoted_text_bounds_use_postgres_quoting(self):
+ adapter = PostgresNeutralRangeAdapter()
+ value = Range("a b", "c", "[)")
+ assert adapter.to_database(value, str) == '["a b","c")'
+ assert adapter.from_database('["a b","c")', Range) == value
+
+ def test_quote_and_backslash_escapes_round_trip(self):
+ adapter = PostgresNeutralRangeAdapter()
+ value = Range('a"b\\c', "z", "[)")
+ text = adapter.to_database(value, str)
+ assert text == '["a\\"b\\\\c","z")'
+ assert adapter.from_database(text, Range) == value
+
+ def test_date_bounds_need_an_element_type_hint(self):
+ adapter = PostgresNeutralRangeAdapter()
+ value = Range(date(2024, 1, 1), date(2024, 12, 31), "[)")
+ text = adapter.to_database(value, str)
+ assert text == '["2024-01-01","2024-12-31")'
+ decoded = adapter.from_database(text, Range, {"range_type": "daterange"})
+ assert decoded == value
+
+ def test_datetime_bounds_need_an_element_type_hint(self):
+ adapter = PostgresNeutralRangeAdapter()
+ value = Range(datetime(2024, 1, 1, 12, 0), datetime(2024, 1, 2, 12, 0), "[)")
+ text = adapter.to_database(value, str)
+ assert adapter.from_database(text, Range, {"element_type": "datetime"}) == value
+
+ def test_timestamp_with_timezone_bounds_need_a_hint(self):
+ adapter = PostgresNeutralRangeAdapter()
+ value = Range(
+ datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc),
+ datetime(2024, 1, 2, 12, 0, tzinfo=timezone.utc),
+ "[)",
+ )
+ text = adapter.to_database(value, str)
+ assert adapter.from_database(text, Range, {"range_type": "tstzrange"}) == value
+
+ def test_time_bounds_need_a_hint(self):
+ adapter = PostgresNeutralRangeAdapter()
+ value = Range(time(9, 0), time(17, 30), "[)")
+ text = adapter.to_database(value, str)
+ assert adapter.from_database(text, Range, {"element_type": "time"}) == value
+
+ def test_quoted_bounds_without_a_hint_stay_strings(self):
+ adapter = PostgresNeutralRangeAdapter()
+ decoded = adapter.from_database('["2024-01-01","2024-01-02")', Range)
+ assert decoded.lower == "2024-01-01"
+ assert isinstance(decoded.lower, str)
+
+ def test_a_bad_hint_value_is_wrapped(self):
+ adapter = PostgresNeutralRangeAdapter()
+ with pytest.raises(TypeConversionError):
+ adapter.from_database('["not-a-date","2024-01-02")', Range, {"element_type": "date"})
+
+ def test_an_unknown_hint_label_is_wrapped(self):
+ adapter = PostgresNeutralRangeAdapter()
+ with pytest.raises(TypeConversionError):
+ adapter.from_database("[1,2)", Range, {"element_type": "uuid"})
+
+ def test_empty_range(self):
+ adapter = PostgresNeutralRangeAdapter()
+ value = Range(empty=True)
+ assert adapter.to_database(value, str) == "empty"
+ assert adapter.from_database("empty", Range) == value
+
+ def test_multirange_round_trip(self):
+ adapter = PostgresNeutralRangeAdapter()
+ value = Multirange((Range(1, 5), Range(10, 15)))
+ assert adapter.to_database(value, str) == "{[1,5),[10,15)}"
+ assert adapter.from_database("{[1,5),[10,15)}", Multirange) == value
+ assert adapter.from_database("{}", Multirange) == Multirange(())
+
+ def test_decodes_the_backend_wrappers(self):
+ adapter = PostgresNeutralRangeAdapter()
+ wrapper = PostgresRange(1, 10, lower_inc=True, upper_inc=False)
+ assert adapter.from_database(wrapper, Range) == Range(1, 10, "[)")
+ multi = PostgresMultirange([wrapper, PostgresRange(20, 30)])
+ assert adapter.from_database(multi, Multirange) == Multirange((Range(1, 10), Range(20, 30)))
+
+ def test_decodes_psycopg_range_objects(self):
+ psycopg_range = pytest.importorskip("psycopg.types.range")
+ adapter = PostgresNeutralRangeAdapter()
+ value = psycopg_range.Range(1, 5, "[)")
+ assert adapter.from_database(value, Range) == Range(1, 5, "[)")
+ assert adapter.from_database([value, psycopg_range.Range(10, 15, "[)")], Multirange) == (
+ Multirange((Range(1, 5), Range(10, 15)))
+ )
+
+ def test_malformed_literals_are_wrapped(self):
+ adapter = PostgresNeutralRangeAdapter()
+ for value in ("1,2", "[1,2", "[1,2,3)", "[a,b", "{[1,2)"):
+ with pytest.raises(TypeConversionError):
+ adapter.from_database(value, Range)
+
+ def test_target_type_mismatch_is_wrapped(self):
+ adapter = PostgresNeutralRangeAdapter()
+ with pytest.raises(TypeConversionError):
+ adapter.from_database("[1,2)", Multirange)
+
+
+class TestMacAddressAdapter:
+ def test_canonical_text_round_trip(self):
+ adapter = PostgresNeutralMacAddressAdapter()
+ mac = MacAddress.parse("08:00:2B:01:02:03")
+ assert adapter.to_database(mac, str) == "08:00:2b:01:02:03"
+ assert adapter.from_database("08:00:2b:01:02:03", MacAddress) == mac
+
+ def test_eui64_option_expands_six_octets(self):
+ adapter = PostgresNeutralMacAddressAdapter()
+ mac = MacAddress.parse("08:00:2b:01:02:03")
+ assert adapter.to_database(mac, str, {"eui64": True}) == ("08:00:2b:ff:fe:01:02:03")
+ assert adapter.to_database(mac, str, {"version": 8}) == ("08:00:2b:ff:fe:01:02:03")
+
+ def test_decodes_bytes_and_backend_wrappers(self):
+ adapter = PostgresNeutralMacAddressAdapter()
+ expected = MacAddress.parse("08:00:2b:01:02:03")
+ assert adapter.from_database(b"\x08\x00\x2b\x01\x02\x03", MacAddress) == expected
+ assert adapter.from_database(PostgresMacaddr("08:00:2b:01:02:03"), MacAddress) == (expected)
+ assert adapter.from_database(
+ PostgresMacaddr8("08:00:2b:ff:fe:01:02:03"), MacAddress
+ ) == MacAddress.parse("08:00:2b:ff:fe:01:02:03")
+
+ def test_invalid_input_is_wrapped(self):
+ adapter = PostgresNeutralMacAddressAdapter()
+ with pytest.raises(TypeConversionError):
+ adapter.from_database("08:00:2b:01:02", MacAddress)
+ with pytest.raises(TypeConversionError):
+ adapter.to_database(MacAddress.parse("08:00:2b:01:02:03"), int)
+
+
+# ---------------------------------------------------------------------------
+# Remaining branches: pass-throughs, per-family refusals, option guards, and
+# the literal parser's own error contract.
+# ---------------------------------------------------------------------------
+
+
+class TestGeometryRemainingBranches:
+ def test_a_concrete_geometry_is_carried_through(self):
+ adapter = PostgresNeutralGeometryAdapter()
+ value = Point(1, 2)
+ assert adapter.from_database(value, Geometry) is value
+
+ def test_a_non_geometry_value_is_named(self):
+ adapter = PostgresNeutralGeometryAdapter()
+ with pytest.raises(TypeConversionError, match="must decode from WKT/EWKT text"):
+ adapter.from_database(42, Geometry)
+
+ def test_hex_ewkb_output_is_refused_with_the_right_advice(self):
+ """PostGIS's default output is hex EWKB; the adapter asks for WKT
+ instead of pretending to decode it."""
+ adapter = PostgresNeutralGeometryAdapter()
+ with pytest.raises(TypeConversionError, match="hex EWKB"):
+ adapter.from_database("0101000020E6100000", Geometry)
+
+
+class TestVectorRemainingBranches:
+ def test_a_neutral_vector_is_carried_through(self):
+ adapter = PostgresNeutralVectorAdapter()
+ value = Vector((1.0, 2.0))
+ assert adapter.from_database(value, Vector) is value
+
+ def test_a_non_vector_value_is_named(self):
+ adapter = PostgresNeutralVectorAdapter()
+ with pytest.raises(TypeConversionError, match="pgvector must decode from text"):
+ adapter.from_database(object(), Vector)
+
+ def test_a_non_finite_component_in_text_is_permitted(self):
+ adapter = PostgresNeutralVectorAdapter()
+ parsed = adapter.from_database("[nan,1.0]", Vector)
+ assert parsed.allow_non_finite is True
+
+
+class TestBitStringRemainingBranches:
+ def test_a_neutral_bit_string_is_carried_through(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ value = BitString.from_bits("101")
+ assert adapter.from_database(value, BitString) is value
+
+ def test_a_wrapper_without_a_declared_length_keeps_its_own(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ bits = adapter.from_database(PostgresBitString("101", length=3), BitString)
+ assert bits.to_bits() == "101"
+
+ def test_empty_bytes_are_refused(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ with pytest.raises(TypeConversionError, match="bytes must not be empty"):
+ adapter.from_database(b"", BitString)
+
+ def test_an_integer_is_read_as_bits(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ assert adapter.from_database(5, BitString).to_bits() == "101"
+
+ def test_a_non_bit_value_is_named(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ with pytest.raises(TypeConversionError, match="must decode from text, bytes, int"):
+ adapter.from_database(1.5, BitString)
+
+ def test_a_declared_length_must_be_a_positive_integer(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ with pytest.raises(TypeConversionError, match=r"must be int, got bool"):
+ adapter.from_database("101", BitString, {"bit_length": True})
+ with pytest.raises(TypeConversionError, match="must be at least 1"):
+ adapter.from_database("101", BitString, {"bit_length": 0})
+
+ def test_a_literal_spelling_is_read_and_written(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ assert adapter.from_database("B'101'", BitString).to_bits() == "101"
+ assert adapter.to_database(BitString.from_bits("101"), str, {"literal": True}) == "B'101'"
+
+ def test_the_wire_form_is_text_only(self):
+ adapter = PostgresNeutralBitStringAdapter()
+ with pytest.raises(TypeConversionError, match="target_type must be str"):
+ adapter.to_database(BitString.from_bits("101"), bytes)
+
+
+class TestRangeRemainingBranches:
+ def test_a_neutral_range_is_carried_through(self):
+ adapter = PostgresNeutralRangeAdapter()
+ value = Range(1, 2, "[)")
+ assert adapter.from_database(value, Range) is value
+
+ def test_an_empty_sequence_is_an_empty_multirange(self):
+ adapter = PostgresNeutralRangeAdapter()
+ assert adapter.from_database([], Multirange) == Multirange(())
+
+ def test_a_sequence_of_non_ranges_is_refused(self):
+ adapter = PostgresNeutralRangeAdapter()
+ with pytest.raises(TypeConversionError, match="must contain range objects"):
+ adapter.from_database([{"a": 1}], Multirange)
+
+ def test_a_non_range_value_is_named(self):
+ adapter = PostgresNeutralRangeAdapter()
+ with pytest.raises(TypeConversionError, match="must decode from text, a backend/driver"):
+ adapter.from_database(42, Range)
+
+ def test_the_wire_form_is_text_only(self):
+ adapter = PostgresNeutralRangeAdapter()
+ with pytest.raises(TypeConversionError, match="target_type must be str"):
+ adapter.to_database(Range(1, 2, "[)"), bytes)
+
+ def test_an_element_hint_must_be_text(self):
+ adapter = PostgresNeutralRangeAdapter()
+ with pytest.raises(TypeConversionError, match="must be str"):
+ adapter.from_database("[1,2]", Range, {"element_type": 1})
+
+ def test_an_unknown_element_hint_is_named(self):
+ adapter = PostgresNeutralRangeAdapter()
+ with pytest.raises(TypeConversionError, match="unsupported range element type hint"):
+ adapter.from_database("[1,2]", Range, {"element_type": "bogus"})
+
+ def test_a_malformed_bound_of_each_label_is_named(self):
+ adapter = PostgresNeutralRangeAdapter()
+ for label in ("date", "time", "datetime", "int", "decimal", "float"):
+ with pytest.raises(TypeConversionError, match="invalid .* range bound"):
+ adapter.from_database('["x","y"]', Range, {"element_type": label})
+
+ def test_a_non_finite_bound_is_read_as_its_float(self):
+ adapter = PostgresNeutralRangeAdapter()
+ parsed = adapter.from_database("[nan,1]", Range)
+ assert math.isnan(parsed.lower)
+
+ def test_bracket_and_quote_errors_are_named(self):
+ adapter = PostgresNeutralRangeAdapter()
+ for text, reason in (
+ ("[1)]", "unbalanced closing bracket"),
+ ("[(1,2]", "unbalanced brackets"),
+ ('["abc]', "unterminated quoted range bound"),
+ ):
+ with pytest.raises(TypeConversionError, match=reason):
+ adapter.from_database(text, Range)
+
+ def test_an_empty_and_a_truncated_literal_are_named(self):
+ adapter = PostgresNeutralRangeAdapter()
+ with pytest.raises(TypeConversionError, match="range literal is empty"):
+ adapter.from_database("", Range)
+ with pytest.raises(TypeConversionError, match="range literal is too short"):
+ adapter.from_database("[", Range)
+
+ def test_an_infinite_bound_is_normalised_to_the_exclusive_bracket(self):
+ adapter = PostgresNeutralRangeAdapter()
+ parsed = adapter.from_database("[,]", Range)
+ assert parsed.lower is None and parsed.upper is None
+ assert parsed.bounds == "()"
+
+
+class TestMacAddressRemainingBranches:
+ def test_a_neutral_mac_is_carried_through(self):
+ adapter = PostgresNeutralMacAddressAdapter()
+ value = MacAddress.parse("08:00:2b:01:02:03")
+ assert adapter.from_database(value, MacAddress) is value
+
+ def test_the_backend_wrapper_is_read(self):
+ adapter = PostgresNeutralMacAddressAdapter()
+ parsed = adapter.from_database(PostgresMacaddr("08:00:2b:01:02:03"), MacAddress)
+ assert str(parsed) == "08:00:2b:01:02:03"
+
+ def test_a_non_mac_value_is_named(self):
+ adapter = PostgresNeutralMacAddressAdapter()
+ with pytest.raises(TypeConversionError, match="must decode from text, bytes, or a backend MAC"):
+ adapter.from_database(42, MacAddress)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py
index 5aa30bc9..53f59e10 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py
@@ -1,110 +1,127 @@
# tests/rhosocial/activerecord_postgres_test/feature/backend/conftest.py
+"""Fixtures for the backend-owned tests.
+
+The backend runs these against a real server. The scenario supplies the
+connection parameters; the database name is derived from the directory that
+owns the test, so two directories never share tables.
+"""
+from rhosocial.activerecord.testsuite.pytest_plugin import Declaration
+import os
+from typing import Any, Dict, Tuple, Type
+
import pytest
import pytest_asyncio
-import yaml
-import os
-from typing import Dict, Any, Tuple, Type # noqa: F401
-from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import AsyncPostgresBackend
+import support.postgres
+
from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
+from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import (
+ AsyncPostgresBackend,
+)
from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig
+DECLARATION = Declaration(
+ uses_database=True,
+ parallel=False,
+ purpose="Backend-owned PostgreSQL tests; pure-render scopes stay ungrouped.",
+ passes_means="backend-specific behavior matches PostgreSQL semantics",
+ fails_means="a backend contract is violated or a directory database is corrupted",
+)
# --- Scenario Loading Logic ---
-SCENARIO_MAP: Dict[str, Dict[str, Any]] = {}
+SCENARIO_MAP: Dict[str, Dict[str, Any]] = dict(support.postgres.SCENARIO_MAP)
-def register_scenario(name: str, config: Dict[str, Any]):
- SCENARIO_MAP[name] = config
-def _load_scenarios_from_config():
- """
- Load scenarios from a configuration file.
- Uses POSTGRES_SCENARIOS_CONFIG_PATH or a default path.
+def _apply_scenario_filter():
+ """Filter SCENARIO_MAP based on the active scenarios env var.
+
+ Keeps the backend-feature scenarios consistent with the scenarios active
+ for the rest of the test run.
"""
- config_path = None
- env_config_path = os.getenv("POSTGRES_SCENARIOS_CONFIG_PATH")
-
- if env_config_path and os.path.exists(env_config_path):
- config_path = env_config_path
- else:
- # Path is relative to this file's location
- default_path = os.path.join(os.path.dirname(__file__), "../../../../config", "postgres_scenarios.yaml")
- if os.path.exists(default_path):
- config_path = default_path
- elif env_config_path:
- print(f"Warning: Scenario file specified in POSTGRES_SCENARIOS_CONFIG_PATH not found: {env_config_path}")
- return
-
- if not config_path:
- raise FileNotFoundError(
- "No PostgreSQL scenarios configuration file found. "
- "Set POSTGRES_SCENARIOS_CONFIG_PATH or place postgres_scenarios.yaml in tests/config."
- )
+ filter_str = os.getenv("POSTGRES_ACTIVE_SCENARIOS") or os.getenv(
+ "TESTSUITE_ACTIVE_SCENARIOS"
+ )
+ if not filter_str:
+ return
+ allowed = set(s.strip() for s in filter_str.split(",") if s.strip())
+ if not allowed:
+ return
+ for name in [n for n in SCENARIO_MAP if n not in allowed]:
+ del SCENARIO_MAP[name]
- try:
- with open(config_path, 'r', encoding='utf-8') as f:
- config_data = yaml.safe_load(f)
- if 'scenarios' not in config_data:
- raise ValueError(f"Configuration file {config_path} does not contain 'scenarios' key")
+_apply_scenario_filter()
+
+
+def get_enabled_scenarios() -> Dict[str, Any]:
+ return SCENARIO_MAP
+
+
+def get_scenario_names():
+ return list(get_enabled_scenarios().keys())
+
+
+_PREPARED_DATABASES = set()
+
+
+def _database_for(request) -> str:
+ """Derive the logical database the directory owning the test runs in."""
+ parts = list(request.node.path.parts)
+ try:
+ index = max(i for i, part in enumerate(parts) if part == "backend")
+ except ValueError:
+ return "test_backend"
+ names = [part for part in parts[index + 1 : -1] if part]
+ return "test_backend" + "".join("_" + name for name in names)
- for scenario_name, config in config_data['scenarios'].items():
- if config: # Ensure config is not null or empty
- register_scenario(scenario_name, config)
- except ImportError:
- raise ImportError("PyYAML is required to load scenario configuration files") # noqa: B904
+def _prepare_database(scenario_name: str, database: str) -> None:
+ """Create the directory's database once per scenario."""
+ key = (scenario_name, database)
+ if key in _PREPARED_DATABASES:
+ return
+ support.postgres.scenario(scenario_name).reset_database(database)
+ _PREPARED_DATABASES.add(key)
-_load_scenarios_from_config()
-def get_scenario_config(name: str) -> Dict[str, Any]:
+def get_scenario(
+ name: str, database: str = "test_backend"
+) -> Tuple[Type[PostgresBackend], PostgresConnectionConfig]:
if name not in SCENARIO_MAP:
if SCENARIO_MAP:
name = next(iter(SCENARIO_MAP))
else:
- raise ValueError("No scenarios registered or enabled")
- config_dict = SCENARIO_MAP[name].copy()
- # Apply the pooled database name so parallel workers never share a schema.
- from providers.pooling import resolve_database_name
+ raise ValueError("No scenarios registered")
+ _prepare_database(name, database)
+ return PostgresBackend, support.postgres.scenario(name).make_config(database)
- pooled_db = resolve_database_name(name)
- if pooled_db:
- config_dict["database"] = pooled_db
- return config_dict
# --- Provider Logic for Fixtures ---
+
class BackendFeatureProvider:
def __init__(self):
self._backend = None
self._async_backend = None
- def setup_backend(self, scenario_name: str):
- print(f"DEBUG: setup_backend called with scenario_name: {scenario_name}")
+ def setup_backend(self, scenario_name: str, database: str):
if self._backend:
return self._backend
- config_dict = get_scenario_config(scenario_name)
- # Remove 'enabled' keyword as it's not a connection parameter
- config_dict.pop('enabled', None)
- config = PostgresConnectionConfig(**config_dict)
- self._backend = PostgresBackend(connection_config=config)
+ backend_class, config = get_scenario(scenario_name, database)
+ self._backend = backend_class(connection_config=config)
self._backend.connect()
- # Introspect and adapt to detect server version and extensions
+ # Introspect and adapt to detect server version and extensions.
self._backend.introspect_and_adapt()
return self._backend
- async def setup_async_backend(self, scenario_name: str):
- print(f"DEBUG: setup_async_backend called with scenario_name: {scenario_name}")
+ async def setup_async_backend(self, scenario_name: str, database: str):
if self._async_backend:
return self._async_backend
- config_dict = get_scenario_config(scenario_name)
- # Remove 'enabled' keyword as it's not a connection parameter
- config_dict.pop('enabled', None)
- config = PostgresConnectionConfig(**config_dict)
+ _, config = get_scenario(scenario_name, database)
self._async_backend = AsyncPostgresBackend(connection_config=config)
await self._async_backend.connect()
- # Introspect and adapt to detect server version and extensions
+ # Introspect and adapt to detect server version and extensions.
await self._async_backend.introspect_and_adapt()
return self._async_backend
@@ -118,26 +135,26 @@ async def async_cleanup(self):
await self._async_backend.disconnect()
self._async_backend = None
+
# --- Fixtures ---
-def get_scenario_names():
- return list(SCENARIO_MAP.keys())
@pytest.fixture(scope="function", params=get_scenario_names())
def postgres_backend(request):
scenario_name = request.param
provider = BackendFeatureProvider()
- backend = provider.setup_backend(scenario_name)
- backend.scenario_name = scenario_name # Attach for test reference
+ backend = provider.setup_backend(scenario_name, _database_for(request))
+ backend.scenario_name = scenario_name # Attach for test reference
yield backend
provider.cleanup()
+
@pytest_asyncio.fixture(scope="function", params=get_scenario_names())
async def async_postgres_backend(request):
scenario_name = request.param
provider = BackendFeatureProvider()
- backend = await provider.setup_async_backend(scenario_name)
- backend.scenario_name = scenario_name # Attach for test reference
+ backend = await provider.setup_async_backend(scenario_name, _database_for(request))
+ backend.scenario_name = scenario_name # Attach for test reference
yield backend
await provider.async_cleanup()
@@ -146,38 +163,38 @@ async def async_postgres_backend(request):
@pytest.fixture(scope="function")
-def postgres_backend_single():
+def postgres_backend_single(request):
"""Non-parameterized fixture using the first available scenario."""
scenario_names = get_scenario_names()
if not scenario_names:
pytest.skip("No PostgreSQL scenarios configured")
scenario_name = scenario_names[0]
provider = BackendFeatureProvider()
- backend = provider.setup_backend(scenario_name)
+ backend = provider.setup_backend(scenario_name, _database_for(request))
backend.scenario_name = scenario_name
yield backend
provider.cleanup()
@pytest_asyncio.fixture(scope="function")
-async def async_postgres_backend_single():
+async def async_postgres_backend_single(request):
"""Non-parameterized async fixture using the first available scenario."""
scenario_names = get_scenario_names()
if not scenario_names:
pytest.skip("No PostgreSQL scenarios configured")
scenario_name = scenario_names[0]
provider = BackendFeatureProvider()
- backend = await provider.setup_async_backend(scenario_name)
+ backend = await provider.setup_async_backend(scenario_name, _database_for(request))
backend.scenario_name = scenario_name
yield backend
await provider.async_cleanup()
-# --- Control Backend for Session Modification Tests ---
+# --- Class-scoped Backend Fixtures ---
@pytest.fixture(scope="class")
-def postgres_backend_class():
+def postgres_backend_class(request):
"""Class-scoped backend fixture for extension integration tests.
Uses the first available scenario. Suitable for test classes where
@@ -188,21 +205,21 @@ def postgres_backend_class():
pytest.skip("No PostgreSQL scenarios configured")
scenario_name = scenario_names[0]
provider = BackendFeatureProvider()
- backend = provider.setup_backend(scenario_name)
+ backend = provider.setup_backend(scenario_name, _database_for(request))
backend.scenario_name = scenario_name
yield backend
provider.cleanup()
@pytest_asyncio.fixture(scope="class")
-async def async_postgres_backend_class():
+async def async_postgres_backend_class(request):
"""Class-scoped async backend fixture for extension integration tests."""
scenario_names = get_scenario_names()
if not scenario_names:
pytest.skip("No PostgreSQL scenarios configured")
scenario_name = scenario_names[0]
provider = BackendFeatureProvider()
- backend = await provider.setup_async_backend(scenario_name)
+ backend = await provider.setup_async_backend(scenario_name, _database_for(request))
backend.scenario_name = scenario_name
yield backend
await provider.async_cleanup()
@@ -212,7 +229,7 @@ async def async_postgres_backend_class():
@pytest.fixture(scope="function")
-def postgres_control_backend():
+def postgres_control_backend(request):
"""
Dedicated control backend for tests that modify PostgreSQL session settings.
@@ -230,13 +247,13 @@ def postgres_control_backend():
pytest.skip("No PostgreSQL scenarios configured")
scenario_name = scenario_names[0]
provider = BackendFeatureProvider()
- backend = provider.setup_backend(scenario_name)
+ backend = provider.setup_backend(scenario_name, _database_for(request))
yield backend
provider.cleanup()
@pytest_asyncio.fixture(scope="function")
-async def async_postgres_control_backend():
+async def async_postgres_control_backend(request):
"""
Dedicated async control backend for tests that modify PostgreSQL session settings.
@@ -248,7 +265,7 @@ async def async_postgres_control_backend():
pytest.skip("No PostgreSQL scenarios configured")
scenario_name = scenario_names[0]
provider = BackendFeatureProvider()
- backend = await provider.setup_async_backend(scenario_name)
+ backend = await provider.setup_async_backend(scenario_name, _database_for(request))
yield backend
await provider.async_cleanup()
@@ -257,6 +274,7 @@ async def async_postgres_control_backend():
def postgres_dialect():
"""Fixture providing PostgresDialect instance for testing transaction expressions."""
from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect
+
return PostgresDialect(version=(15, 0, 0))
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_cli_offline.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_cli_offline.py
new file mode 100644
index 00000000..98a11069
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_cli_offline.py
@@ -0,0 +1,1503 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_cli_offline.py
+"""Offline unit tests for the PostgreSQL CLI subcommands.
+
+Every test here is pure: parser construction, serialization/formatting helpers,
+validation maps and handler dispatch are exercised with MagicMock / AsyncMock
+backends and providers. No PostgreSQL server, socket or driver is contacted.
+"""
+
+import argparse
+import json
+import sys
+import types
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from rhosocial.activerecord.backend.errors import ConnectionError, QueryError
+from rhosocial.activerecord.backend.impl.postgres.cli import info as info_mod
+from rhosocial.activerecord.backend.impl.postgres.cli import introspect as introspect_mod
+from rhosocial.activerecord.backend.impl.postgres.cli import query as query_mod
+from rhosocial.activerecord.backend.impl.postgres.cli import status as status_mod
+from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect
+from rhosocial.activerecord.backend.introspection.status import (
+ ConnectionInfo,
+ DatabaseBriefInfo,
+ ExtensionInfo,
+ ServerOverview,
+ SessionInfo,
+ StatusCategory,
+ StatusItem,
+ StorageInfo,
+ UserInfo,
+)
+
+
+def _args(**overrides):
+ """A namespace carrying every flag the four handlers may read."""
+ base = dict(
+ output="json",
+ rich_ascii=False,
+ verbose=0,
+ type="all",
+ database="db",
+ named_connection=None,
+ is_async=False,
+ version=None,
+ sql=None,
+ file=None,
+ log_level="INFO",
+ name=None,
+ column=None,
+ right_table=None,
+ right_column=None,
+ include_system=False,
+ connection_params=[],
+ )
+ base.update(overrides)
+ return argparse.Namespace(**base)
+
+
+def _subparser(factory):
+ return factory(argparse.ArgumentParser(prog="pgx").add_subparsers(dest="command"))
+
+
+# ===========================================================================
+# status
+# ===========================================================================
+
+
+class TestStatusParser:
+ def test_defaults(self):
+ args = _subparser(status_mod.create_parser).parse_args([])
+ assert args.type == "all"
+ assert args.output == "table"
+ assert args.verbose == 0
+ assert args.rich_ascii is False
+
+ @pytest.mark.parametrize("status_type", status_mod.STATUS_TYPES)
+ def test_every_status_type_accepted(self, status_type):
+ parser = _subparser(status_mod.create_parser)
+ assert parser.parse_args([status_type]).type == status_type
+
+ def test_invalid_type_rejected(self):
+ with pytest.raises(SystemExit):
+ _subparser(status_mod.create_parser).parse_args(["bogus"])
+
+ @pytest.mark.parametrize("output", ["table", "json", "csv", "tsv"])
+ def test_output_choices(self, output):
+ assert _subparser(status_mod.create_parser).parse_args(["-o", output]).output == output
+
+ def test_invalid_output_rejected(self):
+ with pytest.raises(SystemExit):
+ _subparser(status_mod.create_parser).parse_args(["-o", "xml"])
+
+ @pytest.mark.parametrize(
+ "flags,attr,value",
+ [
+ (["-vvv"], "verbose", 3),
+ (["--rich-ascii"], "rich_ascii", True),
+ (["--async"], "is_async", True),
+ (["--named-connection", "app.db"], "named_connection", "app.db"),
+ ],
+ )
+ def test_flags(self, flags, attr, value):
+ assert getattr(_subparser(status_mod.create_parser).parse_args(flags), attr) == value
+
+
+class TestStatusHandleDispatch:
+ def test_missing_database_exits(self, capsys):
+ with pytest.raises(SystemExit) as exc:
+ status_mod.handle(_args(database=None))
+ assert exc.value.code == 1
+ assert "database is required" in capsys.readouterr().err
+
+ def test_sync_dispatch(self):
+ args = _args(rich_ascii=True)
+ with patch.object(status_mod, "create_provider") as provider_factory, patch.object(
+ status_mod, "resolve_connection_config_from_args", return_value="cfg"
+ ), patch.object(status_mod, "PostgresBackend") as backend_cls, patch.object(
+ status_mod, "_handle_status_sync"
+ ) as handler:
+ status_mod.handle(args)
+ provider_factory.assert_called_once_with("json", ascii_borders=True)
+ backend_cls.assert_called_once_with(connection_config="cfg")
+ handler.assert_called_once_with(
+ args, backend_cls.return_value, provider_factory.return_value
+ )
+
+ def test_async_dispatch(self):
+ args = _args(is_async=True)
+ coroutine = object()
+ with patch.object(status_mod, "create_provider"), patch.object(
+ status_mod, "resolve_connection_config_from_args", return_value="cfg"
+ ), patch.object(status_mod, "AsyncPostgresBackend") as backend_cls, patch.object(
+ status_mod, "_handle_status_async", new=MagicMock(return_value=coroutine)
+ ) as handler, patch.object(
+ status_mod, "run_coroutine"
+ ) as runner:
+ status_mod.handle(args)
+ backend_cls.assert_called_once_with(connection_config="cfg")
+ handler.assert_called_once()
+ runner.assert_called_once_with(coroutine)
+
+
+class TestStatusSyncHandler:
+ @pytest.mark.parametrize(
+ "status_type,method,title,wrapped",
+ [
+ ("config", "list_configuration", "Configuration", False),
+ ("performance", "list_configuration", "Performance", False),
+ ("connections", "get_connection_info", "Connections", True),
+ ("storage", "get_storage_info", "Storage", True),
+ ("databases", "list_databases", "Databases", False),
+ ("users", "list_users", "Users", False),
+ ],
+ )
+ def test_section_dispatch(self, status_type, method, title, wrapped):
+ backend = MagicMock()
+ backend._connection = False
+ sample = [{"name": "x", "value": 1}]
+ getattr(backend.introspector.status, method).return_value = sample
+ provider = MagicMock()
+ args = _args(type=status_type)
+ status_mod._handle_status_sync(args, backend, provider)
+ backend.connect.assert_called_once_with()
+ backend.introspect_and_adapt.assert_called_once_with()
+ expected = [sample] if wrapped else sample
+ provider.display_results.assert_called_once_with(expected, title=title)
+
+ def test_all_prints_json(self, capsys):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.status.get_overview.return_value = {"server_version": "16"}
+ status_mod._handle_status_sync(_args(type="all"), backend, MagicMock())
+ assert json.loads(capsys.readouterr().out) == {"server_version": "16"}
+
+ @pytest.mark.parametrize("output", ["csv", "tsv"])
+ def test_all_falls_back_to_json_for_tabular_formats(self, output, capsys):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.status.get_overview.return_value = {"k": "v"}
+ status_mod._handle_status_sync(_args(type="all", output=output), backend, MagicMock())
+ assert json.loads(capsys.readouterr().out) == {"k": "v"}
+
+ def test_all_uses_rich_when_available(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.status.get_overview.return_value = {"k": "v"}
+ with patch.object(status_mod, "RICH_AVAILABLE", True), patch.object(
+ status_mod, "_display_status_rich"
+ ) as rich:
+ status_mod._handle_status_sync(_args(type="all", output="table"), backend, MagicMock())
+ rich.assert_called_once_with({"k": "v"}, 0)
+
+ def test_all_uses_json_without_rich(self, capsys):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.status.get_overview.return_value = {"k": "v"}
+ with patch.object(status_mod, "RICH_AVAILABLE", False):
+ status_mod._handle_status_sync(_args(type="all", output="table"), backend, MagicMock())
+ assert json.loads(capsys.readouterr().out) == {"k": "v"}
+
+ def test_disconnect_when_connected(self):
+ backend = MagicMock()
+ backend._connection = object()
+ backend.introspector.status.get_overview.return_value = {}
+ status_mod._handle_status_sync(_args(type="all"), backend, MagicMock())
+ backend.disconnect.assert_called_once_with()
+
+ def test_connection_error_exits(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.connect.side_effect = ConnectionError("no db")
+ provider = MagicMock()
+ with pytest.raises(SystemExit) as exc:
+ status_mod._handle_status_sync(_args(), backend, provider)
+ assert exc.value.code == 1
+ provider.display_connection_error.assert_called_once()
+
+ def test_query_error_exits(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspect_and_adapt.side_effect = QueryError("bad sql")
+ provider = MagicMock()
+ with pytest.raises(SystemExit):
+ status_mod._handle_status_sync(_args(), backend, provider)
+ provider.display_query_error.assert_called_once()
+
+ def test_unexpected_error_exits(self, capsys):
+ backend = MagicMock()
+ backend._connection = False
+ backend.connect.side_effect = RuntimeError("boom")
+ with pytest.raises(SystemExit):
+ status_mod._handle_status_sync(_args(), backend, MagicMock())
+ assert "Error during status introspection" in capsys.readouterr().err
+
+
+class TestStatusAsyncHandler:
+ @pytest.mark.parametrize(
+ "status_type,method,title",
+ [
+ ("config", "list_configuration", "Configuration"),
+ ("connections", "get_connection_info", "Connections"),
+ ("users", "list_users", "Users"),
+ ],
+ )
+ async def test_async_section_dispatch(self, status_type, method, title):
+ backend = AsyncMock()
+ backend._connection = False
+ introspector = MagicMock()
+ setattr(introspector, method, AsyncMock(return_value=[{"a": 1}]))
+ backend.introspector = MagicMock(status=introspector)
+ provider = MagicMock()
+ await status_mod._handle_status_async(_args(type=status_type), backend, provider)
+ backend.connect.assert_awaited_once_with()
+ backend.introspect_and_adapt.assert_awaited_once_with()
+ expected = [[{"a": 1}]] if method == "get_connection_info" else [{"a": 1}]
+ provider.display_results.assert_called_once_with(expected, title=title)
+
+ async def test_async_all_prints_json(self, capsys):
+ backend = AsyncMock()
+ backend._connection = False
+ backend.introspector = MagicMock(
+ status=MagicMock(get_overview=AsyncMock(return_value={"v": 16}))
+ )
+ await status_mod._handle_status_async(_args(type="all"), backend, MagicMock())
+ assert json.loads(capsys.readouterr().out) == {"v": 16}
+
+ async def test_async_connection_error_exits(self):
+ backend = AsyncMock()
+ backend._connection = False
+ backend.connect.side_effect = ConnectionError("no db")
+ provider = MagicMock()
+ with pytest.raises(SystemExit):
+ await status_mod._handle_status_async(_args(), backend, provider)
+ provider.display_connection_error.assert_called_once()
+
+ async def test_async_disconnect_when_connected(self):
+ backend = AsyncMock()
+ backend._connection = object()
+ backend.introspector = MagicMock(status=MagicMock(get_overview=AsyncMock(return_value={})))
+ await status_mod._handle_status_async(_args(type="all"), backend, MagicMock())
+ backend.disconnect.assert_awaited_once_with()
+
+
+# ===========================================================================
+# info
+# ===========================================================================
+
+
+class TestInfoParser:
+ def test_defaults(self):
+ args = _subparser(info_mod.create_parser).parse_args([])
+ assert args.output == "table"
+ assert args.verbose == 0
+ assert args.version is None
+ assert args.rich_ascii is False
+
+ @pytest.mark.parametrize("output", info_mod.INFO_OUTPUT_CHOICES)
+ def test_output_choices(self, output):
+ assert _subparser(info_mod.create_parser).parse_args(["-o", output]).output == output
+
+ def test_output_rejects_csv(self):
+ with pytest.raises(SystemExit):
+ _subparser(info_mod.create_parser).parse_args(["-o", "csv"])
+
+ def test_version_and_verbosity(self):
+ args = _subparser(info_mod.create_parser).parse_args(["--version", "15.4.1", "-vv"])
+ assert args.version == "15.4.1"
+ assert args.verbose == 2
+
+
+class _Proto:
+ def supports_alpha(self):
+ return True
+
+ def supports_beta(self):
+ return False
+
+ def is_gamma_available(self):
+ return True
+
+ def supports_explain_format(self, fmt):
+ return fmt in ("TEXT", "JSON")
+
+ def supports_needs_arg(self, required):
+ return True
+
+ def helper_not_a_check(self):
+ return True
+
+
+class _ProtoDialect:
+ def supports_alpha(self):
+ return True
+
+ def supports_beta(self):
+ return 0
+
+ def is_gamma_available(self):
+ return 1
+
+ def supports_explain_format(self, fmt):
+ return fmt in ("TEXT", "JSON")
+
+ def supports_needs_arg(self, required):
+ return True
+
+
+class TestInfoHelpers:
+ @pytest.mark.parametrize(
+ "text,expected",
+ [
+ ("15.4.1", (15, 4, 1)),
+ ("13", (13, 0, 0)),
+ ("15.2", (15, 2, 0)),
+ ("9.6.1", (9, 6, 1)),
+ ("16.0.0", (16, 0, 0)),
+ ],
+ )
+ def test_parse_version(self, text, expected):
+ assert info_mod.parse_version(text) == expected
+
+ def test_get_protocol_support_methods(self):
+ assert info_mod.get_protocol_support_methods(_Proto) == [
+ "is_gamma_available",
+ "supports_alpha",
+ "supports_beta",
+ "supports_explain_format",
+ "supports_needs_arg",
+ ]
+
+ def test_check_protocol_support(self):
+ result = info_mod.check_protocol_support(_ProtoDialect(), _Proto)
+ assert result["supports_alpha"] is True
+ assert result["supports_beta"] is False
+ assert result["is_gamma_available"] is True
+ assert result["supports_needs_arg"] is False
+ explain = result["supports_explain_format"]
+ assert explain["supported"] == 2
+ assert explain["total"] == 6
+ assert explain["args"]["TEXT"] is True
+ assert explain["args"]["DOT"] is False
+
+ def test_check_protocol_support_missing_method(self):
+ class _Empty:
+ pass
+
+ result = info_mod.check_protocol_support(object(), _Proto)
+ assert set(result) == set(info_mod.get_protocol_support_methods(_Proto))
+ assert all(value is False for value in result.values())
+
+ @pytest.mark.parametrize(
+ "methods,expected",
+ [
+ ({"a": True, "b": False}, (1, 2)),
+ ({"a": {"supported": 2, "total": 6}}, (2, 6)),
+ ({"a": True, "b": {"supported": 3, "total": 3}}, (4, 4)),
+ ],
+ )
+ def test_calculate_protocol_stats(self, methods, expected):
+ assert info_mod._calculate_protocol_stats(methods) == expected
+
+ def test_build_protocol_info(self):
+ info = info_mod._build_protocol_info(_ProtoDialect(), "G", [_Proto], 0)
+ stats = info["_Proto"]
+ assert set(stats) == {"supported", "total", "percentage"}
+ assert stats["total"] == 10
+ assert stats["percentage"] == 40.0
+
+ def test_build_protocol_info_verbose_includes_methods(self):
+ info = info_mod._build_protocol_info(_ProtoDialect(), "G", [_Proto], 2)
+ assert "methods" in info["_Proto"]
+
+ @pytest.mark.parametrize(
+ "pct,expected",
+ [
+ (100, ("green", "[OK]")),
+ (75, ("yellow", "[~]")),
+ (25, ("red", "[~]")),
+ (0, ("red", "[X]")),
+ ],
+ )
+ def test_get_status_style(self, pct, expected):
+ assert info_mod._get_status_style(pct) == expected
+
+ @pytest.mark.parametrize(
+ "method,expected",
+ [("supports_explain_format", "explain format"), ("supports_x", "x")],
+ )
+ def test_format_method_display(self, method, expected):
+ assert info_mod._format_method_display(method) == expected
+
+ def test_constants(self):
+ assert info_mod.DIALECT_SPECIFIC_GROUPS == {"PostgreSQL Native", "PostgreSQL Extensions"}
+ assert info_mod.SUPPORT_METHOD_ALL_ARGS["supports_explain_format"] == [
+ "TEXT",
+ "JSON",
+ "XML",
+ "YAML",
+ "TREE",
+ "DOT",
+ ]
+
+
+class TestInfoHandle:
+ def test_default_version_without_connection(self, capsys):
+ args = _args(output="json", version=None)
+ with patch.object(info_mod, "create_provider") as factory, patch.object(
+ info_mod, "_build_protocol_info", return_value={}
+ ):
+ info_mod.handle(args)
+ factory.assert_called_once_with("json", ascii_borders=False)
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["database"] == {
+ "type": "postgresql",
+ "version": "13.0.0",
+ "version_tuple": [13, 0, 0],
+ "connected": False,
+ }
+ assert payload["features"]["extensions"] == {}
+
+ def test_version_override(self, capsys):
+ args = _args(output="json", version="15.2.3")
+ with patch.object(info_mod, "create_provider"), patch.object(
+ info_mod, "_build_protocol_info", return_value={}
+ ):
+ info_mod.handle(args)
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["database"]["version"] == "15.2.3"
+ assert payload["database"]["version_tuple"] == [15, 2, 3]
+
+ def test_connected_path_reports_extensions(self, capsys):
+ dialect = PostgresDialect(version=(15, 2, 3))
+ ext = SimpleNamespace(installed=True, available=True, version="1.3", schema="public")
+ dialect._extensions = {"pgcrypto": ext}
+ backend = MagicMock()
+ backend.dialect = dialect
+ backend.get_server_version.return_value = (15, 2, 3)
+ args = _args(output="json", database="mydb")
+ with patch.object(info_mod, "create_provider"), patch.object(
+ info_mod, "_build_protocol_info", return_value={}
+ ), patch.object(info_mod, "resolve_connection_config_from_args", return_value="cfg"), patch(
+ "rhosocial.activerecord.backend.impl.postgres.backend.PostgresBackend",
+ return_value=backend,
+ ) as backend_cls:
+ info_mod.handle(args)
+ backend_cls.assert_called_once_with(connection_config="cfg")
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["database"]["connected"] is True
+ assert payload["database"]["version"] == "15.2.3"
+ assert payload["features"]["extensions"]["pgcrypto"] == {
+ "installed": True,
+ "available": True,
+ "version": "1.3",
+ "schema": "public",
+ }
+ backend.disconnect.assert_called_once_with()
+
+ def test_connection_failure_falls_back_to_defaults(self, capsys):
+ args = _args(output="json", database="mydb", version="14.1.0")
+ with patch.object(info_mod, "create_provider"), patch.object(
+ info_mod, "_build_protocol_info", return_value={}
+ ), patch.object(
+ info_mod, "resolve_connection_config_from_args", side_effect=RuntimeError("no db")
+ ):
+ info_mod.handle(args)
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["database"]["connected"] is False
+ assert payload["database"]["version"] == "14.1.0"
+
+
+# ===========================================================================
+# introspect
+# ===========================================================================
+
+
+class TestIntrospectParser:
+ def test_defaults(self):
+ args = _subparser(introspect_mod.create_parser).parse_args(["tables"])
+ assert args.type == "tables"
+ assert args.output == "table"
+ assert args.name is None
+ assert args.include_system is False
+
+ @pytest.mark.parametrize("kind", introspect_mod.INTROSPECT_TYPES)
+ def test_all_types_accepted(self, kind):
+ assert _subparser(introspect_mod.create_parser).parse_args([kind]).type == kind
+
+ def test_invalid_type_rejected(self):
+ with pytest.raises(SystemExit):
+ _subparser(introspect_mod.create_parser).parse_args(["bogus"])
+
+ def test_name_and_flags(self):
+ args = _subparser(introspect_mod.create_parser).parse_args(
+ ["value-samples", "orders", "--column", "email", "--include-system", "--async"]
+ )
+ assert args.name == "orders"
+ assert args.column == "email"
+ assert args.include_system is True
+ assert args.is_async is True
+
+ def test_join_coverage_flags(self):
+ args = _subparser(introspect_mod.create_parser).parse_args(
+ ["join-coverage", "a", "--column", "x", "--right-table", "b", "--right-column", "y"]
+ )
+ assert (args.right_table, args.right_column) == ("b", "y")
+
+
+class TestValidateName:
+ @pytest.mark.parametrize(
+ "kind", [k for k, v in introspect_mod._NAME_RULE.items() if v == "required"]
+ )
+ def test_required_missing_exits(self, kind):
+ with pytest.raises(SystemExit) as exc:
+ introspect_mod._validate_name(_args(type=kind, name=None))
+ assert exc.value.code == 1
+
+ @pytest.mark.parametrize(
+ "kind", [k for k, v in introspect_mod._NAME_RULE.items() if v == "forbidden"]
+ )
+ def test_forbidden_with_name_exits(self, kind):
+ with pytest.raises(SystemExit) as exc:
+ introspect_mod._validate_name(_args(type=kind, name="obj"))
+ assert exc.value.code == 2
+
+ @pytest.mark.parametrize("kind,rule", sorted(introspect_mod._NAME_RULE.items()))
+ def test_valid_invocation_accepted(self, kind, rule):
+ name = None if rule == "forbidden" else "obj"
+ introspect_mod._validate_name(_args(type=kind, name=name))
+
+
+class TestRequireCapability:
+ @pytest.mark.parametrize("kind,switch", sorted(introspect_mod._TYPE_CAPABILITIES.items()))
+ def test_unsupported_switch_exits(self, kind, switch):
+ backend = MagicMock()
+ dialect = MagicMock()
+ setattr(dialect, switch, MagicMock(return_value=False))
+ backend.dialect = dialect
+ with pytest.raises(SystemExit) as exc:
+ introspect_mod._require_capability(backend, _args(type=kind))
+ assert exc.value.code == 2
+
+ @pytest.mark.parametrize("kind,switch", sorted(introspect_mod._TYPE_CAPABILITIES.items()))
+ def test_supported_switch_passes(self, kind, switch):
+ backend = MagicMock()
+ dialect = MagicMock()
+ setattr(dialect, switch, MagicMock(return_value=True))
+ backend.dialect = dialect
+ introspect_mod._require_capability(backend, _args(type=kind))
+
+ def test_missing_switch_passes(self):
+ backend = MagicMock()
+ backend.dialect = object()
+ introspect_mod._require_capability(backend, _args(type="tables"))
+
+ def test_missing_dialect_passes(self):
+ backend = MagicMock()
+ backend.dialect = None
+ introspect_mod._require_capability(backend, _args(type="tables"))
+
+
+class TestRefuseUnusedArguments:
+ @pytest.mark.parametrize("kind", ["tables", "columns", "database", "table-stats"])
+ def test_column_on_wrong_type_exits(self, kind):
+ with pytest.raises(SystemExit) as exc:
+ introspect_mod._refuse_unused_arguments(_args(type=kind, column="c"))
+ assert exc.value.code == 2
+
+ @pytest.mark.parametrize("kind", ["value-samples", "join-coverage"])
+ def test_column_on_probe_type_accepted(self, kind):
+ introspect_mod._refuse_unused_arguments(_args(type=kind, column="c"))
+
+ @pytest.mark.parametrize("kind", ["tables", "columns", "value-samples"])
+ def test_right_flags_on_wrong_type_exits(self, kind):
+ with pytest.raises(SystemExit) as exc:
+ introspect_mod._refuse_unused_arguments(_args(type=kind, right_table="b"))
+ assert exc.value.code == 2
+
+ def test_right_flags_on_join_coverage_accepted(self):
+ introspect_mod._refuse_unused_arguments(
+ _args(type="join-coverage", right_table="b", right_column="y")
+ )
+
+
+class TestExtensionRows:
+ def test_extension_rows(self):
+ rows = introspect_mod._extension_rows(
+ [
+ ExtensionInfo(
+ name="pgcrypto", version="1.3", schema="public", description="crypto"
+ ),
+ ExtensionInfo(name="hstore"),
+ ]
+ )
+ assert rows == [
+ {"name": "pgcrypto", "version": "1.3", "schema": "public", "description": "crypto"},
+ {"name": "hstore", "version": None, "schema": None, "description": None},
+ ]
+
+
+class TestIntrospectHandleDispatch:
+ def test_missing_database_exits(self, capsys):
+ with pytest.raises(SystemExit) as exc:
+ introspect_mod.handle(_args(type="tables", database=None))
+ assert exc.value.code == 1
+ assert "database is required" in capsys.readouterr().err
+
+ def test_sync_dispatch(self):
+ args = _args(type="tables")
+ with patch.object(introspect_mod, "create_provider") as factory, patch.object(
+ introspect_mod, "resolve_connection_config_from_args", return_value="cfg"
+ ), patch.object(introspect_mod, "PostgresBackend") as backend_cls, patch.object(
+ introspect_mod, "_handle_introspect_sync"
+ ) as handler:
+ introspect_mod.handle(args)
+ factory.assert_called_once_with("json", ascii_borders=False)
+ backend_cls.assert_called_once_with(connection_config="cfg")
+ handler.assert_called_once_with(args, backend_cls.return_value, factory.return_value)
+
+ def test_async_dispatch(self):
+ args = _args(type="tables", is_async=True)
+ coroutine = object()
+ with patch.object(introspect_mod, "create_provider"), patch.object(
+ introspect_mod, "resolve_connection_config_from_args", return_value="cfg"
+ ), patch.object(introspect_mod, "AsyncPostgresBackend") as backend_cls, patch.object(
+ introspect_mod, "_handle_introspect_async", new=MagicMock(return_value=coroutine)
+ ) as handler, patch.object(
+ introspect_mod, "run_coroutine"
+ ) as runner:
+ introspect_mod.handle(args)
+ backend_cls.assert_called_once_with(connection_config="cfg")
+ handler.assert_called_once()
+ runner.assert_called_once_with(coroutine)
+
+
+_SYNC_CASES = [
+ ("tables", None, "list_tables", dict(schema=None, include_system=False), "Tables", False),
+ ("views", None, "list_views", dict(schema=None), "Views", False),
+ ("columns", "users", "list_columns", dict(schema=None), "Columns of users", False),
+ ("indexes", "users", "list_indexes", dict(schema=None), "Indexes of users", False),
+ (
+ "foreign-keys",
+ "users",
+ "list_foreign_keys",
+ dict(schema=None),
+ "Foreign Keys of users",
+ False,
+ ),
+ ("triggers", None, "list_triggers", dict(table_name=None, schema=None), "Triggers", False),
+ ("database", None, "get_database_info", {}, "Database Info", True),
+ (
+ "materialized-views",
+ None,
+ "list_materialized_views",
+ dict(schema=None, include_system=False),
+ "Materialized Views",
+ False,
+ ),
+ ("sequences", None, "list_sequences", dict(schema=None), "Sequences", False),
+ ("partitions", "orders", "list_partitions", dict(schema=None), "Partitions of orders", False),
+ ("routines", None, "list_routines", dict(schema=None, routine_name=None), "Routines", False),
+ ("types", None, "list_types", dict(schema=None, type_name=None), "Types", False),
+ (
+ "operators",
+ None,
+ "list_operators",
+ dict(schema=None, operator_name=None),
+ "Operators",
+ False,
+ ),
+ (
+ "operator-classes",
+ None,
+ "list_operator_classes",
+ dict(schema=None, operator_class_name=None),
+ "Operator Classes",
+ False,
+ ),
+ (
+ "operator-families",
+ None,
+ "list_operator_families",
+ dict(schema=None, operator_family_name=None),
+ "Operator Families",
+ False,
+ ),
+ ("unused-indexes", None, "list_unused_indexes", dict(schema=None), "Unused Indexes", False),
+ ("table-stats", None, "list_table_usage_stats", dict(schema=None), "Table Usage Stats", False),
+ ("runtime", None, "list_runtime_metrics", dict(schema=None), "Runtime Metrics", False),
+ ("index-stats", None, "list_index_usage_stats", dict(schema=None), "Index Usage Stats", False),
+ (
+ "dependencies",
+ None,
+ "list_object_dependencies",
+ dict(object_name=None, schema=None),
+ "Object Dependencies",
+ False,
+ ),
+ (
+ "column-profiles",
+ "orders",
+ "list_column_data_profiles",
+ dict(schema=None),
+ "Column profiles of orders",
+ False,
+ ),
+]
+
+
+class TestIntrospectSyncHandler:
+ @pytest.mark.parametrize("kind,name,method,kwargs,title,wrapped", _SYNC_CASES)
+ def test_family_dispatch(self, kind, name, method, kwargs, title, wrapped):
+ backend = MagicMock()
+ backend._connection = False
+ sample = [{"k": "v"}]
+ getattr(backend.introspector, method).return_value = sample
+ provider = MagicMock()
+ introspect_mod._handle_introspect_sync(_args(type=kind, name=name), backend, provider)
+ backend.connect.assert_called_once_with()
+ backend.introspect_and_adapt.assert_called_once_with()
+ if name and method in (
+ "list_columns",
+ "list_indexes",
+ "list_foreign_keys",
+ "list_partitions",
+ "list_column_data_profiles",
+ ):
+ getattr(backend.introspector, method).assert_called_once_with(name, **kwargs)
+ else:
+ getattr(backend.introspector, method).assert_called_once_with(**kwargs)
+ expected = [sample] if wrapped else sample
+ provider.display_results.assert_called_once_with(expected, title=title)
+
+ def test_extensions_family(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.list_extensions.return_value = [
+ ExtensionInfo(name="pgcrypto", version="1.3", schema="public", description=None)
+ ]
+ provider = MagicMock()
+ introspect_mod._handle_introspect_sync(_args(type="extensions"), backend, provider)
+ provider.display_results.assert_called_once_with(
+ [{"name": "pgcrypto", "version": "1.3", "schema": "public", "description": None}],
+ title="Extensions",
+ )
+
+ def test_value_samples(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.sample_column_values.return_value = [{"value": 1}]
+ provider = MagicMock()
+ introspect_mod._handle_introspect_sync(
+ _args(type="value-samples", name="orders", column="email"), backend, provider
+ )
+ backend.introspector.sample_column_values.assert_called_once_with(
+ "orders", "email", schema=None
+ )
+ provider.display_results.assert_called_once_with(
+ [{"value": 1}], title="Values of orders.email"
+ )
+
+ def test_join_coverage(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.estimate_join_coverage.return_value = {"overlap": 0.5}
+ provider = MagicMock()
+ introspect_mod._handle_introspect_sync(
+ _args(
+ type="join-coverage",
+ name="orders",
+ column="buyer",
+ right_table="users",
+ right_column="id",
+ ),
+ backend,
+ provider,
+ )
+ backend.introspector.estimate_join_coverage.assert_called_once_with(
+ "orders", "buyer", "users", "id", schema=None
+ )
+ provider.display_results.assert_called_once_with([{"overlap": 0.5}], title="Join Coverage")
+
+ @pytest.mark.parametrize(
+ "kind,name,method",
+ [
+ ("views", "missing", "get_view_info"),
+ ("extensions", "missing", "get_extension_info"),
+ ("materialized-views", "missing", "get_materialized_view_info"),
+ ("sequences", "missing", "get_sequence_info"),
+ ],
+ )
+ def test_named_object_not_found_exits(self, kind, name, method):
+ backend = MagicMock()
+ backend._connection = False
+ getattr(backend.introspector, method).return_value = None
+ with pytest.raises(SystemExit) as exc:
+ introspect_mod._handle_introspect_sync(
+ _args(type=kind, name=name), backend, MagicMock()
+ )
+ assert exc.value.code == 1
+
+ def test_value_samples_requires_column(self):
+ backend = MagicMock()
+ backend._connection = False
+ with pytest.raises(SystemExit) as exc:
+ introspect_mod._handle_introspect_sync(
+ _args(type="value-samples", name="orders", column=None), backend, MagicMock()
+ )
+ assert exc.value.code == 1
+
+ def test_join_coverage_requires_right_flags(self):
+ backend = MagicMock()
+ backend._connection = False
+ with pytest.raises(SystemExit):
+ introspect_mod._handle_introspect_sync(
+ _args(type="join-coverage", name="orders", column="buyer"), backend, MagicMock()
+ )
+
+ def test_connection_error_exits(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.connect.side_effect = ConnectionError("down")
+ provider = MagicMock()
+ with pytest.raises(SystemExit):
+ introspect_mod._handle_introspect_sync(_args(type="tables"), backend, provider)
+ provider.display_connection_error.assert_called_once()
+
+
+class TestIntrospectAsyncHandler:
+ @pytest.mark.parametrize("kind,name,method,kwargs,title,wrapped", _SYNC_CASES[:6])
+ async def test_async_family_dispatch(self, kind, name, method, kwargs, title, wrapped):
+ backend = AsyncMock()
+ backend._connection = False
+ introspector = MagicMock()
+ setattr(introspector, method, AsyncMock(return_value=[{"k": "v"}]))
+ backend.introspector = introspector
+ backend.dialect = None
+ provider = MagicMock()
+ await introspect_mod._handle_introspect_async(
+ _args(type=kind, name=name), backend, provider
+ )
+ backend.connect.assert_awaited_once_with()
+ backend.introspect_and_adapt.assert_awaited_once_with()
+ expected = [[{"k": "v"}]] if wrapped else [{"k": "v"}]
+ provider.display_results.assert_called_once_with(expected, title=title)
+
+ async def test_async_value_samples(self):
+ backend = AsyncMock()
+ backend._connection = False
+ backend.introspector = MagicMock(
+ sample_column_values=AsyncMock(return_value=[{"value": 2}])
+ )
+ backend.dialect = None
+ provider = MagicMock()
+ await introspect_mod._handle_introspect_async(
+ _args(type="value-samples", name="t", column="c"), backend, provider
+ )
+ provider.display_results.assert_called_once_with([{"value": 2}], title="Values of t.c")
+
+ async def test_async_unsupported_capability_exits(self):
+ backend = AsyncMock()
+ backend._connection = False
+ dialect = MagicMock()
+ dialect.supports_table_introspection = MagicMock(return_value=False)
+ backend.dialect = dialect
+ with pytest.raises(SystemExit) as exc:
+ await introspect_mod._handle_introspect_async(
+ _args(type="tables"), backend, MagicMock()
+ )
+ assert exc.value.code == 2
+
+
+# ===========================================================================
+# query
+# ===========================================================================
+
+
+class TestQueryParser:
+ def test_defaults(self):
+ args = _subparser(query_mod.create_parser).parse_args([])
+ assert args.output == "table"
+ assert args.sql is None
+ assert args.file is None
+ assert args.log_level == "INFO"
+ assert args.rich_ascii is False
+
+ @pytest.mark.parametrize("output", ["table", "json", "csv", "tsv"])
+ def test_output_choices(self, output):
+ assert _subparser(query_mod.create_parser).parse_args(["-o", output]).output == output
+
+ def test_sql_and_file(self):
+ parser = _subparser(query_mod.create_parser)
+ assert parser.parse_args(["SELECT 1"]).sql == "SELECT 1"
+ assert parser.parse_args(["-f", "q.sql"]).file == "q.sql"
+
+
+class TestQueryHandleValidation:
+ def test_invalid_log_level_raises(self):
+ with pytest.raises(ValueError, match="Invalid log level"):
+ query_mod.handle(_args(sql="SELECT 1", log_level="NOPE"))
+
+ def test_missing_sql_exits(self, capsys):
+ fake_stdin = MagicMock()
+ fake_stdin.isatty.return_value = True
+ with patch.object(query_mod.sys, "stdin", fake_stdin):
+ with pytest.raises(SystemExit) as exc:
+ query_mod.handle(_args(sql=None, file=None))
+ assert exc.value.code == 1
+ assert "No SQL query provided" in capsys.readouterr().err
+
+ def test_multiple_statements_exit(self):
+ with pytest.raises(SystemExit) as exc:
+ query_mod.handle(_args(sql="SELECT 1; SELECT 2;"))
+ assert exc.value.code == 1
+
+ def test_single_trailing_semicolon_allowed(self):
+ with patch.object(query_mod, "create_provider"), patch.object(
+ query_mod.logging, "basicConfig"
+ ), patch.object(
+ query_mod, "resolve_connection_config_from_args", return_value="cfg"
+ ), patch.object(
+ query_mod, "PostgresBackend"
+ ), patch.object(
+ query_mod, "_execute_query_sync"
+ ) as executor:
+ query_mod.handle(_args(sql="SELECT 1;"))
+ executor.assert_called_once()
+
+ def test_file_not_found_exits(self):
+ with pytest.raises(SystemExit) as exc:
+ query_mod.handle(_args(sql=None, file="no/such/query.sql"))
+ assert exc.value.code == 1
+
+ def test_file_source(self, tmp_path):
+ path = tmp_path / "q.sql"
+ path.write_text("SELECT 42", encoding="utf-8")
+ with patch.object(query_mod, "create_provider"), patch.object(
+ query_mod.logging, "basicConfig"
+ ), patch.object(
+ query_mod, "resolve_connection_config_from_args", return_value="cfg"
+ ), patch.object(
+ query_mod, "PostgresBackend"
+ ), patch.object(
+ query_mod, "_execute_query_sync"
+ ) as executor:
+ query_mod.handle(_args(sql=None, file=str(path)))
+ assert executor.call_args.args[0] == "SELECT 42"
+
+ def test_stdin_source(self):
+ fake_stdin = MagicMock()
+ fake_stdin.isatty.return_value = False
+ fake_stdin.read.return_value = "SELECT 7"
+ with patch.object(query_mod.sys, "stdin", fake_stdin), patch.object(
+ query_mod, "create_provider"
+ ), patch.object(query_mod.logging, "basicConfig"), patch.object(
+ query_mod, "resolve_connection_config_from_args", return_value="cfg"
+ ), patch.object(
+ query_mod, "PostgresBackend"
+ ), patch.object(
+ query_mod, "_execute_query_sync"
+ ) as executor:
+ query_mod.handle(_args(sql=None, file=None))
+ assert executor.call_args.args[0] == "SELECT 7"
+
+
+class TestQueryHandleDispatch:
+ def test_sync_dispatch(self):
+ args = _args(sql="SELECT 1", log_level="DEBUG", rich_ascii=True)
+ with patch.object(query_mod, "create_provider") as factory, patch.object(
+ query_mod.logging, "basicConfig"
+ ) as logging_mod, patch.object(
+ query_mod, "resolve_connection_config_from_args", return_value="cfg"
+ ), patch.object(
+ query_mod, "PostgresBackend"
+ ) as backend_cls, patch.object(
+ query_mod, "_execute_query_sync"
+ ) as executor:
+ query_mod.handle(args)
+ factory.assert_called_once_with("json", ascii_borders=True)
+ logging_mod.assert_called_once()
+ factory.return_value.display_greeting.assert_called_once_with()
+ backend_cls.assert_called_once_with(connection_config="cfg")
+ executor.assert_called_once_with(
+ "SELECT 1", backend_cls.return_value, factory.return_value, use_ascii=True
+ )
+
+ def test_async_dispatch(self):
+ args = _args(sql="SELECT 1", is_async=True)
+ coroutine = object()
+ with patch.object(query_mod, "create_provider"), patch.object(
+ query_mod.logging, "basicConfig"
+ ), patch.object(
+ query_mod, "resolve_connection_config_from_args", return_value="cfg"
+ ), patch.object(
+ query_mod, "AsyncPostgresBackend"
+ ) as backend_cls, patch.object(
+ query_mod, "_execute_query_async", new=MagicMock(return_value=coroutine)
+ ) as executor, patch.object(
+ query_mod, "run_coroutine"
+ ) as runner:
+ query_mod.handle(args)
+ backend_cls.assert_called_once_with(connection_config="cfg")
+ executor.assert_called_once()
+ runner.assert_called_once_with(coroutine)
+
+
+class TestQueryExecuteSync:
+ def test_result_with_data(self):
+ backend = MagicMock()
+ backend._connection = True
+ backend.execute.return_value = SimpleNamespace(
+ affected_rows=2, duration=0.5, data=[{"a": 1}]
+ )
+ provider = MagicMock()
+ query_mod._execute_query_sync("SELECT 1", backend, provider, use_ascii=False)
+ provider.display_query.assert_called_once_with("SELECT 1", is_async=False)
+ provider.display_success.assert_called_once_with(2, 0.5)
+ provider.display_results.assert_called_once_with([{"a": 1}], use_ascii=False)
+ backend.disconnect.assert_called_once_with()
+ provider.display_disconnect.assert_called_once_with(is_async=False)
+
+ def test_result_without_data(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.execute.return_value = SimpleNamespace(affected_rows=0, duration=0.1, data=[])
+ provider = MagicMock()
+ query_mod._execute_query_sync("UPDATE t", backend, provider)
+ provider.display_no_data.assert_called_once_with()
+ provider.display_results.assert_not_called()
+
+ def test_no_result_object(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.execute.return_value = None
+ provider = MagicMock()
+ query_mod._execute_query_sync("SET x", backend, provider)
+ provider.display_no_result_object.assert_called_once_with()
+
+ def test_connection_error_exits(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.connect.side_effect = ConnectionError("down")
+ provider = MagicMock()
+ with pytest.raises(SystemExit):
+ query_mod._execute_query_sync("SELECT 1", backend, provider)
+ provider.display_connection_error.assert_called_once()
+
+ def test_query_error_exits(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.execute.side_effect = QueryError("bad")
+ provider = MagicMock()
+ with pytest.raises(SystemExit):
+ query_mod._execute_query_sync("SELECT 1", backend, provider)
+ provider.display_query_error.assert_called_once()
+
+ def test_unexpected_error_exits(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.execute.side_effect = RuntimeError("boom")
+ provider = MagicMock()
+ with pytest.raises(SystemExit):
+ query_mod._execute_query_sync("SELECT 1", backend, provider)
+ provider.display_unexpected_error.assert_called_once()
+
+
+class TestQueryExecuteAsync:
+ async def test_result_with_data(self):
+ backend = AsyncMock()
+ backend._connection = True
+ backend.execute.return_value = SimpleNamespace(
+ affected_rows=1, duration=0.2, data=[{"b": 2}]
+ )
+ provider = MagicMock()
+ await query_mod._execute_query_async("SELECT 1", backend, provider, use_ascii=True)
+ backend.connect.assert_awaited_once_with()
+ provider.display_query.assert_called_once_with("SELECT 1", is_async=True)
+ provider.display_results.assert_called_once_with([{"b": 2}], use_ascii=True)
+ backend.disconnect.assert_awaited_once_with()
+ provider.display_disconnect.assert_called_once_with(is_async=True)
+
+ async def test_no_result_object(self):
+ backend = AsyncMock()
+ backend._connection = False
+ backend.execute.return_value = None
+ provider = MagicMock()
+ await query_mod._execute_query_async("SELECT 1", backend, provider)
+ provider.display_no_result_object.assert_called_once_with()
+
+ async def test_connection_error_exits(self):
+ backend = AsyncMock()
+ backend._connection = False
+ backend.connect.side_effect = ConnectionError("down")
+ provider = MagicMock()
+ with pytest.raises(SystemExit):
+ await query_mod._execute_query_async("SELECT 1", backend, provider)
+ provider.display_connection_error.assert_called_once()
+
+ async def test_unexpected_error_exits(self):
+ backend = AsyncMock()
+ backend._connection = False
+ backend.execute.side_effect = RuntimeError("boom")
+ provider = MagicMock()
+ with pytest.raises(SystemExit):
+ await query_mod._execute_query_async("SELECT 1", backend, provider)
+ provider.display_unexpected_error.assert_called_once_with(
+ backend.execute.side_effect, is_async=True
+ )
+
+
+# ===========================================================================
+# rich rendering (fake rich modules -- no optional dependency required)
+# ===========================================================================
+
+
+class _FakeTable:
+ def __init__(self, *args, **kwargs):
+ self.columns = []
+ self.rows = []
+
+ def add_column(self, *args, **kwargs):
+ self.columns.append(args)
+
+ def add_row(self, *args, **kwargs):
+ self.rows.append(args)
+
+
+class _FakeConsole:
+ printed = []
+
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def print(self, *args, **kwargs):
+ for item in args:
+ if isinstance(item, _FakeTable):
+ for names in item.columns:
+ _FakeConsole.printed.extend(str(name) for name in names)
+ for row in item.rows:
+ _FakeConsole.printed.extend(str(value) for value in row)
+ else:
+ _FakeConsole.printed.append(str(item))
+
+
+@pytest.fixture
+def fake_rich():
+ console_mod = types.ModuleType("rich.console")
+ console_mod.Console = _FakeConsole
+ table_mod = types.ModuleType("rich.table")
+ table_mod.Table = _FakeTable
+ rich_mod = types.ModuleType("rich")
+ rich_mod.console = console_mod
+ rich_mod.table = table_mod
+ with patch.dict(
+ sys.modules, {"rich": rich_mod, "rich.console": console_mod, "rich.table": table_mod}
+ ):
+ _FakeConsole.printed = []
+ yield _FakeConsole
+
+
+def _full_overview():
+ overview = ServerOverview(server_version="16.2", server_vendor="PostgreSQL")
+ overview.session = SessionInfo(
+ user="bob",
+ database="db",
+ schema="public",
+ host="h",
+ ssl_enabled=True,
+ ssl_version="TLS1.3",
+ ssl_cipher="AES",
+ password_used=True,
+ )
+ overview.connections = ConnectionInfo(active_count=5, max_connections=100)
+ overview.storage = StorageInfo(total_size_bytes=1024**3)
+ overview.configuration = [
+ StatusItem(
+ "shared_buffers",
+ "128MB",
+ StatusCategory.CONFIGURATION,
+ description="buffer cache",
+ is_readonly=True,
+ ),
+ StatusItem("work_mem", "4MB", StatusCategory.PERFORMANCE, unit="MB"),
+ ]
+ overview.databases = [
+ DatabaseBriefInfo(
+ name="db",
+ size_bytes=2048,
+ table_count=3,
+ view_count=1,
+ extra={"schemas": {"public": {"tables": 2, "views": 1}}},
+ )
+ ]
+ overview.users = [UserInfo(name="bob", is_superuser=True)]
+ overview.wal = SimpleNamespace(
+ wal_level="replica",
+ wal_files=2,
+ wal_size_bytes=4096,
+ checkpoint_count=7,
+ checkpoint_time="now",
+ wal_segments=3,
+ )
+ overview.replication = SimpleNamespace(
+ is_primary=True,
+ replication_slots=1,
+ active_replications=2,
+ streaming=True,
+ lag_bytes=512,
+ )
+ overview.archive = SimpleNamespace(
+ archive_mode="on",
+ archive_command="x" * 60,
+ archive_timeout=30,
+ archived_count=4,
+ failed_count=0,
+ )
+ overview.security = SimpleNamespace(
+ ssl_enabled=True,
+ ssl_cert_file="c",
+ ssl_key_file="k",
+ ssl_ca_file="ca",
+ password_encryption="scram",
+ row_security=False,
+ )
+ overview.extensions = [SimpleNamespace(name="pgcrypto", version="1.3", schema="public")]
+ return overview
+
+
+class TestStatusRichDisplay:
+ def test_all_sections_render(self, fake_rich):
+ status_mod._display_status_rich(_full_overview(), verbose=1)
+ out = " ".join(fake_rich.printed)
+ for label in (
+ "Server Status",
+ "Session",
+ "Configuration",
+ "Performance",
+ "Storage",
+ "Databases",
+ "Schemas in db",
+ "Users",
+ "WAL",
+ "Replication",
+ "Archive",
+ "Security",
+ "Extensions",
+ ):
+ assert label in out
+ assert "1.0 GB" in out
+ assert "..." in out # the long archive command is truncated
+
+ def test_non_verbose_paths(self, fake_rich):
+ status_mod._display_status_rich(_full_overview(), verbose=0)
+ out = " ".join(fake_rich.printed)
+ assert "buffer cache" not in out
+ assert "16.2" in out
+
+ def test_optional_sections_absent(self, fake_rich):
+ overview = ServerOverview(server_version="16", server_vendor="PostgreSQL")
+ status_mod._display_status_rich(overview, verbose=2)
+ out = " ".join(fake_rich.printed)
+ assert "Server Status" in out
+ assert "Session" not in out
+ assert "WAL" not in out
+
+
+class TestInfoRichDisplay:
+ def _legacy_info(self):
+ return {
+ "postgresql": {"version": "16.0"},
+ "extensions": {
+ "pgcrypto": SimpleNamespace(
+ installed=True, available=True, version="1.3", schema="public"
+ ),
+ "hstore": SimpleNamespace(
+ installed=False, available=True, version="1.4", schema=None
+ ),
+ },
+ "protocols": {
+ "Query Features": {
+ "ProtoA": {
+ "percentage": 100.0,
+ "supported": 1,
+ "total": 1,
+ "methods": {
+ "supports_x": True,
+ "supports_explain_format": {"args": {"TEXT": True, "YAML": False}},
+ },
+ }
+ },
+ "PostgreSQL Native": {"ProtoB": {"percentage": 0.0, "supported": 0, "total": 2}},
+ },
+ }
+
+ def test_connected_detailed_render(self, fake_rich):
+ extensions = self._legacy_info()["extensions"]
+ info_mod._display_info_rich(self._legacy_info(), 2, "16.0", extensions, is_connected=True)
+ out = " ".join(fake_rich.printed)
+ for label in (
+ "Environment Information",
+ "actual connection",
+ "Extension Support",
+ "Installed",
+ "Available (not installed)",
+ "Protocol Support",
+ "Detailed",
+ "dialect-specific",
+ "ProtoA",
+ "ProtoB",
+ "explain format",
+ ):
+ assert label in out
+
+ def test_disconnected_family_overview(self, fake_rich):
+ info_mod._display_info_rich(self._legacy_info(), 0, "13.0.0", None, is_connected=False)
+ out = " ".join(fake_rich.printed)
+ assert "default value" in out
+ assert "Family Overview" in out
+
+
+# ===========================================================================
+# introspect: remaining per-object and error branches
+# ===========================================================================
+
+
+class TestIntrospectExtraBranches:
+ @pytest.mark.parametrize(
+ "kind,name,method,title",
+ [
+ ("views", "v", "get_view_info", "View v"),
+ ("materialized-views", "mv", "get_materialized_view_info", "Materialized View mv"),
+ ("sequences", "s", "get_sequence_info", "Sequence s"),
+ ],
+ )
+ def test_named_object_found(self, kind, name, method, title):
+ backend = MagicMock()
+ backend._connection = False
+ getattr(backend.introspector, method).return_value = {"name": name}
+ provider = MagicMock()
+ introspect_mod._handle_introspect_sync(_args(type=kind, name=name), backend, provider)
+ provider.display_results.assert_called_once_with([{"name": name}], title=title)
+
+ def test_named_extension_found(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.get_extension_info.return_value = ExtensionInfo(
+ name="pgcrypto", version="1.3", schema="public", description="crypto"
+ )
+ provider = MagicMock()
+ introspect_mod._handle_introspect_sync(
+ _args(type="extensions", name="pgcrypto"), backend, provider
+ )
+ provider.display_results.assert_called_once_with(
+ [{"name": "pgcrypto", "version": "1.3", "schema": "public", "description": "crypto"}],
+ title="Extension pgcrypto",
+ )
+
+ def test_table_storage_found(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.list_tables.return_value = [
+ DatabaseBriefInfo(name="other"),
+ DatabaseBriefInfo(name="orders", size_bytes=128),
+ ]
+ provider = MagicMock()
+ introspect_mod._handle_introspect_sync(
+ _args(type="table-storage", name="orders"), backend, provider
+ )
+ provider.display_results.assert_called_once()
+ assert provider.display_results.call_args.kwargs["title"] == "Table storage orders"
+
+ def test_table_storage_not_found_exits(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.list_tables.return_value = [DatabaseBriefInfo(name="other")]
+ with pytest.raises(SystemExit) as exc:
+ introspect_mod._handle_introspect_sync(
+ _args(type="table-storage", name="orders"), backend, MagicMock()
+ )
+ assert exc.value.code == 1
+
+ def test_dependencies_with_name(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.list_object_dependencies.return_value = [{"edge": 1}]
+ provider = MagicMock()
+ introspect_mod._handle_introspect_sync(
+ _args(type="dependencies", name="orders"), backend, provider
+ )
+ provider.display_results.assert_called_once_with(
+ [{"edge": 1}], title="Dependencies of orders"
+ )
+
+ def test_join_coverage_without_measurement_exits(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.estimate_join_coverage.return_value = None
+ args = _args(type="join-coverage", name="a", column="x", right_table="b", right_column="y")
+ with pytest.raises(SystemExit) as exc:
+ introspect_mod._handle_introspect_sync(args, backend, MagicMock())
+ assert exc.value.code == 1
+
+ def test_query_error_exits(self):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.list_tables.side_effect = QueryError("bad")
+ provider = MagicMock()
+ with pytest.raises(SystemExit):
+ introspect_mod._handle_introspect_sync(_args(type="tables"), backend, provider)
+ provider.display_query_error.assert_called_once()
+
+ def test_unexpected_error_exits(self, capsys):
+ backend = MagicMock()
+ backend._connection = False
+ backend.introspector.list_tables.side_effect = RuntimeError("boom")
+ with pytest.raises(SystemExit):
+ introspect_mod._handle_introspect_sync(_args(type="tables"), backend, MagicMock())
+ assert "Error during introspection" in capsys.readouterr().err
+
+ async def test_named_object_found_async(self):
+ backend = AsyncMock()
+ backend._connection = False
+ backend.dialect = None
+ backend.introspector = MagicMock(get_view_info=AsyncMock(return_value={"name": "v"}))
+ provider = MagicMock()
+ await introspect_mod._handle_introspect_async(
+ _args(type="views", name="v"), backend, provider
+ )
+ provider.display_results.assert_called_once_with([{"name": "v"}], title="View v")
+
+ async def test_table_storage_async(self):
+ backend = AsyncMock()
+ backend._connection = False
+ backend.dialect = None
+ backend.introspector = MagicMock(
+ list_tables=AsyncMock(return_value=[DatabaseBriefInfo(name="orders", size_bytes=8)])
+ )
+ provider = MagicMock()
+ await introspect_mod._handle_introspect_async(
+ _args(type="table-storage", name="orders"), backend, provider
+ )
+ assert provider.display_results.call_args.kwargs["title"] == "Table storage orders"
+
+ async def test_join_coverage_without_measurement_async(self):
+ backend = AsyncMock()
+ backend._connection = False
+ backend.dialect = None
+ backend.introspector = MagicMock(estimate_join_coverage=AsyncMock(return_value=None))
+ args = _args(type="join-coverage", name="a", column="x", right_table="b", right_column="y")
+ with pytest.raises(SystemExit):
+ await introspect_mod._handle_introspect_async(args, backend, MagicMock())
+
+ async def test_query_error_async(self):
+ backend = AsyncMock()
+ backend._connection = False
+ backend.dialect = None
+ backend.introspector = MagicMock(list_tables=AsyncMock(side_effect=QueryError("bad")))
+ provider = MagicMock()
+ with pytest.raises(SystemExit):
+ await introspect_mod._handle_introspect_async(_args(type="tables"), backend, provider)
+ provider.display_query_error.assert_called_once()
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_status_cli.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_status_cli.py
new file mode 100644
index 00000000..ea90f810
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/cli/test_status_cli.py
@@ -0,0 +1,220 @@
+# tests/activerecord_postgres_test/feature/backend/construct/cli/test_status_cli.py
+"""Backend-owned tests for ``postgres.cli.status``.
+
+The shared testsuite covers data-operation compatibility, not this backend's
+CLI surface. These portable tests pin the parts of the status subcommand that
+are common to every backend: parser shape, pure serialization/size helpers,
+rich rendering of the overview header, and the dispatch guard. No live server
+is needed.
+"""
+from dataclasses import dataclass
+from enum import Enum
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from rhosocial.activerecord.backend.impl.postgres.cli import status as mod
+from rhosocial.activerecord.backend.introspection.status import ServerOverview
+
+
+# ---------------------------------------------------------------------------
+# create_parser
+# ---------------------------------------------------------------------------
+
+
+class TestCreateParser:
+ def test_parser_defaults_and_choices(self):
+ import argparse
+
+ subs = argparse.ArgumentParser(prog="x").add_subparsers(dest="command")
+ parser = mod.create_parser(subs)
+ args = parser.parse_args([])
+ assert args.type == "all"
+ assert args.output == "table"
+ assert args.verbose == 0
+ assert args.rich_ascii is False
+
+ @pytest.mark.parametrize("t", mod.STATUS_TYPES)
+ def test_all_status_types_accepted(self, t):
+ import argparse
+
+ subs = argparse.ArgumentParser(prog="x").add_subparsers(dest="command")
+ parser = mod.create_parser(subs)
+ assert parser.parse_args([t]).type == t
+
+ def test_verbose_is_counted(self):
+ import argparse
+
+ subs = argparse.ArgumentParser(prog="x").add_subparsers(dest="command")
+ parser = mod.create_parser(subs)
+ assert parser.parse_args(["-vvv"]).verbose == 3
+
+
+# ---------------------------------------------------------------------------
+# _serialize_for_output
+# ---------------------------------------------------------------------------
+
+
+class _Colour(Enum):
+ RED = "red"
+
+
+@dataclass
+class _Point:
+ x: int
+ y: int
+
+
+class _WithModelDump:
+ def model_dump(self, mode="python"):
+ return {"a": 1, "mode": mode}
+
+
+class _Fallback:
+ def __str__(self):
+ return "fallback"
+
+
+class TestSerializeForOutput:
+ def test_none_and_scalars(self):
+ assert mod._serialize_for_output(None) is None
+ assert mod._serialize_for_output("x") == "x"
+ assert mod._serialize_for_output(3) == 3
+ assert mod._serialize_for_output(1.5) == 1.5
+ assert mod._serialize_for_output(True) is True
+
+ def test_enum(self):
+ assert mod._serialize_for_output(_Colour.RED) == "red"
+
+ def test_dataclass(self):
+ assert mod._serialize_for_output(_Point(1, 2)) == {"x": 1, "y": 2}
+
+ def test_dict_and_list_recursive(self):
+ obj = {"p": _Point(1, 2), "c": _Colour.RED, "items": [_Colour.RED, 2]}
+ assert mod._serialize_for_output(obj) == {
+ "p": {"x": 1, "y": 2}, "c": "red", "items": ["red", 2],
+ }
+
+ def test_tuple_becomes_list(self):
+ assert mod._serialize_for_output((1, 2)) == [1, 2]
+
+ def test_model_dump(self):
+ assert mod._serialize_for_output(_WithModelDump()) == {"a": 1, "mode": "json"}
+
+ def test_model_dump_typeerror_falls_back(self):
+ class BadNoMode:
+ def model_dump(self):
+ return {"ok": True}
+
+ assert mod._serialize_for_output(BadNoMode()) == {"ok": True}
+
+ def test_unknown_falls_back_to_str(self):
+ assert mod._serialize_for_output(_Fallback()) == "fallback"
+
+
+# ---------------------------------------------------------------------------
+# _format_size
+# ---------------------------------------------------------------------------
+
+
+class TestFormatSize:
+ @pytest.mark.parametrize(
+ "size,expected",
+ [
+ (0, "0.0 B"),
+ (512, "512.0 B"),
+ (1024, "1.0 KB"),
+ (1024 * 1024, "1.0 MB"),
+ (1024**3, "1.0 GB"),
+ (1024**4, "1.0 TB"),
+ (1024**5, "1.0 PB"),
+ ],
+ )
+ def test_units(self, size, expected):
+ assert mod._format_size(size) == expected
+
+
+# ---------------------------------------------------------------------------
+# _display_status_rich (fake rich so it runs without the optional dependency)
+# ---------------------------------------------------------------------------
+
+
+class _FakeTable:
+ def __init__(self, *a, **k):
+ self.columns = []
+ self.rows = []
+
+ def add_column(self, *a, **k):
+ self.columns.append((a, k))
+
+ def add_row(self, *a, **k):
+ self.rows.append((a, k))
+
+
+class _FakeConsole:
+ printed = []
+
+ def __init__(self, *a, **k):
+ pass
+
+ def print(self, *a, **k):
+ for item in a:
+ if isinstance(item, _FakeTable):
+ for args, kwargs in item.columns:
+ _FakeConsole.printed.extend(str(x) for x in args)
+ for args, kwargs in item.rows:
+ _FakeConsole.printed.extend(str(x) for x in args)
+ else:
+ _FakeConsole.printed.append(str(item))
+
+
+@pytest.fixture
+def fake_rich():
+ import sys
+ import types
+
+ console_mod = types.ModuleType("rich.console")
+ console_mod.Console = _FakeConsole
+ table_mod = types.ModuleType("rich.table")
+ table_mod.Table = _FakeTable
+ rich_mod = types.ModuleType("rich")
+ rich_mod.console = console_mod
+ rich_mod.table = table_mod
+ with patch.dict(
+ sys.modules,
+ {"rich": rich_mod, "rich.console": console_mod, "rich.table": table_mod},
+ ):
+ _FakeConsole.printed = []
+ yield
+
+
+class TestDisplayStatusRich:
+ def test_header_always_rendered(self, fake_rich):
+ ov = ServerOverview(server_version="8.0", server_vendor="Vendor")
+ mod._display_status_rich(ov)
+ out = " ".join(_FakeConsole.printed)
+ assert "Server Status" in out
+ assert "8.0" in out
+ assert "Vendor" in out
+
+ def test_verbose_adds_columns(self, fake_rich):
+ ov = ServerOverview(server_version="8.0", server_vendor="Vendor")
+ mod._display_status_rich(ov, verbose=1)
+ # At minimum the console was driven with more than the bare header.
+ assert len(_FakeConsole.printed) >= 3
+
+
+# ---------------------------------------------------------------------------
+# handle: shared dispatch guard
+# ---------------------------------------------------------------------------
+
+
+class TestHandleDispatch:
+ def test_requires_database(self, capsys):
+ args = MagicMock()
+ args.database = None
+ args.named_connection = None
+ with pytest.raises(SystemExit) as e:
+ mod.handle(args)
+ assert e.value.code == 1
+ assert "database is required" in capsys.readouterr().err
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/connection/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/connection/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_auto_increment_ddl.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py
similarity index 55%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_auto_increment_ddl.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py
index ef195797..74e344dc 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_auto_increment_ddl.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py
@@ -1,20 +1,22 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_auto_increment_ddl.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_auto_increment_ddl.py
"""Regression tests for DDL compilation of auto-increment, standard types,
boolean defaults, and timestamps.
Covers bugs found in rbac cross-backend testing:
-- is_auto_increment=True on PRIMARY_KEY must produce GENERATED BY DEFAULT
- AS IDENTITY (was missing — caused INSERT id=NULL NOT NULL violation).
+- is_auto_increment=True on PRIMARY_KEY must produce a SERIAL type (was
+ missing — caused INSERT id=NULL NOT NULL violation).
- format_create_table_statement must return a string for all types.
- BooleanType with DEFAULT True must be accepted.
- TimestampType must map to TIMESTAMP.
-The auto-increment constraint compiles to the SQL-standard identity clause, so
-it is version-gated: PostgreSQL 9 must refuse it rather than render a
-``GENERATED`` clause its server rejects, and the refusal must name the feature
-instead of falling back to ``SERIAL`` (the SERIAL type family stays available
-for users who ask for it explicitly).
+An auto-increment constraint compiles to the ``SERIAL`` pseudo-type on every
+version: SERIAL predates the identity clause, its observable behaviour is the
+one the constraint asks for, and one spelling keeps 9 through 19 identical.
+The SQL-standard identity clause remains available to a caller that asks for
+it explicitly (``IdentityClause``); it is simply not what an auto-increment
+request means.
"""
+from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402
import pytest
@@ -41,20 +43,20 @@ def dialect():
return PostgresDialect(version=(16, 0, 0))
-def _pk(dialect):
- return [
- ColumnConstraint(
- dialect,
- branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True),
- )
- ]
+def _id_column(dialect, data_type):
+ suggested_type, attributes = auto_increment_parts(dialect, data_type)
+ return ColumnDefinition(
+ dialect, "id", suggested_type,
+ constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))],
+ attributes=attributes,
+ )
def _build_table(dialect):
return CreateTableStatement(
dialect=dialect, table=Table(dialect, 'test_tbl'),
columns=[
- ColumnDefinition(dialect, "id", IntegerType(dialect=dialect), constraints=_pk(dialect)),
+ _id_column(dialect, IntegerType(dialect=dialect)),
ColumnDefinition(dialect, "name", TextType(dialect=dialect),
constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]),
ColumnDefinition(dialect, "flag", BooleanType(dialect=dialect),
@@ -70,8 +72,8 @@ class TestAutoIncrementDDL:
def test_auto_increment_in_ddl(self, dialect):
sql, _ = _build_table(dialect).to_sql()
- assert "GENERATED BY DEFAULT AS IDENTITY" in sql.upper(), \
- f"auto-increment missing: {sql}"
+ assert "SERIAL" in sql.upper(), f"auto-increment missing: {sql}"
+ assert "GENERATED" not in sql.upper(), f"unexpected identity clause: {sql}"
def test_all_standard_types_compile(self, dialect):
sql, params = _build_table(dialect).to_sql()
@@ -82,7 +84,7 @@ def test_boolean_default_true(self, dialect):
expr = CreateTableStatement(
dialect=dialect, table=Table(dialect, 'bool_test'),
columns=[
- ColumnDefinition(dialect, "id", IntegerType(dialect=dialect), constraints=_pk(dialect)),
+ _id_column(dialect, IntegerType(dialect=dialect)),
ColumnDefinition(dialect, "flag", BooleanType(dialect=dialect),
constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)),
ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, True))]),
@@ -95,7 +97,7 @@ def test_timestamp_type(self, dialect):
expr = CreateTableStatement(
dialect=dialect, table=Table(dialect, 'ts_test'),
columns=[
- ColumnDefinition(dialect, "id", IntegerType(dialect=dialect), constraints=_pk(dialect)),
+ _id_column(dialect, IntegerType(dialect=dialect)),
ColumnDefinition(dialect, "created_at", TimestampType(dialect=dialect)),
],
)
@@ -103,28 +105,49 @@ def test_timestamp_type(self, dialect):
assert "TIMESTAMP" in sql.upper()
-class TestAutoIncrementVersionGate:
- """The constraint compiles to an identity clause, so it carries the gate."""
+class TestAutoIncrementIsSerial:
+ """An auto-increment request is a SERIAL type, on every version."""
@pytest.mark.parametrize(
- "version", [(10, 0, 0), (14, 0, 0), (18, 0, 0)], ids=lambda v: str(v)
+ "version", [(9, 6, 0), (10, 0, 0), (14, 0, 0), (18, 0, 0)], ids=lambda v: str(v)
)
- def test_identity_clause_rendered_from_pg10(self, version):
+ def test_serial_on_every_version(self, version):
sql, _ = _build_table(PostgresDialect(version=version)).to_sql()
- assert "GENERATED BY DEFAULT AS IDENTITY" in sql.upper()
+ assert "SERIAL" in sql.upper()
+ assert "GENERATED" not in sql.upper()
- def test_refused_on_pg9(self):
- """PostgreSQL 9 has no identity columns: refuse, do not fall back."""
- with pytest.raises(UnsupportedFeatureError, match="IDENTITY column"):
- _build_table(PostgresDialect(version=(9, 6, 0))).to_sql()
+ def test_integer_widths_map_to_their_serial(self):
+ dialect = PostgresDialect(version=(16, 0, 0))
+ from rhosocial.activerecord.backend.expression.types import (
+ BigIntType,
+ SmallIntType,
+ )
- def test_refusal_is_not_a_serial_rewrite(self):
- """The refused request must not be silently rewritten to a SERIAL type."""
+ for core_type, expected in (
+ (SmallIntType, "SMALLSERIAL"),
+ (BigIntType, "BIGSERIAL"),
+ ):
+ expr = CreateTableStatement(
+ dialect=dialect,
+ table=Table(dialect, "serial_tbl"),
+ columns=[
+ _id_column(dialect, core_type(dialect=dialect))
+ ],
+ )
+ sql, _ = expr.to_sql()
+ assert expected in sql.upper(), sql
+
+ def test_non_integer_auto_increment_is_refused(self):
+ """SERIAL has three widths; anything else is refused, not approximated."""
+ dialect = PostgresDialect(version=(16, 0, 0))
+ # The backend suggestion is consulted when the column definition is
+ # built, so the refusal happens there rather than at render time.
+ with pytest.raises(UnsupportedFeatureError, match="AUTO_INCREMENT column"):
+ _id_column(dialect, TextType(dialect=dialect))
+
+ def test_serial_type_still_spellable_explicitly(self):
+ """A caller that asks for SERIAL by type keeps that path."""
dialect = PostgresDialect(version=(9, 6, 0))
- with pytest.raises(UnsupportedFeatureError):
- _build_table(dialect).to_sql()
- # A user who wants SERIAL asks for the type explicitly, and that path
- # is version-independent.
from rhosocial.activerecord.backend.impl.postgres.expression.types import (
PostgresSerialType,
)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_column_definition.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_column_definition.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_column_definition.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_column_definition.py
index b0bff327..7f69af74 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_column_definition.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_column_definition.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_column_definition.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_column_definition.py
"""Tests for the PostgreSQL-specific column definition expressions."""
import pytest
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_constraint_capabilities.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_constraint_capabilities.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_constraint_capabilities.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_constraint_capabilities.py
index 623f812e..271d1995 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_constraint_capabilities.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_constraint_capabilities.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_constraint_capabilities.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_constraint_capabilities.py
"""PostgreSQL constraint capability switches, pinned to live measurements.
Every value asserted here was measured against the instances
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_create_table_like.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_create_table_like.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_create_table_like.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_create_table_like.py
index 068ca3da..9207765e 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_create_table_like.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_create_table_like.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_create_table_like.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_create_table_like.py
"""
PostgreSQL CREATE TABLE ... LIKE syntax tests.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_database_ddl.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_database_ddl.py
similarity index 91%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_database_ddl.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_database_ddl.py
index f62ec7de..043c82e5 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_database_ddl.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_database_ddl.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_database_ddl.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_database_ddl.py
"""Explicit PostgresDialect database DDL capability + rendering tests."""
from rhosocial.activerecord.backend.expression.objects import Database
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_source_collection.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_source_collection.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_source_collection.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_source_collection.py
index c1acfe5c..96201752 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_source_collection.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_source_collection.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_source_collection.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_source_collection.py
try:
from typing import Annotated, Optional
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_type_offline.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_type_offline.py
new file mode 100644
index 00000000..96d25d8f
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_type_offline.py
@@ -0,0 +1,623 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_ddl_type_offline.py
+"""Offline unit tests for the PostgreSQL user-defined TYPE DDL mixin.
+
+A connectionless :class:`PostgresDialect` is constructed directly and its
+``format_*`` / ``supports_*`` methods are exercised against representative
+definitions and alter actions. No connection, driver or server is involved.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError
+from rhosocial.activerecord.backend.expression.objects import Type
+from rhosocial.activerecord.backend.expression.statements.ddl_type import (
+ AlterTypeStatement,
+ CreateTypeStatement,
+)
+from rhosocial.activerecord.backend.expression.types import DataType
+from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect
+from rhosocial.activerecord.backend.impl.postgres.expression.ddl.type import (
+ PostgresAddEnumValueAction,
+ PostgresAddTypeAttributeAction,
+ PostgresAlterTypeAttributeAction,
+ PostgresBaseTypeDefinition,
+ PostgresChangeTypeOwnerAction,
+ PostgresCompositeTypeAttribute,
+ PostgresCompositeTypeDefinition,
+ PostgresDropTypeAttributeAction,
+ PostgresDropTypeExpression,
+ PostgresEnumTypeDefinition,
+ PostgresRangeTypeDefinition,
+ PostgresRenameEnumValueAction,
+ PostgresRenameTypeAction,
+ PostgresRenameTypeAttributeAction,
+ PostgresSetTypePropertiesAction,
+ PostgresSetTypeSchemaAction,
+ PostgresShellTypeDefinition,
+)
+
+PG96 = (9, 6, 0)
+PG10 = (10, 0, 0)
+PG13 = (13, 0, 0)
+PG14 = (14, 0, 0)
+PG16 = (16, 0, 0)
+
+
+def _dialect(version=PG16):
+ return PostgresDialect(version=version)
+
+
+def _type(name, schema=None):
+ return Type(_dialect(), name, schema_name=schema)
+
+
+def _data_type(text, dialect=None):
+ return DataType.as_type(dialect or _dialect(), text)
+
+
+# ===========================================================================
+# capability switches
+# ===========================================================================
+
+
+class TestCapabilities:
+ @pytest.mark.parametrize("version,supported", [((9, 5, 0), False), (PG96, True), (PG16, True)])
+ def test_type_objects_versions(self, version, supported):
+ assert _dialect(version).supports_type_objects() is supported
+
+ @pytest.mark.parametrize(
+ "method",
+ [
+ "supports_type_objects",
+ "supports_create_type",
+ "supports_alter_type",
+ "supports_drop_type",
+ "supports_drop_type_if_exists",
+ "supports_multiple_type_alter_actions",
+ "supports_drop_type_cascade",
+ "supports_drop_type_restrict",
+ "supports_type_if_exists",
+ "supports_type_cascade",
+ ],
+ )
+ def test_supported_on_modern_server(self, method):
+ assert getattr(_dialect(PG16), method)() is True
+
+ @pytest.mark.parametrize(
+ "method",
+ [
+ "supports_create_type_if_not_exists",
+ "supports_create_type_or_replace",
+ "supports_alter_type_if_exists",
+ "supports_type_if_not_exists",
+ ],
+ )
+ def test_never_supported(self, method):
+ assert getattr(_dialect(PG16), method)() is False
+
+ @pytest.mark.parametrize(
+ "method",
+ [
+ "supports_type_objects",
+ "supports_create_type",
+ "supports_alter_type",
+ "supports_drop_type",
+ "supports_drop_type_if_exists",
+ "supports_multiple_type_alter_actions",
+ "supports_drop_type_cascade",
+ "supports_drop_type_restrict",
+ ],
+ )
+ def test_not_supported_before_96(self, method):
+ assert getattr(_dialect((9, 5, 0)), method)() is False
+
+ def test_supported_type_definitions(self):
+ assert _dialect(PG16).supported_type_definitions() == (
+ PostgresCompositeTypeDefinition,
+ PostgresEnumTypeDefinition,
+ PostgresRangeTypeDefinition,
+ PostgresBaseTypeDefinition,
+ PostgresShellTypeDefinition,
+ )
+ assert _dialect((9, 5, 0)).supported_type_definitions() == ()
+
+ @pytest.mark.parametrize(
+ "definition",
+ [
+ PostgresCompositeTypeDefinition,
+ PostgresEnumTypeDefinition,
+ PostgresRangeTypeDefinition,
+ PostgresBaseTypeDefinition,
+ PostgresShellTypeDefinition,
+ ],
+ )
+ def test_supports_type_definition(self, definition):
+ assert _dialect(PG16).supports_type_definition(definition) is True
+ assert _dialect((9, 5, 0)).supports_type_definition(definition) is False
+
+ @pytest.mark.parametrize("bogus", [str, int, object])
+ def test_rejects_unknown_definition(self, bogus):
+ assert _dialect(PG16).supports_type_definition(bogus) is False
+
+ @pytest.mark.parametrize(
+ "action",
+ [
+ PostgresRenameTypeAction,
+ PostgresSetTypeSchemaAction,
+ PostgresChangeTypeOwnerAction,
+ PostgresRenameTypeAttributeAction,
+ PostgresAddTypeAttributeAction,
+ PostgresDropTypeAttributeAction,
+ PostgresAlterTypeAttributeAction,
+ PostgresAddEnumValueAction,
+ PostgresRenameEnumValueAction,
+ PostgresSetTypePropertiesAction,
+ ],
+ )
+ def test_supports_all_actions_on_modern_server(self, action):
+ assert _dialect(PG16).supports_type_alter_action(action) is True
+
+ @pytest.mark.parametrize(
+ "action,version,expected",
+ [
+ (PostgresRenameEnumValueAction, PG96, False),
+ (PostgresRenameEnumValueAction, PG10, True),
+ (PostgresSetTypePropertiesAction, PG10, False),
+ (PostgresSetTypePropertiesAction, PG13, True),
+ (PostgresAddEnumValueAction, PG96, True),
+ ],
+ )
+ def test_version_gated_actions(self, action, version, expected):
+ assert _dialect(version).supports_type_alter_action(action) is expected
+
+ @pytest.mark.parametrize("bogus", [str, object])
+ def test_rejects_unknown_action(self, bogus):
+ assert _dialect(PG16).supports_type_alter_action(bogus) is False
+
+
+# ===========================================================================
+# pure formatting helpers
+# ===========================================================================
+
+
+class TestFormattingHelpers:
+ @pytest.mark.parametrize(
+ "name,schema,expected",
+ [
+ ("name", None, '"name"'),
+ ("name", "public", '"public"."name"'),
+ ("MiXeD", "MySchema", '"MySchema"."MiXeD"'),
+ ],
+ )
+ def test_qualified_identifier(self, name, schema, expected):
+ assert _dialect()._format_qualified_identifier(name, schema) == expected
+
+ @pytest.mark.parametrize("value", ["", "a..b", ".b", "a."])
+ def test_qualified_identifier_rejects_empty_segments(self, value):
+ with pytest.raises(ValueError, match="non-empty segments"):
+ _dialect()._format_qualified_identifier(value)
+
+ @pytest.mark.parametrize(
+ "text",
+ ["INTEGER", "TEXT", "UUID", "NUMERIC", "TIMESTAMP", "JSONB", "DECIMAL(10,2)", "TEXT[]"],
+ )
+ def test_data_type_rendering(self, text):
+ assert _dialect()._format_type_data_type(_data_type(text)) == text
+
+ def test_data_type_requires_data_type(self):
+ with pytest.raises(TypeError, match="must be a DataType"):
+ _dialect()._format_type_data_type("TEXT")
+
+ def test_data_type_rejects_bind_parameters(self):
+ fake = MagicMock(spec=DataType)
+ fake.to_sql.return_value = ("?", ("param",))
+ with pytest.raises(ValueError, match="without bind parameters"):
+ _dialect()._format_type_data_type(fake)
+
+ @pytest.mark.parametrize(
+ "cascade,restrict,expected",
+ [(False, False, ""), (True, False, "CASCADE"), (False, True, "RESTRICT")],
+ )
+ def test_behavior(self, cascade, restrict, expected):
+ assert _dialect()._format_type_behavior(cascade, restrict) == expected
+
+ def test_behavior_rejects_both(self):
+ with pytest.raises(ValueError, match="mutually exclusive"):
+ _dialect()._format_type_behavior(True, True)
+
+ def test_enum_value(self):
+ assert _dialect()._format_postgres_enum_value("a'b") == "'a''b'"
+
+ def test_enum_value_requires_string(self):
+ with pytest.raises(TypeError, match="must be strings"):
+ _dialect()._format_postgres_enum_value(1)
+
+ def test_composite_attribute(self):
+ attr = PostgresCompositeTypeAttribute(
+ "label", _data_type("TEXT"), collation="public.mycoll"
+ )
+ assert _dialect()._format_postgres_composite_attribute(attr) == (
+ '"label" TEXT COLLATE "public"."mycoll"'
+ )
+
+ def test_composite_attribute_without_collation(self):
+ attr = PostgresCompositeTypeAttribute("n", _data_type("INTEGER"))
+ assert _dialect()._format_postgres_composite_attribute(attr) == '"n" INTEGER'
+
+
+# ===========================================================================
+# CREATE TYPE / type definitions
+# ===========================================================================
+
+
+class TestCreateType:
+ def test_enum_helper(self):
+ sql, params = _dialect().format_create_type_enum_statement("mood", ["happy", "sad"])
+ assert sql == "CREATE TYPE \"mood\" AS ENUM ('happy', 'sad')"
+ assert params == ()
+
+ def test_enum_helper_with_schema(self):
+ sql, _ = _dialect().format_create_type_enum_statement("mood", ["ok"], schema="public")
+ assert sql == 'CREATE TYPE "public"."mood" AS ENUM (\'ok\')'
+
+ def test_composite_statement(self):
+ definition = PostgresCompositeTypeDefinition(
+ _dialect(),
+ [
+ PostgresCompositeTypeAttribute("x", _data_type("INTEGER")),
+ PostgresCompositeTypeAttribute(
+ "label", _data_type("TEXT"), collation="public.mycoll"
+ ),
+ ],
+ )
+ sql, params = _dialect().format_create_type_statement(
+ CreateTypeStatement(_dialect(), _type("addr"), definition)
+ )
+ assert sql == 'CREATE TYPE "addr" AS ("x" INTEGER, "label" TEXT COLLATE "public"."mycoll")'
+ assert params == ()
+
+ def test_statement_type_must_be_type_object(self):
+ definition = PostgresEnumTypeDefinition(_dialect(), ["a"])
+ bad = MagicMock()
+ bad.definition_kind = "enum"
+ with pytest.raises(TypeError, match="must be a Type"):
+ _dialect().format_create_type_statement(
+ CreateTypeStatement(_dialect(), bad, definition)
+ )
+
+ @pytest.mark.parametrize(
+ "kwargs,match",
+ [
+ (dict(if_not_exists=True), "IF NOT EXISTS"),
+ (dict(or_replace=True), "OR REPLACE"),
+ ],
+ )
+ def test_unsupported_create_modifiers(self, kwargs, match):
+ definition = PostgresEnumTypeDefinition(_dialect(), ["a"])
+ with pytest.raises(UnsupportedFeatureError, match=match):
+ _dialect().format_create_type_statement(
+ CreateTypeStatement(_dialect(), _type("mood"), definition, **kwargs)
+ )
+
+ def test_create_type_requires_96(self):
+ with pytest.raises(UnsupportedFeatureError, match="CREATE TYPE"):
+ _dialect((9, 5, 0)).format_create_type_enum_statement("mood", ["a"])
+
+ def test_definition_must_be_supported(self):
+ with pytest.raises(UnsupportedFeatureError, match="TYPE definition"):
+ _dialect().format_create_type_statement(
+ CreateTypeStatement(_dialect(), _type("mood"), MagicMock())
+ )
+
+
+class TestTypeDefinitions:
+ def test_enum_definition(self):
+ definition = PostgresEnumTypeDefinition(_dialect(), ["a", "b'c"])
+ assert definition.definition_kind == "enum"
+ assert _dialect().format_type_definition(definition) == ("AS ENUM ('a', 'b''c')", ())
+
+ @pytest.mark.parametrize("labels", [["a", "a"], [1]])
+ def test_enum_definition_rejects_bad_labels(self, labels):
+ with pytest.raises((ValueError, TypeError)):
+ PostgresEnumTypeDefinition(_dialect(), labels)
+
+ def test_range_definition_minimal(self):
+ definition = PostgresRangeTypeDefinition(_dialect(), _data_type("INTEGER"))
+ assert _dialect().format_type_definition(definition) == ("AS RANGE (SUBTYPE = INTEGER)", ())
+
+ def test_range_definition_full(self):
+ definition = PostgresRangeTypeDefinition(
+ _dialect(),
+ _data_type("NUMERIC"),
+ subtype_operator_class="public.opc",
+ collation="public.coll",
+ canonical_function="public.canon",
+ subtype_diff_function="public.diff",
+ multirange_type_name="public.mr",
+ )
+ sql, params = _dialect().format_type_definition(definition)
+ assert sql == (
+ 'AS RANGE (SUBTYPE = NUMERIC, SUBTYPE_OPCLASS = "public"."opc", '
+ 'COLLATION = "public"."coll", CANONICAL = "public"."canon", '
+ 'SUBTYPE_DIFF = "public"."diff", MULTIRANGE_TYPE_NAME = "public"."mr")'
+ )
+ assert params == ()
+
+ def test_multirange_requires_14(self):
+ definition = PostgresRangeTypeDefinition(
+ _dialect(PG13), _data_type("INT4RANGE"), multirange_type_name="public.mr"
+ )
+ with pytest.raises(UnsupportedFeatureError, match="MULTIRANGE_TYPE_NAME"):
+ _dialect(PG13).format_type_definition(definition)
+
+ def test_base_definition_full(self):
+ definition = PostgresBaseTypeDefinition(
+ _dialect(),
+ input_function="public.in_fn",
+ output_function="public.out_fn",
+ internallength=4,
+ passedbyvalue=True,
+ alignment="int4",
+ storage="plain",
+ like_type=_data_type("INTEGER"),
+ category="U",
+ preferred=True,
+ default="x",
+ element=_data_type("TEXT"),
+ delimiter=",",
+ collatable=True,
+ )
+ sql, params = _dialect().format_type_definition(definition)
+ assert sql == (
+ '(INPUT = "public"."in_fn", OUTPUT = "public"."out_fn", INTERNALLENGTH = 4, '
+ 'PASSEDBYVALUE, ALIGNMENT = "int4", STORAGE = "plain", LIKE = INTEGER, '
+ "CATEGORY = \"U\", PREFERRED = TRUE, DEFAULT = 'x', ELEMENT = TEXT, "
+ "DELIMITER = ',', COLLATABLE = TRUE)"
+ )
+ assert params == ()
+
+ def test_base_definition_variable_length(self):
+ definition = PostgresBaseTypeDefinition(
+ _dialect(),
+ input_function="in",
+ output_function="out",
+ internallength="VARIABLE",
+ )
+ assert "INTERNALLENGTH = VARIABLE" in _dialect().format_type_definition(definition)[0]
+
+ def test_base_subscript_requires_14(self):
+ definition = PostgresBaseTypeDefinition(
+ _dialect(PG13),
+ input_function="public.i",
+ output_function="public.o",
+ subscript_function="public.s",
+ )
+ with pytest.raises(UnsupportedFeatureError, match="SUBSCRIPT"):
+ _dialect(PG13).format_type_definition(definition)
+
+ def test_base_requires_io_functions(self):
+ with pytest.raises(ValueError, match="required"):
+ PostgresBaseTypeDefinition(_dialect(), input_function="only_in")
+
+ def test_shell_definition_is_empty(self):
+ assert _dialect().format_type_definition(PostgresShellTypeDefinition(_dialect())) == (
+ "",
+ (),
+ )
+
+ def test_unknown_definition_rejected(self):
+ with pytest.raises(UnsupportedFeatureError, match="TYPE definition"):
+ _dialect().format_type_definition(MagicMock(definition_kind="bogus"))
+
+
+# ===========================================================================
+# ALTER TYPE actions and statements
+# ===========================================================================
+
+
+class TestAlterActions:
+ @pytest.mark.parametrize(
+ "action,expected",
+ [
+ (PostgresRenameTypeAction(_dialect(), "newname"), 'RENAME TO "newname"'),
+ (PostgresSetTypeSchemaAction(_dialect(), "other"), 'SET SCHEMA "other"'),
+ (PostgresChangeTypeOwnerAction(_dialect(), "bob"), 'OWNER TO "bob"'),
+ (
+ PostgresRenameTypeAttributeAction(_dialect(), "old", "new", cascade=True),
+ 'RENAME ATTRIBUTE "old" TO "new" CASCADE',
+ ),
+ (
+ PostgresAddTypeAttributeAction(
+ _dialect(), "extra", _data_type("TEXT"), collation="public.c"
+ ),
+ 'ADD ATTRIBUTE "extra" TEXT COLLATE "public"."c"',
+ ),
+ (
+ PostgresDropTypeAttributeAction(_dialect(), "gone", if_exists=True, restrict=True),
+ 'DROP ATTRIBUTE IF EXISTS "gone" RESTRICT',
+ ),
+ (
+ PostgresAlterTypeAttributeAction(
+ _dialect(), "col", _data_type("INTEGER"), set_data=True
+ ),
+ 'ALTER ATTRIBUTE "col" SET DATA TYPE INTEGER',
+ ),
+ (
+ PostgresAlterTypeAttributeAction(_dialect(), "col", _data_type("TEXT")),
+ 'ALTER ATTRIBUTE "col" TYPE TEXT',
+ ),
+ (
+ PostgresAddEnumValueAction(_dialect(), "new", before="z"),
+ "ADD VALUE 'new' BEFORE 'z'",
+ ),
+ (
+ PostgresAddEnumValueAction(_dialect(), "new", after="a", if_not_exists=True),
+ "ADD VALUE IF NOT EXISTS 'new' AFTER 'a'",
+ ),
+ (
+ PostgresRenameEnumValueAction(_dialect(), "old", "new"),
+ "RENAME VALUE 'old' TO 'new'",
+ ),
+ (
+ PostgresSetTypePropertiesAction(
+ _dialect(), {"STORAGE": "plain", "RECEIVE": "public.recv"}
+ ),
+ 'SET (STORAGE = "plain", RECEIVE = "public"."recv")',
+ ),
+ ],
+ )
+ def test_action_sql(self, action, expected):
+ assert _dialect().format_type_alter_action(action) == (expected, ())
+
+ def test_set_properties_none_becomes_none(self):
+ action = PostgresSetTypePropertiesAction(_dialect(), {"RECEIVE": None})
+ assert _dialect().format_type_alter_action(action) == ("SET (RECEIVE = NONE)", ())
+
+ def test_rename_enum_value_requires_10(self):
+ action = PostgresRenameEnumValueAction(_dialect(PG96), "a", "b")
+ with pytest.raises(UnsupportedFeatureError, match="RENAME VALUE"):
+ _dialect(PG96).format_type_alter_action(action)
+
+ def test_add_enum_if_not_exists_requires_93(self):
+ dialect = _dialect((9, 2, 0))
+ action = PostgresAddEnumValueAction(dialect, "x", if_not_exists=True)
+ with patch.object(dialect, "supports_type_objects", return_value=True):
+ with pytest.raises(UnsupportedFeatureError, match="IF NOT EXISTS"):
+ dialect.format_type_alter_action(action)
+
+ def test_set_properties_requires_13(self):
+ action = PostgresSetTypePropertiesAction(_dialect(PG10), {"RECEIVE": "public.r"})
+ with pytest.raises(UnsupportedFeatureError, match="SET properties"):
+ _dialect(PG10).format_type_alter_action(action)
+
+ def test_set_subscript_requires_14(self):
+ action = PostgresSetTypePropertiesAction(_dialect(PG13), {"SUBSCRIPT": "public.s"})
+ with pytest.raises(UnsupportedFeatureError, match="SUBSCRIPT"):
+ _dialect(PG13).format_type_alter_action(action)
+
+ def test_set_storage_none_rejected(self):
+ with pytest.raises(ValueError, match="STORAGE"):
+ PostgresSetTypePropertiesAction(_dialect(), {"STORAGE": None})
+
+ def test_unknown_action_rejected(self):
+ with pytest.raises(UnsupportedFeatureError, match="ALTER TYPE action"):
+ _dialect().format_type_alter_action(MagicMock(action_kind="bogus"))
+
+ def test_add_enum_rejects_before_and_after(self):
+ with pytest.raises(ValueError, match="mutually exclusive"):
+ PostgresAddEnumValueAction(_dialect(), "x", before="a", after="b")
+
+
+class TestAlterStatement:
+ def test_single_action(self):
+ statement = AlterTypeStatement(
+ _dialect(), _type("mood"), [PostgresAddEnumValueAction(_dialect(), "x")]
+ )
+ assert _dialect().format_alter_type_statement(statement) == (
+ "ALTER TYPE \"mood\" ADD VALUE 'x'",
+ (),
+ )
+
+ def test_multiple_combinable_actions(self):
+ statement = AlterTypeStatement(
+ _dialect(),
+ _type("addr"),
+ [
+ PostgresAddTypeAttributeAction(_dialect(), "a", _data_type("TEXT")),
+ PostgresDropTypeAttributeAction(_dialect(), "b"),
+ ],
+ )
+ assert _dialect().format_alter_type_statement(statement) == (
+ 'ALTER TYPE "addr" ADD ATTRIBUTE "a" TEXT, DROP ATTRIBUTE "b"',
+ (),
+ )
+
+ def test_multiple_non_combinable_actions_rejected(self):
+ statement = AlterTypeStatement(
+ _dialect(),
+ _type("mood"),
+ [
+ PostgresAddEnumValueAction(_dialect(), "a"),
+ PostgresRenameTypeAction(_dialect(), "b"),
+ ],
+ )
+ with pytest.raises(UnsupportedFeatureError, match="multiple ALTER TYPE actions"):
+ _dialect().format_alter_type_statement(statement)
+
+ def test_if_exists_unsupported(self):
+ statement = AlterTypeStatement(
+ _dialect(),
+ _type("mood"),
+ [PostgresAddEnumValueAction(_dialect(), "x")],
+ if_exists=True,
+ )
+ with pytest.raises(UnsupportedFeatureError, match="IF EXISTS"):
+ _dialect().format_alter_type_statement(statement)
+
+ def test_statement_type_must_be_type_object(self):
+ statement = AlterTypeStatement(
+ _dialect(), MagicMock(), [PostgresAddEnumValueAction(_dialect(), "x")]
+ )
+ with pytest.raises(TypeError, match="must be a Type"):
+ _dialect().format_alter_type_statement(statement)
+
+
+# ===========================================================================
+# DROP TYPE
+# ===========================================================================
+
+
+class TestDropType:
+ def test_by_name(self):
+ assert _dialect().format_drop_type_statement(name="mood") == ('DROP TYPE "mood"', ())
+
+ def test_with_schema_and_if_exists(self):
+ assert _dialect().format_drop_type_statement(
+ name="mood", schema="public", if_exists=True
+ ) == ('DROP TYPE IF EXISTS "public"."mood"', ())
+
+ def test_legacy_schema_name(self):
+ assert _dialect().format_drop_type_statement(name="mood", schema_name="public") == (
+ 'DROP TYPE "public"."mood"',
+ (),
+ )
+
+ def test_cascade(self):
+ assert _dialect().format_drop_type_statement(name="mood", cascade=True) == (
+ 'DROP TYPE "mood" CASCADE',
+ (),
+ )
+
+ def test_restrict_via_expression(self):
+ expression = PostgresDropTypeExpression(
+ _dialect(), Type(_dialect(), "mood"), if_exists=True, restrict=True
+ )
+ assert _dialect().format_drop_type_statement(expr=expression) == (
+ 'DROP TYPE IF EXISTS "mood" RESTRICT',
+ (),
+ )
+
+ def test_expr_and_name_are_mutually_exclusive(self):
+ expression = PostgresDropTypeExpression(_dialect(), _type("mood"))
+ with pytest.raises(ValueError, match="mutually exclusive"):
+ _dialect().format_drop_type_statement(expr=expression, name="mood")
+
+ def test_expr_or_name_required(self):
+ with pytest.raises(TypeError, match="required"):
+ _dialect().format_drop_type_statement()
+
+ def test_conflicting_schema_arguments(self):
+ with pytest.raises(ValueError, match="must match"):
+ _dialect().format_drop_type_statement(name="mood", schema="a", schema_name="b")
+
+ def test_drop_type_requires_96(self):
+ with pytest.raises(UnsupportedFeatureError, match="DROP TYPE"):
+ _dialect((9, 5, 0)).format_drop_type_statement(name="mood")
+
+ def test_if_exists_guard(self):
+ dialect = _dialect()
+ with patch.object(dialect, "supports_drop_type_if_exists", return_value=False):
+ with pytest.raises(UnsupportedFeatureError, match="IF EXISTS"):
+ dialect.format_drop_type_statement(name="mood", if_exists=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_generated_column_capabilities.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_generated_column_capabilities.py
similarity index 87%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_generated_column_capabilities.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_generated_column_capabilities.py
index ae0fe338..9cfaa85b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_generated_column_capabilities.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_generated_column_capabilities.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_generated_column_capabilities.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/ddl/test_generated_column_capabilities.py
"""Explicit PostgreSQL generated-column capability assertions.
The generic ``GeneratedColumnExpression``/formatter already covers these
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_alter_table_if_exists.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_alter_table_if_exists.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_alter_table_if_exists.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_alter_table_if_exists.py
index 008204ef..a5d3d165 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_alter_table_if_exists.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_alter_table_if_exists.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_alter_table_if_exists.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_alter_table_if_exists.py
"""Tests for ALTER TABLE IF [NOT] EXISTS qualifier rendering on PostgreSQL.
PostgreSQL supports the vendor extensions since 9.6:
@@ -30,14 +30,14 @@ def dialect():
return PostgresDialect(version=(15, 0, 0))
-class TestPostgresAlterTableModifierCapabilities:
+class TestAlterTableModifierCapabilities:
def test_supports_switches(self, dialect):
assert dialect.supports_add_column_if_not_exists() is True
assert dialect.supports_drop_column_if_exists() is True
assert dialect.supports_drop_constraint_if_exists() is True
-class TestPostgresAddColumnIfNotExists:
+class TestAddColumnIfNotExists:
def test_if_not_exists_renders_qualifier(self, dialect):
action = AddColumnAction(
dialect,
@@ -70,7 +70,7 @@ def test_inside_alter_table(self, dialect):
assert params == ()
-class TestPostgresDropColumnIfExists:
+class TestDropColumnIfExists:
def test_if_exists_renders_qualifier(self, dialect):
action = DropColumnAction(dialect, column_name="x", if_exists=True)
sql, params = action.to_sql()
@@ -85,7 +85,7 @@ def test_none_renders_plain_form(self, dialect):
assert params == ()
-class TestPostgresDropConstraintIfExists:
+class TestDropConstraintIfExists:
def test_if_exists_renders_qualifier(self, dialect):
action = DropTableConstraintAction(
dialect, constraint_name="fkey", if_exists=True
@@ -110,7 +110,7 @@ def test_none_renders_plain_form(self, dialect):
assert params == ()
-class TestPostgresAlterColumnTypeAndUsing:
+class TestAlterColumnTypeAndUsing:
"""SET DATA TYPE with the PostgreSQL ``USING`` conversion expression.
Covered here per plan §6.3: the ALTER COLUMN subclauses added by the
@@ -174,7 +174,7 @@ def test_set_data_type_using_rejected_for_other_ops(self, dialect):
action.to_sql()
-class TestPostgresRenameColumnAndTable:
+class TestRenameColumnAndTable:
"""RENAME COLUMN / RENAME TABLE render through the core actions."""
def test_rename_column(self, dialect):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_database_size_introspection.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_database_size_introspection.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_database_size_introspection.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_database_size_introspection.py
index 5781b756..33ff342a 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_database_size_introspection.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_database_size_introspection.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_database_size_introspection.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_database_size_introspection.py
"""The PostgreSQL database-size query nodes (SQL generation only).
``get_storage_info`` used to spell ``SELECT pg_database_size(%s) as
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_ddl_improvements.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_improvements.py
similarity index 93%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_ddl_improvements.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_improvements.py
index dda58388..d1fd4a5c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_ddl_improvements.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_improvements.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_ddl_improvements.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_improvements.py
"""Tests for PostgreSQL DDL improvements: capability gating, UnsupportedFeatureError."""
import pytest
from unittest.mock import patch, PropertyMock
@@ -14,7 +14,7 @@
from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError
-class TestPostgresViewCapabilityGating:
+class TestViewCapabilityGating:
"""Tests for PostgreSQL VIEW DDL capability gating."""
def test_create_or_replace_view_supported(self):
@@ -43,7 +43,7 @@ def test_materialized_view_supported(self):
assert PostgresDialect(version=(9, 2, 0)).supports_materialized_view() is False
-class TestPostgresColumnCapabilityGating:
+class TestColumnCapabilityGating:
"""Tests for PostgreSQL COLUMN DDL capability gating."""
def test_foreign_key_on_delete_supported(self):
@@ -57,7 +57,7 @@ def test_foreign_key_on_update_supported(self):
assert dialect.supports_foreign_key_on_update() is True
-class TestPostgresSchemaCapabilityGating:
+class TestSchemaCapabilityGating:
"""Tests for PostgreSQL SCHEMA DDL capability gating."""
def test_create_schema_supported(self):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_protocols.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_protocols.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_protocols.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_protocols.py
index aa9e2630..6529b9f7 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_protocols.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_protocols.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_protocols.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ddl_protocols.py
"""Tests for PostgreSQL DDL protocol feature detection.
This module tests the protocol-based feature detection methods:
@@ -44,7 +44,7 @@
from rhosocial.activerecord.backend.impl.postgres.protocols.ddl.type import PostgresTypeSupport
-class TestPostgresPartitionSupportFeatureDetection:
+class TestPartitionSupportFeatureDetection:
"""Test PostgresPartitionSupport feature detection methods."""
def test_supports_table_partitioning_pg9(self):
@@ -188,7 +188,7 @@ def test_supports_partitionwise_aggregate_pg11(self):
assert dialect.supports_partitionwise_aggregate() is True
-class TestPostgresPartitionMixinDirect:
+class TestPartitionMixinDirect:
"""Test PostgresPartitionMixin partition capability methods directly."""
class _Host:
@@ -269,7 +269,7 @@ def test_supports_concurrent_attach_direct(self):
assert self._PartitionMixinPg10().supports_concurrent_attach() is False
-class TestPostgresIndexSupportFeatureDetection:
+class TestIndexSupportFeatureDetection:
"""Test PostgresIndexSupport feature detection methods."""
def test_supports_safe_hash_index_pg9(self):
@@ -353,7 +353,7 @@ def test_supports_spgist_include_pg14(self):
assert dialect.supports_spgist_include() is True
-class TestPostgresMaterializedViewSupportFeatureDetection:
+class TestMaterializedViewSupportFeatureDetection:
"""Test PostgresMaterializedViewSupport feature detection methods."""
def test_supports_materialized_view_concurrent_refresh_pg93(self):
@@ -367,7 +367,7 @@ def test_supports_materialized_view_concurrent_refresh_pg94(self):
assert dialect.supports_materialized_view_concurrent_refresh() is True
-class TestPostgresVacuumFeatureDetection:
+class TestVacuumFeatureDetection:
"""Test PostgresVacuumMixin feature detection methods."""
def test_supports_parallel_vacuum_pg12(self):
@@ -523,7 +523,7 @@ def test_cluster_support_is_runtime_checkable(self):
assert isinstance(PostgresDialect(version=(14, 0, 0)), PostgresClusterSupport)
-class TestPostgresDomainFeatureDetection:
+class TestDomainFeatureDetection:
"""Test PostgresDomainSupport feature detection methods."""
def test_domain_pg95(self):
@@ -541,7 +541,7 @@ def test_domain_support_is_runtime_checkable(self):
assert isinstance(PostgresDialect(version=(14, 0, 0)), PostgresDomainSupport)
-class TestPostgresCollationDDLFeatureDetection:
+class TestCollationDDLFeatureDetection:
"""Test PostgresCollationDDLSupport feature detection methods."""
def test_collation_ddl_pg95(self):
@@ -579,7 +579,7 @@ def test_foreign_table_ddl_support_is_runtime_checkable(self):
)
-class TestPostgresRoutineDDLFeatureDetection:
+class TestRoutineDDLFeatureDetection:
"""Test PostgresRoutineDDLSupport feature detection methods."""
def test_routine_ddl_pg95(self):
@@ -675,7 +675,7 @@ def test_baseline_19(self):
assert d.supports_publication() is True
-class TestPostgresTypeDomainProtocols:
+class TestTypeDomainProtocols:
def test_protocol_derivation_and_runtime_support(self):
# Core split the former umbrella protocols into one per statement
# expression, so a backend protocol derives from each it restates.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect_function_support.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_function_support.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect_function_support.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_function_support.py
index 5c57a253..efcce237 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect_function_support.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_function_support.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect_function_support.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_function_support.py
"""
Test SQLFunctionSupport protocol implementation for PostgreSQL dialect.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_dialect_security.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_security.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_dialect_security.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_security.py
index 377d6c46..38a48760 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_dialect_security.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_security.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_dialect_security.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dialect_security.py
"""
Tests for PostgreSQL dialect SQL injection security fixes.
@@ -264,7 +264,7 @@ def test_exclude_constraint_rejects_raw_where(dialect):
dialect.format_table_exclude_constraint(constraint.branch)
-class TestPostgresEnumSecurity:
+class TestEnumSecurity:
"""Tests for CREATE TYPE ENUM value escaping (fix for SQL injection risk)."""
def test_create_type_enum_values_escaped(self, dialect):
@@ -290,7 +290,7 @@ def test_create_type_enum_sql_injection_blocked(self, dialect):
assert "AS ENUM" in sql
-class TestPostgresStoredProcedureNameSecurity:
+class TestStoredProcedureNameSecurity:
"""Tests for stored procedure names using format_identifier."""
def test_create_procedure_name_quoted(self, dialect):
@@ -332,7 +332,7 @@ def test_procedure_with_schema_quoted(self, dialect):
assert '"my_procedure"' in sql
-class TestPostgresPartialIndexWhereClauseSecurity:
+class TestPartialIndexWhereClauseSecurity:
"""Tests for partial index WHERE clause (ToSQLProtocol support)."""
def test_create_index_with_string_where_clause(self, dialect):
@@ -392,7 +392,7 @@ def to_sql(self):
assert params == ("active",)
-class TestPostgresTriggerFunctionNameSecurity:
+class TestTriggerFunctionNameSecurity:
"""Tests for trigger function name using format_identifier."""
def test_trigger_function_name_quoted(self, dialect):
@@ -438,7 +438,7 @@ def test_trigger_function_name_special_chars_quoted(self, dialect):
assert '"Function With Spaces"' in sql
-class TestPostgresExtendedStatisticsNameSecurity:
+class TestExtendedStatisticsNameSecurity:
"""Tests for extended statistics names using format_identifier."""
def test_create_statistics_name_quoted(self, dialect):
@@ -643,7 +643,7 @@ def test_hstore_operator_not_double_escaped():
# Try to find the file relative to the repo root
import os
for candidate in [
- os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "..", "..", hstore_path),
+ os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "..", "..", "..", hstore_path),
os.path.join(os.getcwd(), hstore_path),
]:
candidate = os.path.normpath(candidate)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_dql_capabilities.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dql_capabilities.py
similarity index 90%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_dql_capabilities.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dql_capabilities.py
index d30a5584..3d681313 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_dql_capabilities.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dql_capabilities.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_dql_capabilities.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_dql_capabilities.py
"""PostgreSQL DQL capability tests: WITH TIES (PG13+) and NULLS ordering."""
import pytest
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_drop_table_cascade.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_drop_table_cascade.py
similarity index 94%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_drop_table_cascade.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_drop_table_cascade.py
index 5ff2a4e5..717f7aa8 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_drop_table_cascade.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_drop_table_cascade.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_drop_table_cascade.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_drop_table_cascade.py
"""Tests for DROP TABLE ... CASCADE/RESTRICT rendering on PostgreSQL.
PostgreSQL declares full SQL-standard CASCADE/RESTRICT support; the generic
@@ -19,7 +19,7 @@ def dialect():
return PostgresDialect(version=(15, 0, 0))
-class TestPostgresDropTableCascade:
+class TestDropTableCascade:
def test_capability_switches(self, dialect):
assert dialect.supports_drop_table_cascade() is True
assert dialect.supports_drop_table_restrict() is True
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_function_versions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_function_versions.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_function_versions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_function_versions.py
index cf3b2623..4ef7e4c5 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_function_versions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_function_versions.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_function_versions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_function_versions.py
"""Unit tests for PostgreSQL function version requirements system.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_identifier_quoting.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_identifier_quoting.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_identifier_quoting.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_identifier_quoting.py
index 3b51b45a..15ecf612 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_identifier_quoting.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_identifier_quoting.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_identifier_quoting.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_identifier_quoting.py
"""
Tests for PostgresDialect identifier quoting.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ilike_support.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ilike_support.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ilike_support.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ilike_support.py
index fbfd16c5..c91ad67c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ilike_support.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ilike_support.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ilike_support.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_ilike_support.py
"""Tests for ILIKE protocol support in PostgreSQL dialect."""
from rhosocial.activerecord.backend.expression.core import Column
from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_insert_on_conflict_clauses.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_insert_on_conflict_clauses.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_insert_on_conflict_clauses.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_insert_on_conflict_clauses.py
index 2b8fb13a..e16fbb9e 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_insert_on_conflict_clauses.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_insert_on_conflict_clauses.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_insert_on_conflict_clauses.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_insert_on_conflict_clauses.py
"""Tests for PostgreSQL ON CONFLICT clause capability and rendering.
Covers:
@@ -27,7 +27,7 @@ def dialect():
return PostgresDialect(version=(15, 0, 0))
-class TestPostgresOnConflictCapabilities:
+class TestOnConflictCapabilities:
"""Capability switch tests."""
def test_supports_upsert_pg94(self):
@@ -59,7 +59,7 @@ def test_multiple_on_conflict_clauses_rejected(self, dialect):
expr.to_sql()
-class TestPostgresOnConflictRendering:
+class TestOnConflictRendering:
"""SQL rendering tests for a single ON CONFLICT clause."""
def test_do_nothing(self, dialect):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_introspection_parsing.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_introspection_parsing.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_introspection_parsing.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_introspection_parsing.py
index 190019f9..2683e921 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_introspection_parsing.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_introspection_parsing.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_introspection_parsing.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_introspection_parsing.py
"""Offline regression tests for the introspection answer shapes.
Three defects used to survive because every test that touched them needed a
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_kind_hygiene.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_kind_hygiene.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_kind_hygiene.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_kind_hygiene.py
index 7ef6d340..a9fa86a7 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_kind_hygiene.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_kind_hygiene.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_kind_hygiene.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_kind_hygiene.py
"""The PostgreSQL expression package's kinds: what they are and how they are named.
The organisation's rule (expression-kinds.md §三, expression-dialect §3 and
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view.py
index 40e0593d..8d709155 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view.py
"""PostgreSQL materialized view DDL tests (SQL generation only, no database).
Covers the regression matrix documented in
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_docs.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_docs.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_docs.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_docs.py
index 44e6ee77..60dbc716 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_docs.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_docs.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_docs.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_docs.py
"""Documentation and example consistency for materialized views.
Docs that drift from the implementation are a defect: the previous MV
@@ -11,7 +11,7 @@
import pytest
-PROJECT_ROOT = Path(__file__).resolve().parents[6]
+PROJECT_ROOT = Path(__file__).resolve().parents[7]
MV_DOC_PAGES = [
PROJECT_ROOT / "docs" / "en_US" / "ddl" / "materialized_view.md",
PROJECT_ROOT / "docs" / "zh_CN" / "ddl" / "materialized_view.md",
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_introspection.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_introspection.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_introspection.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_introspection.py
index 7e16c977..88828c43 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_introspection.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_introspection.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_materialized_view_introspection.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_materialized_view_introspection.py
"""PostgreSQL materialized view introspection tests (SQL generation only).
Covers the introspection half of the regression matrix documented in
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_object_kind_guards.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_object_kind_guards.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_object_kind_guards.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_object_kind_guards.py
index 69776be6..f10d86e5 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_object_kind_guards.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_object_kind_guards.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_object_kind_guards.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_object_kind_guards.py
"""
A statement handed the wrong kind of catalogue object must refuse, not render.
@@ -52,7 +52,7 @@
from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError
from rhosocial.activerecord.backend.expression import objects as objects_mod
-from expression_roundtrip_harness import (
+from rhosocial.activerecord_postgres_test.feature.backend.construct.expression_roundtrip_harness import (
collect_expression_classes,
make_instance,
)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_property_graph_query_format.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_property_graph_query_format.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_property_graph_query_format.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_property_graph_query_format.py
index 61a87d5b..f8fe2f73 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_property_graph_query_format.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_property_graph_query_format.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_property_graph_query_format.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_property_graph_query_format.py
"""Tests for fail-closed PostgreSQL graph capability and formatter safeguards.
SQL/PGQ was withdrawn in PostgreSQL 19 Beta 4 and shipped in no earlier
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_protocol_conformance.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_protocol_conformance.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py
index 44c78727..d4cc1a9f 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_protocol_conformance.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_protocol_conformance.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_protocol_conformance.py
"""
Tests to verify PostgresDialect protocol conformance and protocol non-overlap.
@@ -149,6 +149,7 @@ def get_postgres_protocols():
dialect_protocols.PartitionSupport,
dialect_protocols.ConstraintSupport,
dialect_protocols.TruncateSupport,
+ dialect_protocols.TransactionalDDLSupport,
dialect_protocols.IntrospectionSupport,
dialect_protocols.TransactionControlSupport,
dialect_protocols.SQLFunctionSupport,
@@ -158,10 +159,12 @@ def get_postgres_protocols():
dialect_protocols.GraphTableSupport,
dialect_protocols.ILIKESupport,
dialect_protocols.AutoIncrementColumnSupport,
+ dialect_protocols.IntegerAutoIncrementColumnSuggestionSupport,
+ dialect_protocols.DatabaseAssignedColumnSupport,
dialect_protocols.IdentityColumnSupport,
dialect_protocols.GeneratedColumnSupport,
# The column-type table: `PostgresColumnTypeMixin` answers
- # `suggested_column_types()` for all eighteen common Python types and
+ # `suggested_column_types()` for all twenty-four Python types and
# `suggested_extra_column_types()` with nothing of its own, and the
# dialect composes the mixin. The table is the model layer's source for
# which column class a field's annotation resolves to, so PostgreSQL
@@ -193,7 +196,7 @@ def get_postgres_protocols():
POSTGRES_PROTOCOLS = get_postgres_protocols()
-class TestPostgresDialectProtocolConformance:
+class TestDialectProtocolConformance:
"""Assert PostgresDialect implements all protocols it declares to support."""
@pytest.fixture
@@ -236,7 +239,7 @@ def get_all_generic_protocols() -> dict:
return discovered
-class TestPostgresDialectNegativeProtocolConformance:
+class TestDialectNegativeProtocolConformance:
"""Assert PostgresDialect does not implement intentionally-unsupported protocols."""
@pytest.fixture
@@ -481,7 +484,7 @@ def test_no_interface_overlap_between_protocols(self):
)
-class TestPostgresProtocolDerivation:
+class TestProtocolDerivation:
"""Verify PostgreSQL-specific protocols derive from their generic counterparts.
This ensures that backend-specific protocols inherit the standard interface,
@@ -528,7 +531,7 @@ def test_dialect_satisfies_generic_protocols_via_derivation(self):
)
-class TestPostgresExpressionDialectSeparation:
+class TestExpressionDialectSeparation:
"""Verify PostgreSQL-specific expression classes delegate to dialect for SQL generation.
Expression-Dialect separation means expression classes collect parameters
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_returning_capabilities.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_returning_capabilities.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_returning_capabilities.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_returning_capabilities.py
index 124ceacb..3d65f102 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_returning_capabilities.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_returning_capabilities.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_returning_capabilities.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_returning_capabilities.py
"""PostgreSQL RETURNING capability tests (incl. PG17 OLD/NEW references)."""
import pytest
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_schema_support.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_schema_support.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_schema_support.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_schema_support.py
index cac415fd..d97e3371 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_schema_support.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_schema_support.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_schema_support.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_schema_support.py
"""Tests for the schema capability declared on the PostgreSQL dialect.
Two questions, and they are not the same one. Does the engine *have* schemas --
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_set_operation_and_truncate.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_set_operation_and_truncate.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_set_operation_and_truncate.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_set_operation_and_truncate.py
index b031fd14..2ffc64da 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_set_operation_and_truncate.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_set_operation_and_truncate.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_set_operation_and_truncate.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_set_operation_and_truncate.py
"""Tests for SetOperation and Truncate protocol support in PostgreSQL dialect."""
import pytest # noqa: F401
from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_status_query_nodes.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_status_query_nodes.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_status_query_nodes.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_status_query_nodes.py
index d85209d7..50e5a36d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_status_query_nodes.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_status_query_nodes.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_status_query_nodes.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_status_query_nodes.py
"""The status-introspection nodes (SQL generation only).
The status introspector used to hold the catalog SQL itself: ``execute("SELECT
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_table_storage_introspection.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_table_storage_introspection.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_table_storage_introspection.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_table_storage_introspection.py
index 192eedd8..659372ff 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_table_storage_introspection.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_table_storage_introspection.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/dialect/test_table_storage_introspection.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_table_storage_introspection.py
"""The per-table storage trio (SQL generation and parsing only).
A table's footprint is three numbers PostgreSQL keeps apart: the total, the
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_version_features.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_version_features.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_version_features.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_version_features.py
index db52d62b..4a89d514 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_version_features.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_version_features.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_version_features.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/dialect/test_version_features.py
"""PostgreSQL version-specific feature detection tests.
This module tests the version-specific feature detection methods
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/errors/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/errors/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/conftest.py
similarity index 94%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/expression/conftest.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/conftest.py
index 52e8d375..34bfe02c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/conftest.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/conftest.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/expression/conftest.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/conftest.py
"""The expression tests are parallel by configuration (expression-dialect §12).
An expression test builds a tree, renders it through its own dialect and
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_clause_pair_guard.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_clause_pair_guard.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_clause_pair_guard.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_clause_pair_guard.py
index 41558a21..db22c99c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_clause_pair_guard.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_clause_pair_guard.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_clause_pair_guard.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_clause_pair_guard.py
"""Guard: every clause pair the PostgreSQL dialect consumes is fully spellable.
The rule this file enforces (the round's rule 1/2/3/4):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_domain_expression_roundtrip.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_domain_expression_roundtrip.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_domain_expression_roundtrip.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_domain_expression_roundtrip.py
index 099364e8..d34c7b31 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_domain_expression_roundtrip.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_domain_expression_roundtrip.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_domain_expression_roundtrip.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_domain_expression_roundtrip.py
"""Round-trip contract for ``PostgresCreateDomainExpression``.
``CREATE DOMAIN`` has two mutually exclusive spellings for the same list of
@@ -39,7 +39,9 @@
from rhosocial.activerecord.backend.impl.postgres.expression.ddl.domain import (
PostgresCreateDomainExpression,
)
-from expression_roundtrip_harness import assert_params_equal
+from rhosocial.activerecord_postgres_test.feature.backend.construct.expression_roundtrip_harness import (
+ assert_params_equal,
+)
# Deserialisation resolves a kind through the framework's registry, which ships
# core and the built-in backends. A PostgreSQL class is registered by the code
@@ -88,7 +90,7 @@ def _round_trip(expr, dialect):
return params
-class TestPostgresCreateDomainRoundTrip:
+class TestCreateDomainRoundTrip:
"""Both spellings survive the generic get_params() round trip."""
def test_constraints_spelling_round_trips(self, dialect):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_namespace.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_namespace.py
similarity index 92%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_namespace.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_namespace.py
index 1670cb17..bad59444 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_namespace.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_namespace.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_namespace.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_namespace.py
"""Guardrail: every expression must live under the backend's expression namespace.
``BaseExpression`` subclasses render SQL, so they belong in
@@ -21,6 +21,10 @@
from rhosocial.activerecord.backend.impl import postgres
EXPRESSION_NS = postgres.__name__ + ".expression"
+# Column classes that model a column's *surface* (no family operation) live in
+# ``column_types``, parallel to ``expression`` rather than inside it. They are
+# still BaseExpression subclasses, but that module is a legitimate home.
+COLUMN_TYPES_NS = postgres.__name__ + ".column_types"
BACKEND_NS = postgres.__name__ + "."
@@ -83,6 +87,7 @@ def test_no_expression_defined_outside_expression_namespace(all_expression_class
for cls in all_expression_classes
if cls.__module__.startswith(BACKEND_NS)
and not cls.__module__.startswith(EXPRESSION_NS)
+ and not cls.__module__.startswith(COLUMN_TYPES_NS)
]
assert not offenders, (
"BaseExpression subclasses defined in this backend but outside "
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_roundtrip_all.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_roundtrip_all.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_roundtrip_all.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_roundtrip_all.py
index 47e1f618..9a8125f1 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_roundtrip_all.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_roundtrip_all.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_expression_roundtrip_all.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_roundtrip_all.py
"""
Functional serialization coverage: every registered expression class must
round-trip losslessly through all three encodings (dict / JSON string / XML).
@@ -129,7 +129,7 @@ class name -- ``Literal`` the single exception, naming its fourteen value kinds
import pytest
-from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError
+from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedDataTypeError, UnsupportedFeatureError
from rhosocial.activerecord.backend.expression import graph as graph_mod
from rhosocial.activerecord.backend.expression.advanced_functions import (
CaseExpression,
@@ -325,7 +325,7 @@ class name -- ``Literal`` the single exception, naming its fourteen value kinds
network as pg_network,
range as pg_range,
)
-from expression_roundtrip_harness import (
+from rhosocial.activerecord_postgres_test.feature.backend.construct.expression_roundtrip_harness import (
collect_expression_classes,
make_instance,
register_all,
@@ -1266,7 +1266,7 @@ def _no_such_formatter(formatter_name: str) -> str:
# PostgreSQL has no such type -- ``CREATE TYPE ... AS ENUM`` goes through
# ``PostgresEnumType`` -- so there is no ``format_data_type_enum`` to reach.
"rhosocial.activerecord.backend.expression.types.enum_.EnumType": (
- TypeError,
+ UnsupportedDataTypeError,
"does not support the generic type 'enum'",
),
@@ -1346,7 +1346,7 @@ def _no_such_formatter(formatter_name: str) -> str:
# UnsupportedFeatureError, because the class is incomplete rather than the
# dialect being unable.
"rhosocial.activerecord.backend.expression.types._base.DataType": (
- TypeError,
+ UnsupportedDataTypeError,
"does not support the generic type None",
),
@@ -1372,11 +1372,11 @@ def _no_such_formatter(formatter_name: str) -> str:
# there is no ``format_data_type_binary`` to dispatch to. A dialect gap, not a
# defect: the dialect is saying it cannot render them.
"rhosocial.activerecord.backend.expression.types.binary.BinaryType": (
- TypeError,
+ UnsupportedDataTypeError,
"does not support the generic type 'binary'",
),
"rhosocial.activerecord.backend.expression.types.binary.VarBinaryType": (
- TypeError,
+ UnsupportedDataTypeError,
"does not support the generic type 'varbinary'",
),
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/test_expression_signatures.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_signatures.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/expression/test_expression_signatures.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_signatures.py
index a0f3130b..9aad043c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/test_expression_signatures.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_signatures.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/expression/test_expression_signatures.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expression_signatures.py
"""SQL-snapshot tests for format-signature-compliant expression classes.
These tests build expressions with a bare ``PostgresDialect`` (no DB
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/test_expressions_transaction.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expressions_transaction.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/expression/test_expressions_transaction.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/test_expressions_transaction.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/vector_search_test.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/vector_search_test.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/expression/vector_search_test.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/vector_search_test.py
index 10cd7eea..83562f76 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression/vector_search_test.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/vector_search_test.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/expression/vector_search_test.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression/vector_search_test.py
"""SQL-snapshot tests for the pgvector similarity-search helpers.
These tests build expressions with a bare ``PostgresDialect`` (no DB
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression_roundtrip_harness.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression_roundtrip_harness.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/expression_roundtrip_harness.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression_roundtrip_harness.py
index ef3bf622..a5397b95 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/expression_roundtrip_harness.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression_roundtrip_harness.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/expression_roundtrip_harness.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/expression_roundtrip_harness.py
"""
Expression serialization round-trip / contract test helpers (PostgreSQL-local copy).
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_array_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_array_functions.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_array_functions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_array_functions.py
index 62a802fa..22818741 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_array_functions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_array_functions.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_array_functions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_array_functions.py
"""
Tests for PostgreSQL Array functions.
@@ -31,7 +31,7 @@
)
-class TestPostgresArrayFunctions:
+class TestArrayFunctions:
"""Tests for PostgreSQL array functions."""
def test_array_agg(self, postgres_dialect: PostgresDialect):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_datetime_interval_expressions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_datetime_interval_expressions.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_datetime_interval_expressions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_datetime_interval_expressions.py
index 7f47f67b..5e504978 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_datetime_interval_expressions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_datetime_interval_expressions.py
@@ -1,5 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/
-# test_postgres_datetime_interval_expressions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_datetime_interval_expressions.py
"""Tests for PostgreSQL datetime interval expressions."""
import pytest
@@ -18,7 +17,7 @@
from rhosocial.activerecord.backend.expression.types import IntegerType
-class TestPostgresDateTimeIntervalExpressions:
+class TestDateTimeIntervalExpressions:
@pytest.mark.parametrize(
"field",
["year", "month", "day", "hour", "minute", "second"],
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extension_type_operations.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_operations.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extension_type_operations.py
index 07808478..3041f986 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_operations.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extension_type_operations.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_operations.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extension_type_operations.py
"""PostgreSQL's own types, and what you can do with them.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extensions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extensions.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extensions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extensions.py
index f68b9bf8..3a0e6d20 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extensions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extensions.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extensions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_extensions.py
"""Unit tests for PostgreSQL extension mixins and functions.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_hstore_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_hstore_functions.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_hstore_functions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_hstore_functions.py
index 376c0476..5913bbe6 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_hstore_functions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_hstore_functions.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_hstore_functions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_hstore_functions.py
"""
Tests for PostgreSQL hstore function factories.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_math_enhanced_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_math_enhanced_functions.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_math_enhanced_functions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_math_enhanced_functions.py
index 64ddbd91..d42f7b13 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_math_enhanced_functions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_math_enhanced_functions.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_math_enhanced_functions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_math_enhanced_functions.py
"""
Tests for PostgreSQL-specific enhanced math functions.
@@ -21,7 +21,7 @@
)
-class TestPostgresMathEnhancedFunctions:
+class TestMathEnhancedFunctions:
"""Tests for PostgreSQL enhanced math functions."""
def test_round__default(self, postgres_dialect: PostgresDialect):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_network_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_network_functions.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_network_functions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_network_functions.py
index 242d8677..8a8f15d6 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_network_functions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_network_functions.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_network_functions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_network_functions.py
"""
Tests for PostgreSQL Network Address functions.
@@ -30,7 +30,7 @@
)
-class TestPostgresNetworkFunctions:
+class TestNetworkFunctions:
"""Tests for PostgreSQL network functions."""
def test_inet_client_addr(self, postgres_dialect: PostgresDialect):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_pgvector_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_pgvector_functions.py
similarity index 94%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_pgvector_functions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_pgvector_functions.py
index 98a41fee..3e169b17 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_pgvector_functions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_pgvector_functions.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_pgvector_functions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_pgvector_functions.py
"""
Tests for PostgreSQL pgvector function factories.
@@ -82,6 +82,10 @@ def test_vector_cosine_similarity(self, postgres_dialect: PostgresDialect):
sql, params = result.to_sql()
assert "-" in sql
assert "<=>" in sql
+ # The distance must be grouped: without the parentheses the server
+ # reads ``1 - col <=> x`` as ``(1 - col) <=> x`` and refuses it.
+ assert " - (" in sql
+ assert "<=>" in sql
class TestPgvectorLiteralFunction:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_postgis_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_postgis_functions.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_postgis_functions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_postgis_functions.py
index 252210ed..e3f3ba83 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_postgis_functions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_postgis_functions.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_postgis_functions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_postgis_functions.py
"""
Tests for PostgreSQL PostGIS function factories.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_range_constructors.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_constructors.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_range_constructors.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_constructors.py
index 6cdba6ae..da170c5b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_range_constructors.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_constructors.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_range_constructors.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_constructors.py
"""
Tests for PostgreSQL Range Type Constructors.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_functions.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_functions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_functions.py
index 7915ca51..a8e8f794 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_functions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_functions.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_functions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_range_functions.py
"""Unit tests for PostgreSQL range functions.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_uuid_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_uuid_functions.py
similarity index 93%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_uuid_functions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_uuid_functions.py
index 754665d9..34818bb1 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_uuid_functions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_uuid_functions.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_uuid_functions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/functions/test_uuid_functions.py
"""
Tests for PostgreSQL UUID functions.
@@ -18,7 +18,7 @@
)
-class TestPostgresUUIDFunctions:
+class TestUUIDFunctions:
"""Tests for PostgreSQL UUID functions."""
def test_uuid_generate_v1(self, postgres_dialect: PostgresDialect):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/introspection/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/introspection/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_address_standardizer.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_address_standardizer.py
similarity index 93%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_address_standardizer.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_address_standardizer.py
index 2f5c93ac..13212842 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_address_standardizer.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_address_standardizer.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_address_standardizer.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_address_standardizer.py
"""Unit tests for PostgreSQL address_standardizer extension functions.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_bloom.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_bloom.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_bloom.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_bloom.py
index dd3c8834..f1545bfd 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_bloom.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_bloom.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_bloom.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_bloom.py
"""
Unit tests for PostgreSQL bloom extension mixin.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gin.py
similarity index 93%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gin.py
index be9a93c2..11d34c57 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gin.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gin.py
"""
Unit tests for PostgreSQL btree_gin extension mixin.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gist.py
similarity index 94%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gist.py
index 49bcebea..bd811c11 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gist.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_btree_gist.py
"""
Unit tests for PostgreSQL btree_gist extension mixin.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_citext.py
similarity index 94%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_citext.py
index a595453e..81645dab 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_citext.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_citext.py
"""
Unit tests for PostgreSQL citext extension.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_cube.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_cube.py
index 21e4c4e7..234cd39d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_cube.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_cube.py
"""
Unit tests for PostgreSQL cube extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_alter_config.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_ddl_alter_config.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_alter_config.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_ddl_alter_config.py
index 6a5bd10d..d4619de7 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_alter_config.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_ddl_alter_config.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_expressions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_ddl_alter_config.py
"""Tests for PostgreSQL DDL expression classes.
This module tests the expression-based format methods for DDL operations,
@@ -197,7 +197,7 @@ def test_verbose_false_schema(self, dialect):
assert sql == 'CLUSTER "app"."orders"'
-class TestPostgresAlterColumnUsingExpression:
+class TestAlterColumnUsingExpression:
"""ALTER COLUMN ... SET DATA TYPE ... USING."""
@pytest.fixture
@@ -255,7 +255,7 @@ def test_without_using_unaffected(self, dialect):
assert sql == 'ALTER COLUMN "price" SET DATA TYPE NUMERIC(10,2)'
-class TestPostgresAlterColumnModifierMixin:
+class TestAlterColumnModifierMixin:
"""ADD/DROP COLUMN and DROP CONSTRAINT IF [NOT] EXISTS qualifiers."""
@pytest.fixture
@@ -312,7 +312,7 @@ def test_drop_constraint_if_exists_cascade(self, dialect):
assert sql == 'DROP CONSTRAINT IF EXISTS "user_email_key" CASCADE'
-class TestPostgresConstraintCapabilities:
+class TestConstraintCapabilities:
"""PostgreSQL-only constraint capability switches."""
@pytest.fixture
@@ -325,7 +325,7 @@ def test_capabilities(self, dialect):
assert dialect.supports_drop_constraint_if_exists() is True
-class TestPostgresConstraintDeferral:
+class TestConstraintDeferral:
"""``DEFERRABLE`` / ``INITIALLY`` is not an all-kinds grant.
The ``column_constraint`` / ``table_constraint`` grammar figures draw
@@ -435,7 +435,7 @@ def test_alter_constraint_enforced_splits_by_kind_and_version(self):
action.to_sql()
-class TestPostgresTypeDDL:
+class TestTypeDDL:
"""CREATE/DROP TYPE capability switches and formatting."""
@pytest.fixture
@@ -478,7 +478,7 @@ def test_drop_type_full(self, dialect):
assert sql == 'DROP TYPE IF EXISTS "app"."color" CASCADE'
-class TestPostgresConstraintEnforcement:
+class TestConstraintEnforcement:
def test_capability_versions(self):
"""The two enforcement probes are grammar gates with no kind in them.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extended_statistics.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_extended_statistics.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extended_statistics.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_extended_statistics.py
index cc5eb684..8ec51391 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extended_statistics.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_extended_statistics.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extended_statistics.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_extended_statistics.py
"""Unit tests for PostgreSQL extended statistics mixin.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_fuzzystrmatch.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_fuzzystrmatch.py
index ba5e9aa4..6107c4f4 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_fuzzystrmatch.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_fuzzystrmatch.py
"""
Unit tests for PostgreSQL fuzzystrmatch extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_hypopg.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_hypopg.py
index 35584d05..067f50c1 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_hypopg.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_hypopg.py
"""
Unit tests for PostgreSQL hypopg extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_index_pg.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_index_pg.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_index_pg.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_index_pg.py
index afc0b22c..2026a79d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_index_pg.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_index_pg.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_index_pg.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_index_pg.py
"""Unit tests for PostgreSQL index mixin.
Tests for:
@@ -994,7 +994,7 @@ def test_alter_statistics_missing_params_raises(self):
expr.to_sql()
-class TestPostgresIndexMixinDirect:
+class TestIndexMixinDirect:
"""Test PostgresIndexMixin directly (not through PostgresDialect)."""
class _Host:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_orafce.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_orafce.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_orafce.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_orafce.py
index 3ecaa115..c0c37cda 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_orafce.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_orafce.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_orafce.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_orafce.py
"""
Unit tests for PostgreSQL orafce extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_cron.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_cron.py
index 138ff103..da5a53c3 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_cron.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_cron.py
"""
Unit tests for PostgreSQL pg_cron extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_partman.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_partman.py
index 8f393855..ae29e858 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_partman.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_partman.py
"""
Unit tests for PostgreSQL pg_partman extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_repack.py
similarity index 91%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_repack.py
index 43ced5b7..c75c8d96 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_repack.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_repack.py
"""
Unit tests for PostgreSQL pg_repack extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_stat_statements.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_stat_statements.py
index d05c84d4..6ce61437 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_stat_statements.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_stat_statements.py
"""Unit tests for PostgreSQL pg_stat_statements extension mixin and functions."""
from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_surgery.py
similarity index 93%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_surgery.py
index 26ae704d..fe9fdb24 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_surgery.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_surgery.py
"""
Unit tests for PostgreSQL pg_surgery extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_walinspect.py
similarity index 94%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_walinspect.py
index f2516961..7ecfee56 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_walinspect.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pg_walinspect.py
"""
Unit tests for PostgreSQL pg_walinspect extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgaudit.py
similarity index 88%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgaudit.py
index 9d1da526..f8eb255e 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgaudit.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgaudit.py
"""Unit tests for PostgreSQL pgaudit extension mixin."""
from rhosocial.activerecord.backend.impl.postgres.mixins.extensions.pgaudit import PostgresPgauditMixin
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgcrypto.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgcrypto.py
index b644bf98..6495eaa4 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgcrypto.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pgcrypto.py
"""
Unit tests for PostgreSQL pgcrypto extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pglogical.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pglogical.py
index 0a3a13c2..f59cbd7e 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pglogical.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_pglogical.py
"""
Unit tests for PostgreSQL pglogical extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_policy.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_policy.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_policy.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_policy.py
index e1a65541..606fac4b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_policy.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_policy.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_policy.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_policy.py
"""Unit tests for PostgreSQL Row-Level Security POLICY DDL.
Tests cover:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_stored_procedure.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_stored_procedure.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_stored_procedure.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_stored_procedure.py
index a912b91e..bcb541a7 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_stored_procedure.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_stored_procedure.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_stored_procedure.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_stored_procedure.py
"""Unit tests for PostgreSQL stored procedure mixin.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_table.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_table.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_table.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_table.py
index 5d00a29b..ca07fc28 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_table.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_table.py
@@ -35,7 +35,7 @@ def test_supports_table_tablespace(self):
assert PostgresDialect().supports_table_tablespace() is True
-class TestPostgresTableMixinDirect:
+class TestTableMixinDirect:
"""Test PostgresTableMixin directly (not through PostgresDialect)."""
class _Host:
@@ -75,7 +75,7 @@ def test_supports_table_tablespace_direct(self):
assert self._TableMixin().supports_table_tablespace() is True
-class TestPostgresTableDDLDeclarations:
+class TestTableDDLDeclarations:
@staticmethod
def _expression(dialect, table="child", *, inherits=None, tablespace=None):
return CreateTableStatement(
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_tablefunc.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_tablefunc.py
index ec7b9152..1a287e01 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_tablefunc.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_tablefunc.py
"""
Unit tests for PostgreSQL tablefunc extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_trigger.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_trigger.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_trigger.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_trigger.py
index 5540deb9..c5be9c77 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_trigger.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_trigger.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_trigger.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_trigger.py
"""Unit tests for PostgreSQL trigger mixin.
Tests for:
@@ -284,7 +284,7 @@ def test_drop_trigger_if_exists(self):
assert "DROP TRIGGER IF EXISTS" in sql
-class TestPostgresTriggerMixinDirect:
+class TestTriggerMixinDirect:
"""Test PostgresTriggerMixin directly (not through PostgresDialect)."""
class _Host:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_uuid_ossp.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_uuid_ossp.py
index 98d0a047..9d501945 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_uuid_ossp.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/mixins/test_uuid_ossp.py
"""
Unit tests for PostgreSQL uuid-ossp extension functions.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/partition/test_partition_offline.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/partition/test_partition_offline.py
new file mode 100644
index 00000000..0e08962b
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/partition/test_partition_offline.py
@@ -0,0 +1,1445 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/partition/test_partition_offline.py
+"""Offline unit tests for PostgreSQL partition maintenance and plan helpers.
+
+Every check here is synchronous and connectionless: pure parsing/comparison
+helpers are called directly, plan derivation is exercised in memory, and the
+catalog/DDL I/O seams are replaced with ``MagicMock``. No PostgreSQL server,
+network or driver connection is involved.
+"""
+
+from dataclasses import FrozenInstanceError
+from datetime import date, datetime, timedelta, timezone
+from unittest.mock import MagicMock
+
+import pytest
+
+from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect
+from rhosocial.activerecord.backend.impl.postgres.partition import (
+ HashBranch,
+ HashPolicy,
+ ListBranch,
+ ListPolicy,
+ PairedDifference,
+ PartitionBatchReport,
+ PartitionInfo,
+ PartitionReport,
+ PartitionSpec,
+ PostgresPartitionMaintenance,
+ PostgresPartitionPlan,
+ RangeBranch,
+ RangePolicy,
+)
+from rhosocial.activerecord.backend.impl.postgres.partition import maintenance as mnt
+from rhosocial.activerecord.backend.impl.postgres.partition import plan as plan_mod
+
+UTC = timezone.utc
+PLUS8 = timezone(timedelta(hours=8))
+PLUS830 = timezone(timedelta(hours=8, minutes=30))
+MINUS5 = timezone(-timedelta(hours=5))
+
+
+def _info(name, **overrides):
+ values = {"name": name, "parent": "events", "level": 1}
+ values.update(overrides)
+ return PartitionInfo(**values)
+
+
+def _spec(name, method="RANGE", **overrides):
+ values = {
+ "name": name,
+ "parent": "events",
+ "method": method,
+ "columns": ("created_at",),
+ "bounds": {},
+ "level": 1,
+ "is_leaf": True,
+ }
+ values.update(overrides)
+ return PartitionSpec(**values)
+
+
+def _range_plan(parent="events", bounds=None):
+ if bounds is None:
+ bounds = ((date(2026, 1, 1), date(2026, 2, 1)),)
+ return PostgresPartitionPlan(
+ parent=parent,
+ method="RANGE",
+ columns="created_at",
+ policy=RangePolicy(bounds=bounds),
+ )
+
+
+def _base():
+ backend = MagicMock()
+ backend.dialect = PostgresDialect(version=(17, 0, 0))
+ return mnt._PartitionMaintenanceBase(backend), backend
+
+
+# --------------------------------------------------------------------------- #
+# Pure bound-text helpers
+# --------------------------------------------------------------------------- #
+class TestUnquoteBoundValue:
+ @pytest.mark.parametrize(
+ "text, expected",
+ [
+ ("'abc'", "abc"),
+ (" 'abc' ", "abc"),
+ ("'a''b'", "a'b"),
+ ("''", ""),
+ ("abc", "abc"),
+ ("", ""),
+ ("'unterminated", "'unterminated"),
+ ("' x '", " x "),
+ ],
+ )
+ def test_unquote(self, text, expected):
+ assert mnt._unquote_bound_value(text) == expected
+
+
+class TestSplitBoundValues:
+ @pytest.mark.parametrize(
+ "text, expected",
+ [
+ ("a, b, c", ("a", "b", "c")),
+ (" a , b ", ("a", "b")),
+ ("'a,b', c", ("'a,b'", "c")),
+ ("'a''b', c", ("'a''b'", "c")),
+ ("'x,y','z'", ("'x,y'", "'z'")),
+ ("", ()),
+ ("a", ("a",)),
+ ("a,,b", ("a", "", "b")),
+ ("a,", ("a",)),
+ ],
+ )
+ def test_split(self, text, expected):
+ assert mnt._split_bound_values(text) == expected
+
+
+class TestParseListValue:
+ @pytest.mark.parametrize(
+ "token, expected",
+ [
+ ("'abc'", "abc"),
+ ("'a''b'", "a'b"),
+ ("'NULL'", "NULL"),
+ ("NULL", None),
+ ("null", None),
+ ("42", 42),
+ ("-7", -7),
+ ("+3", 3),
+ (" 42 ", 42),
+ ("1.5", 1.5),
+ ("-0.25", -0.25),
+ ("abc", "abc"),
+ ("", ""),
+ ],
+ )
+ def test_parse(self, token, expected):
+ assert mnt._parse_list_value(token) == expected
+
+
+class TestParseTemporal:
+ @pytest.mark.parametrize(
+ "text, expected",
+ [
+ ("2026-01-02", date(2026, 1, 2)),
+ ("'2026-01-02'", date(2026, 1, 2)),
+ ("2026-01-02 03:04", datetime(2026, 1, 2, 3, 4)),
+ ("2026-01-02T03:04:05", datetime(2026, 1, 2, 3, 4, 5)),
+ ("2026-01-02 03:04:05.12", datetime(2026, 1, 2, 3, 4, 5, 120000)),
+ ("2026-01-02 03:04:05Z", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)),
+ ("2026-01-02 03:04:05+08", datetime(2026, 1, 2, 3, 4, 5, tzinfo=PLUS8)),
+ ("2026-01-02 03:04:05+08:30", datetime(2026, 1, 2, 3, 4, 5, tzinfo=PLUS830)),
+ ("2026-01-02 03:04:05-05:00", datetime(2026, 1, 2, 3, 4, 5, tzinfo=MINUS5)),
+ ("MINVALUE", None),
+ ("MAXVALUE", None),
+ ("'MAXVALUE'", None),
+ ("NULL", None),
+ ("nonsense", None),
+ ("2026-13-01", None),
+ ("2026-02-30", None),
+ ("2026-01-02 03:04:05.1234567", None),
+ ("", None),
+ ],
+ )
+ def test_parse(self, text, expected):
+ assert mnt._parse_temporal(text) == expected
+
+
+class TestParsePartitionBound:
+ @pytest.mark.parametrize("text", [None, "", " ", 123, "nonsense"])
+ def test_unparseable_returns_none(self, text):
+ assert mnt._parse_partition_bound(text) is None
+
+ def test_range_date_bounds(self):
+ result = mnt._parse_partition_bound("FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')")
+ assert result == {
+ "kind": "RANGE",
+ "range_start": date(2026, 1, 1),
+ "range_end": date(2026, 2, 1),
+ }
+
+ def test_range_with_maxvalue_omits_unparsed_end(self):
+ result = mnt._parse_partition_bound("for values from ('2026-01-01') to (maxvalue)")
+ assert result == {"kind": "RANGE", "range_start": date(2026, 1, 1)}
+
+ def test_list_values(self):
+ result = mnt._parse_partition_bound("FOR VALUES IN ('a', 'b', 3, NULL)")
+ assert result == {"kind": "LIST", "list_values": ("a", "b", 3, None)}
+
+ @pytest.mark.parametrize(
+ "text, modulus, remainder",
+ [
+ ("FOR VALUES WITH (MODULUS 4, REMAINDER 2)", 4, 2),
+ ("for values with (modulus 8, remainder 0)", 8, 0),
+ ("FOR VALUES WITH ( modulus 3 , remainder 1 )", 3, 1),
+ ],
+ )
+ def test_hash_bounds(self, text, modulus, remainder):
+ assert mnt._parse_partition_bound(text) == {
+ "kind": "HASH",
+ "modulus": modulus,
+ "remainder": remainder,
+ }
+
+
+class TestSameBound:
+ @pytest.mark.parametrize(
+ "actual, expected, same",
+ [
+ (date(2026, 1, 1), date(2026, 1, 1), True),
+ (date(2026, 1, 1), date(2026, 1, 2), False),
+ (datetime(2026, 1, 1), datetime(2026, 1, 1), True),
+ (datetime(2026, 1, 1, 12), datetime(2026, 1, 1), False),
+ (date(2026, 1, 1), datetime(2026, 1, 1), True),
+ (datetime(2026, 1, 1), date(2026, 1, 1), True),
+ (date(2026, 1, 1), datetime(2026, 1, 1, 12), False),
+ (datetime(2026, 1, 1, 8, tzinfo=PLUS8), datetime(2026, 1, 1, tzinfo=UTC), True),
+ (datetime(2026, 1, 1, 9, tzinfo=PLUS8), datetime(2026, 1, 1, tzinfo=UTC), False),
+ (datetime(2026, 1, 1, tzinfo=UTC), datetime(2026, 1, 1), True),
+ ("a", "a", True),
+ (1, 1, True),
+ (1, 2, False),
+ (None, None, True),
+ (None, "x", False),
+ ],
+ )
+ def test_same_bound(self, actual, expected, same):
+ assert mnt._same_bound(actual, expected) is same
+
+
+class TestFormatAndNormalise:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 1, 2, 3, 4, 5), "2026-01-02 03:04:05"),
+ (date(2026, 1, 2), "2026-01-02"),
+ (42, "42"),
+ (None, "None"),
+ ],
+ )
+ def test_format_bound_value(self, value, expected):
+ assert mnt._format_bound_value(value) == expected
+
+ @pytest.mark.parametrize(
+ "text, expected",
+ [
+ (" a b ", "a b"),
+ ("\n a\t b \n", "a b"),
+ ("", None),
+ (" ", None),
+ (None, None),
+ (123, None),
+ ],
+ )
+ def test_normalise_bound_text(self, text, expected):
+ assert mnt._normalise_bound_text(text) == expected
+
+
+class TestKeyValueAndSorting:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 1, 1), "2026-01-01"),
+ (datetime(2026, 1, 1, tzinfo=UTC), "2026-01-01"),
+ (datetime(2026, 1, 1, 12, 30), "2026-01-01 12:30:00"),
+ (date(2026, 1, 1), "2026-01-01"),
+ ("abc", "'abc'"),
+ (4, "4"),
+ (None, "None"),
+ ],
+ )
+ def test_key_value(self, value, expected):
+ assert mnt._key_value(value) == expected
+
+ @pytest.mark.parametrize(
+ "values, expected",
+ [
+ ((3, 1, 2), (1, 2, 3)),
+ (("b", "a"), ("a", "b")),
+ (("a", 1), (1, "a")),
+ ((), ()),
+ ],
+ )
+ def test_sorted_values(self, values, expected):
+ assert mnt._sorted_values(values) == expected
+
+
+class TestExtrasBucket:
+ def test_range_bucket(self):
+ info = _info(
+ "p",
+ method="range",
+ extras={"range_start": date(2026, 1, 1), "range_end": date(2026, 2, 1)},
+ )
+ assert mnt._extras_bucket(info) == "RANGE|2026-01-01|2026-02-01"
+
+ def test_range_bucket_normalises_midnight_datetime(self):
+ info = _info(
+ "p",
+ method="RANGE",
+ extras={
+ "range_start": datetime(2026, 1, 1),
+ "range_end": datetime(2026, 2, 1),
+ },
+ )
+ assert mnt._extras_bucket(info) == "RANGE|2026-01-01|2026-02-01"
+
+ def test_hash_bucket(self):
+ info = _info("p", method="HASH", extras={"modulus": 4, "remainder": 2})
+ assert mnt._extras_bucket(info) == "HASH|4|2"
+
+ def test_list_bucket_sorts_values(self):
+ info = _info("p", method="LIST", extras={"list_values": ("b", "a")})
+ assert mnt._extras_bucket(info) == "LIST|'a','b'"
+
+ def test_list_bucket_with_integers(self):
+ info = _info("p", method="LIST", extras={"list_values": (2, 1)})
+ assert mnt._extras_bucket(info) == "LIST|1,2"
+
+ def test_incomplete_or_missing_extras_return_none(self):
+ assert mnt._extras_bucket(_info("p", method="RANGE", extras={"range_start": 1})) is None
+ assert mnt._extras_bucket(_info("p", method="LIST", extras={})) is None
+ assert (
+ mnt._extras_bucket(_info("p", method=None, extras={"modulus": 4, "remainder": 1}))
+ is None
+ )
+
+
+class TestDifferenceKeyAndSignature:
+ def test_extras_take_precedence_over_bound(self):
+ info = _info(
+ "events_2026_01",
+ method="RANGE",
+ bound="some unparsed text",
+ extras={"range_start": date(2026, 1, 1), "range_end": date(2026, 2, 1)},
+ )
+ assert mnt._difference_key(info) == "RANGE|2026-01-01|2026-02-01"
+ assert mnt._boundary_signature(info) == "RANGE|2026-01-01|2026-02-01"
+
+ def test_bound_is_fallback(self):
+ info = _info("events_x", bound=" FOR VALUES IN ('a') ")
+ assert mnt._difference_key(info) == "FOR VALUES IN ('a')"
+ assert mnt._boundary_signature(info) == "FOR VALUES IN ('a')"
+
+ def test_name_suffix_is_last_resort(self):
+ info = _info("events_2026_01", parent="events")
+ assert mnt._difference_key(info) == "2026_01"
+
+ def test_unprefixed_name_used_as_is(self):
+ assert mnt._difference_key(_info("orphan", parent="events")) == "orphan"
+ assert mnt._difference_key(_info("solo", parent=None)) == "solo"
+
+ def test_signature_none_without_extras_or_bound(self):
+ assert mnt._boundary_signature(_info("p")) is None
+
+ def test_boundaries_disagree_on_verbatim_text(self):
+ left = _info("p", bound="for values in ('a')")
+ right = _info("p", bound="FOR VALUES IN ('a')")
+ assert mnt._boundaries_disagree(left, right) is True
+
+ def test_boundaries_agree_on_same_text(self):
+ left = _info("p", bound="FOR VALUES IN ('a')")
+ right = _info("p", bound=" FOR VALUES IN ('a') ")
+ assert mnt._boundaries_disagree(left, right) is False
+
+ def test_boundaries_disagree_falls_back_to_extras(self):
+ extras = {"range_start": date(2026, 1, 1), "range_end": date(2026, 2, 1)}
+ left = _info("p", method="RANGE", extras=extras)
+ right = _info(
+ "p",
+ method="RANGE",
+ extras={"range_start": date(2026, 1, 1), "range_end": date(2026, 3, 1)},
+ )
+ assert mnt._boundaries_disagree(left, right) is True
+ assert mnt._boundaries_disagree(left, _info("p", method="RANGE", extras=extras)) is False
+
+ def test_boundaries_agree_when_both_have_no_signature(self):
+ assert mnt._boundaries_disagree(_info("a"), _info("b")) is False
+
+
+# --------------------------------------------------------------------------- #
+# Shape derivation helpers
+# --------------------------------------------------------------------------- #
+class TestShapeHelpers:
+ def test_policy_shape_none(self):
+ assert mnt._policy_shape(None) is None
+
+ def test_policy_shape_explicit_range(self):
+ policy = RangePolicy(columns="d", bounds=((date(2026, 1, 1), date(2026, 2, 1)),))
+ assert mnt._policy_shape(policy) == ("RANGE", ("d",), None, True)
+
+ @pytest.mark.parametrize(
+ "interval, normalised",
+ [
+ ("quarter", (1, "quarter")),
+ ((3, "month"), (3, "month")),
+ ("15 day", (15, "day")),
+ ],
+ )
+ def test_policy_shape_generated_range(self, interval, normalised):
+ policy = RangePolicy(columns="d", start=date(2026, 1, 1), interval=interval)
+ assert mnt._policy_shape(policy) == ("RANGE", ("d",), normalised, False)
+
+ def test_policy_shape_list(self):
+ policy = ListPolicy(columns="status", groups=(("a",),))
+ assert mnt._policy_shape(policy) == ("LIST", ("status",))
+
+ def test_policy_shape_hash(self):
+ assert mnt._policy_shape(HashPolicy(columns="tenant", modulus=4)) == (
+ "HASH",
+ ("tenant",),
+ 4,
+ )
+
+ def test_branch_shape(self):
+ assert mnt._branch_shape(HashBranch(remainder=0)) == ("HashBranch", None)
+ branch = HashBranch(remainder=1, child=HashPolicy(modulus=2))
+ assert mnt._branch_shape(branch) == ("HashBranch", ("HASH", ("bucket",), 2))
+ branch = RangeBranch(date(2026, 1, 1), date(2026, 2, 1))
+ assert mnt._branch_shape(branch) == ("RangeBranch", None)
+
+ def test_plan_shape_equal_for_identical_plans(self):
+ left = _range_plan()
+ right = _range_plan()
+ assert mnt._plan_shape(left) == mnt._plan_shape(right)
+
+ @pytest.mark.parametrize(
+ "mutate",
+ [
+ lambda p: PostgresPartitionPlan(
+ parent=p.parent,
+ method="LIST",
+ columns=p.columns,
+ policy=ListPolicy(groups=(("a",),)),
+ ),
+ lambda p: PostgresPartitionPlan(
+ parent=p.parent, method="RANGE", columns="other", policy=p.policy
+ ),
+ lambda p: PostgresPartitionPlan(
+ parent=p.parent,
+ method="RANGE",
+ columns=p.columns,
+ policy=RangePolicy(start=date(2027, 1, 1), interval="year"),
+ ),
+ ],
+ )
+ def test_plan_shape_detects_structure_changes(self, mutate):
+ plan = _range_plan()
+ assert mnt._plan_shape(mutate(plan)) != mnt._plan_shape(plan)
+
+ def test_plan_shape_includes_branches(self):
+ plan = PostgresPartitionPlan(
+ parent="events",
+ method="HASH",
+ columns="tenant",
+ modulus=2,
+ branches=(
+ HashBranch(0),
+ HashBranch(1, child=RangePolicy(bounds=((date(2026, 1, 1), date(2026, 2, 1)),))),
+ ),
+ )
+ shape = mnt._plan_shape(plan)
+ assert shape[0] == "HASH"
+ assert shape[2] == 2
+ assert shape[4] == (
+ ("HashBranch", None),
+ ("HashBranch", ("RANGE", ("created_at",), None, True)),
+ )
+
+
+# --------------------------------------------------------------------------- #
+# _PartitionMaintenanceBase helpers
+# --------------------------------------------------------------------------- #
+class TestParseRows:
+ def test_empty_rows(self):
+ assert mnt._PartitionMaintenanceBase._parse_rows([]) == ()
+
+ def test_derives_method_bound_extras_and_stats(self):
+ rows = [
+ {
+ "name": "events_2026_01",
+ "parent": "events",
+ "level": 1,
+ "schema_name": "public",
+ "partition_key": "RANGE (created_at)",
+ "bound": "FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')",
+ "row_count": "12",
+ "total_bytes": "4096",
+ "is_partitioned": 0,
+ }
+ ]
+ info = mnt._PartitionMaintenanceBase._parse_rows(rows)[0]
+ assert info.name == "events_2026_01"
+ assert info.parent == "events"
+ assert info.level == 1
+ assert info.schema == "public"
+ assert info.method == "RANGE"
+ assert info.bound == rows[0]["bound"]
+ assert info.row_count == 12
+ assert info.size_bytes == 4096
+ assert info.is_partitioned is False
+ assert info.extras == {
+ "range_start": date(2026, 1, 1),
+ "range_end": date(2026, 2, 1),
+ }
+
+ @pytest.mark.parametrize(
+ "partition_key, method",
+ [
+ ("HASH (tenant)", "HASH"),
+ ("LIST (status)", "LIST"),
+ ("RANGE (created_at)", "RANGE"),
+ ("KEY (x)", None),
+ (None, None),
+ ("", None),
+ ],
+ )
+ def test_method_detection(self, partition_key, method):
+ info = mnt._PartitionMaintenanceBase._parse_rows(
+ [
+ {"name": "p", "partition_key": partition_key},
+ ]
+ )[0]
+ assert info.method == method
+
+ def test_missing_stats_become_none_and_defaults(self):
+ info = mnt._PartitionMaintenanceBase._parse_rows([{"name": "p"}])[0]
+ assert info.row_count is None
+ assert info.size_bytes is None
+ assert info.level == 0
+ assert info.parent is None
+ assert info.is_partitioned is False
+ assert info.extras == {}
+
+ def test_list_extras_parsed(self):
+ info = mnt._PartitionMaintenanceBase._parse_rows(
+ [
+ {"name": "p", "partition_key": "LIST (status)", "bound": "FOR VALUES IN ('a', 2)"},
+ ]
+ )[0]
+ assert info.extras == {"list_values": ("a", 2)}
+
+
+class TestExpectedHelpers:
+ def test_expected_returns_specs(self):
+ base, _ = _base()
+ specs = base._expected(_range_plan(), None)
+ assert [spec.name for spec in specs] == ["events_2026_01_01"]
+
+ def test_expected_rejects_plan_without_partitions(self):
+ base, _ = _base()
+ plan = PostgresPartitionPlan(parent="events", method="RANGE", columns="d")
+ with pytest.raises(ValueError, match="no partitions"):
+ base._expected(plan, None)
+
+ def test_safe_expected_returns_empty_for_unbounded_plan(self):
+ base, _ = _base()
+ plan = PostgresPartitionPlan(
+ parent="events",
+ method="RANGE",
+ columns="d",
+ policy=RangePolicy(start=date(2026, 1, 1)),
+ )
+ assert base._safe_expected(plan) == ()
+ assert len(base._safe_expected(plan, through=date(2026, 3, 1))) == 2
+
+ def test_safe_expected_reraises_for_bounded_empty_plan(self):
+ base, _ = _base()
+ plan = PostgresPartitionPlan(parent="events", method="RANGE", columns="d")
+ with pytest.raises(ValueError):
+ base._safe_expected(plan)
+
+ def test_actual_names_excludes_root(self):
+ infos = [
+ _info("events", level=0, parent=None),
+ _info("p1", level=1),
+ _info("p1_a", level=2, parent="p1"),
+ ]
+ actual = mnt._PartitionMaintenanceBase._actual_names(infos)
+ assert set(actual) == {"p1", "p1_a"}
+ assert actual["p1"].level == 1
+
+
+class TestBoundaryComparison:
+ def _range_spec(self):
+ return _spec(
+ "events_2026_01_01",
+ method="RANGE",
+ bounds={"from": date(2026, 1, 1), "to": date(2026, 2, 1)},
+ range_start=date(2026, 1, 1),
+ range_end=date(2026, 2, 1),
+ )
+
+ def test_range_matching_bound_has_no_issue(self):
+ base, _ = _base()
+ info = _info("events_2026_01_01", bound="FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')")
+ assert base._boundary_issue(self._range_spec(), info) is None
+ assert base._boundary_mismatch(self._range_spec(), info) is False
+
+ def test_range_mismatch_issue_and_flag(self):
+ base, _ = _base()
+ info = _info("events_2026_01_01", bound="FOR VALUES FROM ('2026-01-01') TO ('2026-03-01')")
+ assert base._boundary_issue(self._range_spec(), info) == (
+ "boundary mismatch for events_2026_01_01: catalog "
+ "2026-01-01..2026-03-01, plan 2026-01-01..2026-02-01"
+ )
+ assert base._boundary_mismatch(self._range_spec(), info) is True
+
+ def test_unparsed_bound_issue_but_no_mismatch(self):
+ base, _ = _base()
+ info = _info("events_2026_01_01", bound=None)
+ assert base._boundary_issue(self._range_spec(), info) == (
+ "unparsed bound for events_2026_01_01: "
+ )
+ assert base._boundary_mismatch(self._range_spec(), info) is False
+
+ def test_maxvalue_bound_is_unparsed_issue(self):
+ base, _ = _base()
+ info = _info("events_2026_01_01", bound="FOR VALUES FROM ('2026-01-01') TO (MAXVALUE)")
+ assert base._boundary_issue(self._range_spec(), info).startswith("unparsed bound")
+
+ def test_kind_mismatch(self):
+ base, _ = _base()
+ info = _info("events_2026_01_01", bound="FOR VALUES IN ('a')")
+ assert base._boundary_issue(self._range_spec(), info) == (
+ "boundary mismatch for events_2026_01_01: catalog LIST bound, plan RANGE bound"
+ )
+ assert base._boundary_mismatch(self._range_spec(), info) is True
+
+ def test_list_boundary_comparison(self):
+ base, _ = _base()
+ spec = _spec("events_a", method="LIST", bounds={"values": ("a", "b")})
+ matching = _info("events_a", bound="FOR VALUES IN ('b', 'a')")
+ assert base._boundary_issue(spec, matching) is None
+ assert base._boundary_mismatch(spec, matching) is False
+ wrong = _info("events_a", bound="FOR VALUES IN ('x')")
+ assert base._boundary_issue(spec, wrong) == (
+ "boundary mismatch for events_a: catalog values ('x',), plan values ('a', 'b')"
+ )
+ assert base._boundary_mismatch(spec, wrong) is True
+
+ def test_hash_boundary_comparison(self):
+ base, _ = _base()
+ spec = _spec("events_p2", method="HASH", bounds={"modulus": 4, "remainder": 2})
+ matching = _info("events_p2", bound="FOR VALUES WITH (MODULUS 4, REMAINDER 2)")
+ assert base._boundary_issue(spec, matching) is None
+ wrong = _info("events_p2", bound="FOR VALUES WITH (MODULUS 4, REMAINDER 1)")
+ assert base._boundary_issue(spec, wrong) == (
+ "boundary mismatch for events_p2: catalog modulus 4 remainder 1, "
+ "plan modulus 4 remainder 2"
+ )
+ assert base._boundary_mismatch(spec, wrong) is True
+
+ def test_needs_partition_missing_or_mismatched(self):
+ base, _ = _base()
+ spec = self._range_spec()
+ assert base._needs_partition(spec, {}) is True
+ matching = _info(spec.name, bound="FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')")
+ assert base._needs_partition(spec, {spec.name: matching}) is False
+ wrong = _info(spec.name, bound="FOR VALUES FROM ('2026-01-01') TO ('2026-03-01')")
+ assert base._needs_partition(spec, {spec.name: wrong}) is True
+
+ def test_missing_pairs(self):
+ base, _ = _base()
+ spec = self._range_spec()
+ assert base._missing([spec], {}) == (("events", spec.name),)
+ matching = _info(spec.name, bound="FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')")
+ assert base._missing([spec], {spec.name: matching}) == ()
+
+
+class TestOtherBaseHelpers:
+ def test_orphans_bounded(self):
+ base, _ = _base()
+ plan = _range_plan()
+ spec = _spec("events_2026_01_01")
+ actual = {"events_2026_01_01": _info("events_2026_01_01"), "events_z": _info("events_z")}
+ assert base._orphans(plan, [spec], actual, None) == ("events_z",)
+
+ def test_orphans_unbounded(self):
+ base, _ = _base()
+ plan = PostgresPartitionPlan(
+ parent="events",
+ method="RANGE",
+ columns="d",
+ policy=RangePolicy(start=date(2026, 1, 1)),
+ )
+ assert base._orphans(plan, [], {"x": _info("x")}, None) == ()
+
+ def test_units_flat_plan(self):
+ specs = [_spec("a"), _spec("b")]
+ assert mnt._PartitionMaintenanceBase._units(_range_plan(), specs) == (tuple(specs),)
+ assert mnt._PartitionMaintenanceBase._units(_range_plan(), []) == ()
+
+ def test_units_multilevel_plan(self):
+ plan = PostgresPartitionPlan(
+ parent="events",
+ method="HASH",
+ columns="tenant",
+ modulus=2,
+ branches=(HashBranch(0), HashBranch(1)),
+ )
+ branch0 = _spec("events_p0", level=1)
+ leaf0 = _spec("events_p0_0", level=2, parent="events_p0")
+ branch1 = _spec("events_p1", level=1)
+ assert mnt._PartitionMaintenanceBase._units(plan, [branch0, leaf0, branch1]) == (
+ (branch0, leaf0),
+ (branch1,),
+ )
+
+ def test_continuity_gap_and_overlap(self):
+ base, _ = _base()
+ specs = [
+ _spec("a", range_start=date(2026, 1, 1), range_end=date(2026, 2, 1)),
+ _spec("b", range_start=date(2026, 2, 2), range_end=date(2026, 3, 1)),
+ _spec("c", range_start=date(2026, 2, 15), range_end=date(2026, 3, 15), parent="other"),
+ ]
+ issues = base._continuity_issues(specs)
+ assert "gap in events between a and b" in issues
+ assert "overlap in other between b and c" not in issues # b is in a different parent
+
+ def test_continuity_overlap(self):
+ base, _ = _base()
+ specs = [
+ _spec("a", range_start=date(2026, 1, 1), range_end=date(2026, 2, 1)),
+ _spec("b", range_start=date(2026, 1, 15), range_end=date(2026, 2, 15)),
+ ]
+ assert base._continuity_issues(specs) == ("overlap in events between a and b",)
+
+ def test_continuity_ignores_unranged_specs(self):
+ base, _ = _base()
+ assert base._continuity_issues([_spec("a"), _spec("b")]) == ()
+
+ def test_structure_issues_clean(self):
+ base, _ = _base()
+ plan = _range_plan()
+ root = _info("events", level=0, parent=None, method="RANGE")
+ spec = _spec(
+ "events_2026_01_01",
+ method="RANGE",
+ bounds={"from": date(2026, 1, 1), "to": date(2026, 2, 1)},
+ range_start=date(2026, 1, 1),
+ range_end=date(2026, 2, 1),
+ )
+ info = _info(spec.name, bound="FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')")
+ assert base._structure_issues(plan, [root, info], [spec]) == ()
+
+ def test_structure_issues_no_root(self):
+ base, _ = _base()
+ assert base._structure_issues(_range_plan(), [], []) == (
+ "partitioned parent events does not exist",
+ )
+
+ def test_structure_issues_root_method_mismatch(self):
+ base, _ = _base()
+ root = _info("events", level=0, parent=None, method="LIST")
+ assert base._structure_issues(_range_plan(), [root], []) == (
+ "parent events is partitioned by LIST, plan says RANGE",
+ )
+
+ def test_structure_issues_parent_and_leaf_flags(self):
+ base, _ = _base()
+ root = _info("events", level=0, parent=None, method="RANGE")
+ spec = _spec(
+ "p",
+ bounds={"from": date(2026, 1, 1), "to": date(2026, 2, 1)},
+ range_start=date(2026, 1, 1),
+ range_end=date(2026, 2, 1),
+ )
+ info = _info(
+ "p",
+ parent="other",
+ is_partitioned=True,
+ bound="FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')",
+ )
+ issues = base._structure_issues(_range_plan(), [root, info], [spec])
+ assert "p belongs to other, plan expects events" in issues
+ assert "leaf p is partitioned; plan expects it to be a leaf" in issues
+
+ def test_structure_issues_branch_flags(self):
+ base, _ = _base()
+ root = _info("events", level=0, parent=None, method="RANGE")
+ spec = _spec("p", child_method="RANGE")
+ plain = _info("p", is_partitioned=False)
+ issues = base._structure_issues(_range_plan(), [root, plain], [spec])
+ assert "branch p is not further partitioned; RANGE leaves are missing" in issues
+ wrong = _info("p", is_partitioned=True, method="HASH")
+ issues = base._structure_issues(_range_plan(), [root, wrong], [spec])
+ assert "branch p is partitioned by HASH, plan says RANGE" in issues
+
+ def test_report_composition(self):
+ base, _ = _base()
+ plan = _range_plan()
+ infos = (_info("events", level=0, parent=None, method="RANGE"),)
+ specs = (_spec("events_2026_01_01"),)
+ report = base._report(plan, infos, specs, None, dry_run=True)
+ assert report.target == "events"
+ assert report.partitions == infos
+ assert report.missing == (("events", "events_2026_01_01"),)
+ assert report.issues == ()
+ assert report.dry_run is True
+
+ def test_without(self):
+ specs = [_spec("a"), _spec("b"), _spec("c")]
+ assert mnt._PartitionMaintenanceBase._without(specs, ["b"]) == (specs[0], specs[2])
+
+ def test_drop_candidates_rejects_non_date_cutoff(self):
+ base, _ = _base()
+ with pytest.raises(TypeError, match="cutoff must be a date or datetime"):
+ base._drop_candidates(_range_plan(), "2026-02-15", [], None)
+
+ def test_drop_candidates_selects_early_existing_leaves(self):
+ base, _ = _base()
+ plan = _range_plan(
+ bounds=(
+ (date(2026, 1, 1), date(2026, 2, 1)),
+ (date(2026, 2, 1), date(2026, 3, 1)),
+ )
+ )
+ infos = [
+ _info("events_2026_01_01", bound="FOR VALUES FROM ('2026-01-01') " "TO ('2026-02-01')"),
+ _info("events_2026_02_01", bound="FOR VALUES FROM ('2026-02-01') " "TO ('2026-03-01')"),
+ ]
+ candidates = base._drop_candidates(plan, date(2026, 2, 15), infos, None)
+ assert [spec.name for spec in candidates] == ["events_2026_01_01"]
+
+ def test_resolve_batch_dedup_and_pairs(self):
+ plan_a = _range_plan("a")
+ plan_b = _range_plan("b")
+ entries, unique = mnt._PartitionMaintenanceBase._resolve_batch(
+ [plan_a, plan_a, plan_b], None
+ )
+ assert entries == ()
+ assert unique == (plan_a, plan_b)
+ entries, unique = mnt._PartitionMaintenanceBase._resolve_batch(
+ None, [("pair", plan_a, plan_b)]
+ )
+ assert entries == (("pair", plan_a, plan_b),)
+ assert unique == (plan_a, plan_b)
+
+ @pytest.mark.parametrize(
+ "plans, pairs, message",
+ [
+ ([], None, "at least one plan"),
+ (["x"], None, "must be PostgresPartitionPlan"),
+ (None, [("bad",)], "must be \\(name, left_plan, right_plan\\)"),
+ ],
+ )
+ def test_resolve_batch_errors(self, plans, pairs, message):
+ with pytest.raises((TypeError, ValueError), match=message):
+ mnt._PartitionMaintenanceBase._resolve_batch(plans, pairs)
+
+ def test_bucket_map_flags_duplicates(self):
+ infos = [
+ _info("a", level=1, bound="FOR VALUES IN ('x')"),
+ _info("b", level=1, bound="FOR VALUES IN ('x')"),
+ _info("skip", level=2, bound="FOR VALUES IN ('y')"),
+ ]
+ issues = []
+ buckets = mnt._PartitionMaintenanceBase._bucket_map("p", "left", infos, issues)
+ assert set(buckets) == {"FOR VALUES IN ('x')"}
+ assert "duplicate bucket" in issues[0]
+
+ def test_paired_report_differences_and_issues(self):
+ base, _ = _base()
+ left_plan = _range_plan("left_t")
+ right_plan = _range_plan("right_t")
+ left_report = PartitionReport(
+ target="left_t",
+ partitions=(_info("l_only", level=1, bound="FOR VALUES IN ('left')"),),
+ )
+ right_report = PartitionReport(
+ target="right_t",
+ partitions=(_info("r_only", level=1, bound="FOR VALUES IN ('right')"),),
+ )
+ differences, issues = base._paired_report(
+ (("p", left_plan, right_plan),),
+ {"left_t": left_report, "right_t": right_report},
+ )
+ assert issues == ()
+ assert differences == (
+ PairedDifference("p", "FOR VALUES IN ('left')", "left", "l_only", None),
+ PairedDifference("p", "FOR VALUES IN ('right')", "right", None, "r_only"),
+ )
+
+ def test_paired_report_incompatible_plan(self):
+ base, _ = _base()
+ left_plan = _range_plan("left_t")
+ right_plan = PostgresPartitionPlan(
+ parent="right_t",
+ method="LIST",
+ columns="d",
+ policy=ListPolicy(groups=(("a",),)),
+ )
+ differences, issues = base._paired_report((("p", left_plan, right_plan),), {})
+ assert differences == ()
+ assert issues == ("pair p plans are not comparable",)
+
+ def test_paired_report_boundary_drift_with_same_semantic_key(self):
+ base, _ = _base()
+ left_plan = _range_plan("t_left")
+ right_plan = _range_plan("t_right")
+ extras = {"range_start": date(2026, 1, 1), "range_end": date(2026, 2, 1)}
+ left = _info(
+ "l",
+ level=1,
+ method="RANGE",
+ extras=extras,
+ bound="FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')",
+ )
+ right = _info(
+ "r",
+ level=1,
+ method="RANGE",
+ extras=extras,
+ bound="for values from ('2026-01-01') to ('2026-02-01')",
+ )
+ reports = {
+ "t_left": PartitionReport(target="t_left", partitions=(left,)),
+ "t_right": PartitionReport(target="t_right", partitions=(right,)),
+ }
+ differences, issues = base._paired_report((("p", left_plan, right_plan),), reports)
+ assert differences == ()
+ assert issues == ("boundary mismatch for p/RANGE|2026-01-01|2026-02-01",)
+
+ def test_batch_report_assembly(self):
+ reports = {"t": PartitionReport(target="t")}
+ batch = mnt._PartitionMaintenanceBase._batch_report(
+ (("p", _range_plan("a"), _range_plan("b")),),
+ reports,
+ (PairedDifference("p", "k", "left", "l", None),),
+ ("issue",),
+ )
+ assert isinstance(batch, PartitionBatchReport)
+ assert batch.reports == reports
+ assert batch.pairs == ("p",)
+ assert batch.issues == ("issue",)
+ assert len(batch.differences) == 1
+
+
+# --------------------------------------------------------------------------- #
+# I/O seams (mocked)
+# --------------------------------------------------------------------------- #
+class TestIoSeams:
+ def test_base_seams_raise_not_implemented(self):
+ base, _ = _base()
+ with pytest.raises(NotImplementedError):
+ base._fetch_rows("SELECT 1", ())
+ with pytest.raises(NotImplementedError):
+ base._execute("DDL", ())
+ with pytest.raises(NotImplementedError):
+ base._run_units(_range_plan(), (), lambda spec: None)
+
+ def test_sync_fetch_and_execute_delegate_to_backend(self):
+ backend = MagicMock()
+ backend.dialect = PostgresDialect(version=(17, 0, 0))
+ backend.fetch_all.return_value = [{"name": "p"}]
+ maintenance = PostgresPartitionMaintenance(backend)
+ assert maintenance._fetch_rows("SELECT", ("p",)) == [{"name": "p"}]
+ backend.fetch_all.assert_called_once_with("SELECT", ("p",))
+ maintenance._execute("DDL", ("p",))
+ backend.execute.assert_called_once_with("DDL", ("p",))
+
+ def test_infos_uses_fetch_seam_and_parses_rows(self):
+ base, _ = _base()
+ rows = [
+ {
+ "name": "events_2026_01_01",
+ "parent": "events",
+ "level": 1,
+ "partition_key": "RANGE (created_at)",
+ "bound": "FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')",
+ }
+ ]
+ base._fetch_rows = MagicMock(return_value=rows)
+ infos = base._infos(_range_plan())
+ assert base._fetch_rows.call_count == 1
+ sql, params = base._fetch_rows.call_args.args
+ assert "partition_tree" in sql
+ assert params == ("events",)
+ assert infos[0].name == "events_2026_01_01"
+ assert "range_start" in infos[0].extras
+
+
+# --------------------------------------------------------------------------- #
+# plan.py pure helpers and policy objects
+# --------------------------------------------------------------------------- #
+class TestPlanModuleHelpers:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ ("a", ("a",)),
+ (("a", "b"), ("a", "b")),
+ (["a", "b"], ("a", "b")),
+ ],
+ )
+ def test_as_columns_valid(self, value, expected):
+ assert plan_mod._as_columns(value) == expected
+
+ @pytest.mark.parametrize("value", [None, 1, {}])
+ def test_as_columns_wrong_type(self, value):
+ with pytest.raises(TypeError, match="columns must be a string"):
+ plan_mod._as_columns(value)
+
+ @pytest.mark.parametrize("value", [(), [], ("",), ("a", " ")])
+ def test_as_columns_empty(self, value):
+ with pytest.raises(ValueError):
+ plan_mod._as_columns(value)
+
+ @pytest.mark.parametrize(
+ "method, expected",
+ [
+ ("range", "RANGE"),
+ ("List", "LIST"),
+ ("HASH", "HASH"),
+ ],
+ )
+ def test_normalise_method(self, method, expected):
+ assert plan_mod._normalise_method(method) == expected
+
+ @pytest.mark.parametrize("method", ["KEY", "", None, 1])
+ def test_normalise_method_rejects_unknown(self, method):
+ with pytest.raises(ValueError, match="method must be one of"):
+ plan_mod._normalise_method(method)
+
+ @pytest.mark.parametrize(
+ "values, expected",
+ [
+ (("a", "b"), "a_b"),
+ ((1, 2), "1_2"),
+ (("a-b",), "a_b"),
+ (("",), "value"),
+ ],
+ )
+ def test_label_from_values(self, values, expected):
+ assert plan_mod._label_from_values(values) == expected
+
+ def test_render_label(self):
+ assert (
+ plan_mod._render_label("{year}-{month:02d}", date(2026, 3, 1), date(2026, 4, 1))
+ == "2026-03"
+ )
+ assert plan_mod._render_label("q{quarter}", date(2026, 4, 1), date(2026, 7, 1)) == "q2"
+
+
+class TestRangePolicy:
+ def test_method_and_explicit_bounds(self):
+ policy = RangePolicy(columns="d", bounds=((date(2026, 1, 1), date(2026, 2, 1)),))
+ assert policy.method == "RANGE"
+ assert list(policy.iter_bounds()) == [(date(2026, 1, 1), date(2026, 2, 1))]
+ assert policy.label_for(date(2026, 1, 1), date(2026, 2, 1)) == "2026_01_01"
+
+ def test_generated_bounds_by_count(self):
+ policy = RangePolicy(start=date(2026, 1, 1), count=3)
+ assert list(policy.iter_bounds()) == [
+ (date(2026, 1, 1), date(2026, 2, 1)),
+ (date(2026, 2, 1), date(2026, 3, 1)),
+ (date(2026, 3, 1), date(2026, 4, 1)),
+ ]
+ assert policy.label_for(date(2026, 1, 1), date(2026, 2, 1)) == "2026_01"
+
+ def test_generated_bounds_by_through(self):
+ policy = RangePolicy(start=date(2026, 1, 1), interval=(15, "day"))
+ assert list(policy.iter_bounds(through=date(2026, 1, 20))) == [
+ (date(2026, 1, 1), date(2026, 1, 16)),
+ (date(2026, 1, 16), date(2026, 1, 31)),
+ ]
+
+ def test_generated_policy_without_horizon_raises(self):
+ policy = RangePolicy(start=date(2026, 1, 1))
+ with pytest.raises(ValueError, match="count or through"):
+ list(policy.iter_bounds())
+
+ def test_custom_label_pattern(self):
+ policy = RangePolicy(
+ start=date(2026, 1, 1),
+ count=1,
+ label_pattern="y{year}q{quarter}",
+ )
+ assert policy.label_for(date(2026, 1, 1), date(2026, 4, 1)) == "y2026q1"
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {},
+ {"start": date(2026, 1, 1), "bounds": ((date(2026, 1, 1), date(2026, 2, 1)),)},
+ {"start": "2026-01-01"},
+ {"start": date(2026, 1, 1), "count": 0},
+ {"start": date(2026, 1, 1), "count": True},
+ {"start": date(2026, 1, 1), "interval": "fortnight"},
+ {"bounds": ()},
+ {"bounds": ((date(2026, 1, 1),),)},
+ {"bounds": ((date(2026, 2, 1), date(2026, 1, 1)),)},
+ ],
+ )
+ def test_invalid_construction(self, kwargs):
+ with pytest.raises((TypeError, ValueError)):
+ RangePolicy(**kwargs)
+
+
+class TestListPolicy:
+ def test_iter_groups_derived_labels(self):
+ policy = ListPolicy(columns="status", groups=(("a", "b"), ("c",)))
+ assert policy.method == "LIST"
+ assert list(policy.iter_groups()) == [(("a", "b"), "a_b"), (("c",), "c")]
+
+ def test_iter_groups_explicit_labels(self):
+ policy = ListPolicy(groups=(("a",), ("b",)), labels=("first", "second"))
+ assert list(policy.iter_groups()) == [(("a",), "first"), (("b",), "second")]
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {},
+ {"groups": ((),)},
+ {"groups": (("a",),), "labels": ("one", "two")},
+ {"groups": (("a",),), "labels": ("",)},
+ ],
+ )
+ def test_invalid_construction(self, kwargs):
+ with pytest.raises(ValueError):
+ ListPolicy(**kwargs)
+
+
+class TestHashPolicy:
+ def test_all_remainders(self):
+ policy = HashPolicy(modulus=3)
+ assert policy.method == "HASH"
+ assert list(policy.iter_remainders()) == [0, 1, 2]
+
+ def test_selected_remainders(self):
+ policy = HashPolicy(modulus=4, remainders=(2, 0))
+ assert list(policy.iter_remainders()) == [2, 0]
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"modulus": 0},
+ {"modulus": -1},
+ {"modulus": True},
+ {"modulus": "4"},
+ {"modulus": 4, "remainders": ()},
+ {"modulus": 4, "remainders": (4,)},
+ {"modulus": 4, "remainders": (1, 1)},
+ {"modulus": 4, "remainders": (True,)},
+ ],
+ )
+ def test_invalid_construction(self, kwargs):
+ with pytest.raises((TypeError, ValueError)):
+ HashPolicy(**kwargs)
+
+
+class TestBranches:
+ def test_hash_branch_defaults(self):
+ branch = HashBranch(remainder=3)
+ assert branch.remainder == 3
+ assert branch.child is None
+ assert branch.name is None
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"remainder": "0"},
+ {"remainder": True},
+ {"remainder": -1},
+ {"remainder": 0, "name": " "},
+ ],
+ )
+ def test_hash_branch_invalid(self, kwargs):
+ with pytest.raises((TypeError, ValueError)):
+ HashBranch(**kwargs)
+
+ def test_range_branch(self):
+ branch = RangeBranch(date(2026, 1, 1), date(2026, 2, 1), label="jan")
+ assert branch.label == "jan"
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"start": "2026-01-01", "end": date(2026, 2, 1)},
+ {"start": date(2026, 2, 1), "end": date(2026, 1, 1)},
+ {"start": date(2026, 1, 1), "end": date(2026, 1, 1), "name": " "},
+ {"start": date(2026, 1, 1), "end": date(2026, 2, 1), "label": ""},
+ ],
+ )
+ def test_range_branch_invalid(self, kwargs):
+ with pytest.raises((TypeError, ValueError)):
+ RangeBranch(**kwargs)
+
+ def test_list_branch_normalises_values(self):
+ assert ListBranch(values=["a", "b"]).values == ("a", "b")
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"values": ()},
+ {"values": ("a",), "name": ""},
+ {"values": ("a",), "label": " "},
+ ],
+ )
+ def test_list_branch_invalid(self, kwargs):
+ with pytest.raises(ValueError):
+ ListBranch(**kwargs)
+
+
+class TestPostgresPartitionPlan:
+ def test_method_and_columns_normalised(self):
+ plan = PostgresPartitionPlan(
+ parent="events",
+ method="range",
+ columns="d",
+ policy=RangePolicy(count=1, start=date(2026, 1, 1)),
+ )
+ assert plan.method == "RANGE"
+ assert plan.columns == ("d",)
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"parent": ""},
+ {"parent": "e", "method": "KEY"},
+ {"parent": "e", "method": "RANGE", "columns": ()},
+ {"parent": "e", "method": "RANGE", "name_pattern": "x"},
+ {"parent": "e", "method": "RANGE", "name_pattern": ""},
+ {"parent": "e", "method": "RANGE", "schema": " "},
+ ],
+ )
+ def test_invalid_plan_fields(self, kwargs):
+ with pytest.raises((TypeError, ValueError)):
+ PostgresPartitionPlan(**kwargs)
+
+ def test_policy_and_branches_mutually_exclusive(self):
+ with pytest.raises(ValueError, match="mutually exclusive"):
+ PostgresPartitionPlan(
+ parent="e",
+ method="HASH",
+ columns="tenant",
+ modulus=2,
+ branches=(HashBranch(0),),
+ policy=HashPolicy(modulus=2),
+ )
+
+ @pytest.mark.parametrize(
+ "kwargs, message",
+ [
+ (
+ {
+ "parent": "e",
+ "method": "HASH",
+ "columns": "tenant",
+ "policy": RangePolicy(bounds=((date(2026, 1, 1), date(2026, 2, 1)),)),
+ },
+ "must be a HashPolicy",
+ ),
+ (
+ {
+ "parent": "e",
+ "method": "HASH",
+ "columns": "tenant",
+ "branches": (HashBranch(0),),
+ },
+ "requires modulus",
+ ),
+ (
+ {"parent": "e", "method": "RANGE", "columns": "d", "modulus": 2},
+ "only meaningful for a HASH parent",
+ ),
+ (
+ {
+ "parent": "e",
+ "method": "HASH",
+ "columns": "tenant",
+ "modulus": 0,
+ "branches": (HashBranch(0),),
+ },
+ "positive integer",
+ ),
+ (
+ {
+ "parent": "e",
+ "method": "HASH",
+ "columns": "tenant",
+ "modulus": 1,
+ "branches": (HashBranch(1),),
+ },
+ "less than modulus",
+ ),
+ ],
+ )
+ def test_hash_specific_validation(self, kwargs, message):
+ with pytest.raises((TypeError, ValueError), match=message):
+ PostgresPartitionPlan(**kwargs)
+
+ @pytest.mark.parametrize(
+ "method, branch",
+ [
+ ("HASH", RangeBranch(date(2026, 1, 1), date(2026, 2, 1))),
+ ("RANGE", HashBranch(0)),
+ ("LIST", HashBranch(0)),
+ ],
+ )
+ def test_branch_type_must_match_method(self, method, branch):
+ with pytest.raises(ValueError, match="branches must be"):
+ PostgresPartitionPlan(parent="e", method=method, columns="d", branches=(branch,))
+
+ def test_branch_suffix_variants(self):
+ plan = PostgresPartitionPlan(
+ parent="events",
+ method="HASH",
+ columns="tenant",
+ modulus=2,
+ branches=(HashBranch(0), HashBranch(1, name="custom")),
+ )
+ assert plan.branch_suffix(0, plan.branches[0]) == "p0"
+ assert plan.branch_suffix(1, plan.branches[1]) == "custom"
+ assert plan.branch_name(0, plan.branches[0]) == "events_p0"
+ assert plan.branch_name(1, plan.branches[1]) == "events_custom"
+
+ def test_branch_suffix_range_and_list(self):
+ range_branch = RangeBranch(date(2026, 3, 1), date(2026, 4, 1), label="march")
+ list_branch = ListBranch(values=("a", "b"))
+ assert (
+ plan_mod.PostgresPartitionPlan(
+ parent="e", method="RANGE", columns="d", branches=(range_branch,)
+ ).branch_suffix(0, range_branch)
+ == "march"
+ )
+ assert (
+ plan_mod.PostgresPartitionPlan(
+ parent="e", method="LIST", columns="d", branches=(list_branch,)
+ ).branch_suffix(0, list_branch)
+ == "a_b"
+ )
+
+ def test_custom_name_pattern(self):
+ plan = PostgresPartitionPlan(
+ parent="events",
+ method="HASH",
+ columns="tenant",
+ modulus=2,
+ branches=(HashBranch(0),),
+ name_pattern="{parent}~{suffix}",
+ )
+ assert plan.branch_name(0, plan.branches[0]) == "events~p0"
+
+ def test_iter_specs_flat(self):
+ plan = _range_plan(
+ bounds=(
+ (date(2026, 1, 1), date(2026, 2, 1)),
+ (date(2026, 2, 1), date(2026, 3, 1)),
+ )
+ )
+ specs = list(plan.iter_specs())
+ assert [spec.name for spec in specs] == [
+ "events_2026_01_01",
+ "events_2026_02_01",
+ ]
+ assert all(spec.level == 1 and spec.is_leaf for spec in specs)
+
+ def test_iter_specs_multilevel_order(self):
+ plan = PostgresPartitionPlan(
+ parent="events",
+ method="HASH",
+ columns="tenant",
+ modulus=2,
+ branches=(
+ HashBranch(0, child=RangePolicy(bounds=((date(2026, 1, 1), date(2026, 2, 1)),))),
+ HashBranch(1),
+ ),
+ )
+ specs = list(plan.iter_specs())
+ assert [spec.level for spec in specs] == [1, 2, 1]
+ assert specs[0].name == "events_p0"
+ assert specs[0].child_method == "RANGE"
+ assert specs[1].name == "events_p0_2026_01_01"
+ assert specs[1].parent == "events_p0"
+ assert specs[2].is_leaf is True
+
+ def test_iter_specs_duplicate_name_raises(self):
+ plan = PostgresPartitionPlan(
+ parent="events",
+ method="HASH",
+ columns="tenant",
+ modulus=2,
+ branches=(HashBranch(0, name="same"), HashBranch(1, name="same")),
+ )
+ with pytest.raises(ValueError, match="duplicate partition name"):
+ list(plan.iter_specs())
+
+ @pytest.mark.parametrize(
+ "plan, through, bounded",
+ [
+ (_range_plan(), None, True),
+ (
+ PostgresPartitionPlan(
+ parent="e",
+ method="RANGE",
+ columns="d",
+ policy=RangePolicy(start=date(2026, 1, 1)),
+ ),
+ None,
+ False,
+ ),
+ (
+ PostgresPartitionPlan(
+ parent="e",
+ method="RANGE",
+ columns="d",
+ policy=RangePolicy(start=date(2026, 1, 1)),
+ ),
+ date(2026, 3, 1),
+ True,
+ ),
+ (PostgresPartitionPlan(parent="e", method="RANGE", columns="d"), None, True),
+ ],
+ )
+ def test_is_fully_bounded(self, plan, through, bounded):
+ assert plan.is_fully_bounded(through=through) is bounded
+
+
+class TestPartitionSpec:
+ def test_fields_and_equality(self):
+ spec = _spec(
+ "p",
+ range_start=date(2026, 1, 1),
+ range_end=date(2026, 2, 1),
+ child_method="HASH",
+ child_columns=("tenant",),
+ label="jan",
+ )
+ assert spec.name == "p"
+ assert spec.parent == "events"
+ assert spec.child_columns == ("tenant",)
+ assert spec == _spec(
+ "p",
+ range_start=date(2026, 1, 1),
+ range_end=date(2026, 2, 1),
+ child_method="HASH",
+ child_columns=("tenant",),
+ label="jan",
+ )
+
+ def test_frozen(self):
+ spec = _spec("p")
+ with pytest.raises(FrozenInstanceError):
+ spec.name = "other"
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/partition_syntax_fixtures.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/partition_syntax_fixtures.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/partition_syntax_fixtures.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/partition_syntax_fixtures.py
index 92cd37e7..9a8845c1 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/partition_syntax_fixtures.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/partition_syntax_fixtures.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/partition_syntax_fixtures.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/partition_syntax_fixtures.py
"""Fixture table for PostgreSQL partition syntax families.
Every case is an offline description of one PostgreSQL partitioning shape:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_expressions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_expressions.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_expressions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_expressions.py
index ffbc82af..6f0fb85c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_expressions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_expressions.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_expressions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_expressions.py
"""Tests for PostgreSQL DDL expression classes.
This module tests the expression-based format methods for DDL operations,
@@ -51,7 +51,7 @@
PostgresExtendedStatisticsMixin, # noqa: F401
)
-class TestPostgresRefreshMaterializedViewExpression:
+class TestRefreshMaterializedViewExpression:
"""Test PostgresRefreshMaterializedViewPgStatement."""
@pytest.fixture
@@ -140,7 +140,7 @@ def test_refresh_concurrently_and_no_data(self, dialect):
assert params == ()
-class TestPostgresCommentExpression:
+class TestCommentExpression:
"""Test PostgresCommentOnStatement."""
@pytest.fixture
@@ -244,7 +244,7 @@ def test_comment_with_schema(self, dialect):
assert params == ("Public users table",)
-class TestPostgresPartitionedTableCreation:
+class TestPartitionedTableCreation:
"""Test PostgreSQL CREATE TABLE ... PARTITION BY support."""
@pytest.fixture
@@ -500,7 +500,7 @@ def test_child_multi_column_list_partition_clause_rejected(self, dialect):
expr.to_sql()
-class TestPostgresPartitionValue:
+class TestPartitionValue:
"""Test safe PostgreSQL partition bound value formatting."""
@pytest.fixture
@@ -604,7 +604,7 @@ def test_partition_value_requires_pg10(self):
PostgresPartitionValue(dialect, 1).to_sql()
-class TestPostgresCreatePartitionExpression:
+class TestCreatePartitionExpression:
"""Test PostgresCreatePartitionStatement."""
@pytest.fixture
@@ -957,7 +957,7 @@ def test_create_partition_requires_pg10(self):
expr.to_sql()
-class TestPostgresDetachPartitionExpression:
+class TestDetachPartitionExpression:
"""Test PostgresDetachPartitionStatement."""
@pytest.fixture
@@ -1049,7 +1049,7 @@ def test_detach_partition_requires_pg10(self):
expr.to_sql()
-class TestPostgresAttachPartitionExpression:
+class TestAttachPartitionExpression:
"""Test PostgresAttachPartitionStatement."""
@pytest.fixture
@@ -1277,7 +1277,7 @@ def test_attach_partition_requires_pg10(self):
expr.to_sql()
-class TestPostgresPartitionMetadataExpression:
+class TestPartitionMetadataExpression:
"""Test PostgreSQL partition metadata query expression."""
def test_metadata_query_for_parent(self):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_objects.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_objects.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_objects.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_objects.py
index e64fb3e1..a41b6f96 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_objects.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_objects.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_ddl_expressions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_ddl_objects.py
"""Tests for PostgreSQL DDL expression classes.
This module tests the expression-based format methods for DDL operations,
@@ -107,7 +107,7 @@
_PG_ROUNDTRIP_REGISTRY.register_node(PostgresCompositeTypeDefinition)
-class TestPostgresDomainExpression:
+class TestDomainExpression:
"""CREATE / ALTER / DROP DOMAIN."""
@pytest.fixture
@@ -337,7 +337,7 @@ def test_drop_domain_flags(self, dialect):
expression.to_sql()
-class TestPostgresTypeDDLExpressions:
+class TestTypeDDLExpressions:
@pytest.fixture
def dialect(self):
return PostgresDialect(version=(14, 0, 0))
@@ -727,7 +727,7 @@ def test_base_subscript_version_boundary(self):
assert 'SUBSCRIPT = "box_subscript"' in sql
-class TestPostgresCollationDDLExpression:
+class TestCollationDDLExpression:
"""CREATE / DROP COLLATION DDL."""
@pytest.fixture
@@ -855,7 +855,7 @@ def test_version_gate_96(self):
PostgresDropForeignTableStatement(d, "ft").to_sql()
-class TestPostgresRoutineDDLExpression:
+class TestRoutineDDLExpression:
"""CREATE / DROP FUNCTION and AGGREGATE."""
@pytest.fixture
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_plan.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_plan.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_plan.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_plan.py
index f20971b2..80fb689f 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_plan.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_plan.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_plan.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_plan.py
"""Unit tests for PostgreSQL partition plans and maintenance planning.
No server is required. Plan generation, naming, DDL rendering and catalog
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_syntax_matrix.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_syntax_matrix.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_syntax_matrix.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_syntax_matrix.py
index 1ab7ab7b..bc18c2fe 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_syntax_matrix.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_syntax_matrix.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_partition_syntax_matrix.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_partition_syntax_matrix.py
"""Offline matrix for PostgreSQL partition syntax families.
Each test consumes ``partition_syntax_case`` from
@@ -32,7 +32,7 @@
PartitionRetention,
PartitionValidator,
)
-from partition_syntax_fixtures import ( # noqa: F401 (fixture re-export)
+from rhosocial.activerecord_postgres_test.feature.backend.construct.statements.partition_syntax_fixtures import ( # noqa: F401 (fixture re-export)
PartitionSyntaxCase,
partition_syntax_case as _matrix_case,
)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_pg19_copy_repack.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_pg19_copy_repack.py
index 5448b8f0..9e645163 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_pg19_copy_repack.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_pg19_copy_repack.py
"""Tests for PostgreSQL COPY and native REPACK expressions and APIs."""
from contextlib import contextmanager
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_expressions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_postgres_expressions.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_expressions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_postgres_expressions.py
index 9c1fa2d9..67ef7f2c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_expressions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_postgres_expressions.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_expressions.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_postgres_expressions.py
"""Tests for PostgreSQL-specific expression classes and format methods.
This module tests the expression-based format methods for DDL/DML operations,
@@ -20,7 +20,7 @@
)
-class TestPostgresVacuumExpression:
+class TestVacuumExpression:
"""Test PostgresVacuumStatement and format_vacuum_statement."""
@pytest.fixture
@@ -95,7 +95,7 @@ def test_vacuum_truncate_excludes_full(self, dialect):
expr.to_sql()
-class TestPostgresAnalyzeExpression:
+class TestAnalyzeExpression:
"""Test PostgresAnalyzeStatement and format_analyze_statement."""
@pytest.fixture
@@ -121,7 +121,7 @@ def test_analyze_with_columns(self, dialect):
assert '("id", "name", "email")' in sql
-class TestPostgresCreatePartitionExpression:
+class TestCreatePartitionExpression:
"""Test PostgresCreatePartitionStatement and format_create_partition_statement."""
@pytest.fixture
@@ -247,7 +247,7 @@ def test_partition_with_tablespace(self, dialect):
assert 'TABLESPACE "fast_storage"' in sql
-class TestPostgresDetachPartitionExpression:
+class TestDetachPartitionExpression:
"""Test PostgresDetachPartitionStatement and format_detach_partition_statement."""
@pytest.fixture
@@ -302,7 +302,7 @@ def test_finalize_requires_concurrently(self, dialect):
expr.to_sql()
-class TestPostgresAttachPartitionExpression:
+class TestAttachPartitionExpression:
"""Test PostgresAttachPartitionStatement and format_attach_partition_statement."""
@pytest.fixture
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_set_constraints_statement.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_set_constraints_statement.py
similarity index 93%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_set_constraints_statement.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_set_constraints_statement.py
index d7f236e7..4caef929 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_set_constraints_statement.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_set_constraints_statement.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_set_constraints_statement.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/statements/test_set_constraints_statement.py
"""The PostgreSQL ``SET CONSTRAINTS`` statement node (SQL generation only).
``defer_constraint`` used to spell the statement at the call site with an
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_adapters.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py
similarity index 61%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_adapters.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py
index 92105126..851d7a0d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_adapters.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_adapters.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_adapters.py
"""Offline adapter round-trip coverage for the PostgreSQL backend."""
import uuid
from decimal import Decimal
@@ -225,4 +225,125 @@ def test_roundtrip(self, vec):
v = [1.0, 2.5, 3.0]
s = vec.to_database(v, str)
assert isinstance(s, str)
- assert vec.from_database(s, list) == v
\ No newline at end of file
+ assert vec.from_database(s, list) == v
+class TestRangeAdapterRefusals:
+ """The custom range adapters' refusals, and the psycopg values they read.
+
+ These are the ``PostgresRange`` / ``PostgresMultirange`` wrapper adapters
+ (the ones a CUSTOM/BOTH range mode registers), not the neutral ones: their
+ wire form is PostgreSQL's literal, and their read path accepts psycopg's
+ native objects so a native-mode result can still be consumed.
+ """
+
+ def test_a_tuple_with_invalid_bounds_is_refused(self, range_a):
+ with pytest.raises(ValueError, match="Invalid bounds specification"):
+ range_a.to_database((1, 2, "(("), str)
+
+ def test_a_tuple_must_carry_two_or_three_elements(self, range_a):
+ with pytest.raises(ValueError, match="2 or 3 elements"):
+ range_a.to_database((1,), str)
+
+ def test_a_string_without_brackets_is_refused(self, range_a):
+ with pytest.raises(ValueError, match="Invalid range string format"):
+ range_a.to_database("1,2", str)
+
+ def test_a_value_that_is_no_range_is_refused_on_write(self, range_a):
+ with pytest.raises(TypeError, match="Cannot convert"):
+ range_a.to_database({"lower": 1}, str)
+
+ def test_a_psycopg_range_is_read(self, range_a):
+ from psycopg.types.range import Range as PsycopgRange
+
+ converted = range_a.from_database(PsycopgRange(1, 3, "[)"), str)
+
+ assert converted.to_postgres_string() == "[1,3)"
+
+ def test_a_value_that_is_no_range_is_refused_on_read(self, range_a):
+ with pytest.raises(TypeError, match="Cannot convert"):
+ range_a.from_database({"lower": 1}, str)
+
+ def test_a_multirange_literal_is_carried_through(self, multi_range):
+ assert multi_range.to_database("{[(1,3)]}", str) == "{[(1,3)]}"
+
+ def test_a_multirange_refuses_an_unknown_value_on_write(self, multi_range):
+ with pytest.raises(TypeError, match="Cannot convert"):
+ multi_range.to_database({"a": 1}, str)
+
+ def test_a_psycopg_multirange_is_read(self, multi_range):
+ from psycopg.types.multirange import Multirange as PsycopgMultirange
+ from psycopg.types.range import Range as PsycopgRange
+
+ converted = multi_range.from_database(PsycopgMultirange([PsycopgRange(1, 3, "[)")]), str)
+
+ assert len(converted.ranges) == 1
+ assert converted.ranges[0].to_postgres_string() == "[1,3)"
+
+ def test_a_multirange_refuses_a_value_it_cannot_read(self, multi_range):
+ with pytest.raises(TypeError, match="Cannot convert"):
+ multi_range.from_database({"a": 1}, str)
+
+
+class TestJSONBBatchPaths:
+ """The JSONB batch override: a text target re-serialises, everything else
+ is handed back decoded (with the object hook applied if one is configured)."""
+
+ def test_a_text_target_re_serialises_documents(self, jsonb):
+ assert jsonb.from_database_batch([{"a": 1}, [1], "raw"], str) == [
+ '{"a": 1}',
+ "[1]",
+ "raw",
+ ]
+
+ def test_absent_values_stay_absent_and_documents_decode(self, jsonb):
+ assert jsonb.from_database_batch([None, {"a": 1}], dict) == [None, {"a": 1}]
+
+
+class TestEnumAdapterOptionGuards:
+ """``enum_type`` / ``enum_class`` are declarations supplied by the field;
+ anything that is not the declared shape is ignored rather than trusted."""
+
+ def test_a_non_postgres_enum_type_does_not_validate(self, enum_a):
+ assert enum_a.to_database("ACTIVE", str, {"enum_type": object()}) == "ACTIVE"
+
+ def test_a_non_enum_class_does_not_rebuild(self, enum_a):
+ assert enum_a.from_database("ACTIVE", str, {"enum_class": object}) == "ACTIVE"
+
+class TestNetworkAddressBatches:
+ """Both directions in bulk, including the absent values."""
+
+ def test_batch_write_and_read(self, net_addr):
+ assert net_addr.to_database_batch(["192.168.1.1", None], str) == ["192.168.1.1", None]
+
+ parsed = net_addr.from_database_batch(["192.168.1.1", None], str)
+ assert str(parsed[0]) == "192.168.1.1"
+ assert parsed[1] is None
+
+ def test_scalar_absence(self, net_addr):
+ assert net_addr.from_database(None, str) is None
+
+
+class TestMacaddrRefusals:
+ """``MACADDR`` accepts text, bytes and the wrapper; everything else is
+ named in the refusal."""
+
+ def test_absence_passes_through(self, mac):
+ assert mac.to_database(None, str) is None
+ assert mac.from_database(None, str) is None
+
+ def test_bytes_are_accepted_on_write(self, mac):
+ assert mac.to_database(b"\x08\x00\x2b\x01\x02\x03", str) == "08:00:2b:01:02:03"
+
+ def test_an_unsupported_write_type_is_named(self, mac):
+ with pytest.raises(TypeError, match="Cannot convert"):
+ mac.to_database(42, str)
+
+ def test_an_unsupported_read_type_is_named(self, mac):
+ with pytest.raises(TypeError, match="Cannot convert"):
+ mac.from_database(42, str)
+
+ def test_both_batch_directions(self, mac):
+ text = "08:00:2b:01:02:03"
+ assert mac.to_database_batch([text, None], str) == [text, None]
+
+ parsed = mac.from_database_batch([text], str)
+ assert str(parsed[0]) == text
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_bitstring_types.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_bitstring_types.py
index 138c63cb..7c242757 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_bitstring_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_bitstring_types.py
"""
Unit tests for PostgreSQL bit string types.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py
new file mode 100644
index 00000000..46a67979
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py
@@ -0,0 +1,384 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_operations.py
+"""The server-specific operations on PostgreSQL's own column classes.
+
+Each operation is a thin façade over a function/operator node this backend
+already has. These tests assert the SQL it renders: adding an operation is a
+deliberate edit here, not a name that quietly promises more than the server
+can execute. Live round-trips are done against the configured scenarios; the
+render assertions are the part that needs no server.
+"""
+
+import pytest
+
+from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresAreaGeometryColumn,
+ PostgresGeometryColumn,
+)
+from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect
+
+
+@pytest.fixture
+def dialect():
+ return PostgresDialect(version=(16, 0, 0))
+
+
+@pytest.fixture
+def geometry(dialect):
+ return PostgresGeometryColumn(dialect, "g")
+
+
+# ---------------------------------------------------------------------------
+# Geometry: PostgreSQL's built-in geometric operators (no extension needed)
+# ---------------------------------------------------------------------------
+
+
+def test_distance_is_available_on_every_geometry(geometry):
+ """``<->`` answers on point, line, lseg, box, path, polygon and circle."""
+ expr = geometry.distance_to("(1,1)")
+ assert expr.to_sql() == ('"g" <-> %s', ("(1,1)",))
+
+
+@pytest.mark.parametrize(
+ "method, operator",
+ [
+ ("contains", "@>"),
+ ("contained_by", "<@"),
+ ("overlaps", "&&"),
+ ],
+)
+def test_area_geometry_operators_against_a_literal(dialect, method, operator):
+ column = PostgresAreaGeometryColumn(dialect, "g")
+ expr = getattr(column, method)("(1,1)")
+ assert expr.to_sql() == (f'"g" {operator} %s', ("(1,1)",))
+
+
+@pytest.mark.parametrize(
+ "method, operator",
+ [
+ ("distance_to", "<->"),
+ ("contains", "@>"),
+ ("contained_by", "<@"),
+ ("overlaps", "&&"),
+ ],
+)
+def test_geometry_operators_against_a_column(geometry, dialect, method, operator):
+ if method == "distance_to":
+ source, other = geometry, PostgresGeometryColumn(dialect, "h")
+ else:
+ source = PostgresAreaGeometryColumn(dialect, "g")
+ other = PostgresAreaGeometryColumn(dialect, "h")
+ expr = getattr(source, method)(other)
+ assert expr.to_sql() == (f'"g" {operator} "h"', ())
+
+
+def test_the_area_operators_are_not_offered_on_a_point(dialect):
+ """A point has no ``@>``; resolving Point must not hand out a false one."""
+ from rhosocial.activerecord.backend.impl.postgres.type_values import Box, Point
+
+ assert dialect.suggested_extra_column_types()[Point] is PostgresGeometryColumn
+ assert dialect.suggested_extra_column_types()[Box] is PostgresAreaGeometryColumn
+ assert not hasattr(PostgresGeometryColumn(dialect, "p"), "contains")
+ assert hasattr(PostgresAreaGeometryColumn(dialect, "b"), "contains")
+
+
+# ---------------------------------------------------------------------------
+# Bit strings: built-in bitwise operators and length/count functions
+# ---------------------------------------------------------------------------
+
+
+@pytest.fixture
+def bits(dialect):
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresBitStringColumn,
+ )
+
+ return PostgresBitStringColumn(dialect, "b")
+
+
+@pytest.mark.parametrize(
+ "method, operator",
+ [("bit_and", "&"), ("bit_or", "|"), ("bit_xor", "#")],
+)
+def test_bitwise_binary_operators(bits, dialect, method, operator):
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresBitStringColumn,
+ )
+
+ expr = getattr(bits, method)(PostgresBitStringColumn(dialect, "h"))
+ assert expr.to_sql() == (f'"b" {operator} "h"', ())
+
+
+def test_bitwise_not_and_length(bits):
+ assert bits.bit_not().to_sql() == ('~ "b"', ())
+ assert bits.bit_length().to_sql() == ('BIT_LENGTH("b")', ())
+ assert bits.bit_count().to_sql() == ('BIT_COUNT("b")', ())
+
+
+@pytest.mark.parametrize("method, operator", [("shift_left", "<<"), ("shift_right", ">>")])
+def test_bitwise_shifts(bits, method, operator):
+ assert getattr(bits, method)(2).to_sql() == (f'"b" {operator} %s', (2,))
+
+
+# ---------------------------------------------------------------------------
+# Ranges: native operators and functions, gated on the range capability
+# ---------------------------------------------------------------------------
+
+
+@pytest.fixture
+def ranges(dialect):
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresRangeColumn,
+ )
+
+ return PostgresRangeColumn(dialect, "r")
+
+
+@pytest.mark.parametrize(
+ "method, operator",
+ [("contains", "@>"), ("contained_by", "<@"), ("overlaps", "&&")],
+)
+def test_range_operators(ranges, method, operator):
+ assert getattr(ranges, method)(5).to_sql() == (f'"r" {operator} %s', (5,))
+
+
+@pytest.mark.parametrize(
+ "method, sql",
+ [("is_empty", 'ISEMPTY("r")'), ("lower", 'LOWER("r")'), ("upper", 'UPPER("r")')],
+)
+def test_range_functions(ranges, method, sql):
+ assert getattr(ranges, method)().to_sql() == (sql, ())
+
+
+@pytest.mark.parametrize("method", ["contains", "contained_by", "overlaps"])
+def test_range_operators_fail_on_a_server_without_them(method):
+ from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresRangeColumn,
+ )
+
+ old = PostgresDialect(version=(9, 1, 0))
+ column = PostgresRangeColumn(old, "r")
+ with pytest.raises(UnsupportedFeatureError, match="supports_range_operators"):
+ getattr(column, method)(5)
+
+
+@pytest.mark.parametrize("method", ["is_empty", "lower", "upper"])
+def test_range_functions_fail_on_a_server_without_them(method):
+ from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresRangeColumn,
+ )
+
+ old = PostgresDialect(version=(9, 1, 0))
+ column = PostgresRangeColumn(old, "r")
+ with pytest.raises(UnsupportedFeatureError, match="supports_range_functions"):
+ getattr(column, method)()
+
+
+# ---------------------------------------------------------------------------
+# Multiranges: the same operators on a native multirange column
+# ---------------------------------------------------------------------------
+
+
+@pytest.fixture
+def multiranges(dialect):
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresMultirangeColumn,
+ )
+
+ return PostgresMultirangeColumn(dialect, "m")
+
+
+@pytest.mark.parametrize(
+ "method, operator",
+ [("contains", "@>"), ("contained_by", "<@"), ("overlaps", "&&")],
+)
+def test_multirange_operators(multiranges, method, operator):
+ assert getattr(multiranges, method)(5).to_sql() == (f'"m" {operator} %s', (5,))
+
+
+@pytest.mark.parametrize("method", ["contains", "contained_by", "overlaps"])
+def test_multirange_operators_fail_without_the_capability(method):
+ from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresMultirangeColumn,
+ )
+
+ old = PostgresDialect(version=(9, 1, 0))
+ column = PostgresMultirangeColumn(old, "m")
+ with pytest.raises(UnsupportedFeatureError, match="supports_multirange"):
+ getattr(column, method)(5)
+
+
+# ---------------------------------------------------------------------------
+# Text search: the match operator and ranking function
+# ---------------------------------------------------------------------------
+
+
+@pytest.fixture
+def tsvector(dialect):
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresTextSearchColumn,
+ )
+
+ return PostgresTextSearchColumn(dialect, "tv")
+
+
+def test_text_search_matches(tsvector):
+ assert tsvector.matches("foo & bar").to_sql() == ('"tv" @@ %s', ("foo & bar",))
+
+
+def test_text_search_rank(tsvector):
+ assert tsvector.rank("foo").to_sql() == ('TS_RANK("tv", %s)', ("foo",))
+
+
+# ---------------------------------------------------------------------------
+# pgvector: distance operators, gated on the extension's capability
+# ---------------------------------------------------------------------------
+
+
+@pytest.fixture
+def vectors(dialect, monkeypatch):
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresVectorColumn,
+ )
+
+ monkeypatch.setattr(dialect, "supports_pgvector_similarity_search", lambda: True)
+ return PostgresVectorColumn(dialect, "v")
+
+
+@pytest.mark.parametrize(
+ "method, operator",
+ [
+ ("l2_distance", "<->"),
+ ("cosine_distance", "<=>"),
+ ("inner_product", "<#>"),
+ ],
+)
+def test_vector_distance_operators(vectors, method, operator):
+ sql, params = getattr(vectors, method)([1.0, 2.0]).to_sql()
+ assert sql == f'"v" {operator} %s::VECTOR(2)'
+ assert params == ("[1.0, 2.0]",)
+
+
+def test_vector_cosine_similarity(vectors):
+ sql, params = vectors.cosine_similarity([1.0, 2.0]).to_sql()
+ assert sql == '%s - ("v" <=> %s::VECTOR(2))'
+ assert params == (1, "[1.0, 2.0]")
+
+
+@pytest.mark.parametrize(
+ "method", ["l2_distance", "cosine_distance", "inner_product", "cosine_similarity"]
+)
+def test_vector_ops_fail_when_the_extension_is_not_available(dialect, method):
+ from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresVectorColumn,
+ )
+
+ column = PostgresVectorColumn(dialect, "v")
+ with pytest.raises(UnsupportedFeatureError, match="supports_pgvector_similarity_search"):
+ getattr(column, method)([1.0, 2.0])
+
+
+# ---------------------------------------------------------------------------
+# hstore: key existence, gated on the extension's operators
+# ---------------------------------------------------------------------------
+
+
+@pytest.fixture
+def hstore(dialect, monkeypatch):
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresHstoreColumn,
+ )
+
+ monkeypatch.setattr(dialect, "supports_hstore_operators", lambda: True)
+ return PostgresHstoreColumn(dialect, "h")
+
+
+@pytest.mark.parametrize("method, name", [("exist", "EXIST"), ("defined", "DEFINED")])
+def test_hstore_key_predicates(hstore, method, name):
+ sql, params = getattr(hstore, method)("k").to_sql()
+ assert sql == f'{name}("h", %s)'
+ assert params == ("k",)
+
+
+@pytest.mark.parametrize("method", ["exist", "defined"])
+def test_hstore_ops_fail_when_the_extension_is_not_available(dialect, method):
+ from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresHstoreColumn,
+ )
+
+ column = PostgresHstoreColumn(dialect, "h")
+ with pytest.raises(UnsupportedFeatureError, match="supports_hstore_operators"):
+ getattr(column, method)("k")
+
+
+# ---------------------------------------------------------------------------
+# PostGIS: ST_* on the wrapper's column class, gated on the extension
+# ---------------------------------------------------------------------------
+
+
+@pytest.fixture
+def postgis(dialect, monkeypatch):
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgisGeometryColumn,
+ )
+
+ monkeypatch.setattr(dialect, "supports_postgis_spatial_functions", lambda: True)
+ return PostgisGeometryColumn(dialect, "g")
+
+
+@pytest.mark.parametrize(
+ "method, name",
+ [
+ ("st_contains", "ST_CONTAINS"),
+ ("st_within", "ST_WITHIN"),
+ ("st_intersects", "ST_INTERSECTS"),
+ ("st_distance", "ST_DISTANCE"),
+ ],
+)
+def test_postgis_predicates_and_distance(postgis, dialect, method, name):
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgisGeometryColumn,
+ )
+
+ other = PostgisGeometryColumn(dialect, "h")
+ sql, params = getattr(postgis, method)(other).to_sql()
+ assert sql == f'{name}("g", "h")'
+ assert params == ()
+
+
+@pytest.mark.parametrize("method, name", [("st_area", "ST_AREA"), ("st_length", "ST_LENGTH")])
+def test_postgis_measurements(postgis, method, name):
+ assert getattr(postgis, method)().to_sql() == (f'{name}("g")', ())
+
+
+@pytest.mark.parametrize(
+ "method",
+ ["st_distance", "st_contains", "st_within", "st_intersects", "st_area", "st_length"],
+)
+def test_postgis_ops_fail_without_the_extension(dialect, method):
+ from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgisGeometryColumn,
+ )
+
+ column = PostgisGeometryColumn(dialect, "g")
+ args = () if method in ("st_area", "st_length") else (column,)
+ with pytest.raises(UnsupportedFeatureError, match="supports_postgis_spatial_functions"):
+ getattr(column, method)(*args)
+
+
+def test_the_postgis_wrapper_resolves_to_the_extension_class(dialect):
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgisGeometryColumn,
+ )
+ from rhosocial.activerecord.backend.impl.postgres.type_values import (
+ Point,
+ PostgresGeometry,
+ )
+
+ assert dialect.suggested_extra_column_types()[PostgresGeometry] is PostgisGeometryColumn
+ assert dialect.suggested_extra_column_types()[Point] is not PostgisGeometryColumn
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_column_type_suggestions.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py
similarity index 69%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_column_type_suggestions.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py
index 30de4844..18597231 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_column_type_suggestions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py
@@ -1,18 +1,19 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_column_type_suggestions.py
-"""PostgreSQL's column-type table, and the one entry it refuses.
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_column_type_suggestions.py
+"""PostgreSQL's column-type table, and where its own operations live.
The protocol's obligation on a backend is three things
(``backend/dialect/mixins/column_type.py``, the contract list in
``testsuite/feature/query/typed_column/column_helpers.COMMON_TYPES``):
-1. **Answer every entry.** All eighteen of the closed list, none of them
+1. **Answer every entry.** All twenty-four of the closed list, none of them
silently absent. A hole is a lie told to the model layer.
2. **Say so where this backend differs.** Here: native arrays for the four
sequence entries, where seven backends carry a JSON document.
3. **Refuse only what it truly cannot express** -- with ``None``, which reaches
- the caller as a resolution error rather than as a silent pick. Here: the one
- entry, ``datetime.timedelta``, whose native ``interval`` this server carries
- but whose operations no core column class names.
+ the caller as a resolution error rather than as a silent pick. Here:
+ nothing. ``timedelta`` names ``IntervalColumn`` and the six complex families
+ name their core classes, all of which promise only the surface every column
+ has.
No database is needed for any of it: the question is which class an annotation
resolves to, and the dialect already knows the server version.
@@ -105,15 +106,37 @@ def test_the_table_has_no_entry_beyond_the_protocol(dialect):
assert extra == set()
-def test_the_backend_declares_no_extra_python_types(dialect):
- """The framework's eighteen are the whole of what PostgreSQL answers for.
+def test_the_backend_declares_its_own_python_types_separately(dialect):
+ """The framework's twenty-four stay in their own table.
- Its *server* types beyond them (``interval``, ``xml``, the multirange
- family) are reached through their ``DataType`` spelling, not through a
- Python-annotation entry of their own: annotating a field with an
- unregistered custom class is what ``UseColumnType`` is for.
+ PostgreSQL models value classes beyond them (``Point``, ``PostgresXML``,
+ ``PostgresMoney``, the object identifiers), and the protocol reports those
+ through ``suggested_extra_column_types()`` so "the framework has an answer"
+ stays distinguishable from "this backend has one of its own".
"""
- assert dialect.suggested_extra_column_types() == {}
+ extra = dialect.suggested_extra_column_types()
+ assert set(extra) - set(COMMON_TYPES) == set(extra)
+ assert extra
+
+
+def test_every_extra_entry_answers_with_a_column_class(dialect):
+ """The same two-state rule as the common table: a class, never a hole."""
+ from rhosocial.activerecord.backend.expression.column_types import ColumnBase
+
+ extra = dialect.suggested_extra_column_types()
+ for entry, column_class in extra.items():
+ assert isinstance(column_class, type), entry
+ assert issubclass(column_class, ColumnBase), entry
+
+
+def test_every_extra_class_builds_and_renders(dialect):
+ """An extras cell is only real if the column it names can be built."""
+ from rhosocial.activerecord.backend.expression.column_types import ColumnBase
+
+ for column_class in dialect.suggested_extra_column_types().values():
+ column = column_class(dialect, "c")
+ assert isinstance(column, ColumnBase)
+ assert column.to_sql() == ('"c"', ())
def test_the_table_agrees_with_the_module_level_constant(dialect):
@@ -225,41 +248,99 @@ class Mood(enum.Enum):
assert resolve(dialect, Mood) is StringColumn
-def test_the_interval_entry_is_refused_until_core_grows_an_interval_column(dialect):
- """**The one deliberate refusal**, and the reasons it is not ``None``'s
- opposite either.
+def test_the_interval_entry_names_the_core_interval_class(dialect):
+ """A duration is a duration, not a number of its own family.
PostgreSQL has a real ``interval`` type where eight backends have no answer
- at all (the protocol's own survey, §1), so there is no "this backend cannot
- carry a duration" story here: psycopg binds a ``timedelta`` and reads one
- back, and the ``DataType`` layer spells the storage
- (``format_data_type_interval``). What no core column class offers is the
- *operation* surface -- ``justify_hours``, ``EXTRACT(... FROM interval)``,
- the field qualifiers -- and naming a number class would offer
- transcendentals the server refuses: ``sqrt(interval '1 day')`` is an error.
-
- ``NumericColumn`` was the answer the last version of this table gave, and
- it was a *declared* over-claim kept visible only because ``FloatColumn``
- and ``DecimalColumn`` existed to differ from. With the numeric family merged
- into one class that visibility is gone, so the honest answer under the
- rebuilt protocol is ``None``: the gap reaches the model layer as a
- resolution error naming the way out, instead of as a number class that
- cannot keep its promise.
-
- When core grows an ``IntervalColumn``, this entry is where it goes -- so
- this test fails then, on purpose.
+ at all (the protocol's own survey, §1): psycopg binds a ``timedelta`` and
+ reads one back, and the ``DataType`` layer spells the storage
+ (``format_data_type_interval``).
+
+ The class matters because ``interval`` refuses the numeric operations --
+ ``sqrt(interval '1 day')`` is an error -- and offers operations of its own
+ (``justify_hours``, ``EXTRACT(... FROM interval)``, field qualifiers).
+ ``IntervalColumn`` names the value without claiming either side: the
+ numeric surface is not offered, and PostgreSQL's own operations belong to
+ a PostgreSQL-named subclass.
"""
- assert dialect.suggested_column_types()[datetime.timedelta] is None
+ from rhosocial.activerecord.backend.expression.column_types import IntervalColumn
+ from rhosocial.activerecord.backend.impl.dummy.column_type import DUMMY_COLUMN_TYPES
- with pytest.raises(ColumnTypeResolutionError) as excinfo:
- resolve(dialect, datetime.timedelta)
- assert "UseColumnType" in str(excinfo.value)
+ assert dialect.suggested_column_types()[datetime.timedelta] is IntervalColumn
+ assert resolve(dialect, datetime.timedelta) is IntervalColumn
+ # Both dialects now answer it, so there is no gap left to refuse.
+ assert DUMMY_COLUMN_TYPES[datetime.timedelta] is IntervalColumn
- # The refusal is this table's, not the framework's: the generic numeric
- # answer is what the portable baseline would have said.
- from rhosocial.activerecord.backend.impl.dummy.column_type import DUMMY_COLUMN_TYPES
- assert DUMMY_COLUMN_TYPES[datetime.timedelta] is NumericColumn
+def test_the_complex_families_name_the_core_column_classes(dialect):
+ """Six families, one answer each -- and no operation beyond the column surface.
+
+ The classes carry alias, null tests, casting and collation only. PostGIS,
+ the range operators and bit arithmetic are this server's own spellings and
+ belong to backend-named subclasses, which the extra table will carry.
+ """
+ from rhosocial.activerecord.backend.adapters import (
+ BitString,
+ Geometry,
+ MacAddress,
+ Multirange,
+ Range,
+ Vector,
+ )
+ from rhosocial.activerecord.backend.expression.column_types import (
+ BitStringColumn,
+ GeometryColumn,
+ MacAddressColumn,
+ MultirangeColumn,
+ RangeColumn,
+ VectorColumn,
+ )
+
+ expected = {
+ Geometry: GeometryColumn,
+ Vector: VectorColumn,
+ BitString: BitStringColumn,
+ Range: RangeColumn,
+ Multirange: MultirangeColumn,
+ MacAddress: MacAddressColumn,
+ }
+ for entry, klass in expected.items():
+ assert dialect.suggested_column_types()[entry] is klass
+ assert resolve(dialect, entry) is klass
+
+
+def test_the_complex_families_are_named_by_this_backend(dialect):
+ """PostGIS, range and vector spellings belong to PostgreSQL-named classes.
+
+ The core classes stay the shared floor; the names that carry this server's
+ own operations live in ``impl.postgres.column_types`` and are reachable
+ with ``UseColumnType``.
+ """
+ from rhosocial.activerecord.backend.impl.postgres import column_types as pg
+
+ for column_class in dialect.suggested_extra_column_types().values():
+ assert column_class.__module__ == pg.__name__
+ assert column_class.__name__.startswith(("Postgres", "Postgis"))
+
+
+def test_a_postgres_named_class_is_usable_through_use_column_type(dialect):
+ """A field can declare the stronger surface explicitly.
+
+ ``Point`` on its own resolves to the column class the extras table records;
+ a ``UseColumnType`` declaration overrides that with any class whose values
+ the same annotation can hold.
+ """
+ from rhosocial.activerecord.base.fields import UseColumnType
+ from rhosocial.activerecord.backend.impl.postgres.column_types import (
+ PostgresGeometryColumn,
+ )
+ from rhosocial.activerecord.backend.impl.postgres.type_values import Point
+
+ assert resolve(dialect, Point) is PostgresGeometryColumn
+ assert (
+ resolve_column_class(dialect, Point, UseColumnType(PostgresGeometryColumn))
+ is PostgresGeometryColumn
+ )
# ---------------------------------------------------------------------------
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_core_type_mappings.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_core_type_mappings.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_core_type_mappings.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_core_type_mappings.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_data_type_formatting.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_data_type_formatting.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_data_type_formatting.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_data_type_formatting.py
index 90e19354..6291775e 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_data_type_formatting.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_data_type_formatting.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_data_type_formatting.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_data_type_formatting.py
"""Pure-function tests for PostgreSQL DataType formatting and parsing.
These tests exercise ``PostgresTypeFormatSupportMixin`` (the
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_enum_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_enum_types.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_enum_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_enum_types.py
index 7818c75c..9f3ea826 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_enum_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_enum_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_enum_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_enum_types.py
"""Unit tests for PostgreSQL ENUM types.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_expression_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_expression_types.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_expression_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_expression_types.py
index 70bbaa5b..1c776605 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_expression_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_expression_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_expression_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_expression_types.py
"""Tests for PostgreSQL-specific DataType subclasses (pure, no DB).
Covers the base classes each PostgreSQL type is anchored to, equality and
@@ -36,7 +36,7 @@
)
-class TestPostgresTypesAreAnchoredToCoreConcepts:
+class TestTypesAreAnchoredToCoreConcepts:
"""A backend type that says "I am this concept" must be that concept.
Without this, ``isinstance(col.data_type, IntegerType)`` is false for a
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_geometry_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_geometry_types.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_geometry_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_geometry_types.py
index 44a7a457..d20bf2cf 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_geometry_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_geometry_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_geometry_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_geometry_types.py
"""
Unit tests for PostgreSQL geometry types.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_hstore_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_hstore_types.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_hstore_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_hstore_types.py
index fbe3c3f5..bac6c186 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_hstore_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_hstore_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_hstore_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_hstore_types.py
"""Unit tests for PostgreSQL hstore type.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_jsonpath_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_jsonpath_types.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_jsonpath_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_jsonpath_types.py
index 94551e3a..00b5aceb 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_jsonpath_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_jsonpath_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_jsonpath_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_jsonpath_types.py
"""
Unit tests for PostgreSQL jsonpath type support.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_literal_values.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_literal_values.py
index bef74dd9..ba0f4be9 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_literal_values.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_literal_values.py
"""Value literals on PostgreSQL: binding and the three tier-2 spellings.
Core collapsed the twelve typed-value classes into one ``Literal`` node
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_lsn_types.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_lsn_types.py
index 9865183d..f3832b8b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_lsn_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_lsn_types.py
"""Unit tests for PostgreSQL pg_lsn type.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_macaddr8_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_macaddr8_types.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_macaddr8_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_macaddr8_types.py
index f32ab682..cbbe4e92 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_macaddr8_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_macaddr8_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_macaddr8_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_macaddr8_types.py
"""Unit tests for PostgreSQL MACADDR8 type.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_money_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_money_types.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_money_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_money_types.py
index be49b29a..ad00a6ad 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_money_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_money_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_money_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_money_types.py
"""Unit tests for PostgreSQL MONEY type.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_oid_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_oid_types.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_oid_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_oid_types.py
index f1bc7d10..b5e9de96 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_oid_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_oid_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_oid_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_oid_types.py
"""Unit tests for PostgreSQL OID types.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pgvector_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_pgvector_types.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pgvector_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_pgvector_types.py
index 4af6d2e0..ce65a5fe 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pgvector_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_pgvector_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pgvector_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_pgvector_types.py
"""Unit tests for PostgreSQL pgvector type.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgis_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgis_types.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgis_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgis_types.py
index eb14ce0e..a9bf03e1 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgis_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgis_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgis_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgis_types.py
"""Unit tests for PostgreSQL PostGIS geometry type.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgres_data_type_protocol_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgres_data_type_protocol_contract.py
new file mode 100644
index 00000000..308d622a
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_postgres_data_type_protocol_contract.py
@@ -0,0 +1,112 @@
+# tests/.../test_postgres_data_type_protocol_contract.py
+"""This backend's own data-type protocol contract (D9 + substitutes).
+
+Backend functionality is tested here, in this repository: nothing in this file
+belongs in the shared testsuite. Core concepts are discovered, not listed, so a
+concept added to core later cannot slip past a stale list.
+"""
+
+import pytest
+
+from rhosocial.activerecord.backend.expression.types import DataType
+from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect
+
+#: Versions spanning the gates this backend declares.
+VERSIONS = [(9, 1, 0), (16, 0, 0)]
+
+
+def _dialect(version):
+ return PostgresDialect(version=version)
+
+
+def _core_concepts():
+ seen = set()
+ stack = [DataType]
+ while stack:
+ klass = stack.pop()
+ if klass in seen:
+ continue
+ seen.add(klass)
+ stack.extend(klass.__subclasses__())
+ return sorted(
+ {
+ klass.name
+ for klass in seen
+ if klass is not DataType
+ and klass.__module__.startswith("rhosocial.activerecord.backend.expression.types")
+ and klass.name
+ }
+ )
+
+
+def _renderable_substitute(dialect, klass):
+ """Minimum valid construction for substitutes that carry parameters.
+
+ These three cannot be built with no arguments; the values are chosen only
+ to exercise rendering, not to stand for any real column.
+ """
+ if klass.__name__ == "PostgresEnumColumnType":
+ return klass(dialect, type_name="status", values=["a", "b"])
+ if klass.__name__ == "MySQLVarBinaryType":
+ return klass(dialect, length=16)
+ if klass.__name__ == "CustomType":
+ return klass(dialect, raw="ARRAY")
+ return klass(dialect)
+
+
+@pytest.mark.parametrize("version", VERSIONS)
+def test_every_core_concept_is_declared(version):
+ """D9: rendered or substituted -- silence is not an answer."""
+ dialect = _dialect(version)
+ supported = set(dialect.supports_data_types())
+ substitutes = dialect.substitute_data_types()
+ undeclared = [
+ name for name in _core_concepts() if name not in supported and name not in substitutes
+ ]
+ assert not undeclared, f"{version}: {undeclared} are neither rendered nor substituted"
+
+
+@pytest.mark.parametrize("version", VERSIONS)
+def test_substitutes_are_disjoint_and_renderable(version):
+ """A substitute must be a DataType class this dialect really writes."""
+ dialect = _dialect(version)
+ supported = set(dialect.supports_data_types())
+ substitutes = dialect.substitute_data_types()
+ assert not supported & set(substitutes)
+
+ for key, klass in substitutes.items():
+ assert isinstance(klass, type) and issubclass(klass, DataType), key
+ sql, _ = dialect.format_data_type(_renderable_substitute(dialect, klass))
+ assert sql, f"{version}: {key} -> {klass.__name__} renders nothing"
+
+
+@pytest.mark.parametrize("version", VERSIONS)
+def test_formatter_and_probe_families_are_one_to_one(version):
+ """D10: a formatter has a probe, and an absent answer is an explicit probe.
+
+ ``supports_data_types()`` may omit a version-gated concept; that is an
+ answer only when its probe says False. A formatter with no probe at all,
+ or a supported key with no formatter, breaks the 1:1 discipline.
+ """
+ dialect = _dialect(version)
+ format_names = {
+ member[len("format_data_type_") :]
+ for member in dir(dialect)
+ if member.startswith("format_data_type_")
+ }
+ probe_names = {
+ member[len("supports_data_type_") :]
+ for member in dir(dialect)
+ if member.startswith("supports_data_type_")
+ }
+ assert format_names, "the dialect must implement a format_data_type_* family"
+ assert format_names == probe_names, (
+ f"format-only: {sorted(format_names - probe_names)}, "
+ f"probe-only: {sorted(probe_names - format_names)}"
+ )
+
+ supported = set(dialect.supports_data_types())
+ assert supported <= format_names
+ for name in sorted(format_names - supported):
+ probe = getattr(dialect, f"supports_data_type_{name}")
+ assert probe() is False, f"{name} has a formatter but no False probe explains its absence"
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_range_types.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_range_types.py
index 79a4464d..be187cae 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_range_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_range_types.py
"""
Unit tests for PostgreSQL range types.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_textsearch_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_textsearch_types.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_textsearch_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_textsearch_types.py
index 9bd78fef..ba4247bf 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_textsearch_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_textsearch_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_textsearch_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_textsearch_types.py
"""
Unit tests for PostgreSQL text search types.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_type_casting.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_casting.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_type_casting.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_casting.py
index 54685e9c..3f418509 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_type_casting.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_casting.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_type_casting.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_casting.py
"""Unit tests for PostgreSQL type casting functionality.
Tests for:
@@ -137,7 +137,7 @@ def test_cast_expression_supports_arithmetic(self):
assert params == (1.1,)
-class TestPostgresDialectFormatCast:
+class TestDialectFormatCast:
"""Tests for PostgreSQL dialect format_cast_expression method."""
def setup_method(self):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_type_compatibility.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_compatibility.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_type_compatibility.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_compatibility.py
index a784aaf8..dfbe69de 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_type_compatibility.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_compatibility.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_type_compatibility.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_compatibility.py
"""PostgreSQL type compatibility tests.
This module tests the extended type compatibility checking
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_postgres_type_protocol.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_protocol.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_postgres_type_protocol.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_protocol.py
index 38188f8d..2a754de1 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_postgres_type_protocol.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_protocol.py
@@ -1,10 +1,10 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/types/test_postgres_type_protocol.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_type_protocol.py
"""Tests for the formalised core DataType protocol conformance.
Verifies:
- format family == supports family (1:1 correspondence)
- supports_data_types() includes postgres_* + core entries
-- suggested_data_types(): values are DataType classes; keys disjoint from supported
+- substitute_data_types(): values are DataType classes; keys disjoint from supported
- dialect_options forwarding and equality
"""
@@ -201,32 +201,32 @@ def test_supports_data_types_values_are_data_type_classes(dialect):
# ---------------------------------------------------------------------------
-# W4: suggested_data_types()
+# W4: substitute_data_types()
# ---------------------------------------------------------------------------
-def test_suggested_data_types_returns_dict(dialect):
- result = dialect.suggested_data_types()
+def test_substitute_data_types_returns_dict(dialect):
+ result = dialect.substitute_data_types()
assert isinstance(result, dict)
-def test_suggested_data_types_values_are_classes(dialect):
- result = dialect.suggested_data_types()
+def test_substitute_data_types_values_are_classes(dialect):
+ result = dialect.substitute_data_types()
for name, cls in result.items():
assert isinstance(cls, type), (
- f"suggested_data_types()[{name!r}] is not a class: {cls!r}"
+ f"substitute_data_types()[{name!r}] is not a class: {cls!r}"
)
assert issubclass(cls, DataType), (
- f"suggested_data_types()[{name!r}] = {cls.__name__} is not a DataType subclass"
+ f"substitute_data_types()[{name!r}] = {cls.__name__} is not a DataType subclass"
)
-def test_suggested_data_types_keys_disjoint_from_supported(dialect):
+def test_substitute_data_types_keys_disjoint_from_supported(dialect):
supported = set(dialect.supports_data_types().keys())
- suggested = set(dialect.suggested_data_types().keys())
+ suggested = set(dialect.substitute_data_types().keys())
overlap = supported & suggested
assert not overlap, (
- f"suggested_data_types() keys overlap with supports_data_types(): {overlap}"
+ f"substitute_data_types() keys overlap with supports_data_types(): {overlap}"
)
@@ -678,7 +678,7 @@ def registry(self):
import importlib.util
from pathlib import Path
- path = Path(__file__).resolve().parent.parent / (
+ path = Path(__file__).resolve().parent.parent / "expression" / (
"test_expression_roundtrip_all.py"
)
spec = importlib.util.spec_from_file_location("postgres_rt_registry", path)
@@ -689,7 +689,7 @@ def registry(self):
return registry
def test_every_rendered_type_parses_back_coherently(self, dialect, registry):
- from expression_roundtrip_harness import (
+ from rhosocial.activerecord_postgres_test.feature.backend.construct.expression_roundtrip_harness import (
parse_roundtrip_failures,
)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_type_adapter.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_type_adapter.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_type_adapter.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_type_adapter.py
index 1b2bd676..f540d19d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_type_adapter.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_type_adapter.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_type_adapter.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_type_adapter.py
"""Unit tests for PostgreSQL UUID type adapter.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_values.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_values.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_values.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_values.py
index dc8df4ed..9d376518 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_values.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_values.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_uuid_values.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_uuid_values.py
"""UUID value expressions on PostgreSQL.
PostgreSQL has two routes to a generated UUID — the built-in
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_xml_types.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_xml_types.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_xml_types.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_xml_types.py
index 66511538..b376e140 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_xml_types.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_xml_types.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_xml_types.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/construct/types/test_xml_types.py
"""Unit tests for PostgreSQL XML type.
Tests for:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/examples_compile_test.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/core/examples_compile_test.py
similarity index 88%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/examples_compile_test.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/core/examples_compile_test.py
index 837afc53..ac2d13bf 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/examples_compile_test.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/core/examples_compile_test.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/examples_compile_test.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/core/examples_compile_test.py
"""Guard against syntax/API drift in the runnable examples.
Every script under ``examples/`` must at least compile. This test runs
@@ -9,10 +9,8 @@
import py_compile
from pathlib import Path
-import pytest
-
EXAMPLES_ROOT = (
- Path(__file__).resolve().parents[5]
+ Path(__file__).resolve().parents[6]
/ "src" / "rhosocial" / "activerecord" / "backend" / "impl" / "postgres"
/ "examples"
)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_support.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_async_support.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_support.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_async_support.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py
new file mode 100644
index 00000000..88c80550
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py
@@ -0,0 +1,74 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/core/test_get_type_adapters.py
+"""The backend's adapter inventory is a catalogue, not a recommendation.
+
+PostgreSQL-specific adapters are registered during construction and never need
+a server, so the whole file runs without a database. What is pinned here is the
+shape of ``get_type_adapters()``: it implements the core protocol, it lists
+classes once each, and it answers in the same order every time.
+"""
+
+import pytest
+
+from rhosocial.activerecord.backend.impl.postgres.backend import (
+ AsyncPostgresBackend,
+ PostgresBackend,
+)
+from rhosocial.activerecord.backend.type_adapter import TypeAdapterCatalogProtocol
+
+
+def _backend_class_key(adapter):
+ adapter_class = type(adapter)
+ return (adapter_class.__module__, adapter_class.__qualname__)
+
+
+@pytest.fixture(params=[PostgresBackend, AsyncPostgresBackend])
+def backend(request):
+ """A constructed backend: neither branch opens a connection."""
+ return request.param(database="adapter_inventory_unit")
+
+
+class TestGetTypeAdapters:
+ def test_implements_the_catalogue_protocol(self, backend):
+ assert isinstance(backend, TypeAdapterCatalogProtocol)
+
+ def test_inventory_is_not_empty(self, backend):
+ assert backend.get_type_adapters()
+
+ def test_each_adapter_class_appears_once(self, backend):
+ keys = [_backend_class_key(adapter) for adapter in backend.get_type_adapters()]
+ assert len(keys) == len(set(keys))
+
+ def test_order_is_deterministic_and_sorted_by_class(self, backend):
+ first = [_backend_class_key(adapter) for adapter in backend.get_type_adapters()]
+ second = [_backend_class_key(adapter) for adapter in backend.get_type_adapters()]
+ assert first == second
+ assert first == sorted(first)
+
+ def test_a_new_list_is_returned_on_each_call(self, backend):
+ first = backend.get_type_adapters()
+ second = backend.get_type_adapters()
+ assert first is not second
+ assert first == second
+
+ def test_default_adapter_suggestions_are_still_provided(self, backend):
+ suggestions = backend.get_default_adapter_suggestions()
+ assert isinstance(suggestions, dict)
+ assert suggestions
+
+def test_every_extra_value_class_has_an_adapter(backend):
+ """An extra suggestion is only usable if the value can also be adapted.
+
+ The suggestion table says what column a bare field is declared as; the
+ adapter registry says whether that field can be written and read back. An
+ entry without an adapter would build a column nothing can carry a value
+ into, which is worse than refusing the type outright.
+ """
+ extras = backend.dialect.suggested_extra_data_types()
+ registered = {py for (py, _db) in backend.adapter_registry.get_all_adapters()}
+
+ missing = [entry.__name__ for entry in extras if entry not in registered]
+ assert missing == [], (
+ f"{type(backend).__name__} suggests a declaration for {missing} but has no "
+ f"adapter registered for those value classes"
+ )
+
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/errors/test_error_taxonomy_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/errors/test_error_taxonomy_contract.py
deleted file mode 100644
index 66d3dab7..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/errors/test_error_taxonomy_contract.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/errors/test_error_taxonomy_contract.py
-"""Run the shared error taxonomy contract against this backend.
-
-The testsuite module imports only the core taxonomy, so no PostgreSQL
-connection is needed. Importing the module is the whole wrapper: pytest
-collects the classes and methods it defines.
-"""
-
-from rhosocial.activerecord.testsuite.feature.backend.errors.test_error_taxonomy import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/conftest.py
similarity index 93%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/conftest.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/conftest.py
index d0e85429..293158be 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/conftest.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/conftest.py
@@ -1,9 +1,10 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/conftest.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/conftest.py
"""
Test fixtures for PostgreSQL named connection tests.
"""
import types
from unittest.mock import MagicMock
+
import pytest
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/example_connections.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/example_connections.py
similarity index 92%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/example_connections.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/example_connections.py
index 029ebd28..1b55ed8e 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/example_connections.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/example_connections.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/example_connections.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/example_connections.py
"""
Example named connections for PostgreSQL testing.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli.py
index 4c685b42..98b6d593 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli.py
"""
Tests for PostgreSQL backend CLI.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli_connection_args.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_connection_args.py
similarity index 93%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli_connection_args.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_connection_args.py
index fccee4ec..cb5f50d1 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli_connection_args.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_connection_args.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_cli_connection_args.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_connection_args.py
"""Offline tests for ``resolve_connection_config_from_args`` (SSL mapping, etc.)."""
import argparse
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_live.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_live.py
new file mode 100644
index 00000000..4fb551c6
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_live.py
@@ -0,0 +1,143 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_cli_live.py
+"""End-to-end PostgreSQL CLI tests against a real server.
+
+The offline suites under ``feature/backend/construct/cli`` and the sibling files
+in this directory prove argument wiring and dispatch with fakes. These drive
+``main()`` with the connection parameters of the live ``postgres_backend_single``
+fixture, so a passing test means the command connected, ran, and rendered a
+machine-readable answer -- not merely that the parser accepted the argv.
+
+When no PostgreSQL scenario is configured the fixture skips, so these cases are
+inert on a machine without a server and run for real in CI.
+"""
+
+import json
+
+import pytest
+
+from rhosocial.activerecord.backend.impl.postgres.__main__ import main
+
+#: ``PostgresConnectionConfig.sslmode`` (libpq spelling) -> the CLI's --ssl choice.
+_SSL_TO_CLI = {
+ "disable": "disabled",
+ "allow": "auto",
+ "prefer": "auto",
+ "require": "require",
+ "verify-ca": "verify-ca",
+ "verify-full": "verify-full",
+}
+
+
+def _connection_argv(config):
+ """Build connection flags for the scenario the fixture connected with."""
+ argv = [
+ "--host",
+ config.host,
+ "--port",
+ str(config.port),
+ "--database",
+ config.database,
+ "--user",
+ config.username,
+ "--password",
+ config.password or "",
+ ]
+ sslmode = getattr(config, "sslmode", None)
+ if sslmode:
+ argv += ["--ssl", _SSL_TO_CLI.get(sslmode, "auto")]
+ return argv
+
+
+@pytest.fixture
+def probed_backend(postgres_backend_single):
+ """Give the catalogue listings one known table to find."""
+ backend = postgres_backend_single
+ backend.execute('DROP TABLE IF EXISTS "cli_live_probe"')
+ backend.execute('CREATE TABLE "cli_live_probe" (id INTEGER PRIMARY KEY)')
+ yield backend
+ backend.execute('DROP TABLE IF EXISTS "cli_live_probe"')
+
+
+class TestLiveCli:
+ """Each subcommand returns non-empty, expected JSON from the live server."""
+
+ def test_info(self, postgres_backend_single, capsys):
+ main(["info", "-o", "json", *_connection_argv(postgres_backend_single.config)])
+ payload = json.loads(capsys.readouterr().out)
+ assert isinstance(payload, dict) and payload
+ assert {"database", "features", "protocols"} <= payload.keys()
+ assert payload["database"]["type"] == "postgresql"
+ assert payload["database"]["connected"] is True
+ assert payload["database"]["version"]
+
+ def test_query(self, postgres_backend_single, capsys):
+ main(
+ [
+ "query",
+ "-o",
+ "json",
+ *_connection_argv(postgres_backend_single.config),
+ "SELECT 1 AS n",
+ ]
+ )
+ payload = json.loads(capsys.readouterr().out)
+ assert isinstance(payload, list) and len(payload) == 1
+ assert int(payload[0]["n"]) == 1
+
+ def test_introspect_tables(self, probed_backend, capsys):
+ main(
+ [
+ "introspect",
+ "tables",
+ "-o",
+ "json",
+ *_connection_argv(probed_backend.config),
+ ]
+ )
+ payload = json.loads(capsys.readouterr().out)
+ assert isinstance(payload, list) and payload
+ assert "cli_live_probe" in [row["name"] for row in payload]
+
+ def test_introspect_database(self, probed_backend, capsys):
+ main(
+ [
+ "introspect",
+ "database",
+ "-o",
+ "json",
+ *_connection_argv(probed_backend.config),
+ ]
+ )
+ payload = json.loads(capsys.readouterr().out)
+ assert isinstance(payload, list) and payload
+ assert {"name", "version", "vendor"} <= payload[0].keys()
+ assert payload[0]["name"]
+
+ def test_status_all(self, postgres_backend_single, capsys):
+ main(
+ [
+ "status",
+ "all",
+ "-o",
+ "json",
+ *_connection_argv(postgres_backend_single.config),
+ ]
+ )
+ payload = json.loads(capsys.readouterr().out)
+ assert isinstance(payload, dict) and payload
+ assert {"server_version", "server_vendor", "configuration"} <= payload.keys()
+ assert payload["server_version"]
+
+ def test_status_config(self, postgres_backend_single, capsys):
+ main(
+ [
+ "status",
+ "config",
+ "-o",
+ "json",
+ *_connection_argv(postgres_backend_single.config),
+ ]
+ )
+ payload = json.loads(capsys.readouterr().out)
+ assert isinstance(payload, list) and payload
+ assert all(row.get("name") for row in payload)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_named_connection_cli.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_named_connection_cli.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_named_connection_cli.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_named_connection_cli.py
index 3ae58da7..85c7be36 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_named_connection_cli.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_named_connection_cli.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_cli.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_named_connection_cli.py
"""
Tests for PostgreSQL CLI parameter resolution.
@@ -35,7 +35,7 @@ def __init__(
self.connection_params = connection_params or []
-class TestPostgresConnectionConfigPriority:
+class TestConnectionConfigPriority:
"""Test connection config resolution priority for PostgreSQL CLI."""
def test_default_values(self):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_resolver.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_resolver.py
similarity index 92%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_resolver.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_resolver.py
index 8b5f912d..e4a06244 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_resolver.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_resolver.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/named_connection/test_resolver.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/cli/test_resolver.py
"""
Tests for PostgreSQL named connection resolver.
@@ -27,7 +27,7 @@
from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig
-class TestPostgresNamedConnectionResolverUnit:
+class TestNamedConnectionResolverUnit:
"""Unit tests for NamedConnectionResolver with PostgreSQL backend."""
def test_resolve_postgres_config(self):
@@ -117,13 +117,13 @@ def prod_db():
assert "prod_db" in names
-class TestPostgresNamedConnectionsIntegration:
+class TestNamedConnectionsIntegration:
"""Integration tests using actual example_connections module."""
def test_postgres_18_connection(self):
"""Test resolving the postgres_18 named connection."""
config = resolve_named_connection(
- "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections.postgres_18",
+ "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections.postgres_18",
{},
)
assert isinstance(config, PostgresConnectionConfig)
@@ -135,7 +135,7 @@ def test_postgres_18_connection(self):
def test_postgres_18_with_custom_database(self):
"""Test resolving postgres_18 with custom database parameter."""
config = resolve_named_connection(
- "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections.postgres_18",
+ "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections.postgres_18",
{"database": "my_app"},
)
assert isinstance(config, PostgresConnectionConfig)
@@ -144,7 +144,7 @@ def test_postgres_18_with_custom_database(self):
def test_postgres_18_with_pool(self):
"""Test resolving postgres_18_with_pool named connection."""
config = resolve_named_connection(
- "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections.postgres_18_with_pool",
+ "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections.postgres_18_with_pool",
{},
)
assert isinstance(config, PostgresConnectionConfig)
@@ -153,7 +153,7 @@ def test_postgres_18_with_pool(self):
def test_postgres_18_with_custom_pool_size(self):
"""Test resolving postgres_18_with_pool with custom pool_size."""
config = resolve_named_connection(
- "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections.postgres_18_with_pool",
+ "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections.postgres_18_with_pool",
{"pool_size": "10"},
)
assert isinstance(config, PostgresConnectionConfig)
@@ -162,7 +162,7 @@ def test_postgres_18_with_custom_pool_size(self):
def test_postgres_18_readonly(self):
"""Test resolving postgres_18_readonly named connection."""
config = resolve_named_connection(
- "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections.postgres_18_readonly",
+ "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections.postgres_18_readonly",
{},
)
assert isinstance(config, PostgresConnectionConfig)
@@ -171,7 +171,7 @@ def test_postgres_18_readonly(self):
def test_list_example_connections(self):
"""Test listing connections in example_connections module."""
connections = list_named_connections_in_module(
- "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections"
+ "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections"
)
names = [c["name"] for c in connections]
assert "postgres_18" in names
@@ -181,7 +181,7 @@ def test_list_example_connections(self):
def test_describe_postgres_18(self):
"""Test describing the postgres_18 connection."""
resolver = NamedConnectionResolver(
- "rhosocial.activerecord_postgres_test.feature.backend.named_connection.example_connections.postgres_18"
+ "rhosocial.activerecord_postgres_test.feature.backend.execute.cli.example_connections.postgres_18"
).load()
info = resolver.describe()
assert info["is_class"] is False
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_advisory_lock.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_advisory_lock.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_advisory_lock.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_advisory_lock.py
index 9533d015..4a6d5aa3 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_advisory_lock.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_advisory_lock.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_advisory_lock.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_advisory_lock.py
"""
PostgreSQL advisory lock tests.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_concurrency_protocol.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_concurrency_protocol.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_concurrency_protocol.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_concurrency_protocol.py
index 64511089..5fa7d124 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_concurrency_protocol.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_concurrency_protocol.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_concurrency_protocol.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/concurrency/test_concurrency_protocol.py
"""
Test for ConcurrencyAware protocol implementation in PostgreSQL backend.
@@ -10,7 +10,7 @@
from rhosocial.activerecord.backend.protocols import ConcurrencyAware, ConcurrencyHint
-class TestPostgresConcurrencyAware:
+class TestConcurrencyAware:
"""Test ConcurrencyAware protocol implementation for PostgreSQL backend."""
def test_postgres_backend_implements_protocol(self, postgres_backend_single):
@@ -41,7 +41,7 @@ def test_postgres_concurrency_hint_returns_hint_object(self, postgres_backend_si
assert isinstance(hint, ConcurrencyHint)
-class TestAsyncPostgresConcurrencyAware:
+class TestAsyncConcurrencyAware:
"""Test ConcurrencyAware protocol implementation for async PostgreSQL backend."""
@pytest.mark.asyncio
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py
new file mode 100644
index 00000000..4b391c4b
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py
@@ -0,0 +1,21 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/conftest.py
+"""Group the backend-owned execute tests by their directory-owned database.
+
+The root ``backend/conftest.py`` declares ``parallel=False`` so pure-render
+scopes stay ungrouped. Every directory under ``execute/`` however drives a
+live server and owns its own database (named from the directory path), so its
+tests must stay on one worker per scenario. Declaring ``parallel=True`` here
+makes the testsuite plugin pin each such directory to one worker per scenario;
+the group key is derived from the test file's own directory, so different
+execute directories still run in parallel.
+"""
+from rhosocial.activerecord.testsuite.pytest_plugin import Declaration
+
+
+DECLARATION = Declaration(
+ uses_database=True,
+ parallel=True,
+ purpose="PostgreSQL execute tests against each directory-owned database.",
+ passes_means="the live-database contract of the execute directory holds on PostgreSQL",
+ fails_means="the directory-owned database is corrupted or a backend behavior is wrong",
+)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_initialization.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_backend_initialization.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_initialization.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_backend_initialization.py
index 8e1db137..a3a0ac9b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_initialization.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_backend_initialization.py
@@ -10,7 +10,7 @@
)
-class TestPostgresBackendInitialization:
+class TestBackendInitialization:
def test_sync_backend_builds_default_config_from_kwargs(self):
backend = PostgresBackend(database="app_db", username="app_user", application_name="tests")
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_config.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_config.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_config.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_config.py
index defa213f..e764340c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_config.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_config.py
@@ -232,7 +232,7 @@ def test_custom_values(self):
assert mixin.enable_type_compatibility_warnings is False
-class TestPostgresConnectionConfigTypeAdapter:
+class TestConnectionConfigTypeAdapter:
"""Test PostgresConnectionConfig with type adapter settings."""
def test_config_default_type_adapter_settings(self):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_connection_config.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_config.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_connection_config.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_config.py
index e1082eaa..78905731 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_connection_config.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_config.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_connection_config.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_config.py
"""
Unit tests for PostgresConnectionConfig autocommit option.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_connection_resilience.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_resilience.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_connection_resilience.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_resilience.py
index 33580f3b..75ca6e0e 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_connection_resilience.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_resilience.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_connection_resilience.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_connection_resilience.py
"""
Connection Resilience Tests
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_cursor_pollution.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_cursor_pollution.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_cursor_pollution.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_cursor_pollution.py
index c174b2ce..fc04c0f7 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_cursor_pollution.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_cursor_pollution.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_cursor_pollution.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_cursor_pollution.py
"""
PostgreSQL cursor result set pollution tests.
@@ -16,7 +16,7 @@
pytestmark = [pytest.mark.feature, pytest.mark.backend]
-class TestPostgresCursorPollution:
+class TestCursorPollution:
"""Cursor pollution: sync PostgreSQL backend."""
def test_get_server_version_then_query(self, postgres_backend):
@@ -77,7 +77,7 @@ def test_high_frequency_version_query_cycle(self, postgres_backend):
logger.info("PostgreSQL high-frequency version query cycle 200 iterations passed")
-class TestAsyncPostgresCursorPollution:
+class TestAsyncCursorPollution:
"""Cursor pollution: async PostgreSQL backend."""
@pytest.mark.asyncio
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_dialect.py
similarity index 90%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_dialect.py
index dfcc03dc..e2033b16 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_dialect.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_dialect.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_dialect.py
"""
PostgreSQL backend dialect tests using real database connection.
@@ -9,7 +9,7 @@
import pytest_asyncio # noqa: F401
-class TestPostgreSQLDialectBackend:
+class TestDialect:
"""Synchronous dialect tests for PostgreSQL backend."""
def test_format_identifier(self, postgres_backend):
@@ -32,7 +32,7 @@ def test_quote_parameter(self, postgres_backend):
assert "$1" in result_sql
-class TestAsyncPostgreSQLDialectBackend:
+class TestAsyncDialect:
"""Asynchronous dialect tests for PostgreSQL backend."""
async def test_async_format_identifier(self, async_postgres_backend):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_ssl_connection_params.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_ssl_connection_params.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_ssl_connection_params.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_ssl_connection_params.py
index 106db47e..79efb913 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_ssl_connection_params.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_ssl_connection_params.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_ssl_connection_params.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_ssl_connection_params.py
"""Regression tests: SSL/TLS config must actually reach ``psycopg.connect()``.
The config exposes libpq keyword names (``sslmode``/``sslcert``/``sslkey``/
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_version.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_version.py
similarity index 90%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_version.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_version.py
index 51adb382..6897c053 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_version.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_version.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_version.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/connection/test_version.py
import pytest
import pytest_asyncio # noqa: F401
@@ -6,7 +6,7 @@
from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
-class TestPostgresVersion:
+class TestVersion:
"""Tests for server version retrieval against a live database."""
def test_get_version_parsing(self, postgres_backend: PostgresBackend):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_column_mapping_backend.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_column_mapping_backend.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_column_mapping_backend.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_column_mapping_backend.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_column_mapping_backend.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_column_mapping_backend_async.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_column_mapping_backend.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_column_mapping_backend_async.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_crud_backend.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_crud_backend.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend.py
index d0d9a702..dd50f2e9 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_crud_backend.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_crud_backend.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend.py
"""
PostgreSQL backend CRUD tests using real database connection.
@@ -10,7 +10,7 @@
from decimal import Decimal
-class TestPostgreSQLCRUDBackend:
+class TestCRUD:
"""Synchronous CRUD tests for PostgreSQL backend."""
@pytest.fixture
@@ -124,7 +124,7 @@ def test_fetch_none(self, postgres_backend, test_table):
assert row is None
-class TestAsyncPostgreSQLCRUDBackend:
+class TestAsyncCRUD:
"""Asynchronous CRUD tests for PostgreSQL backend."""
@pytest_asyncio.fixture
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_crud_backend.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend_async.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_crud_backend.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend_async.py
index 6d57f119..30801a47 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_crud_backend.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend_async.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_async_crud_backend.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/crud/test_crud_backend_async.py
from datetime import datetime
import pytest
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_column/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_column/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_constraint/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_constraint/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_index/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_index/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_schema_namespace.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_table/test_schema_namespace.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_schema_namespace.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_table/test_schema_namespace.py
index 6512bded..af25e9c7 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_schema_namespace.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_table/test_schema_namespace.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_schema_namespace.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_table/test_schema_namespace.py
"""
Tests for PostgreSQL schema namespace support.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py
similarity index 90%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/conftest.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py
index f585d068..b6ba3af2 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/conftest.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py
@@ -1,5 +1,6 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/conftest.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/conftest.py
"""Fixtures for PostgreSQL materialized view integration tests."""
+from rhosocial.activerecord.testsuite.pytest_plugin import Declaration
import pytest
import pytest_asyncio
@@ -17,6 +18,14 @@
from rhosocial.activerecord.backend.options import ExecutionOptions
from rhosocial.activerecord.backend.schema import StatementType
+DECLARATION = Declaration(
+ uses_database=True,
+ parallel=True,
+ purpose="PostgreSQL materialized view tests (ddl_view) against the directory-owned database.",
+ passes_means="the live-database contract of this directory holds on PostgreSQL",
+ fails_means="the directory-owned database is corrupted or a backend behavior is wrong",
+)
+
DDL = ExecutionOptions(stmt_type=StatementType.DDL)
DQL = ExecutionOptions(stmt_type=StatementType.DQL)
@@ -142,4 +151,3 @@ def _create(view=None, query=None, **kwargs):
return expression
return _create
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_materialized_view_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_materialized_view_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_materialized_view_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_materialized_view_integration.py
index 098c5bfc..10f88fff 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_materialized_view_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_materialized_view_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_materialized_view_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_materialized_view_integration.py
"""PostgreSQL materialized view integration tests (require a live server).
Covers the server-behaviour half of the regression matrix documented in
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_view_execution.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_view_execution.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_view_execution.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_view_execution.py
index b374f7a7..8fc3d1d1 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_view_execution.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_view_execution.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_view_execution.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/ddl_view/test_view_execution.py
"""
Tests for PostgreSQL VIEW and MATERIALIZED VIEW functionality with actual database execution.
@@ -126,7 +126,7 @@ def postgres_view_backend(postgres_backend):
options=ExecutionOptions(stmt_type=StatementType.DDL))
-class TestPostgresViewExecution:
+class TestViewExecution:
"""Tests for CREATE VIEW and DROP VIEW with actual execution."""
def test_create_view_basic(self, postgres_view_backend):
@@ -313,7 +313,7 @@ def test_drop_view_cascade(self, postgres_view_backend):
assert result is not None
-class TestPostgresMaterializedViewExecution:
+class TestMaterializedViewExecution:
"""Tests for CREATE MATERIALIZED VIEW and related operations."""
def test_create_materialized_view_basic(self, postgres_view_backend):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_many.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_execute_many.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_many.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_execute_many.py
index bd0a032c..959d1a53 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_many.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_execute_many.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_many.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_execute_many.py
"""
PostgreSQL execute_many tests for batch operations.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_pg19_copy_repack_integration.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_pg19_copy_repack_integration.py
index f6809037..f97c345d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_pg19_copy_repack_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_pg19_copy_repack_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_insert/test_pg19_copy_repack_integration.py
"""Live PostgreSQL COPY and REPACK integration tests."""
import pytest
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_model_truncate.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_update_delete/test_model_truncate.py
similarity index 93%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_model_truncate.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_update_delete/test_model_truncate.py
index f215773e..db6cf264 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_model_truncate.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_update_delete/test_model_truncate.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_model_truncate.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/dml_update_delete/test_model_truncate.py
"""PostgreSQL rendering tests for model-bound TRUNCATE expressions."""
from rhosocial.activerecord.backend.expression.objects import Table
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_driver_error_mapping.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_driver_error_mapping.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_driver_error_mapping.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_driver_error_mapping.py
index 650369c4..604ec08d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_driver_error_mapping.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_driver_error_mapping.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_driver_error_mapping.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_driver_error_mapping.py
"""PostgreSQL driver error mapping unit tests.
These tests instantiate psycopg exception classes and drive the backend's
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_error_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_execute_error_contract.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_error_contract.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_execute_error_contract.py
index ec48f4be..42556e77 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_error_contract.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_execute_error_contract.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_execute_error_contract.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/errors/test_execute_error_contract.py
"""PostgreSQL execute-phase error contract tests.
No PostgreSQL server is required: the tests instantiate unconnected backends
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/fulltext_spatial/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/fulltext_spatial/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_functions_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_bitstring_functions_integration.py
similarity index 94%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_functions_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_bitstring_functions_integration.py
index 610588ed..9f85f270 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_functions_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_bitstring_functions_integration.py
@@ -159,8 +159,8 @@ def test_bit_set_bit_executes(self, postgres_backend):
def test_bit_count_executes_on_postgres_14_plus(self, postgres_backend):
"""Test bit_count(bit) function on PostgreSQL 14+."""
- if postgres_backend.get_server_version() < (14, 0, 0):
- pytest.skip("bit_count requires PostgreSQL 14+")
+ if not postgres_backend.dialect.supports_bit_count():
+ pytest.skip("bit_count requires PostgreSQL 14+ per supports_bit_count")
expr = bit_count(postgres_backend.dialect, _bit(postgres_backend.dialect, "101011"))
result = _execute_expression(postgres_backend, expr)
@@ -169,12 +169,8 @@ def test_bit_count_executes_on_postgres_14_plus(self, postgres_backend):
def test_bit_count_skips_before_postgres_14(self, postgres_backend):
"""Test bit_count version gate for PostgreSQL versions before 14."""
- version = postgres_backend.get_server_version()
- if version >= (14, 0, 0):
- assert version >= (14, 0, 0)
- return
-
- pytest.skip("bit_count requires PostgreSQL 14+")
+ if not postgres_backend.dialect.supports_bit_count():
+ pytest.skip("bit_count requires PostgreSQL 14+ per supports_bit_count")
class TestAsyncBitStringFunctionsIntegration:
@@ -209,8 +205,8 @@ async def test_async_bit_get_bit_executes(self, async_postgres_backend):
@pytest.mark.asyncio
async def test_async_bit_count_executes_on_postgres_14_plus(self, async_postgres_backend):
"""Test async bit_count(bit) function on PostgreSQL 14+."""
- if await async_postgres_backend.get_server_version() < (14, 0, 0):
- pytest.skip("bit_count requires PostgreSQL 14+")
+ if not async_postgres_backend.dialect.supports_bit_count():
+ pytest.skip("bit_count requires PostgreSQL 14+ per supports_bit_count")
expr = bit_count(
async_postgres_backend.dialect,
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_seconds_between.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_seconds_between.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_seconds_between.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_seconds_between.py
index c921f787..488b8c57 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_postgres_seconds_between.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_seconds_between.py
@@ -1,5 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/
-# test_postgres_seconds_between.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/functions/test_seconds_between.py
"""Signed, fractional seconds between two instants on PostgreSQL.
What matters here is what a calendar-component sum gets wrong: the sign,
@@ -72,7 +71,7 @@ def _seconds_query(dialect) -> QueryStatement:
)
-class TestPostgresSecondsBetweenExpression:
+class TestSecondsBetweenExpression:
"""The SQL PostgreSQL renders for the node."""
def test_columns(self, postgres_dialect):
@@ -152,7 +151,7 @@ def test_query_integration(self, postgres_dialect):
assert params == ()
-class TestSyncPostgresSecondsBetweenExecution:
+class TestSyncSecondsBetweenExecution:
"""The value the PostgreSQL spelling actually produces."""
def test_signed_fractional_semantics(self, postgres_backend_single):
@@ -172,7 +171,7 @@ def test_signed_fractional_semantics(self, postgres_backend_single):
backend.execute(_CLEANUP)
-class TestAsyncPostgresSecondsBetweenExecution:
+class TestAsyncSecondsBetweenExecution:
"""The same value asked through the async backend."""
@pytest.mark.asyncio
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py
similarity index 94%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/conftest.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py
index 11b4e784..83cd9e47 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/conftest.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py
@@ -1,15 +1,25 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/conftest.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/conftest.py
"""
Pytest fixtures for PostgreSQL introspection tests.
This module provides fixtures for testing database introspection
functionality with PostgreSQL backends.
"""
+from rhosocial.activerecord.testsuite.pytest_plugin import Declaration
import pytest
import pytest_asyncio
+DECLARATION = Declaration(
+ uses_database=True,
+ parallel=True,
+ purpose="PostgreSQL introspection tests (introspection) against the directory-owned database.",
+ passes_means="the live-database contract of this directory holds on PostgreSQL",
+ fails_means="the directory-owned database is corrupted or a backend behavior is wrong",
+)
+
+
# SQL statements for test tables
_TABLES_SQL = [
"DROP TABLE IF EXISTS post_tags CASCADE",
@@ -300,4 +310,4 @@ async def async_backend_with_sequence(async_postgres_backend):
async_postgres_backend.introspector.clear_cache()
await _async_execute_sql_list(async_postgres_backend, _CLEANUP_SEQUENCE_SQL)
except Exception:
- pass
+ pass
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_basic.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_basic.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_basic.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_basic.py
index 7f2ea667..30880ddd 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_basic.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_basic.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_basic.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_basic.py
"""
Tests for basic PostgreSQL introspection functionality.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cache.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cache.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cache.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cache.py
index fc529be5..5faa527c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cache.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cache.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cache.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cache.py
"""
Tests for PostgreSQL introspection caching functionality.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_capabilities.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_capabilities.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_capabilities.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_capabilities.py
index c5b91259..a7dbc1f3 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_capabilities.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_capabilities.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_capabilities.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_capabilities.py # noqa: E501
"""Offline gates on the introspect types and their capability switches.
The CLI advertises one type per catalogue family, and a type is only offered
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_names.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_names.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_names.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_names.py
index 2c0e5944..8da12197 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_names.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_names.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_names.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_names.py
"""Offline tests for what ``NAME`` means to each introspect type.
A type either answers for one catalogue object or lists a family. The ones
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_objects.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_objects.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_objects.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_objects.py
index 282a3b48..3984123b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_objects.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_objects.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_cli_objects.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_cli_objects.py
"""
Black-box CLI tests for the types that answer for a recognised server object:
``views``, ``materialized-views``, ``sequences`` and ``extensions``.
@@ -22,7 +22,7 @@
from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
from rhosocial.activerecord.backend.impl.postgres.cli.introspect import INTROSPECT_TYPES
from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig
-from providers.scenarios import SCENARIO_MAP, get_scenario_raw
+from support.postgres import SCENARIO_MAP, get_scenario_raw
# The CLI runs its async handler inside ``asyncio.run``, which on Windows
# builds the ProactorEventLoop psycopg refuses to work with. That is the
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_columns.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_columns.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_columns.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_columns.py
index 70aefb5f..e7eb2972 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_columns.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_columns.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_columns.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_columns.py
"""
Tests for PostgreSQL column introspection functionality.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_coverage_families.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_coverage_families.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_coverage_families.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_coverage_families.py
index 2b6320be..df3a78eb 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_coverage_families.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_coverage_families.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_coverage_families.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_coverage_families.py # noqa: E501
"""Offline tests for the catalogue families added for introspection coverage.
The statements are rendered trees and the parsers are pure Python, so
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_data_profile.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_data_profile.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_data_profile.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_data_profile.py
index ff857d04..d0e6e09d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_data_profile.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_data_profile.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_data_profile.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_data_profile.py
"""The data-profile family, measured against a real server.
Rendering these statements proves only that they are well-formed. What needs
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_default_schema.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_default_schema.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_default_schema.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_default_schema.py
index 922e8a99..0e39cb80 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_default_schema.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_default_schema.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_default_schema.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_default_schema.py
"""Offline tests for ``default_schema`` config-aware resolution.
Both introspection stacks gained config-aware default-schema resolution:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_family_census.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_family_census.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_family_census.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_family_census.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_foreign_keys.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_foreign_keys.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_foreign_keys.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_foreign_keys.py
index 2ffa8430..4400b0e8 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_foreign_keys.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_foreign_keys.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_foreign_keys.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_foreign_keys.py
"""
Tests for PostgreSQL foreign key introspection functionality.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_indexes.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_indexes.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_indexes.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_indexes.py
index df558dc4..548df2d4 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_indexes.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_indexes.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_indexes.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_indexes.py
"""
Tests for PostgreSQL index introspection functionality.
@@ -225,7 +225,7 @@ def test_primary_key_detection_in_indexes(self, backend_with_tables):
assert pk_indexes[0].name == "users_pkey"
-class TestPostgreSQLSpecificIndexTypes:
+class TestSpecificIndexTypes:
"""Tests for PostgreSQL-specific index types."""
def test_unique_index(self, backend_with_tables):
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_profile_source.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_profile_source.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_profile_source.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_profile_source.py
index 384b556c..0e48b2d4 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_profile_source.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_profile_source.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_introspection_profile_source.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_profile_source.py
"""The provenance of a profile, and the default both twins offer.
``ProfileSource`` is core's closed set for where a profile number came from.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_sequences.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_sequences.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_sequences.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_sequences.py
index e6a369bb..bb7b3190 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_sequences.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_sequences.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_sequences.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_sequences.py
"""
Tests for PostgreSQL sequence, materialized view and extension introspection.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_tables.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_tables.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_tables.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_tables.py
index 2fa48649..d1db167f 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_tables.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_tables.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_tables.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_tables.py
"""
Tests for PostgreSQL table introspection functionality.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_triggers.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_triggers.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_triggers.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_triggers.py
index ed0137a7..19874ccb 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_triggers.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_triggers.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_triggers.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_triggers.py
"""
Tests for PostgreSQL trigger introspection functionality.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_unused_indexes.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_unused_indexes.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_unused_indexes.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_unused_indexes.py
index c16cf586..366c666f 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_unused_indexes.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_unused_indexes.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_unused_indexes.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_unused_indexes.py
"""Unused-indexes listing: statement shape and live execution.
The family reads two catalog relations that answer two different questions:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_views.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_views.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_views.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_views.py
index 731bcf23..442cf944 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_views.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_views.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_introspection_views.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_introspection_views.py
"""
Tests for PostgreSQL view introspection functionality.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_status_introspector.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_status_introspector.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector.py
index a3da7481..1abcb53b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_status_introspector.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/introspection/test_status_introspector.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector.py
"""
Tests for PostgreSQL status introspector.
@@ -28,7 +28,7 @@
)
-class TestPostgreSQLStatusIntrospector:
+class TestStatusIntrospector:
"""Tests for synchronous PostgreSQL status introspector."""
def test_get_overview(self, postgres_backend_single):
@@ -253,7 +253,7 @@ def test_status_item_readonly_flag(self, postgres_backend_single):
assert port_item.is_readonly is True
-class TestPostgreSQLStatusIntrospectorMixin:
+class TestStatusIntrospectorMixin:
"""Tests for PostgreSQLStatusIntrospectorMixin helper methods."""
def test_parse_setting_value_int(self, postgres_backend_single):
@@ -358,7 +358,7 @@ def test_security_category_items(self, postgres_backend_single):
assert item.category == StatusCategory.SECURITY
-class TestAsyncPostgreSQLStatusIntrospector:
+class TestAsyncStatusIntrospector:
"""Tests for asynchronous PostgreSQL status introspector."""
@pytest.mark.asyncio
@@ -553,7 +553,7 @@ async def test_status_item_readonly_flag(self, async_postgres_backend_single):
assert port_item.is_readonly is True
-class TestAsyncPostgreSQLStatusIntrospectorMixin:
+class TestAsyncStatusIntrospectorMixin:
"""Tests for async PostgreSQLStatusIntrospectorMixin helper methods."""
@pytest.mark.asyncio
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector_async_offline.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector_async_offline.py
new file mode 100644
index 00000000..ce34b8d8
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/introspection/test_status_introspector_async_offline.py
@@ -0,0 +1,970 @@
+# tests/.../feature/backend/execute/introspection/test_status_introspector_async_offline.py
+"""Offline unit tests for ``AsyncPostgreSQLStatusIntrospector``.
+
+PostgreSQL has a native async driver, so the async introspector must be covered
+without a live server. Every I/O seam is an ``AsyncMock``: the fake backend's
+``execute`` coroutine dispatches on a stable SQL token and returns a controlled
+``result.data`` payload. A real (pure-Python, version-adapted) ``PostgresDialect``
+is used only so the query expression nodes render real SQL -- no connection,
+socket or network is involved.
+
+Only ``AsyncPostgreSQLStatusIntrospector`` is exercised here; the synchronous
+introspector is covered by ``test_status_introspector.py``.
+"""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect
+from rhosocial.activerecord.backend.impl.postgres.introspection.status_introspector import (
+ AsyncPostgreSQLStatusIntrospector,
+ POSTGRES_CONFIG_VARIABLES,
+)
+from rhosocial.activerecord.backend.impl.postgres.introspection.status_types import (
+ ArchiveInfo,
+ PostgreSQLServerOverview,
+ ReplicationInfo,
+ SecurityInfo,
+ WALInfo,
+)
+from rhosocial.activerecord.backend.introspection.status import (
+ ConnectionInfo,
+ DatabaseBriefInfo,
+ ExtensionInfo,
+ SessionInfo,
+ StatusCategory,
+ StatusItem,
+ StorageInfo,
+ UserInfo,
+)
+
+
+# ---------------------------------------------------------------------------
+# SQL dispatch tokens. Each is a stable substring of the SQL rendered by the
+# (version-adapted) PostgresDialect. SHOW statements are matched exactly because
+# "SHOW ssl" is a prefix of "SHOW ssl_cert_file" / "SHOW ssl_key_file" / ... .
+# ---------------------------------------------------------------------------
+class SQL:
+ SETTINGS_ALL = "pg_settings ORDER BY name"
+ SETTINGS_NAMED = "pg_settings WHERE name IN"
+ ACTIVITY = "total_connections"
+ SHOW_MAX_CONN = "SHOW max_connections"
+ DB_SIZE = "PG_DATABASE_SIZE(%s)"
+ DB_LIST = "FROM pg_database"
+ CURRENT_DB = "SELECT CURRENT_DATABASE()"
+ SCHEMA_STATS = "FROM pg_namespace"
+ ROLE_LIST = "FROM pg_roles"
+ CURRENT_USER = "SELECT CURRENT_USER"
+ CURRENT_SCHEMA = "SELECT CURRENT_SCHEMA()"
+ CLIENT_ADDR = "INET_CLIENT_ADDR()"
+ SSL_SESSION = "FROM pg_stat_ssl"
+ SHOW_WAL_LEVEL = "SHOW wal_level"
+ WAL_POSITION = 'AS "wal_bytes"'
+ WAL_FILES = "pg_ls_waldir"
+ CHECKPOINT_COUNT = "checkpoint_count"
+ CHECKPOINT_LSN = "checkpoint_info"
+ SHOW_WAL_KEEP_SIZE = "SHOW wal_keep_size"
+ SHOW_WAL_KEEP_SEGMENTS = "SHOW wal_keep_segments"
+ RECOVERY = "PG_IS_IN_RECOVERY()"
+ REPL_SLOTS = "pg_replication_slots"
+ ACTIVE_REPL = "pg_stat_replication"
+ REPL_LAG = 'AS "lag_bytes"'
+ SHOW_ARCHIVE_MODE = "SHOW archive_mode"
+ SHOW_ARCHIVE_COMMAND = "SHOW archive_command"
+ SHOW_ARCHIVE_TIMEOUT = "SHOW archive_timeout"
+ ARCHIVE_STATS = "FROM pg_stat_archiver"
+ SHOW_SSL = "SHOW ssl"
+ SHOW_SSL_CERT = "SHOW ssl_cert_file"
+ SHOW_SSL_KEY = "SHOW ssl_key_file"
+ SHOW_SSL_CA = "SHOW ssl_ca_file"
+ SHOW_PASSWORD_ENCRYPTION = "SHOW password_encryption"
+ SHOW_ROW_SECURITY = "SHOW row_security"
+ EXT_LIST = "FROM pg_extension"
+
+
+class FakeBackend:
+ """Minimal backend double: a real dialect plus an async execute seam."""
+
+ def __init__(self, responses=None, version=(16, 0, 0), database="testdb", password=None):
+ self.dialect = PostgresDialect()
+ self.dialect.version = tuple(version)
+ self.config = SimpleNamespace(database=database, password=password)
+ self._server_version_cache = tuple(version)
+ self.get_server_version = Mock(return_value=tuple(version))
+ self.raise_all = False
+ self.null_result = False
+ self.execute = AsyncMock(side_effect=self._dispatch)
+ self._responses = dict(responses or {})
+
+ def _dispatch(self, sql, params=None):
+ if self.null_result:
+ return None
+ if self.raise_all:
+ raise RuntimeError("simulated backend failure")
+ for token, payload in self._responses.items():
+ matched = (sql == token) if token.startswith("SHOW ") else (token in sql)
+ if matched:
+ if isinstance(payload, BaseException):
+ raise payload
+ return SimpleNamespace(data=payload)
+ return SimpleNamespace(data=[])
+
+
+def make_introspector(responses=None, **backend_kwargs):
+ """Build an async introspector wired to a fully mocked backend."""
+ backend = FakeBackend(responses, **backend_kwargs)
+ return AsyncPostgreSQLStatusIntrospector(backend), backend
+
+
+def setting(name, value, unit=None):
+ return {"name": name, "setting": value, "unit": unit}
+
+
+def show(value):
+ """A SHOW statement returns one row with a single (anonymously named) column."""
+ return [{"value": value}]
+
+
+# ---------------------------------------------------------------------------
+# get_overview
+# ---------------------------------------------------------------------------
+class TestAsyncOverview:
+ async def test_get_overview_happy_path_populates_all_families(self):
+ responses = {
+ SQL.SETTINGS_ALL: [setting("port", "5432")],
+ SQL.SETTINGS_NAMED: [setting("checkpoint_timeout", "300", "s")],
+ SQL.ACTIVITY: [{"total_connections": 12}],
+ SQL.SHOW_MAX_CONN: show("100"),
+ SQL.DB_SIZE: [{"size_bytes": 4096}],
+ SQL.DB_LIST: [{"name": "testdb", "size_bytes": 4096}],
+ SQL.CURRENT_DB: [{"current_database": "testdb"}],
+ SQL.SCHEMA_STATS: [{"schema_name": "public", "table_count": 3, "view_count": 1}],
+ SQL.ROLE_LIST: [{"name": "alice", "is_superuser": True, "owner": "postgres"}],
+ SQL.CURRENT_USER: [{"current_user": "alice"}],
+ SQL.CURRENT_SCHEMA: [{"current_schema": "public"}],
+ SQL.CLIENT_ADDR: [{"inet_client_addr": "10.0.0.5"}],
+ SQL.SSL_SESSION: [{"ssl": "t", "version": "TLSv1.3", "cipher": "AES"}],
+ SQL.SHOW_WAL_LEVEL: show("replica"),
+ SQL.WAL_POSITION: [{"wal_bytes": 1024}],
+ SQL.WAL_FILES: [{"wal_files": 7}],
+ SQL.CHECKPOINT_COUNT: [{"checkpoint_count": 9}],
+ SQL.CHECKPOINT_LSN: [{"checkpoint_info": "0/16B7F20"}],
+ SQL.SHOW_WAL_KEEP_SIZE: show("128MB"),
+ SQL.RECOVERY: show("f"),
+ SQL.REPL_SLOTS: [{"slot_count": 2}],
+ SQL.ACTIVE_REPL: [{"active_count": 1}],
+ SQL.REPL_LAG: [{"lag_bytes": 512}],
+ SQL.SHOW_ARCHIVE_MODE: show("on"),
+ SQL.SHOW_ARCHIVE_COMMAND: show("wal-archive"),
+ SQL.SHOW_ARCHIVE_TIMEOUT: show("300"),
+ SQL.ARCHIVE_STATS: [{"archived_count": 5, "failed_count": 0}],
+ SQL.SHOW_SSL: show("on"),
+ SQL.SHOW_SSL_CERT: show("server.crt"),
+ SQL.SHOW_SSL_KEY: show("server.key"),
+ SQL.SHOW_SSL_CA: show("ca.crt"),
+ SQL.SHOW_PASSWORD_ENCRYPTION: show("scram-sha-256"),
+ SQL.SHOW_ROW_SECURITY: show("on"),
+ SQL.EXT_LIST: [{"name": "uuid-ossp", "version": "1.1", "schema": "public"}],
+ }
+ introspector, _ = make_introspector(responses, password="secret")
+
+ overview = await introspector.get_overview()
+
+ assert isinstance(overview, PostgreSQLServerOverview)
+ assert overview.server_vendor == "PostgreSQL"
+ assert overview.server_version == "16.0.0"
+ assert [item.name for item in overview.configuration] == ["port"]
+ assert [item.name for item in overview.performance] == ["checkpoint_timeout"]
+ assert isinstance(overview.connections, ConnectionInfo)
+ assert overview.connections.active_count == 12
+ assert overview.connections.max_connections == 100
+ assert isinstance(overview.storage, StorageInfo)
+ assert overview.storage.total_size_bytes == 4096
+ assert isinstance(overview.databases[0], DatabaseBriefInfo)
+ assert "schemas" in overview.databases[0].extra
+ assert isinstance(overview.users[0], UserInfo)
+ assert isinstance(overview.session, SessionInfo)
+ assert overview.session.user == "alice"
+ assert overview.session.password_used is True
+ assert isinstance(overview.wal, WALInfo)
+ assert overview.wal.wal_level == "replica"
+ assert isinstance(overview.replication, ReplicationInfo)
+ assert overview.replication.is_primary is True
+ assert isinstance(overview.archive, ArchiveInfo)
+ assert overview.archive.archive_mode == "on"
+ assert isinstance(overview.security, SecurityInfo)
+ assert overview.security.ssl_enabled is True
+ assert isinstance(overview.extensions[0], ExtensionInfo)
+
+ async def test_get_overview_with_no_rows_returns_empty_collections(self):
+ introspector, _ = make_introspector()
+
+ overview = await introspector.get_overview()
+
+ assert overview.configuration == []
+ assert overview.performance == []
+ assert overview.databases == []
+ assert overview.users == []
+ assert overview.extensions == []
+ assert overview.session.user is None
+ assert overview.wal == WALInfo()
+ assert overview.replication == ReplicationInfo()
+ assert overview.archive == ArchiveInfo()
+ assert overview.security == SecurityInfo()
+
+ async def test_get_overview_to_dict_serializes_engine_families(self):
+ introspector, _ = make_introspector()
+ overview = await introspector.get_overview()
+
+ payload = overview.to_dict()
+
+ assert {"wal", "replication", "archive", "security"} <= payload.keys()
+ assert payload["server_vendor"] == "PostgreSQL"
+
+
+# ---------------------------------------------------------------------------
+# list_configuration
+# ---------------------------------------------------------------------------
+class TestAsyncListConfiguration:
+ SETTINGS = [
+ setting("port", "5432"),
+ setting("shared_buffers", "134217728", "MB"),
+ setting("ssl", "on"),
+ setting("max_wal_senders", "10"),
+ setting("checkpoint_timeout", "300", "s"),
+ setting("bogus.unknown", "ignored"),
+ ]
+
+ async def test_lists_known_settings_with_parsed_values(self):
+ introspector, _ = make_introspector({SQL.SETTINGS_ALL: self.SETTINGS})
+
+ items = await introspector.list_configuration()
+
+ assert all(isinstance(item, StatusItem) for item in items)
+ names = [item.name for item in items]
+ assert "port" in names
+ assert "ssl" in names
+ assert "bogus.unknown" not in names
+ by_name = {item.name: item for item in items}
+ assert by_name["port"].value == "5432"
+ assert by_name["ssl"].value is True
+ assert by_name["port"].is_readonly is True
+
+ async def test_empty_rows_return_no_items(self):
+ introspector, _ = make_introspector()
+
+ assert await introspector.list_configuration() == []
+
+ async def test_row_unit_overrides_declared_unit(self):
+ introspector, _ = make_introspector(
+ {SQL.SETTINGS_ALL: [setting("work_mem", "65536", "kB")]}
+ )
+
+ items = await introspector.list_configuration()
+
+ work_mem = next(item for item in items if item.name == "work_mem")
+ assert work_mem.unit == "kB"
+
+ async def test_missing_row_unit_falls_back_to_declared_unit(self):
+ introspector, _ = make_introspector({SQL.SETTINGS_ALL: [setting("work_mem", "65536")]})
+
+ items = await introspector.list_configuration()
+
+ work_mem = next(item for item in items if item.name == "work_mem")
+ assert work_mem.unit == "bytes"
+
+ @pytest.mark.parametrize(
+ ("category", "expected_name"),
+ [
+ (StatusCategory.CONFIGURATION, "port"),
+ (StatusCategory.SECURITY, "ssl"),
+ (StatusCategory.REPLICATION, "max_wal_senders"),
+ (StatusCategory.PERFORMANCE, "checkpoint_timeout"),
+ ],
+ )
+ async def test_category_filter_keeps_only_matching_items(self, category, expected_name):
+ introspector, _ = make_introspector({SQL.SETTINGS_ALL: self.SETTINGS})
+
+ items = await introspector.list_configuration(category=category)
+
+ assert items
+ assert all(item.category == category for item in items)
+ assert expected_name in {item.name for item in items}
+
+ async def test_category_with_no_config_variables_returns_empty(self):
+ introspector, _ = make_introspector({SQL.SETTINGS_ALL: self.SETTINGS})
+
+ items = await introspector.list_configuration(category=StatusCategory.CONNECTION)
+
+ assert items == []
+
+ async def test_all_declared_categories_are_reachable(self):
+ expected = {cat for _, cat, _, _, _ in POSTGRES_CONFIG_VARIABLES}
+ assert expected == {
+ StatusCategory.CONFIGURATION,
+ StatusCategory.PERFORMANCE,
+ StatusCategory.SECURITY,
+ StatusCategory.REPLICATION,
+ }
+
+
+# ---------------------------------------------------------------------------
+# list_performance_metrics
+# ---------------------------------------------------------------------------
+class TestAsyncPerformanceMetrics:
+ async def test_maps_named_settings_to_performance_items(self):
+ rows = [
+ setting("checkpoint_timeout", "300", "s"),
+ setting("archive_command", "wal-archive"),
+ setting("bogus.unknown", "x"),
+ ]
+ introspector, _ = make_introspector({SQL.SETTINGS_NAMED: rows})
+
+ items = await introspector.list_performance_metrics()
+
+ assert {item.name for item in items} == {"checkpoint_timeout", "archive_command"}
+ assert all(item.category == StatusCategory.PERFORMANCE for item in items)
+ assert all(isinstance(item, StatusItem) for item in items)
+
+ async def test_empty_rows_return_no_items(self):
+ introspector, _ = make_introspector()
+
+ assert await introspector.list_performance_metrics() == []
+
+ async def test_category_argument_does_not_alter_mapping(self):
+ rows = [setting("archive_timeout", "60", "s")]
+ introspector, _ = make_introspector({SQL.SETTINGS_NAMED: rows})
+
+ items = await introspector.list_performance_metrics(category=StatusCategory.SECURITY)
+
+ assert len(items) == 1
+ assert items[0].category == StatusCategory.PERFORMANCE
+
+
+# ---------------------------------------------------------------------------
+# get_connection_info
+# ---------------------------------------------------------------------------
+class TestAsyncConnectionInfo:
+ async def test_returns_activity_total_and_max_connections(self):
+ responses = {
+ SQL.ACTIVITY: [{"total_connections": 42}],
+ SQL.SHOW_MAX_CONN: show("200"),
+ }
+ introspector, _ = make_introspector(responses)
+
+ info = await introspector.get_connection_info()
+
+ assert isinstance(info, ConnectionInfo)
+ assert info.active_count == 42
+ assert info.max_connections == 200
+
+ async def test_activity_row_without_key_defaults_to_one(self):
+ introspector, _ = make_introspector({SQL.ACTIVITY: [{}]})
+
+ info = await introspector.get_connection_info()
+
+ assert info.active_count == 1
+
+ async def test_no_rows_returns_zero_and_none(self):
+ introspector, _ = make_introspector()
+
+ info = await introspector.get_connection_info()
+
+ assert info.active_count == 0
+ assert info.max_connections is None
+
+ async def test_show_failure_is_swallowed(self):
+ responses = {
+ SQL.ACTIVITY: [{"total_connections": 5}],
+ SQL.SHOW_MAX_CONN: RuntimeError("SHOW unsupported"),
+ }
+ introspector, _ = make_introspector(responses)
+
+ info = await introspector.get_connection_info()
+
+ assert info.active_count == 5
+ assert info.max_connections is None
+
+
+# ---------------------------------------------------------------------------
+# get_storage_info
+# ---------------------------------------------------------------------------
+class TestAsyncStorageInfo:
+ async def test_returns_database_size(self):
+ introspector, _ = make_introspector({SQL.DB_SIZE: [{"size_bytes": 987654}]})
+
+ info = await introspector.get_storage_info()
+
+ assert isinstance(info, StorageInfo)
+ assert info.total_size_bytes == 987654
+
+ async def test_empty_rows_leave_size_none(self):
+ introspector, _ = make_introspector()
+
+ info = await introspector.get_storage_info()
+
+ assert info.total_size_bytes is None
+
+ async def test_uses_configured_database_name(self):
+ introspector, backend = make_introspector(database="analytics")
+
+ await introspector.get_storage_info()
+
+ sql = backend.execute.await_args.args[0]
+ assert "PG_DATABASE_SIZE(%s)" in sql
+
+
+# ---------------------------------------------------------------------------
+# list_databases
+# ---------------------------------------------------------------------------
+class TestAsyncListDatabases:
+ async def test_attaches_schema_info_to_current_database(self):
+ responses = {
+ SQL.DB_LIST: [
+ {"name": "postgres", "size_bytes": 100},
+ {"name": "testdb", "size_bytes": 200},
+ ],
+ SQL.CURRENT_DB: [{"current_database": "testdb"}],
+ SQL.SCHEMA_STATS: [
+ {"schema_name": "public", "table_count": 4, "view_count": 2},
+ {"schema_name": "audit", "table_count": 1, "view_count": 0},
+ ],
+ }
+ introspector, _ = make_introspector(responses)
+
+ databases = await introspector.list_databases()
+
+ assert [db.name for db in databases] == ["postgres", "testdb"]
+ assert all(isinstance(db, DatabaseBriefInfo) for db in databases)
+ current = databases[1]
+ assert current.extra["schemas"]["public"] == {"tables": 4, "views": 2}
+ assert current.table_count == 5
+ assert current.view_count == 2
+ assert databases[0].extra == {}
+
+ async def test_schema_rows_without_name_are_skipped(self):
+ responses = {
+ SQL.DB_LIST: [{"name": "testdb", "size_bytes": 200}],
+ SQL.CURRENT_DB: [{"current_database": "testdb"}],
+ SQL.SCHEMA_STATS: [
+ {"schema_name": None, "table_count": 9, "view_count": 9},
+ {"schema_name": "public", "table_count": 2, "view_count": 1},
+ ],
+ }
+ introspector, _ = make_introspector(responses)
+
+ databases = await introspector.list_databases()
+
+ assert databases[0].extra["schemas"] == {"public": {"tables": 2, "views": 1}}
+
+ async def test_no_current_database_leaves_all_databases_without_schema_info(self):
+ responses = {
+ SQL.DB_LIST: [{"name": "testdb", "size_bytes": 200}],
+ SQL.CURRENT_DB: [],
+ SQL.SCHEMA_STATS: [{"schema_name": "public", "table_count": 4, "view_count": 2}],
+ }
+ introspector, _ = make_introspector(responses)
+
+ databases = await introspector.list_databases()
+
+ assert databases[0].extra == {}
+ assert databases[0].table_count is None
+
+ async def test_schema_query_failure_is_swallowed(self):
+ responses = {
+ SQL.DB_LIST: [{"name": "testdb", "size_bytes": 200}],
+ SQL.CURRENT_DB: [{"current_database": "testdb"}],
+ SQL.SCHEMA_STATS: RuntimeError("permission denied"),
+ }
+ introspector, _ = make_introspector(responses)
+
+ databases = await introspector.list_databases()
+
+ assert len(databases) == 1
+ assert databases[0].extra == {}
+
+ async def test_current_database_query_failure_is_swallowed(self):
+ responses = {
+ SQL.DB_LIST: [{"name": "testdb", "size_bytes": 200}],
+ SQL.CURRENT_DB: RuntimeError("query failed"),
+ }
+ introspector, _ = make_introspector(responses)
+
+ databases = await introspector.list_databases()
+
+ assert len(databases) == 1
+
+ async def test_empty_database_list(self):
+ introspector, _ = make_introspector()
+
+ assert await introspector.list_databases() == []
+
+
+# ---------------------------------------------------------------------------
+# list_users
+# ---------------------------------------------------------------------------
+class TestAsyncListUsers:
+ async def test_maps_roles_with_owner_into_extra(self):
+ rows = [
+ {"name": "alice", "is_superuser": True, "owner": "postgres"},
+ {"name": "bob", "is_superuser": False, "owner": None},
+ ]
+ introspector, _ = make_introspector({SQL.ROLE_LIST: rows})
+
+ users = await introspector.list_users()
+
+ assert all(isinstance(user, UserInfo) for user in users)
+ assert users[0].name == "alice"
+ assert users[0].is_superuser is True
+ assert users[0].extra == {"owner": "postgres"}
+ assert users[1].extra == {}
+
+ async def test_empty_roles(self):
+ introspector, _ = make_introspector()
+
+ assert await introspector.list_users() == []
+
+
+# ---------------------------------------------------------------------------
+# get_session_info
+# ---------------------------------------------------------------------------
+class TestAsyncSessionInfo:
+ async def test_full_session_with_ssl_and_password(self):
+ responses = {
+ SQL.CURRENT_USER: [{"current_user": "alice"}],
+ SQL.CURRENT_DB: [{"current_database": "testdb"}],
+ SQL.CURRENT_SCHEMA: [{"current_schema": "public"}],
+ SQL.CLIENT_ADDR: [{"inet_client_addr": "10.0.0.5"}],
+ SQL.SSL_SESSION: [{"ssl": "t", "version": "TLSv1.3", "cipher": "AES-256"}],
+ }
+ introspector, _ = make_introspector(responses, password="pw")
+
+ session = await introspector.get_session_info()
+
+ assert isinstance(session, SessionInfo)
+ assert session.user == "alice"
+ assert session.database == "testdb"
+ assert session.schema == "public"
+ assert session.host == "10.0.0.5"
+ assert session.ssl_enabled is True
+ assert session.ssl_version == "TLSv1.3"
+ assert session.ssl_cipher == "AES-256"
+ assert session.password_used is True
+
+ @pytest.mark.parametrize(
+ ("ssl_value", "expected"),
+ [("t", True), ("true", True), (True, True), ("f", False), (False, False), (None, False)],
+ )
+ async def test_ssl_flag_parsing(self, ssl_value, expected):
+ introspector, _ = make_introspector(
+ {SQL.SSL_SESSION: [{"ssl": ssl_value, "version": None, "cipher": None}]}
+ )
+
+ session = await introspector.get_session_info()
+
+ assert session.ssl_enabled is expected
+
+ async def test_null_client_host_is_ignored(self):
+ introspector, _ = make_introspector({SQL.CLIENT_ADDR: [{"inet_client_addr": None}]})
+
+ session = await introspector.get_session_info()
+
+ assert session.host is None
+
+ async def test_no_rows_leave_session_fields_unset(self):
+ introspector, _ = make_introspector()
+
+ session = await introspector.get_session_info()
+
+ assert session.user is None
+ assert session.database is None
+ assert session.schema is None
+ assert session.host is None
+ assert session.ssl_enabled is None
+ assert session.password_used is False
+
+ async def test_all_queries_failing_still_returns_session_info(self):
+ introspector, backend = make_introspector()
+ backend.raise_all = True
+
+ session = await introspector.get_session_info()
+
+ assert isinstance(session, SessionInfo)
+ assert session.user is None
+ assert session.password_used is False
+
+
+# ---------------------------------------------------------------------------
+# get_wal_info
+# ---------------------------------------------------------------------------
+class TestAsyncWalInfo:
+ def _full_responses(self):
+ return {
+ SQL.SHOW_WAL_LEVEL: show("replica"),
+ SQL.WAL_POSITION: [{"wal_bytes": 2048}],
+ SQL.WAL_FILES: [{"wal_files": 12}],
+ SQL.CHECKPOINT_COUNT: [{"checkpoint_count": 30}],
+ SQL.CHECKPOINT_LSN: [{"checkpoint_info": "0/2000000"}],
+ SQL.SHOW_WAL_KEEP_SIZE: show("64MB"),
+ }
+
+ async def test_full_wal_info(self):
+ introspector, _ = make_introspector(self._full_responses())
+
+ wal = await introspector.get_wal_info()
+
+ assert isinstance(wal, WALInfo)
+ assert wal.wal_level == "replica"
+ assert wal.wal_size_bytes == 2048
+ assert wal.wal_files == 12
+ assert wal.checkpoint_count == 30
+ assert wal.checkpoint_time == "0/2000000"
+ assert wal.wal_segments == "64MB"
+
+ async def test_old_version_skips_pg10_queries_and_uses_keep_segments(self):
+ responses = self._full_responses()
+ responses[SQL.SHOW_WAL_KEEP_SEGMENTS] = show("32")
+ introspector, backend = make_introspector(responses, version=(9, 6, 24))
+
+ wal = await introspector.get_wal_info()
+
+ assert wal.wal_segments == "32"
+ executed = [call.args[0] for call in backend.execute.await_args_list]
+ assert not any("pg_ls_waldir" in sql for sql in executed)
+ assert not any("pg_control_checkpoint" in sql for sql in executed)
+
+ async def test_empty_rows_leave_fields_none(self):
+ introspector, _ = make_introspector()
+
+ wal = await introspector.get_wal_info()
+
+ assert wal == WALInfo()
+
+ async def test_all_queries_failing_still_returns_wal_info(self):
+ introspector, backend = make_introspector()
+ backend.raise_all = True
+
+ assert await introspector.get_wal_info() == WALInfo()
+
+
+# ---------------------------------------------------------------------------
+# get_replication_info
+# ---------------------------------------------------------------------------
+class TestAsyncReplicationInfo:
+ async def test_primary_with_active_streaming(self):
+ responses = {
+ SQL.RECOVERY: show("f"),
+ SQL.REPL_SLOTS: [{"slot_count": 3}],
+ SQL.ACTIVE_REPL: [{"active_count": 2}],
+ }
+ introspector, _ = make_introspector(responses)
+
+ repl = await introspector.get_replication_info()
+
+ assert isinstance(repl, ReplicationInfo)
+ assert repl.is_primary is True
+ assert repl.is_standby is False
+ assert repl.replication_slots == 3
+ assert repl.active_replications == 2
+ assert repl.streaming is True
+ assert repl.lag_bytes is None
+
+ async def test_standby_reports_lag(self):
+ responses = {
+ SQL.RECOVERY: show("t"),
+ SQL.REPL_SLOTS: [{"slot_count": 1}],
+ SQL.ACTIVE_REPL: [{"active_count": 0}],
+ SQL.REPL_LAG: [{"lag_bytes": 4096}],
+ }
+ introspector, _ = make_introspector(responses)
+
+ repl = await introspector.get_replication_info()
+
+ assert repl.is_standby is True
+ assert repl.is_primary is False
+ assert repl.streaming is False
+ assert repl.lag_bytes == 4096
+
+ @pytest.mark.parametrize("recovery_value", [True, "t", "true"])
+ async def test_truthy_recovery_values_mean_standby(self, recovery_value):
+ introspector, _ = make_introspector({SQL.RECOVERY: show(recovery_value)})
+
+ repl = await introspector.get_replication_info()
+
+ assert repl.is_standby is True
+
+ async def test_standby_lag_query_failure_is_swallowed(self):
+ responses = {
+ SQL.RECOVERY: show("t"),
+ SQL.REPL_LAG: RuntimeError("lag query unsupported"),
+ }
+ introspector, _ = make_introspector(responses)
+
+ repl = await introspector.get_replication_info()
+
+ assert repl.is_standby is True
+ assert repl.lag_bytes is None
+
+ async def test_empty_rows_leave_flags_unset(self):
+ introspector, _ = make_introspector()
+
+ repl = await introspector.get_replication_info()
+
+ assert repl == ReplicationInfo()
+
+ async def test_all_queries_failing_still_returns_replication_info(self):
+ introspector, backend = make_introspector()
+ backend.raise_all = True
+
+ assert await introspector.get_replication_info() == ReplicationInfo()
+
+
+# ---------------------------------------------------------------------------
+# get_archive_info
+# ---------------------------------------------------------------------------
+class TestAsyncArchiveInfo:
+ async def test_full_archive_info_with_integer_timeout(self):
+ responses = {
+ SQL.SHOW_ARCHIVE_MODE: show("on"),
+ SQL.SHOW_ARCHIVE_COMMAND: show("wal-archive %p"),
+ SQL.SHOW_ARCHIVE_TIMEOUT: show("300"),
+ SQL.ARCHIVE_STATS: [
+ {
+ "archived_count": 10,
+ "failed_count": 2,
+ "last_archived": "2026-11-20",
+ "last_failed": "2026-11-19",
+ }
+ ],
+ }
+ introspector, _ = make_introspector(responses)
+
+ archive = await introspector.get_archive_info()
+
+ assert isinstance(archive, ArchiveInfo)
+ assert archive.archive_mode == "on"
+ assert archive.archive_command == "wal-archive %p"
+ assert archive.archive_timeout == 300
+ assert archive.archived_count == 10
+ assert archive.failed_count == 2
+ assert archive.last_archived == "2026-11-20"
+ assert archive.last_failed == "2026-11-19"
+
+ @pytest.mark.parametrize("timeout_value", ["5min", "0", None, ""])
+ async def test_non_integer_or_zero_timeout_is_ignored(self, timeout_value):
+ introspector, _ = make_introspector({SQL.SHOW_ARCHIVE_TIMEOUT: show(timeout_value)})
+
+ archive = await introspector.get_archive_info()
+
+ assert archive.archive_timeout is None
+
+ async def test_archive_stats_with_null_counts_default_to_zero(self):
+ introspector, _ = make_introspector(
+ {SQL.ARCHIVE_STATS: [{"archived_count": None, "failed_count": None}]}
+ )
+
+ archive = await introspector.get_archive_info()
+
+ assert archive.archived_count == 0
+ assert archive.failed_count == 0
+
+ async def test_empty_rows_leave_fields_none(self):
+ introspector, _ = make_introspector()
+
+ assert await introspector.get_archive_info() == ArchiveInfo()
+
+ async def test_all_queries_failing_still_returns_archive_info(self):
+ introspector, backend = make_introspector()
+ backend.raise_all = True
+
+ assert await introspector.get_archive_info() == ArchiveInfo()
+
+
+# ---------------------------------------------------------------------------
+# get_security_info
+# ---------------------------------------------------------------------------
+class TestAsyncSecurityInfo:
+ async def test_full_security_info_from_show_values(self):
+ responses = {
+ SQL.SHOW_SSL: show("on"),
+ SQL.SHOW_SSL_CERT: show("server.crt"),
+ SQL.SHOW_SSL_KEY: show("server.key"),
+ SQL.SHOW_SSL_CA: show("ca.crt"),
+ SQL.SHOW_PASSWORD_ENCRYPTION: show("scram-sha-256"),
+ SQL.SHOW_ROW_SECURITY: show("on"),
+ }
+ introspector, _ = make_introspector(responses)
+
+ security = await introspector.get_security_info()
+
+ assert isinstance(security, SecurityInfo)
+ assert security.ssl_enabled is True
+ assert security.ssl_cert_file == "server.crt"
+ assert security.ssl_key_file == "server.key"
+ assert security.ssl_ca_file == "ca.crt"
+ assert security.password_encryption == "scram-sha-256"
+ assert security.row_security is True
+
+ @pytest.mark.parametrize(
+ ("ssl_value", "rls_value", "expected_ssl", "expected_rls"),
+ [
+ (True, True, True, True),
+ ("off", "off", False, False),
+ (False, False, False, False),
+ ],
+ )
+ async def test_boolean_flags(self, ssl_value, rls_value, expected_ssl, expected_rls):
+ responses = {SQL.SHOW_SSL: show(ssl_value), SQL.SHOW_ROW_SECURITY: show(rls_value)}
+ introspector, _ = make_introspector(responses)
+
+ security = await introspector.get_security_info()
+
+ assert security.ssl_enabled is expected_ssl
+ assert security.row_security is expected_rls
+
+ async def test_empty_rows_leave_fields_none(self):
+ introspector, _ = make_introspector()
+
+ assert await introspector.get_security_info() == SecurityInfo()
+
+ async def test_all_queries_failing_still_returns_security_info(self):
+ introspector, backend = make_introspector()
+ backend.raise_all = True
+
+ assert await introspector.get_security_info() == SecurityInfo()
+
+
+# ---------------------------------------------------------------------------
+# list_extensions
+# ---------------------------------------------------------------------------
+class TestAsyncExtensions:
+ async def test_maps_extension_rows(self):
+ rows = [
+ {"name": "uuid-ossp", "version": "1.1", "schema": "public", "description": "UUIDs"},
+ {"name": "pgcrypto", "version": "1.3", "schema": None, "description": None},
+ ]
+ introspector, _ = make_introspector({SQL.EXT_LIST: rows})
+
+ extensions = await introspector.list_extensions()
+
+ assert len(extensions) == 2
+ assert all(isinstance(ext, ExtensionInfo) for ext in extensions)
+ assert extensions[0].name == "uuid-ossp"
+ assert extensions[0].version == "1.1"
+ assert extensions[0].description == "UUIDs"
+ assert extensions[1].schema is None
+
+ async def test_empty_rows_return_empty_list(self):
+ introspector, _ = make_introspector()
+
+ assert await introspector.list_extensions() == []
+
+ async def test_query_failure_returns_empty_list(self):
+ introspector, backend = make_introspector()
+ backend.raise_all = True
+
+ assert await introspector.list_extensions() == []
+
+
+# ---------------------------------------------------------------------------
+# I/O seam and inherited helpers (through the async class)
+# ---------------------------------------------------------------------------
+class TestAsyncExecutionSeamAndHelpers:
+ async def test_exec_query_async_returns_empty_when_execute_returns_none(self):
+ introspector, backend = make_introspector()
+ backend.null_result = True
+
+ result = await introspector._exec_query_async("SELECT 1")
+
+ assert result == []
+ backend.execute.assert_awaited_once_with("SELECT 1", None)
+
+ async def test_exec_query_async_returns_result_data(self):
+ introspector, backend = make_introspector({SQL.CURRENT_DB: [{"current_database": "x"}]})
+
+ result = await introspector._exec_query_async(*[SQL.CURRENT_DB, ()])
+
+ assert result == [{"current_database": "x"}]
+
+ async def test_get_vendor_name(self):
+ introspector, _ = make_introspector()
+
+ assert introspector._get_vendor_name() == "PostgreSQL"
+
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ (b"utf8", "utf8"),
+ (True, True),
+ ("on", True),
+ ("yes", True),
+ ("off", False),
+ ("no", False),
+ (42, 42),
+ ("5432", "5432"),
+ (1.5, "1.5"),
+ ],
+ )
+ async def test_parse_setting_value(self, raw, expected):
+ introspector, _ = make_introspector()
+
+ assert introspector.parse_setting_value(raw) == expected
+
+ async def test_create_status_item_parses_value(self):
+ introspector, _ = make_introspector()
+
+ item = introspector._create_status_item(
+ name="ssl",
+ value="on",
+ category=StatusCategory.SECURITY,
+ description="SSL enabled",
+ unit=None,
+ is_readonly=True,
+ )
+
+ assert item.value is True
+ assert item.category is StatusCategory.SECURITY
+ assert item.description == "SSL enabled"
+ assert item.is_readonly is True
+
+
+class TestAsyncVersionResolution:
+ async def test_version_string_from_server_version_cache(self):
+ introspector, _ = make_introspector(version=(18, 3, 1))
+
+ assert introspector._get_version_string() == "18.3.1"
+
+ async def test_version_tuple_from_server_version_cache(self):
+ introspector, _ = make_introspector(version=(18, 3, 1))
+
+ assert introspector._get_version_tuple() == (18, 3, 1)
+
+ async def test_version_string_falls_back_to_private_version(self):
+ introspector, backend = make_introspector()
+ del backend._server_version_cache
+ backend._version = (15, 2, 0)
+
+ assert introspector._get_version_string() == "15.2.0"
+
+ async def test_version_string_falls_back_to_get_server_version(self):
+ introspector, backend = make_introspector(version=(14, 1, 0))
+ del backend._server_version_cache
+ backend.get_server_version.return_value = (14, 1, 0)
+
+ assert introspector._get_version_string() == "14.1.0"
+
+ async def test_version_string_unknown_when_all_sources_fail(self):
+ introspector, backend = make_introspector()
+ del backend._server_version_cache
+ backend.get_server_version.side_effect = RuntimeError("no server")
+
+ assert introspector._get_version_string() == "Unknown"
+
+ async def test_version_tuple_unknown_when_all_sources_fail(self):
+ introspector, backend = make_introspector()
+ del backend._server_version_cache
+ backend.get_server_version.side_effect = RuntimeError("no server")
+
+ assert introspector._get_version_tuple() == (0, 0, 0)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_qualified_reference_context.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/join/test_qualified_reference_context.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_qualified_reference_context.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/join/test_qualified_reference_context.py
index 396b2c24..b608c421 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_qualified_reference_context.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/join/test_qualified_reference_context.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_qualified_reference_context.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/join/test_qualified_reference_context.py
"""Column qualifier resolution under JOINs (regression tests).
History: the query layer used to force ``alias=alias or table_name`` on every
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_json_path_modes.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/json/test_json_path_modes.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_json_path_modes.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/json/test_json_path_modes.py
index 16641483..85c1f672 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_json_path_modes.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/json/test_json_path_modes.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_json_path_modes.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/json/test_json_path_modes.py
"""JSON path rendering modes on PostgreSQL.
``format_json_expression`` overrode the core dispatch entry point and ignored
@@ -59,7 +59,7 @@
from rhosocial.activerecord.backend.options import ExecutionOptions
from rhosocial.activerecord.backend.schema import StatementType
-from providers.scenarios import get_enabled_scenarios, get_scenario
+from support.postgres import get_enabled_scenarios, get_scenario
#: A SELECT, so the backend reads the result set back into ``.data``.
DQL = ExecutionOptions(stmt_type=StatementType.DQL)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_advanced_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_advanced_operations.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_advanced_operations.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_advanced_operations.py
index 7d383f51..f59f655d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_advanced_operations.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_advanced_operations.py
@@ -254,7 +254,7 @@ async def async_postgres_range_partition_environment(async_postgres_backend):
await _async_drop_advanced_tables(async_postgres_backend)
-class TestPostgreSQLAdvancedPartitionOperations:
+class TestAdvancedPartitionOperations:
"""Synchronous advanced PostgreSQL partition behavior tests."""
def test_list_partition_routes_rows_and_reports_metadata(self, postgres_backend):
@@ -513,7 +513,7 @@ def test_concurrent_detach_executes_or_reports_environment_limit(
assert RANGE_JAN not in {row["name"] for row in metadata}
-class TestAsyncPostgreSQLAdvancedPartitionOperations:
+class TestAsyncAdvancedPartitionOperations:
"""Asynchronous advanced PostgreSQL partition behavior tests."""
@pytest.mark.asyncio
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_explain.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_explain.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_explain.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_explain.py
index 9d4c6824..ae8b0e28 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_explain.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_explain.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_explain.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_explain.py
"""PostgreSQL EXPLAIN tests for partitioned tables."""
from __future__ import annotations
@@ -237,9 +237,11 @@ def _extract_relation_names(result: PostgresExplainResult) -> list[str]:
def _assert_range_partition_support(dialect):
if not dialect.supports_partitioned_table_creation():
pytest.skip("PostgreSQL scenario does not support declarative partitioning")
- version = dialect.get_server_version()
- if version and version[0] < 11:
- pytest.skip("PostgreSQL 10 does not support primary keys on partitioned tables")
+ if not dialect.supports_partitioned_table_primary_key():
+ pytest.skip(
+ "PostgreSQL 10 does not support primary keys on partitioned tables "
+ "(supports_partitioned_table_primary_key)"
+ )
@pytest.fixture
@@ -275,7 +277,7 @@ def _combined_plan_text(result: PostgresExplainResult) -> str:
return "\n".join(lines)
-class TestPostgresPartitionExplain:
+class TestPartitionExplain:
"""Synchronous EXPLAIN tests for PostgreSQL partition pruning."""
def test_explain_partition_pruning_on_range_predicate(
@@ -360,7 +362,7 @@ def test_explain_full_scan_returns_rows(
assert len(result.raw_rows) > 0
-class TestAsyncPostgresPartitionExplain:
+class TestAsyncPartitionExplain:
"""Asynchronous EXPLAIN tests for PostgreSQL partition pruning."""
@pytest.mark.asyncio
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_multilevel.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_multilevel.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_multilevel.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_multilevel.py
index 72525dfe..3a562a4f 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_multilevel.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_multilevel.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_multilevel.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_multilevel.py
"""Live PostgreSQL tests for multi-level, heterogeneous partitioning.
The tree under test is PostgreSQL's own capability, not a lowest-common-
@@ -249,7 +249,7 @@ def _assert_primary_key(backend, table, expected_columns):
assert column in definition
-class TestPostgresPartitionMultilevel:
+class TestPartitionMultilevel:
"""Synchronous live tests for a heterogeneous two-level tree."""
@pytest.fixture
@@ -442,7 +442,7 @@ def test_drop_branch_removes_one_branch_and_ensure_rebuilds_it(
_assert_tree(rebuilt)
-class TestAsyncPostgresPartitionMultilevel:
+class TestAsyncPartitionMultilevel:
"""Asynchronous live tests; method names mirror the sync class."""
@pytest_asyncio.fixture
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_operations.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_operations.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_operations.py
index 1396cd6a..d54e0627 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_operations.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_operations.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_partition_operations.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/partition/test_partition_operations.py
"""Real PostgreSQL partition operation tests.
These tests execute against the configured PostgreSQL scenarios. They cover
@@ -421,8 +421,11 @@ def _create_production_partitioned_table(backend, partitions):
dialect = backend.dialect
if not dialect.supports_partitioned_table_creation():
pytest.skip("PostgreSQL scenario does not support declarative partitioning")
- if backend.get_server_version() < (11, 0, 0):
- pytest.skip("production partition primary key scenario requires PostgreSQL 11+")
+ if not dialect.supports_partitioned_table_primary_key():
+ pytest.skip(
+ "production partition primary key scenario requires PostgreSQL 11+ "
+ "(supports_partitioned_table_primary_key)"
+ )
for table_name in PRODUCTION_PARTITION_TABLES:
backend.execute(*_drop_table_sql(dialect, table_name))
backend.execute(*_create_production_parent_sql(dialect))
@@ -443,8 +446,11 @@ async def _async_create_production_partitioned_table(backend, partitions):
dialect = backend.dialect
if not dialect.supports_partitioned_table_creation():
pytest.skip("PostgreSQL scenario does not support declarative partitioning")
- if await backend.get_server_version() < (11, 0, 0):
- pytest.skip("production partition primary key scenario requires PostgreSQL 11+")
+ if not dialect.supports_partitioned_table_primary_key():
+ pytest.skip(
+ "production partition primary key scenario requires PostgreSQL 11+ "
+ "(supports_partitioned_table_primary_key)"
+ )
for table_name in PRODUCTION_PARTITION_TABLES:
await backend.execute(*_drop_table_sql(dialect, table_name))
await backend.execute(*_create_production_parent_sql(dialect))
@@ -704,7 +710,7 @@ async def async_pg_partman_table(async_postgres_backend_single):
await async_postgres_backend_single.execute(sql, params)
-class TestPostgreSQLPartitionOperations:
+class TestPartitionOperations:
"""Synchronous real backend tests for common partition operations."""
def test_partition_routing_and_pruning_metadata(self, postgres_backend, partitioned_event_table):
@@ -908,7 +914,7 @@ def test_truncate_partition_keeps_partition_available(self, postgres_backend, pa
assert count == 1
-class TestAsyncPostgreSQLPartitionOperations:
+class TestAsyncPartitionOperations:
"""Asynchronous real backend tests for common partition operations."""
@pytest.mark.asyncio
@@ -1136,7 +1142,7 @@ async def test_truncate_partition_keeps_partition_available(
assert count == 1
-class TestPostgreSQLProductionTimePartitionOperations:
+class TestProductionTimePartitionOperations:
"""Synchronous production-style time partition operation scenarios."""
def test_initial_year_partition_uses_microsecond_boundaries(
@@ -1373,7 +1379,7 @@ def test_detach_expired_year_partition_for_cold_archive(
assert parent_count == 2
-class TestAsyncPostgreSQLProductionTimePartitionOperations:
+class TestAsyncProductionTimePartitionOperations:
"""Asynchronous production-style time partition operation scenarios."""
@pytest.mark.asyncio
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_master_probe_execution.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/capability_probe/test_master_probe_execution.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_master_probe_execution.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/capability_probe/test_master_probe_execution.py
index 407ac6d0..f3b0e27b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_master_probe_execution.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/capability_probe/test_master_probe_execution.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_master_probe_execution.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/capability_probe/test_master_probe_execution.py # noqa: E501
"""Execution confirmation for the master probes this backend declares.
Rendering is not execution: the probe answers below are confirmed against the
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_dialect_security_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/dialect_security/test_dialect_security_integration.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_dialect_security_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/dialect_security/test_dialect_security_integration.py
index d133a64d..e8e1389b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_dialect_security_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/dialect_security/test_dialect_security_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_dialect_security_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/dialect_security/test_dialect_security_integration.py # noqa: E501
"""
Integration tests for PostgreSQL dialect SQL injection security fixes.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_address_standardizer_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/address_standardizer/test_address_standardizer_integration.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_address_standardizer_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/address_standardizer/test_address_standardizer_integration.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_bloom_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/bloom/test_bloom_integration.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_bloom_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/bloom/test_bloom_integration.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gin/test_btree_gin_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gin/test_btree_gin_integration.py
index 1401b708..e8851daa 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gin/test_btree_gin_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gin_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gin/test_btree_gin_integration.py # noqa: E501
"""Integration tests for PostgreSQL btree_gin extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gist/test_btree_gist_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gist/test_btree_gist_integration.py
index af5a59b9..55462e79 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gist/test_btree_gist_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_btree_gist_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/btree_gist/test_btree_gist_integration.py # noqa: E501
"""Integration tests for PostgreSQL btree_gist extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/citext/test_citext_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/citext/test_citext_integration.py
index 84f71fb4..cef95d1e 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/citext/test_citext_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_citext_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/citext/test_citext_integration.py # noqa: E501
"""Integration tests for PostgreSQL citext extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/cube/test_cube_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/cube/test_cube_integration.py
index 95ef700d..25c63938 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/cube/test_cube_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_cube_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/cube/test_cube_integration.py
"""Integration tests for PostgreSQL cube extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_extension_ddl.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ddl/test_extension_ddl.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_extension_ddl.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ddl/test_extension_ddl.py
index 233771af..2a459030 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_extension_ddl.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ddl/test_extension_ddl.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_extension_ddl.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ddl/test_extension_ddl.py
"""
PostgreSQL extension DDL expression tests.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_earthdistance_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/earthdistance/test_earthdistance_integration.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_earthdistance_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/earthdistance/test_earthdistance_integration.py
index a965121e..beb14d57 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_earthdistance_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/earthdistance/test_earthdistance_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_earthdistance_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/earthdistance/test_earthdistance_integration.py # noqa: E501
"""Integration tests for the earthdistance extension.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/fuzzystrmatch/test_fuzzystrmatch_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/fuzzystrmatch/test_fuzzystrmatch_integration.py
index efee69fe..aa223862 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/fuzzystrmatch/test_fuzzystrmatch_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_fuzzystrmatch_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/fuzzystrmatch/test_fuzzystrmatch_integration.py # noqa: E501
"""
Integration tests for PostgreSQL fuzzystrmatch extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hstore_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hstore/test_hstore_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hstore_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hstore/test_hstore_integration.py
index 788034f4..19bad74c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hstore_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hstore/test_hstore_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hstore_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hstore/test_hstore_integration.py # noqa: E501
"""Integration tests for PostgreSQL hstore extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hypopg/test_hypopg_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hypopg/test_hypopg_integration.py
index bdcf4bf9..c6324b48 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hypopg/test_hypopg_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_hypopg_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/hypopg/test_hypopg_integration.py # noqa: E501
"""Integration tests for the hypopg extension.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_intarray_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/intarray/test_intarray_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_intarray_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/intarray/test_intarray_integration.py
index 2c0ca8bd..c25e3750 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_intarray_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/intarray/test_intarray_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_intarray_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/intarray/test_intarray_integration.py # noqa: E501
"""Integration tests for PostgreSQL intarray extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_ltree_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ltree/test_ltree_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_ltree_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ltree/test_ltree_integration.py
index 3e74ee20..48bc12be 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_ltree_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ltree/test_ltree_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_ltree_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/ltree/test_ltree_integration.py
"""Integration tests for PostgreSQL ltree extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_orafce_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/orafce/test_orafce_integration.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_orafce_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/orafce/test_orafce_integration.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_cron/test_pg_cron_integration.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_cron/test_pg_cron_integration.py
index 6ae999c7..ead08c6d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_cron/test_pg_cron_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_cron_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_cron/test_pg_cron_integration.py # noqa: E501
"""Integration tests for the pg_cron extension.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_partman/test_pg_partman_integration.py
similarity index 96%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_partman/test_pg_partman_integration.py
index f0c36cce..11c8ab04 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_partman/test_pg_partman_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_partman_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_partman/test_pg_partman_integration.py # noqa: E501
"""Integration tests for the pg_partman extension.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_repack/test_pg_repack_integration.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_repack/test_pg_repack_integration.py
index 38703d16..454a1d67 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_repack/test_pg_repack_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_repack_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_repack/test_pg_repack_integration.py # noqa: E501
"""Integration tests for the pg_repack extension.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_stat_statements/test_pg_stat_statements_integration.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_stat_statements/test_pg_stat_statements_integration.py
index e9a27ecf..33e83cb9 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_stat_statements/test_pg_stat_statements_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_stat_statements_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_stat_statements/test_pg_stat_statements_integration.py # noqa: E501
"""Integration tests for PostgreSQL pg_stat_statements extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_surgery/test_pg_surgery_integration.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_surgery/test_pg_surgery_integration.py
index eb4b87fb..c901cf62 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_surgery/test_pg_surgery_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_surgery_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_surgery/test_pg_surgery_integration.py # noqa: E501
"""Integration tests for the pg_surgery extension.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_trgm_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_trgm/test_pg_trgm_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_trgm_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_trgm/test_pg_trgm_integration.py
index 16a9abf0..a84be203 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_trgm_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_trgm/test_pg_trgm_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_trgm_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_trgm/test_pg_trgm_integration.py # noqa: E501
"""
Integration tests for PostgreSQL pg_trgm extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_walinspect/test_pg_walinspect_integration.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_walinspect/test_pg_walinspect_integration.py
index 1a2cb04c..afda6f7d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_walinspect/test_pg_walinspect_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pg_walinspect_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pg_walinspect/test_pg_walinspect_integration.py # noqa: E501
"""Integration tests for the pg_walinspect extension.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgaudit/test_pgaudit_integration.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgaudit/test_pgaudit_integration.py
index e67bcd24..40ef2fc1 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgaudit/test_pgaudit_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgaudit_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgaudit/test_pgaudit_integration.py # noqa: E501
"""Integration tests for the pgaudit extension.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgcrypto/test_pgcrypto_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgcrypto/test_pgcrypto_integration.py
index 53c9a5b6..c8f08914 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgcrypto/test_pgcrypto_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgcrypto_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgcrypto/test_pgcrypto_integration.py # noqa: E501
"""
Integration tests for PostgreSQL pgcrypto extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pglogical/test_pglogical_integration.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pglogical/test_pglogical_integration.py
index adf62c1c..433b3e18 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pglogical/test_pglogical_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pglogical_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pglogical/test_pglogical_integration.py # noqa: E501
"""Integration tests for the pglogical extension.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgrouting_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgrouting/test_pgrouting_integration.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgrouting_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgrouting/test_pgrouting_integration.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgvector_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgvector/test_pgvector_integration.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_pgvector_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/pgvector/test_pgvector_integration.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_postgis_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/postgis/test_postgis_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_postgis_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/postgis/test_postgis_integration.py
index cbec0d3d..1a4479e8 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_postgis_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/postgis/test_postgis_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_postgis_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/postgis/test_postgis_integration.py # noqa: E501
"""Integration tests for the PostGIS extension.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_postgis_raster_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/postgis_raster/test_postgis_raster_integration.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_postgis_raster_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/postgis_raster/test_postgis_raster_integration.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/tablefunc/test_tablefunc_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/tablefunc/test_tablefunc_integration.py
index 504986ba..cb274a4d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/tablefunc/test_tablefunc_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_tablefunc_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/tablefunc/test_tablefunc_integration.py # noqa: E501
"""
Integration tests for PostgreSQL tablefunc extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/uuid_ossp/test_uuid_ossp_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/uuid_ossp/test_uuid_ossp_integration.py
index e0313475..ccb740c6 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/uuid_ossp/test_uuid_ossp_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/extensions/test_uuid_ossp_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/extension/uuid_ossp/test_uuid_ossp_integration.py # noqa: E501
"""Integration tests for PostgreSQL uuid-ossp extension with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/bitstring/test_bitstring_integration.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/bitstring/test_bitstring_integration.py
index 49929f50..5a72d5d8 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/bitstring/test_bitstring_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_bitstring_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/bitstring/test_bitstring_integration.py # noqa: E501
"""
Integration tests for PostgreSQL bit string types with real database.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_cast_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/cast/test_cast_integration.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_cast_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/cast/test_cast_integration.py
index 05bad350..f4ebb6b1 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_cast_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/cast/test_cast_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_cast_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/cast/test_cast_integration.py
"""Type conversion against a live PostgreSQL, one case per type.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_enum_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/enum/test_enum_integration.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_enum_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/enum/test_enum_integration.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_execution.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/extension_types/test_extension_type_execution.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_execution.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/extension_types/test_extension_type_execution.py
index cc7f349d..58b30326 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_execution.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/extension_types/test_extension_type_execution.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_extension_type_execution.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/extension_types/test_extension_type_execution.py # noqa: E501
"""The extension type operations, executed.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/literal/test_literal_values_integration.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/literal/test_literal_values_integration.py
index 71b62791..0256e227 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/literal/test_literal_values_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_literal_values_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/literal/test_literal_values_integration.py # noqa: E501
"""Live answers for the tier-2 literal spellings, on the scenario servers.
The rendering half of this question lives in
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/lsn/test_lsn_integration.py
similarity index 92%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/lsn/test_lsn_integration.py
index 7311d209..22021339 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_lsn_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/lsn/test_lsn_integration.py
@@ -20,13 +20,13 @@
def _requires_pg_lsn(backend):
- if backend.get_server_version() < (9, 4, 0):
- pytest.skip("pg_lsn requires PostgreSQL 9.4+")
+ if not backend.dialect.supports_data_type_postgres_pg_lsn():
+ pytest.skip("pg_lsn requires PostgreSQL 9.4+ per supports_data_type_postgres_pg_lsn")
-async def _requires_pg_lsn_async(backend):
- if await backend.get_server_version() < (9, 4, 0):
- pytest.skip("pg_lsn requires PostgreSQL 9.4+")
+def _requires_pg_lsn_async(backend):
+ if not backend.dialect.supports_data_type_postgres_pg_lsn():
+ pytest.skip("pg_lsn requires PostgreSQL 9.4+ per supports_data_type_postgres_pg_lsn")
def _lsn_literal(value):
@@ -124,8 +124,8 @@ def test_lsn_subtraction_executes(self, postgres_backend):
def test_lsn_addition_executes(self, postgres_backend):
"""Add bytes to a pg_lsn value and verify PostgreSQL returns the new LSN."""
- if postgres_backend.get_server_version() < (14, 0, 0):
- pytest.skip("pg_lsn addition requires PostgreSQL 14+")
+ if not postgres_backend.dialect.supports_pg_lsn_addition():
+ pytest.skip("pg_lsn addition requires PostgreSQL 14+ per supports_pg_lsn_addition")
result = postgres_backend.fetch_one("""
SELECT ('16/B374D848'::pg_lsn + 1)::text AS lsn_value
""")
@@ -144,7 +144,7 @@ class TestAsyncLsnIntegration:
@pytest_asyncio.fixture
async def async_lsn_test_table(self, async_postgres_backend):
"""Create a table containing a pg_lsn column for async tests."""
- await _requires_pg_lsn_async(async_postgres_backend)
+ _requires_pg_lsn_async(async_postgres_backend)
await async_postgres_backend.execute(f"DROP TABLE IF EXISTS {ASYNC_LSN_TABLE}")
await async_postgres_backend.execute(f"""
CREATE TABLE {ASYNC_LSN_TABLE} (
@@ -188,7 +188,7 @@ async def test_async_lsn_null_round_trip(
@pytest.mark.asyncio
async def test_async_lsn_subtraction_executes(self, async_postgres_backend):
"""Subtract pg_lsn values asynchronously and verify PostgreSQL byte distance."""
- await _requires_pg_lsn_async(async_postgres_backend)
+ _requires_pg_lsn_async(async_postgres_backend)
result = await async_postgres_backend.fetch_one("""
SELECT '16/B374D849'::pg_lsn - '16/B374D848'::pg_lsn AS distance
""")
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_money_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/money/test_money_integration.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_money_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/money/test_money_integration.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_network_address_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/network/test_network_address_integration.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_network_address_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/network/test_network_address_integration.py
index 553888f9..a1526e87 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_network_address_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/network/test_network_address_integration.py
@@ -132,8 +132,8 @@ def test_insert_and_select_macaddr_value(self, postgres_backend, network_test_ta
def test_insert_and_select_macaddr8_value(self, postgres_backend, network_test_table):
"""Insert a MACADDR8 value and verify PostgreSQL returns canonical text."""
- if postgres_backend.get_server_version() < (10, 0, 0):
- pytest.skip("macaddr8 requires PostgreSQL 10+")
+ if not postgres_backend.dialect.supports_data_type_postgres_macaddr8():
+ pytest.skip("macaddr8 requires PostgreSQL 10+ per supports_data_type_postgres_macaddr8")
literal = _macaddr8_literal(PostgresMacaddr8("08:00:2b:01:02:03:04:05"))
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_oid_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/oid/test_oid_integration.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_oid_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/oid/test_oid_integration.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/range/test_range_types_integration.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/range/test_range_types_integration.py
index e28bc9e2..9c9ca09c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types_integration.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/range/test_range_types_integration.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_range_types_integration.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/range/test_range_types_integration.py # noqa: E501
"""
Integration tests for PostgreSQL range types with real database.
@@ -345,14 +345,13 @@ def test_multirange_version_check(self, postgres_backend):
"""Test multirange version detection via protocol."""
dialect = postgres_backend.dialect
- # Check version-based support
- version = postgres_backend.get_server_version()
- if version >= (14, 0, 0):
- assert dialect.supports_multirange() is True
- assert dialect.supports_multirange_constructor() is True
- else:
- assert dialect.supports_multirange() is False
- assert dialect.supports_multirange_constructor() is False
+ # Multirange is one capability: the types, their constructor and the aggregate
+ # all arrived together in PostgreSQL 14, so every probe the dialect
+ # exposes for the concept has to give one answer.
+ supports = dialect.supports_multirange()
+ assert dialect.supports_multirange_constructor() is supports
+ assert dialect.supports_multirange_agg() is supports
+ assert dialect.supports_data_type_postgres_int4multirange() is supports
def test_range_types_available(self, postgres_backend):
"""Test that numeric range types are available."""
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_xml_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/xml/test_xml_integration.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_xml_integration.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/postgres/types/xml/test_xml_integration.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_explain.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_backend_explain.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_explain.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_backend_explain.py
index 4b37199e..1fafff3c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_explain.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_backend_explain.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_backend_explain.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_backend_explain.py
"""
Integration tests for PostgresBackend.explain() and AsyncPostgresBackend.explain().
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_datetime_interval_explain_examples.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_datetime_interval_explain_examples.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_datetime_interval_explain_examples.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_datetime_interval_explain_examples.py
index d9b6d345..19fe813b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_postgres_datetime_interval_explain_examples.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_datetime_interval_explain_examples.py
@@ -1,5 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/
-# test_postgres_datetime_interval_explain_examples.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_datetime_interval_explain_examples.py
"""PostgreSQL EXPLAIN examples for datetime interval expressions and indexes."""
from decimal import Decimal
@@ -169,7 +168,7 @@ def _assert_temporal_rows(rows):
assert round(float(rows[0]["duration_minutes"])) == 30
-class TestSyncPostgresDateTimeIntervalExplainExamples:
+class TestSyncDateTimeIntervalExplainExamples:
def test_created_at_range_explain_returns_temporal_plan(
self, temporal_indexed_backend
):
@@ -244,7 +243,7 @@ def test_datetime_interval_expressions_work_with_indexed_filter(
_assert_temporal_rows(query_result.data)
-class TestAsyncPostgresDateTimeIntervalExplainExamples:
+class TestAsyncDateTimeIntervalExplainExamples:
@pytest.mark.asyncio
async def test_datetime_range_index_is_available_when_seqscan_disabled(
self, async_temporal_indexed_backend
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py
new file mode 100644
index 00000000..c8217121
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py
@@ -0,0 +1,653 @@
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_postgres_explain_deep.py
+"""Backend-local, deep EXPLAIN tests for PostgreSQL.
+
+The shared testsuite contracts only assert that EXPLAIN *can run*. This file
+interprets what PostgreSQL actually returns, which is deliberately NOT
+generalised into the testsuite because dialects disagree on plan shape.
+PostgreSQL has the richest EXPLAIN surface of the family, so coverage is split:
+
+* **Construction level** (no database needed): the ``supports_explain_*``
+ capability gates and the ``EXPLAIN (ANALYZE, FORMAT JSON, ...)`` SQL rendered
+ by ``PostgresExplainMixin.format_explain_statement``.
+* **Result interpretation** (real PostgreSQL, CI service): the JSON plan tree
+ (``Plan`` / ``Node Type`` / ``Relation Name``) is inspected for sequential
+ scans, aggregate/join nodes, and partition-pruning evidence.
+
+Every statement -- including DDL/DML and the EXPLAIN wrapper -- is built with
+the expression system and passed to the backend as ``*expr.to_sql()`` or as a
+``QueryStatement`` to ``backend.explain()``. Strings appear only as assertion
+expected values; no hand-built SQL is ever handed to a backend API.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime
+from typing import Any, Dict, Iterator, List, Optional, Tuple
+
+import pytest
+import pytest_asyncio
+
+from rhosocial.activerecord.backend.expression import (
+ AllColumnsWildcard,
+ Column,
+ ColumnConstraint,
+ ColumnDefinition,
+ ColumnNotNullConstraint,
+ ComparisonPredicate,
+ CreateIndexStatement,
+ CreateTableStatement,
+ DropTableStatement,
+ InsertStatement,
+ Literal,
+ LogicalPredicate,
+ QueryStatement,
+ TableConstraint,
+ TablePrimaryKeyConstraint,
+ ValuesSource,
+)
+from rhosocial.activerecord.backend.expression.functions import count
+from rhosocial.activerecord.backend.expression.objects import Index, Table
+from rhosocial.activerecord.backend.expression.query_parts import (
+ GroupByHavingClause,
+ JoinClause,
+ WhereClause,
+)
+from rhosocial.activerecord.backend.expression.sources import NamedRelationRef
+from rhosocial.activerecord.backend.expression.statements import (
+ ExplainFormat,
+ ExplainOptions,
+ ExplainStatement,
+ ExplainType,
+ PartitionClause,
+ PartitionStrategy,
+)
+from rhosocial.activerecord.backend.expression.types import (
+ BigIntType,
+ TextType,
+ TimestampType,
+ VarCharType,
+)
+from rhosocial.activerecord.backend.impl.postgres.dialect import PostgresDialect
+from rhosocial.activerecord.backend.impl.postgres.explain import PostgresExplainResult
+from rhosocial.activerecord.backend.impl.postgres.expression import (
+ PostgresCreatePartitionStatement,
+)
+
+# ---------------------------------------------------------------------------
+# Expression builders (no hand-built SQL anywhere)
+# ---------------------------------------------------------------------------
+
+
+def _simple_query(dialect: PostgresDialect, table: str = "explain_deep_events") -> QueryStatement:
+ return QueryStatement(
+ dialect,
+ select=[AllColumnsWildcard(dialect)],
+ from_=NamedRelationRef(dialect, Table(dialect, table)),
+ )
+
+
+def _category_query(dialect: PostgresDialect) -> QueryStatement:
+ return QueryStatement(
+ dialect,
+ select=[AllColumnsWildcard(dialect)],
+ from_=NamedRelationRef(dialect, Table(dialect, "explain_deep_events")),
+ where=WhereClause(
+ dialect,
+ condition=ComparisonPredicate(
+ dialect, "=", Column(dialect, "category"), Literal(dialect, "alpha")
+ ),
+ ),
+ )
+
+
+def _aggregate_query(dialect: PostgresDialect) -> QueryStatement:
+ return QueryStatement(
+ dialect,
+ select=[Column(dialect, "category"), count(dialect).as_("n")],
+ from_=NamedRelationRef(dialect, Table(dialect, "explain_deep_events")),
+ group_by_having=GroupByHavingClause(dialect, group_by=[Column(dialect, "category")]),
+ )
+
+
+def _join_query(dialect: PostgresDialect) -> QueryStatement:
+ left = NamedRelationRef(dialect, Table(dialect, "explain_deep_events"), alias="a")
+ right = NamedRelationRef(dialect, Table(dialect, "explain_deep_events"), alias="b")
+ join = JoinClause(
+ dialect,
+ left_table=left,
+ right_table=right,
+ condition=ComparisonPredicate(
+ dialect,
+ "=",
+ Column(dialect, "category", table="a"),
+ Column(dialect, "category", table="b"),
+ ),
+ )
+ return QueryStatement(dialect, select=[Column(dialect, "id", table="a")], from_=join)
+
+
+def _explain_expr(
+ dialect: PostgresDialect,
+ statement: Any,
+ options: Optional[ExplainOptions] = None,
+) -> ExplainStatement:
+ return ExplainStatement(dialect, statement=statement, options=options)
+
+
+def _render(
+ dialect: PostgresDialect, options: Optional[ExplainOptions] = None
+) -> Tuple[str, tuple]:
+ return _explain_expr(dialect, _simple_query(dialect), options).to_sql()
+
+
+def _require_explain(dialect: PostgresDialect) -> None:
+ if not dialect.supports_explain_plan():
+ pytest.skip("dialect does not support EXPLAIN plans")
+
+
+# ---------------------------------------------------------------------------
+# JSON-plan helpers
+# ---------------------------------------------------------------------------
+
+
+def _parse_json_plan(raw_rows: List[Any]) -> Any:
+ """Extract the JSON plan from rows returned by ``EXPLAIN (FORMAT JSON)``."""
+ if not raw_rows:
+ return {}
+ row = raw_rows[0]
+ if isinstance(row, dict):
+ data = row.get("QUERY PLAN", row)
+ elif isinstance(row, (list, tuple)):
+ data = row[0]
+ else:
+ data = row
+ if isinstance(data, (list, dict)):
+ return data
+ return json.loads(data)
+
+
+def _json_plan(backend: Any, statement: Any) -> Any:
+ """Run ``EXPLAIN (FORMAT JSON)`` built by the expression/dialect system.
+
+ ``backend.explain()`` is used for text plans, but its result wrapper coerces
+ each plan row to ``str`` and therefore cannot carry a JSON document. For the
+ JSON plan we render the very same ``ExplainStatement`` through the dialect
+ and pass ``*expr.to_sql()`` to ``fetch_all`` -- no SQL string is hand-built.
+ """
+ expr = _explain_expr(
+ backend.dialect,
+ statement,
+ options=ExplainOptions(format=ExplainFormat.JSON),
+ )
+ return _parse_json_plan(backend.fetch_all(*expr.to_sql()))
+
+
+async def _async_json_plan(backend: Any, statement: Any) -> Any:
+ expr = _explain_expr(
+ backend.dialect,
+ statement,
+ options=ExplainOptions(format=ExplainFormat.JSON),
+ )
+ return _parse_json_plan(await backend.fetch_all(*expr.to_sql()))
+
+
+def _iter_nodes(plan: Any) -> Iterator[Dict[str, Any]]:
+ if isinstance(plan, list):
+ for item in plan:
+ yield from _iter_nodes(item)
+ elif isinstance(plan, dict):
+ if "Node Type" in plan or "Relation Name" in plan:
+ yield plan
+ for key in ("Plan", "Plans", "Subplans"):
+ child = plan.get(key)
+ if child is not None:
+ yield from _iter_nodes(child)
+
+
+def _node_types(plan: Any) -> List[str]:
+ return [node["Node Type"] for node in _iter_nodes(plan) if "Node Type" in node]
+
+
+def _relation_names(plan: Any) -> List[str]:
+ return [node["Relation Name"] for node in _iter_nodes(plan) if "Relation Name" in node]
+
+
+def _combined_text(result: PostgresExplainResult) -> str:
+ return " ".join(str(row.get("QUERY PLAN", "")) for row in result.raw_rows).upper()
+
+
+# ---------------------------------------------------------------------------
+# DDL/DML builders for the indexed events table
+# ---------------------------------------------------------------------------
+
+_EVENTS_TABLE = "explain_deep_events"
+
+
+def _drop_events(dialect) -> DropTableStatement:
+ return DropTableStatement(dialect=dialect, table=Table(dialect, _EVENTS_TABLE), if_exists=True)
+
+
+def _create_events(dialect) -> CreateTableStatement:
+ return CreateTableStatement(
+ dialect=dialect,
+ table=Table(dialect, _EVENTS_TABLE),
+ columns=[
+ ColumnDefinition(
+ dialect,
+ "id",
+ BigIntType(dialect=dialect),
+ constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))],
+ ),
+ ColumnDefinition(
+ dialect,
+ "category",
+ VarCharType(dialect, 32),
+ constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))],
+ ),
+ ],
+ table_constraints=[
+ TableConstraint(dialect, branch=TablePrimaryKeyConstraint(dialect, ["id"]))
+ ],
+ )
+
+
+def _index_events(dialect) -> CreateIndexStatement:
+ return CreateIndexStatement(
+ dialect=dialect,
+ index=Index(dialect, "idx_explain_deep_category"),
+ table=Table(dialect, _EVENTS_TABLE),
+ columns=["category"],
+ )
+
+
+def _seed_events(dialect) -> InsertStatement:
+ rows = [[i, "alpha" if i % 2 == 0 else "beta"] for i in range(1, 201)]
+ return InsertStatement(
+ dialect=dialect,
+ into=Table(dialect, _EVENTS_TABLE),
+ columns=["id", "category"],
+ source=ValuesSource(dialect, [[Literal(dialect, value) for value in row] for row in rows]),
+ )
+
+
+@pytest.fixture
+def indexed_backend(postgres_backend):
+ dialect = postgres_backend.dialect
+ for expr in (
+ _drop_events(dialect),
+ _create_events(dialect),
+ _index_events(dialect),
+ _seed_events(dialect),
+ ):
+ postgres_backend.execute(*expr.to_sql())
+ yield postgres_backend
+ try:
+ postgres_backend.execute(*_drop_events(dialect).to_sql())
+ except Exception:
+ pass
+
+
+@pytest_asyncio.fixture
+async def async_indexed_backend(async_postgres_backend):
+ dialect = async_postgres_backend.dialect
+ for expr in (
+ _drop_events(dialect),
+ _create_events(dialect),
+ _index_events(dialect),
+ _seed_events(dialect),
+ ):
+ await async_postgres_backend.execute(*expr.to_sql())
+ yield async_postgres_backend
+ try:
+ await async_postgres_backend.execute(*_drop_events(dialect).to_sql())
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------------
+# 1. Capability gates + SQL rendering (construction level, no DB)
+# ---------------------------------------------------------------------------
+
+
+class TestPostgresExplainConstruction:
+ def test_capability_gates(self, postgres_dialect):
+ dialect = postgres_dialect
+ assert dialect.supports_explain_plan() is True
+ assert dialect.supports_explain_analyze() is True
+ for fmt in ("TEXT", "JSON", "XML", "YAML"):
+ assert dialect.supports_explain_format(fmt) is True, fmt
+ assert dialect.supports_explain_format("NOT_A_FORMAT") is False
+
+ def test_plain_explain_rendering(self, postgres_dialect):
+ dialect = postgres_dialect
+ _require_explain(dialect)
+ sql, params = _render(dialect)
+ assert sql.startswith("EXPLAIN SELECT")
+ assert _EVENTS_TABLE in sql
+ assert "(" not in sql, "no option list should be rendered without options"
+ assert params == ()
+
+ def test_analyze_rendering(self, postgres_dialect):
+ dialect = postgres_dialect
+ _require_explain(dialect)
+ if not dialect.supports_explain_analyze():
+ pytest.skip("dialect does not support EXPLAIN ANALYZE")
+ sql, _ = _render(dialect, ExplainOptions(analyze=True))
+ assert sql.startswith("EXPLAIN (ANALYZE)")
+ assert "ANALYZE" in sql
+
+ def test_json_format_rendering(self, postgres_dialect):
+ dialect = postgres_dialect
+ _require_explain(dialect)
+ if not dialect.supports_explain_format("JSON"):
+ pytest.skip("dialect does not support EXPLAIN FORMAT JSON")
+ sql, _ = _render(dialect, ExplainOptions(format=ExplainFormat.JSON))
+ assert sql.startswith("EXPLAIN (FORMAT JSON)")
+ assert "FORMAT JSON" in sql
+ assert "ANALYZE" not in sql
+
+ def test_analyze_and_json_format_combined(self, postgres_dialect):
+ dialect = postgres_dialect
+ _require_explain(dialect)
+ if not dialect.supports_explain_analyze() or not dialect.supports_explain_format("JSON"):
+ pytest.skip("dialect lacks ANALYZE or FORMAT JSON")
+ sql, _ = _render(dialect, ExplainOptions(analyze=True, format=ExplainFormat.JSON))
+ assert "EXPLAIN (ANALYZE, FORMAT JSON)" in sql
+
+ def test_query_plan_type_is_omitted(self, postgres_dialect):
+ dialect = postgres_dialect
+ _require_explain(dialect)
+ sql, _ = _render(dialect, ExplainOptions(type=ExplainType.QUERY_PLAN))
+ assert sql.startswith("EXPLAIN SELECT")
+ assert "QUERY PLAN" not in sql
+
+
+# ---------------------------------------------------------------------------
+# 2. Result interpretation via a real PostgreSQL server (sync)
+# ---------------------------------------------------------------------------
+
+
+class TestPostgresExplainResultInterpretation:
+ def test_text_plan_full_scan(self, indexed_backend):
+ dialect = indexed_backend.dialect
+ _require_explain(dialect)
+ result = indexed_backend.explain(_simple_query(dialect))
+ assert isinstance(result, PostgresExplainResult)
+ assert result.rows
+ combined = _combined_text(result)
+ assert "SEQ SCAN" in combined
+ assert _EVENTS_TABLE.upper() in combined
+ assert result.analyze_index_usage() == "full_scan"
+ assert result.is_full_scan is True
+ assert result.is_index_used is False
+
+ def test_json_plan_exposes_plan_and_node_type(self, indexed_backend):
+ dialect = indexed_backend.dialect
+ if not dialect.supports_explain_format("JSON"):
+ pytest.skip("dialect does not support EXPLAIN FORMAT JSON")
+ plan = _json_plan(indexed_backend, _simple_query(dialect))
+ assert isinstance(plan, list) and plan
+ root = plan[0]["Plan"]
+ assert "Node Type" in root
+ assert root["Node Type"] == "Seq Scan"
+ assert root.get("Relation Name") == _EVENTS_TABLE
+
+ def test_json_plan_category_filter(self, indexed_backend):
+ """An indexed-column predicate still yields an interpretable JSON plan."""
+ dialect = indexed_backend.dialect
+ if not dialect.supports_explain_format("JSON"):
+ pytest.skip("dialect does not support EXPLAIN FORMAT JSON")
+ plan = _json_plan(indexed_backend, _category_query(dialect))
+ types = _node_types(plan)
+ assert any("Scan" in node_type for node_type in types), types
+
+ def test_json_plan_aggregate_node(self, indexed_backend):
+ dialect = indexed_backend.dialect
+ if not dialect.supports_explain_format("JSON"):
+ pytest.skip("dialect does not support EXPLAIN FORMAT JSON")
+ plan = _json_plan(indexed_backend, _aggregate_query(dialect))
+ types = _node_types(plan)
+ assert any("Aggregate" in node_type for node_type in types), types
+
+ def test_json_plan_join_node(self, indexed_backend):
+ dialect = indexed_backend.dialect
+ if not dialect.supports_explain_format("JSON"):
+ pytest.skip("dialect does not support EXPLAIN FORMAT JSON")
+ plan = _json_plan(indexed_backend, _join_query(dialect))
+ types = _node_types(plan)
+ assert any("Join" in node_type or node_type == "Nested Loop" for node_type in types), types
+
+
+# ---------------------------------------------------------------------------
+# 3. Result interpretation (async mirror of the key cases)
+# ---------------------------------------------------------------------------
+
+
+class TestAsyncPostgresExplainResultInterpretation:
+ @pytest.mark.asyncio
+ async def test_text_plan_full_scan(self, async_indexed_backend):
+ dialect = async_indexed_backend.dialect
+ _require_explain(dialect)
+ result = await async_indexed_backend.explain(_simple_query(dialect))
+ assert isinstance(result, PostgresExplainResult)
+ assert result.rows
+ assert "SEQ SCAN" in _combined_text(result)
+ assert result.is_full_scan is True
+
+ @pytest.mark.asyncio
+ async def test_json_plan_exposes_node_type(self, async_indexed_backend):
+ dialect = async_indexed_backend.dialect
+ if not dialect.supports_explain_format("JSON"):
+ pytest.skip("dialect does not support EXPLAIN FORMAT JSON")
+ plan = await _async_json_plan(async_indexed_backend, _simple_query(dialect))
+ root = plan[0]["Plan"]
+ assert root["Node Type"] == "Seq Scan"
+ assert root.get("Relation Name") == _EVENTS_TABLE
+
+ @pytest.mark.asyncio
+ async def test_json_plan_aggregate_node(self, async_indexed_backend):
+ dialect = async_indexed_backend.dialect
+ if not dialect.supports_explain_format("JSON"):
+ pytest.skip("dialect does not support EXPLAIN FORMAT JSON")
+ plan = await _async_json_plan(async_indexed_backend, _aggregate_query(dialect))
+ assert any("Aggregate" in t for t in _node_types(plan))
+
+
+# ---------------------------------------------------------------------------
+# 4. Partition-pruning evidence via a real PostgreSQL server
+# ---------------------------------------------------------------------------
+
+_PART_TABLE = "ar_pg_explain_deep_events"
+_PARTITIONS = {
+ "p2026_01": ("ar_pg_explain_deep_events_p2026_01", datetime(2026, 1, 1), datetime(2026, 2, 1)),
+ "p2026_02": ("ar_pg_explain_deep_events_p2026_02", datetime(2026, 2, 1), datetime(2026, 3, 1)),
+ "p2026_03": ("ar_pg_explain_deep_events_p2026_03", datetime(2026, 3, 1), datetime(2026, 4, 1)),
+}
+
+
+def _drop_partition(dialect, name: str) -> DropTableStatement:
+ return DropTableStatement(dialect=dialect, table=Table(dialect, name), if_exists=True)
+
+
+def _create_partition_parent(dialect) -> CreateTableStatement:
+ return CreateTableStatement(
+ dialect=dialect,
+ table=Table(dialect, _PART_TABLE),
+ columns=[
+ ColumnDefinition(
+ dialect,
+ "id",
+ BigIntType(dialect=dialect),
+ constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))],
+ ),
+ ColumnDefinition(
+ dialect,
+ "created_at",
+ TimestampType(precision=6, dialect=dialect),
+ constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))],
+ ),
+ ColumnDefinition(
+ dialect,
+ "tenant_id",
+ BigIntType(dialect=dialect),
+ constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))],
+ ),
+ ColumnDefinition(dialect, "payload", TextType(dialect=dialect)),
+ ],
+ table_constraints=[
+ TableConstraint(
+ dialect, branch=TablePrimaryKeyConstraint(dialect, ["id", "created_at"])
+ )
+ ],
+ partition=PartitionClause(
+ dialect=dialect,
+ method=PartitionStrategy.RANGE,
+ keys=[Column(dialect, "created_at")],
+ ),
+ )
+
+
+def _create_partition(dialect, name: str, start: datetime, end: datetime):
+ return PostgresCreatePartitionStatement(
+ dialect=dialect,
+ partition_name=name,
+ parent_table=_PART_TABLE,
+ partition_type="RANGE",
+ partition_values={
+ "from": start.strftime("%Y-%m-%d"),
+ "to": end.strftime("%Y-%m-%d"),
+ },
+ )
+
+
+def _seed_partition_rows(dialect) -> InsertStatement:
+ rows = [
+ [1, datetime(2026, 1, 15), 100, "jan"],
+ [2, datetime(2026, 2, 15), 100, "feb"],
+ [3, datetime(2026, 3, 15), 200, "mar"],
+ ]
+ return InsertStatement(
+ dialect=dialect,
+ into=Table(dialect, _PART_TABLE),
+ columns=["id", "created_at", "tenant_id", "payload"],
+ source=ValuesSource(dialect, [[Literal(dialect, value) for value in row] for row in rows]),
+ )
+
+
+def _partition_range_query(dialect, start: datetime, end: datetime) -> QueryStatement:
+ condition = LogicalPredicate(
+ dialect,
+ "AND",
+ ComparisonPredicate(dialect, ">=", Column(dialect, "created_at"), Literal(dialect, start)),
+ ComparisonPredicate(dialect, "<", Column(dialect, "created_at"), Literal(dialect, end)),
+ )
+ return QueryStatement(
+ dialect,
+ select=[AllColumnsWildcard(dialect)],
+ from_=NamedRelationRef(dialect, Table(dialect, _PART_TABLE)),
+ where=WhereClause(dialect, condition=condition),
+ )
+
+
+def _partition_full_scan_query(dialect) -> QueryStatement:
+ return QueryStatement(
+ dialect,
+ select=[AllColumnsWildcard(dialect)],
+ from_=NamedRelationRef(dialect, Table(dialect, _PART_TABLE)),
+ )
+
+
+def _partition_ddl(dialect):
+ exprs = [_drop_partition(dialect, _PART_TABLE)]
+ exprs.extend(_drop_partition(dialect, name) for name, _, _ in _PARTITIONS.values())
+ exprs.append(_create_partition_parent(dialect))
+ exprs.extend(
+ _create_partition(dialect, name, start, end) for name, start, end in _PARTITIONS.values()
+ )
+ exprs.append(_seed_partition_rows(dialect))
+ return exprs
+
+
+def _partition_cleanup(dialect):
+ exprs = [_drop_partition(dialect, name) for name, _, _ in _PARTITIONS.values()]
+ exprs.append(_drop_partition(dialect, _PART_TABLE))
+ return exprs
+
+
+def _require_partition_support(dialect) -> None:
+ _require_explain(dialect)
+ if not dialect.supports_partitioned_table_creation():
+ pytest.skip("server does not support declarative partitioning")
+ if not dialect.supports_partitioned_table_primary_key():
+ pytest.skip("server does not support primary keys on partitioned tables")
+
+
+@pytest.fixture
+def partition_backend(postgres_backend):
+ dialect = postgres_backend.dialect
+ _require_partition_support(dialect)
+ for expr in _partition_ddl(dialect):
+ postgres_backend.execute(*expr.to_sql())
+ yield postgres_backend
+ for expr in _partition_cleanup(dialect):
+ try:
+ postgres_backend.execute(*expr.to_sql())
+ except Exception:
+ pass
+
+
+@pytest_asyncio.fixture
+async def async_partition_backend(async_postgres_backend):
+ dialect = async_postgres_backend.dialect
+ _require_partition_support(dialect)
+ for expr in _partition_ddl(dialect):
+ await async_postgres_backend.execute(*expr.to_sql())
+ yield async_postgres_backend
+ for expr in _partition_cleanup(dialect):
+ try:
+ await async_postgres_backend.execute(*expr.to_sql())
+ except Exception:
+ pass
+
+
+class TestPostgresPartitionPruningEvidence:
+ def test_range_predicate_prunes_unrelated_partitions(self, partition_backend):
+ dialect = partition_backend.dialect
+ if not dialect.supports_explain_format("JSON"):
+ pytest.skip("dialect does not support EXPLAIN FORMAT JSON")
+ plan = _json_plan(
+ partition_backend,
+ _partition_range_query(dialect, datetime(2026, 2, 1), datetime(2026, 3, 1)),
+ )
+ names = _relation_names(plan)
+ target = _PARTITIONS["p2026_02"][0]
+ assert target in names, "target partition missing from plan: %r" % names
+ assert _PARTITIONS["p2026_01"][0] not in names, "unrelated January partition not pruned"
+ assert _PARTITIONS["p2026_03"][0] not in names, "unrelated March partition not pruned"
+
+ def test_full_scan_lists_every_partition(self, partition_backend):
+ dialect = partition_backend.dialect
+ if not dialect.supports_explain_format("JSON"):
+ pytest.skip("dialect does not support EXPLAIN FORMAT JSON")
+ plan = _json_plan(partition_backend, _partition_full_scan_query(dialect))
+ names = _relation_names(plan)
+ for name, _, _ in _PARTITIONS.values():
+ assert name in names, "partition %s missing from full-scan plan" % name
+
+
+class TestAsyncPostgresPartitionPruningEvidence:
+ @pytest.mark.asyncio
+ async def test_range_predicate_prunes_unrelated_partitions(self, async_partition_backend):
+ dialect = async_partition_backend.dialect
+ if not dialect.supports_explain_format("JSON"):
+ pytest.skip("dialect does not support EXPLAIN FORMAT JSON")
+ plan = await _async_json_plan(
+ async_partition_backend,
+ _partition_range_query(dialect, datetime(2026, 2, 1), datetime(2026, 3, 1)),
+ )
+ names = _relation_names(plan)
+ target = _PARTITIONS["p2026_02"][0]
+ assert target in names, "target partition missing from plan: %r" % names
+ assert _PARTITIONS["p2026_01"][0] not in names
+ assert _PARTITIONS["p2026_03"][0] not in names
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_property_graph_query_scenarios.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_property_graph_query_scenarios.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_property_graph_query_scenarios.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_property_graph_query_scenarios.py
index 75d8dc21..1e21cfaa 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_property_graph_query_scenarios.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_property_graph_query_scenarios.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_property_graph_query_scenarios.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_property_graph_query_scenarios.py
"""Capability-gated SQL/PGQ integration scenarios.
These scenarios need a live server that actually implements SQL/PGQ. That was
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_recursive_cte_graph_traversal.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_recursive_cte_graph_traversal.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_recursive_cte_graph_traversal.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_recursive_cte_graph_traversal.py
index ae05ead1..351f2288 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_recursive_cte_graph_traversal.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_recursive_cte_graph_traversal.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/test_recursive_cte_graph_traversal.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_recursive_cte_graph_traversal.py
"""
Recursive CTE graph traversal tests — PGQ quantified path alternative.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_row_level_locks.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_row_level_locks.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_row_level_locks.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/query/test_row_level_locks.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/routine_domain/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/routine_domain/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_identity_execution.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py
similarity index 92%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/test_identity_execution.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py
index 0363b901..ab20bbb0 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/test_identity_execution.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/test_identity_execution.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/sequence_identity/test_identity_execution.py
"""Execution confirmation for PostgreSQL identity / auto-increment / SERIAL DDL.
Rendering is not execution. PostgreSQL 9 renders a well-formed
@@ -19,6 +19,7 @@
Each verdict is preceded by a sentinel: a deliberately invalid statement must
be classified ``REJECTED``, or a null result could be read as acceptance.
"""
+from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402
import pytest
@@ -140,15 +141,15 @@ def _auto_increment_table(dialect, table_name):
columns=[
ColumnDefinition(
dialect,
- "id",
- IntegerType(dialect=dialect),
+ "id"[0],
+ auto_increment_parts(dialect, IntegerType(dialect=dialect))[0],
constraints=[
ColumnConstraint(
dialect,
- branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True),
+ branch=ColumnPrimaryKeyConstraint(dialect),
)
],
- )
+ attributes=auto_increment_parts(dialect, IntegerType(dialect=dialect))[1])
],
)
@@ -234,17 +235,17 @@ def test_no_cycle_is_executable(self, postgres_backend):
assert outcome is ExecutionOutcome.NOT_RENDERED
def test_auto_increment_constraint_matches_the_declaration(self, postgres_backend):
- """The legacy is_auto_increment flag routes through the identity gate."""
+ """The auto-increment flag renders a SERIAL type, accepted on every version."""
dialect = postgres_backend.dialect
outcome = _confirm(
postgres_backend,
_auto_increment_table(dialect, "test_identity_exec_legacy"),
"test_identity_exec_legacy",
)
- if dialect.supports_identity_column():
- assert outcome is ExecutionOutcome.ACCEPTED
- else:
- assert outcome is ExecutionOutcome.NOT_RENDERED
+ # Unlike an identity clause, SERIAL predates the standard and exists on
+ # every version, so the server accepts the declaration whether or not it
+ # has ``supports_identity_column``.
+ assert outcome is ExecutionOutcome.ACCEPTED
class TestSerialTypeExecution:
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/show_admin/.gitkeep b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/show_admin/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_postgres.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_postgres_transaction_features.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_postgres.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_postgres_transaction_features.py
index 048e8ae5..7c261d3e 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_postgres.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_postgres_transaction_features.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_postgres.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_postgres_transaction_features.py
"""
PostgreSQL-specific transaction tests.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_advanced_features.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_advanced_features.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_advanced_features.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_advanced_features.py
index a7b03ba5..b34813c6 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_advanced_features.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_advanced_features.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_advanced_features.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_advanced_features.py
"""
PostgreSQL advanced transaction feature tests.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_backend.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend.py
similarity index 95%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_backend.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend.py
index 430b1c2d..da33ea45 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_backend.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_backend.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend.py
"""
PostgreSQL backend transaction tests using real database connection.
@@ -10,7 +10,7 @@
from decimal import Decimal
-class TestPostgreSQLTransactionBackend:
+class TestTransactionBackend:
"""Synchronous transaction tests for PostgreSQL backend."""
@pytest.fixture
@@ -55,7 +55,7 @@ def test_transaction_rollback(self, postgres_backend, test_table):
assert len(rows) == 0
-class TestAsyncPostgreSQLTransactionBackend:
+class TestAsyncTransactionBackend:
"""Asynchronous transaction tests for PostgreSQL backend."""
@pytest_asyncio.fixture
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_async_transaction_backend.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend_async.py
similarity index 97%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_async_transaction_backend.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend_async.py
index 3ac01641..0a4ae460 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_async_transaction_backend.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend_async.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_async_transaction_backend.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_backend_async.py
import pytest
import pytest_asyncio
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_deferrable.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_deferrable.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_deferrable.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_deferrable.py
index 1194d58b..8cc3fdd0 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_deferrable.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_deferrable.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_deferrable.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_deferrable.py
"""
PostgreSQL transaction deferrable constraint tests.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_isolation.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_isolation.py
similarity index 98%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_isolation.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_isolation.py
index 4952ecf8..2d4df990 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_isolation.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_isolation.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_isolation.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_isolation.py
"""
PostgreSQL transaction isolation level tests.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_mode_effect.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_mode_effect.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_mode_effect.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_mode_effect.py
index 6e8d10f2..e4704b4b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_mode_effect.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_mode_effect.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_mode_effect.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_mode_effect.py
"""
PostgreSQL transaction access mode effect tests.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_savepoint.py b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_savepoint.py
similarity index 99%
rename from tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_savepoint.py
rename to tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_savepoint.py
index b5dadd57..3a71ec26 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_savepoint.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_savepoint.py
@@ -1,4 +1,4 @@
-# tests/rhosocial/activerecord_postgres_test/feature/backend/transaction/test_transaction_savepoint.py
+# tests/rhosocial/activerecord_postgres_test/feature/backend/execute/transaction/test_transaction_savepoint.py
"""
PostgreSQL transaction savepoint tests.
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/conftest.py
new file mode 100644
index 00000000..15576b53
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/conftest.py
@@ -0,0 +1,4 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/conftest.py
+"""Use the shared ``basic/bulk_crud`` minimal test set."""
+
+from rhosocial.activerecord.testsuite.feature.basic.bulk_crud.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations.py
index 8e76ce45..1c01ee58 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations.py
@@ -9,5 +9,3 @@
)
from rhosocial.activerecord.testsuite.feature.basic.bulk_crud.test_bulk_operations import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.bulk_crud.test_bulk_operations_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations_async.py
index 2a67aa45..86952bcd 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations_async.py
@@ -1,3 +1,5 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/bulk_crud/test_bulk_operations_async.py
"""Bridge file for async feature.basic.bulk_crud.test_bulk_operations_async tests."""
from rhosocial.activerecord.testsuite.feature.basic.bulk_crud.test_bulk_operations_async import * # noqa: F401, F403
+
+from rhosocial.activerecord.testsuite.feature.basic.bulk_crud.test_bulk_operations_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/conftest.py
index 1f6cb9a6..ce6d4e5e 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/conftest.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/conftest.py
@@ -3,28 +3,9 @@
Pytest configuration for basic feature tests.
This file imports fixtures from the corresponding testsuite, making them
-available to the tests in this directory. It overrides ``type_adapter_fixtures``
-so the scenario name is passed to the provider. Without this, the sync provider
-always creates the ``type_adapter_tests`` table on the first registered scenario,
-which collides with the async provider when both scenarios run in parallel.
+available to the tests in this directory. The testsuite fixture definitions
+configure each model against the directory's logical database, so no
+scenario-specific override is needed here.
"""
-import pytest
-
-from rhosocial.activerecord.testsuite.feature.basic.conftest import * # noqa: F401,F403
-from rhosocial.activerecord.testsuite.feature.basic.conftest import ( # noqa: F401
- SCENARIO_PARAMS_SYNC,
- PROVIDER_KEY_SYNC,
-)
-from rhosocial.activerecord.testsuite.core.registry import get_provider_registry
-
-
-@pytest.fixture(scope="function", params=SCENARIO_PARAMS_SYNC)
-def type_adapter_fixtures(request):
- scenario = request.param
- provider_registry = get_provider_registry()
- provider_class = provider_registry.get_provider(PROVIDER_KEY_SYNC)
- provider = provider_class()
- model = provider.setup_type_adapter_model_and_schema(scenario)
- yield model
- provider.cleanup_after_test(scenario)
+from rhosocial.activerecord.testsuite.feature.basic.conftest import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context.py
index b5ecbf1d..8f7e8cf3 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context.py
@@ -12,5 +12,3 @@
# Import shared tests from testsuite package
from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_context import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_context_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context_async.py
index 8d360f89..75784cbb 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context_async.py
@@ -1,3 +1,5 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_context_async.py
"""Bridge file for async feature.basic.connection.test_active_record_context_async tests."""
from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_context_async import * # noqa: F401, F403
+
+from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_context_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud.py
index c9488510..eb4e162b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud.py
@@ -12,5 +12,3 @@
# Import shared tests from testsuite package
from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_crud import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_crud_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud_async.py
index a826a9e8..10f67d9c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud_async.py
@@ -1,3 +1,5 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/connection/test_active_record_crud_async.py
"""Bridge file for async feature.basic.connection.test_active_record_crud_async tests."""
from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_crud_async import * # noqa: F401, F403
+
+from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_crud_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/conftest.py
new file mode 100644
index 00000000..030a02ce
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/conftest.py
@@ -0,0 +1,4 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/crud/conftest.py
+"""Use the shared ``basic/crud`` minimal test set."""
+
+from rhosocial.activerecord.testsuite.feature.basic.crud.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py
deleted file mode 100644
index 1f34b0b8..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud.py
-"""
-Bridge file for composite PK CRUD tests from the testsuite.
-"""
-from rhosocial.activerecord.testsuite.feature.basic.crud.test_composite_pk_crud import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.crud.test_composite_pk_crud_async import * # noqa: F403
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py
deleted file mode 100644
index 5bf67d8f..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_composite_pk_crud_async.py
-"""Bridge file for async feature.basic.crud.test_composite_pk_crud_async tests."""
-from rhosocial.activerecord.testsuite.feature.basic.crud.test_composite_pk_crud_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud.py
index ffc5439b..c6624070 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud.py
@@ -16,17 +16,12 @@
# parameterized to run against the scenarios defined in `providers/scenarios.py`.
from rhosocial.activerecord.testsuite.feature.basic.conftest import (
user_class, # noqa: F401
- type_case_class, # noqa: F401
- type_test_model, # noqa: F401
validated_user_class, # noqa: F401
validated_user, # noqa: F401
async_user_class, # noqa: F401
- async_type_case_class, # noqa: F401
async_validated_user_class, # noqa: F401
async_validated_user # noqa: F401
)
# Import shared tests from testsuite package
from rhosocial.activerecord.testsuite.feature.basic.crud.test_crud import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.crud.test_crud_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud_async.py
index b8ffe646..60742940 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud_async.py
@@ -1,3 +1,5 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/crud/test_crud_async.py
"""Bridge file for async feature.basic.crud.test_crud_async tests."""
from rhosocial.activerecord.testsuite.feature.basic.crud.test_crud_async import * # noqa: F401, F403
+
+from rhosocial.activerecord.testsuite.feature.basic.crud.test_crud_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/conftest.py
new file mode 100644
index 00000000..8aa92784
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/conftest.py
+"""Use the shared ``basic/crud_composite_pk`` test set."""
+from rhosocial.activerecord.testsuite.feature.basic.crud_composite_pk.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud.py
new file mode 100644
index 00000000..a8c1157a
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud.py
+"""Bridge file: runs the shared ``basic/crud_composite_pk`` sync tests."""
+from rhosocial.activerecord.testsuite.feature.basic.crud_composite_pk.test_composite_pk_crud import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud_async.py
new file mode 100644
index 00000000..1632ef70
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/crud_composite_pk/test_composite_pk_crud_async.py
+"""Bridge file: runs the shared ``basic/crud_composite_pk`` async tests."""
+from rhosocial.activerecord.testsuite.feature.basic.crud_composite_pk.test_composite_pk_crud_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/ddl/test_data_type_suggestion_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/ddl/test_data_type_suggestion_contract.py
new file mode 100644
index 00000000..36894b94
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/ddl/test_data_type_suggestion_contract.py
@@ -0,0 +1,4 @@
+# tests/activerecord_postgres_test/feature/basic/ddl/test_data_type_suggestion_contract.py
+"""Thin bridge that runs the shared suggested-data-type contract here."""
+
+from rhosocial.activerecord.testsuite.feature.basic.ddl.test_data_type_suggestion_contract import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/events/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/conftest.py
new file mode 100644
index 00000000..30b0011e
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/events/conftest.py
+"""Use the shared ``basic/events`` L2 environment (SQLite backend)."""
+from rhosocial.activerecord.testsuite.feature.basic.events.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/conftest.py
new file mode 100644
index 00000000..4bcf62c1
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/conftest.py
+"""Use the shared ``basic/events/core`` L2 environment (SQLite backend)."""
+from rhosocial.activerecord.testsuite.feature.basic.events.core.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers.py
new file mode 100644
index 00000000..a8b7c529
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers.py
+"""Bridge file for event handler tests from the testsuite."""
+from rhosocial.activerecord.testsuite.feature.basic.events.core.test_handlers import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers_async.py
new file mode 100644
index 00000000..eeefa69d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_handlers_async.py
+"""Bridge file for async event handler tests from the testsuite."""
+from rhosocial.activerecord.testsuite.feature.basic.events.core.test_handlers_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle.py
new file mode 100644
index 00000000..7c39be35
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle.py
+"""Bridge file for event lifecycle tests from the testsuite."""
+from rhosocial.activerecord.testsuite.feature.basic.events.core.test_lifecycle import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle_async.py
new file mode 100644
index 00000000..ff8bd865
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/events/core/test_lifecycle_async.py
+"""Bridge file for async event lifecycle tests from the testsuite."""
+from rhosocial.activerecord.testsuite.feature.basic.events.core.test_lifecycle_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/conftest.py
new file mode 100644
index 00000000..9c50169d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/conftest.py
@@ -0,0 +1,4 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/conftest.py
+"""Use the shared ``basic/expressions`` DB-free test set."""
+
+from rhosocial.activerecord.testsuite.feature.basic.expressions.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions.py
new file mode 100644
index 00000000..f39c4838
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions.py
@@ -0,0 +1,8 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions.py
+"""Bridge for the shared ``basic/expressions`` test module.
+
+The test logic lives in ``rhosocial-activerecord-testsuite``; this
+file only makes its tests discoverable in this backend's test run.
+"""
+
+from rhosocial.activerecord.testsuite.feature.basic.expressions.test_expressions import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions_async.py
new file mode 100644
index 00000000..ef5f0196
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions_async.py
@@ -0,0 +1,8 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/expressions/test_expressions_async.py
+"""Bridge for the shared ``basic/expressions`` test module.
+
+The test logic lives in ``rhosocial-activerecord-testsuite``; this
+file only makes its tests discoverable in this backend's test run.
+"""
+
+from rhosocial.activerecord.testsuite.feature.basic.expressions.test_expressions_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/conftest.py
new file mode 100644
index 00000000..a3e5c8d8
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/conftest.py
@@ -0,0 +1,2 @@
+"""Use the shared ``basic/field_generation`` database-free test set."""
+from rhosocial.activerecord.testsuite.feature.basic.field_generation.conftest import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation.py
new file mode 100644
index 00000000..8e1ef97c
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation.py
@@ -0,0 +1 @@
+from rhosocial.activerecord.testsuite.feature.basic.field_generation.test_field_generation import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation_async.py
new file mode 100644
index 00000000..ae6648ba
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/field_generation/test_field_generation_async.py
@@ -0,0 +1 @@
+from rhosocial.activerecord.testsuite.feature.basic.field_generation.test_field_generation_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/conftest.py
new file mode 100644
index 00000000..26b980e8
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/conftest.py
@@ -0,0 +1,4 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/fields/conftest.py
+"""Use the shared ``basic/fields`` minimal test set."""
+
+from rhosocial.activerecord.testsuite.feature.basic.fields.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field.py
deleted file mode 100644
index 69e0cf80..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field.py
+++ /dev/null
@@ -1,365 +0,0 @@
-# src/rhosocial/activerecord/testsuite/feature/basic/fields/test_derived_field.py
-import pytest
-from typing import ClassVar, Optional
-from typing_extensions import Annotated
-
-from rhosocial.activerecord.base import DerivedField, UseColumn
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.backend.expression import (
- ArithmeticOperation,
- Column,
- Literal,
-)
-
-
-class TestDerivedFieldDeclaration:
-
- def test_derived_fields_registered(self, product_class):
- assert "discounted_price" in product_class.__derived_fields__
- assert "total_value" in product_class.__derived_fields__
-
- def test_descriptor_class_access(self, product_class):
- assert isinstance(product_class.discounted_price, DerivedField)
-
- def test_derived_field_with_static_expression(self, product_class):
- """Test DerivedField constructed with a pre-built expression object (non-callable path)."""
- dialect = product_class.backend().dialect
- static_expr = ArithmeticOperation(
- dialect, "mul", Column(dialect, "price"), Literal(dialect, 2)
- )
- df = DerivedField(static_expr)
- resolved = df.resolve(dialect)
- assert resolved is static_expr
-
- def test_descriptor_instance_default_none(self, product_class):
- p = product_class(name="x", price=10.0, quantity=1)
- assert p.discounted_price is None
- assert p.total_value is None
-
- def test_derived_field_names_mapping(self, product_class):
- names = product_class.__derived_field_names__
- df = product_class.__derived_fields__["discounted_price"]
- assert names[id(df)] == "discounted_price"
-
-
-class TestDerivedFieldQuery:
-
- def _insert(self, Model, name, price, quantity):
- p = Model(name=name, price=price, quantity=quantity)
- p.save()
- return p
-
- def test_find_all_derived_true(self, product_class):
- self._insert(product_class, "A", 100.0, 5)
- results = product_class.find_all(derived=True)
- assert len(results) == 1
- assert results[0].discounted_price == pytest.approx(90.0)
- assert results[0].total_value == pytest.approx(500.0)
-
- def test_find_all_derived_list_by_name(self, product_class):
- self._insert(product_class, "B", 50.0, 3)
- results = product_class.find_all(derived=["total_value"])
- assert len(results) == 1
- assert results[0].total_value == pytest.approx(150.0)
- assert results[0].discounted_price is None
-
- def test_find_all_derived_list_all(self, product_class):
- self._insert(product_class, "C", 200.0, 2)
- results = product_class.find_all(derived=["discounted_price", "total_value"])
- assert results[0].discounted_price == pytest.approx(180.0)
- assert results[0].total_value == pytest.approx(400.0)
-
- def test_find_one_derived(self, product_class):
- p = self._insert(product_class, "D", 80.0, 4)
- result = product_class.find_one(p.id, derived=True)
- assert result.discounted_price == pytest.approx(72.0)
-
- def test_find_one_or_fail_derived(self, product_class):
- p = self._insert(product_class, "D2", 80.0, 4)
- result = product_class.find_one_or_fail(p.id, derived=True)
- assert result.discounted_price == pytest.approx(72.0)
- assert result.total_value == pytest.approx(320.0)
-
- def test_find_one_or_fail_derived_list(self, product_class):
- p = self._insert(product_class, "D3", 80.0, 4)
- result = product_class.find_one_or_fail(p.id, derived=["discounted_price", "total_value"])
- assert result.discounted_price == pytest.approx(72.0)
- assert result.total_value == pytest.approx(320.0)
-
- def test_find_all_derived_false_default(self, product_class):
- self._insert(product_class, "E", 60.0, 1)
- results = product_class.find_all()
- assert results[0].discounted_price is None
- assert results[0].total_value is None
-
- def test_find_all_derived_all(self, product_class):
- self._insert(product_class, "F", 100.0, 5)
- results = product_class.find_all(derived="all")
- assert len(results) == 1
- assert results[0].discounted_price == pytest.approx(90.0)
- assert results[0].total_value == pytest.approx(500.0)
-
- def test_find_one_derived_all(self, product_class):
- p = self._insert(product_class, "G", 80.0, 4)
- result = product_class.find_one(p.id, derived="all")
- assert result.discounted_price == pytest.approx(72.0)
- assert result.total_value == pytest.approx(320.0)
-
- def test_find_one_or_fail_derived_all(self, product_class):
- p = self._insert(product_class, "H", 60.0, 3)
- result = product_class.find_one_or_fail(p.id, derived="all")
- assert result.discounted_price == pytest.approx(54.0)
- assert result.total_value == pytest.approx(180.0)
-
-
-class TestDerivedFieldFormA:
- """Tests for Form A declaration: ClassVar[DerivedField] = DerivedField(...)."""
-
- def test_form_a_fields_registered(self, product_form_a_class):
- assert "discounted_price" in product_form_a_class.__derived_fields__
- assert "total_value" in product_form_a_class.__derived_fields__
-
- def test_form_a_query(self, product_form_a_class):
- p = product_form_a_class(name="FA", price=100.0, quantity=3)
- p.save()
- results = product_form_a_class.find_all(derived=True)
- assert results[0].discounted_price == pytest.approx(90.0)
- assert results[0].total_value == pytest.approx(300.0)
-
- def test_form_a_source_id_mapping(self, product_form_a_class):
- df = product_form_a_class.__derived_fields__["discounted_price"]
- assert df._source_id is not None
- assert product_form_a_class.__derived_field_names__[df._source_id] == "discounted_price"
-
-
-class TestDerivedFieldDictForm:
- """Tests for derived=dict form."""
-
- def _insert(self, Model, name, price, quantity):
- p = Model(name=name, price=price, quantity=quantity)
- p.save()
- return p
-
- def test_derived_dict_with_lambda(self, product_class):
- self._insert(product_class, "D1", 100.0, 4)
- results = product_class.find_all(
- derived={
- "my_discount": lambda d: ArithmeticOperation(
- dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.8)
- )
- }
- )
- assert results[0].__dict__["my_discount"] == pytest.approx(80.0)
-
- def test_derived_dict_with_derived_field_instance(self, product_class):
- self._insert(product_class, "D2", 50.0, 2)
- df = product_class.__derived_fields__["total_value"]
- results = product_class.find_all(
- derived={"tv": df}
- )
- assert results[0].__dict__["tv"] == pytest.approx(100.0)
-
-
- def test_derived_dict_with_expression_object(self, product_class):
- self._insert(product_class, "D3", 80.0, 5)
- dialect = product_class.backend().dialect
- expr = ArithmeticOperation(
- dialect, "mul", Column(dialect, "price"), Literal(dialect, 0.5)
- )
- results = product_class.find_all(
- derived={"half_price": expr}
- )
- assert results[0].__dict__["half_price"] == pytest.approx(40.0)
-
-
-class TestDerivedFieldLookupByInstance:
- """Tests for derived=[DerivedField instance] form."""
-
- def _insert(self, Model, name, price, quantity):
- p = Model(name=name, price=price, quantity=quantity)
- p.save()
- return p
-
- def test_lookup_by_derived_field_instance(self, product_class):
- self._insert(product_class, "L1", 200.0, 1)
- df = product_class.__derived_fields__["discounted_price"]
- results = product_class.find_all(derived=[df])
- assert results[0].discounted_price == pytest.approx(180.0)
-
-
-class TestExtraDerived:
-
- def _insert(self, Model, name, price, quantity):
- p = Model(name=name, price=price, quantity=quantity)
- p.save()
- return p
-
- def test_extra_derived_basic(self, product_class):
- self._insert(product_class, "F", 100.0, 10)
- results = product_class.find_all(
- extra_derived={
- "triple_price": lambda d: ArithmeticOperation(
- dialect, "mul", Column(dialect, d, "price"), Literal(d, 3)
- )
- }
- )
- assert len(results) == 1
- assert results[0].__dict__["triple_price"] == pytest.approx(300.0)
-
- def test_extra_derived_conflict_raises(self, product_class):
- self._insert(product_class, "G", 50.0, 2)
- with pytest.raises(ValueError, match="conflicts with a declared derived field"):
- product_class.find_all(
- extra_derived={
- "discounted_price": lambda d: ArithmeticOperation(
- dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.5)
- )
- }
- )
-
- def test_derived_and_extra_derived_together(self, product_class):
- self._insert(product_class, "H", 40.0, 5)
- results = product_class.find_all(
- derived=True,
- extra_derived={
- "double_qty": lambda d: ArithmeticOperation(
- dialect, "mul", Column(dialect, d, "quantity"), Literal(d, 2)
- )
- }
- )
- assert results[0].discounted_price == pytest.approx(36.0)
- assert results[0].total_value == pytest.approx(200.0)
- assert results[0].__dict__["double_qty"] == pytest.approx(10.0)
-
-
-class TestDerivedFieldWithProxy:
- """Tests for DerivedField using FieldProxy in expressions."""
-
- def _insert(self, Model, name, price, quantity):
- p = Model(name=name, price=price, quantity=quantity)
- p.save()
- return p
-
- def test_proxy_derived_query(self, product_with_proxy_class):
- self._insert(product_with_proxy_class, "P1", 100.0, 4)
- results = product_with_proxy_class.find_all(derived=True)
- assert results[0].discounted_price == pytest.approx(90.0)
- assert results[0].total_value == pytest.approx(400.0)
-
- def test_proxy_derived_all_fields(self, product_with_proxy_class):
- self._insert(product_with_proxy_class, "P2", 200.0, 3)
- results = product_with_proxy_class.find_all(
- derived=["discounted_price", "total_value"]
- )
- assert results[0].discounted_price == pytest.approx(180.0)
- assert results[0].total_value == pytest.approx(600.0)
-
- def test_proxy_derived_not_in_model_fields(self, product_with_proxy_class):
- assert "discounted_price" not in product_with_proxy_class.model_fields
- assert "total_value" not in product_with_proxy_class.model_fields
-
- def test_proxy_derived_not_in_dirty_fields(self, product_with_proxy_class):
- self._insert(product_with_proxy_class, "P3", 50.0, 2)
- instance = product_with_proxy_class.find_all(derived=True)[0]
- instance.__dict__["discounted_price"] = 999.0
- assert "discounted_price" not in instance.dirty_fields
-
- def test_proxy_derived_read_only(self, product_with_proxy_class):
- self._insert(product_with_proxy_class, "P4", 80.0, 1)
- instance = product_with_proxy_class.find_all(derived=True)[0]
- with pytest.raises(AttributeError):
- instance.discounted_price = 123.0
-
- def test_proxy_derived_not_saved_to_db(self, product_with_proxy_class):
- p = self._insert(product_with_proxy_class, "P5", 60.0, 2)
- instance = product_with_proxy_class.find_one(p.id, derived=True)
- assert instance.discounted_price == pytest.approx(54.0)
- instance.name = "P5_modified"
- instance.save()
- fresh = product_with_proxy_class.find_one(p.id, derived=True)
- assert fresh.name == "P5_modified"
- assert fresh.discounted_price == pytest.approx(54.0)
-
-
-class TestDerivedFieldWithUseColumnAndAdapter:
- """Tests for DerivedField with UseColumn and UseAdapter annotations."""
-
- def _insert(self, Model, name, price, quantity):
- p = Model(name=name, price=price, quantity=quantity)
- p.save()
- return p
-
- def test_use_column_alias_in_select(self, product_with_column_and_adapter_class):
- """UseColumn controls the SELECT alias; result maps back to Python field name."""
- self._insert(product_with_column_and_adapter_class, "UC1", 100.0, 5)
- results = product_with_column_and_adapter_class.find_all(derived=True)
- # discounted_price has UseColumn("disc") — alias is "disc" in SQL,
- # but the value is accessible via the Python attribute name
- assert results[0].discounted_price == pytest.approx(90.0)
- assert results[0].total_int == 500
-
- def test_use_adapter_from_database(self, product_with_column_and_adapter_class):
- """UseAdapter applies from_database conversion on the derived field value."""
- self._insert(product_with_column_and_adapter_class, "UA1", 33.3, 3)
- results = product_with_column_and_adapter_class.find_all(derived=["total_int"])
- # 33.3 * 3 = 99.9, adapter rounds to int → 100
- assert results[0].total_int == 100
- assert isinstance(results[0].total_int, int)
-
- def test_use_column_field_not_in_model_fields(self, product_with_column_and_adapter_class):
- assert "discounted_price" not in product_with_column_and_adapter_class.model_fields
- assert "total_int" not in product_with_column_and_adapter_class.model_fields
-
- def test_use_column_column_name_stored(self, product_with_column_and_adapter_class):
- df = product_with_column_and_adapter_class.__derived_fields__["discounted_price"]
- assert df.column_name == "disc"
-
- def test_use_adapter_stored(self, product_with_column_and_adapter_class):
- df = product_with_column_and_adapter_class.__derived_fields__["total_int"]
- assert df.adapter is not None
-
- def test_use_column_and_adapter_together(self, product_with_column_and_adapter_class):
- """Both UseColumn and UseAdapter can coexist on the same derived field."""
- self._insert(product_with_column_and_adapter_class, "CA1", 50.0, 4)
- results = product_with_column_and_adapter_class.find_all(
- derived=["discounted_price", "total_int"]
- )
- assert results[0].discounted_price == pytest.approx(45.0)
- assert results[0].total_int == 200
-
-
-class TestDerivedFieldColumnConflict:
- """Tests that column name conflicts between regular and derived fields are detected."""
-
- def test_use_column_conflict_raises(self):
- """UseColumn on derived field must not duplicate a regular field's column name."""
- with pytest.raises(TypeError, match="conflicts with a regular field's column name"):
- class ConflictModel(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "conflict"
-
- id: Optional[int] = None
- discount_rate: Annotated[float, UseColumn("disc")]
- discounted: ClassVar[Annotated[float, DerivedField(
- lambda d: ArithmeticOperation(
- dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.9)
- ),
- ), UseColumn("disc")]]
-
- def test_use_column_no_conflict_different_names(self):
- """Different column names should not conflict."""
- class NoConflict(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "no_conflict"
-
- id: Optional[int] = None
- discount_rate: Annotated[float, UseColumn("rate")]
- discounted: ClassVar[Annotated[float, DerivedField(
- lambda d: ArithmeticOperation(
- dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.9)
- ),
- ), UseColumn("disc")]]
-
- assert NoConflict.__derived_fields__["discounted"].column_name == "disc"
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field_async.py
deleted file mode 100644
index 82643fe1..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_derived_field_async.py
+++ /dev/null
@@ -1,365 +0,0 @@
-# src/rhosocial/activerecord/testsuite/feature/basic/fields/test_derived_field_async.py
-import pytest
-from typing import ClassVar, Optional
-from typing_extensions import Annotated
-
-from rhosocial.activerecord.base import DerivedField, UseColumn
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.backend.expression import (
- ArithmeticOperation,
- Column,
- Literal,
-)
-
-
-class TestAsyncDerivedFieldDeclaration:
-
- async def test_derived_fields_registered(self, async_product_class):
- assert "discounted_price" in async_product_class.__derived_fields__
- assert "total_value" in async_product_class.__derived_fields__
-
- async def test_descriptor_class_access(self, async_product_class):
- assert isinstance(async_product_class.discounted_price, DerivedField)
-
- async def test_derived_field_with_static_expression(self, async_product_class):
- """Test DerivedField constructed with a pre-built expression object (non-callable path)."""
- dialect = async_product_class.backend().dialect
- static_expr = ArithmeticOperation(
- dialect, "mul", Column(dialect, "price"), Literal(dialect, 2)
- )
- df = DerivedField(static_expr)
- resolved = df.resolve(dialect)
- assert resolved is static_expr
-
- async def test_descriptor_instance_default_none(self, async_product_class):
- p = async_product_class(name="x", price=10.0, quantity=1)
- assert p.discounted_price is None
- assert p.total_value is None
-
- async def test_derived_field_names_mapping(self, async_product_class):
- names = async_product_class.__derived_field_names__
- df = async_product_class.__derived_fields__["discounted_price"]
- assert names[id(df)] == "discounted_price"
-
-
-class TestAsyncDerivedFieldQuery:
-
- async def _insert(self, Model, name, price, quantity):
- p = Model(name=name, price=price, quantity=quantity)
- await p.save()
- return p
-
- async def test_find_all_derived_true(self, async_product_class):
- await self._insert(async_product_class, "A", 100.0, 5)
- results = await async_product_class.find_all(derived=True)
- assert len(results) == 1
- assert results[0].discounted_price == pytest.approx(90.0)
- assert results[0].total_value == pytest.approx(500.0)
-
- async def test_find_all_derived_list_by_name(self, async_product_class):
- await self._insert(async_product_class, "B", 50.0, 3)
- results = await async_product_class.find_all(derived=["total_value"])
- assert len(results) == 1
- assert results[0].total_value == pytest.approx(150.0)
- assert results[0].discounted_price is None
-
- async def test_find_all_derived_list_all(self, async_product_class):
- await self._insert(async_product_class, "C", 200.0, 2)
- results = await async_product_class.find_all(derived=["discounted_price", "total_value"])
- assert results[0].discounted_price == pytest.approx(180.0)
- assert results[0].total_value == pytest.approx(400.0)
-
- async def test_find_one_derived(self, async_product_class):
- p = await self._insert(async_product_class, "D", 80.0, 4)
- result = await async_product_class.find_one(p.id, derived=True)
- assert result.discounted_price == pytest.approx(72.0)
-
- async def test_find_one_or_fail_derived(self, async_product_class):
- p = await self._insert(async_product_class, "D2", 80.0, 4)
- result = await async_product_class.find_one_or_fail(p.id, derived=True)
- assert result.discounted_price == pytest.approx(72.0)
- assert result.total_value == pytest.approx(320.0)
-
- async def test_find_one_or_fail_derived_list(self, async_product_class):
- p = await self._insert(async_product_class, "D3", 80.0, 4)
- result = await async_product_class.find_one_or_fail(p.id, derived=["discounted_price", "total_value"])
- assert result.discounted_price == pytest.approx(72.0)
- assert result.total_value == pytest.approx(320.0)
-
- async def test_find_all_derived_false_default(self, async_product_class):
- await self._insert(async_product_class, "E", 60.0, 1)
- results = await async_product_class.find_all()
- assert results[0].discounted_price is None
- assert results[0].total_value is None
-
- async def test_find_all_derived_all(self, async_product_class):
- await self._insert(async_product_class, "F", 100.0, 5)
- results = await async_product_class.find_all(derived="all")
- assert len(results) == 1
- assert results[0].discounted_price == pytest.approx(90.0)
- assert results[0].total_value == pytest.approx(500.0)
-
- async def test_find_one_derived_all(self, async_product_class):
- p = await self._insert(async_product_class, "G", 80.0, 4)
- result = await async_product_class.find_one(p.id, derived="all")
- assert result.discounted_price == pytest.approx(72.0)
- assert result.total_value == pytest.approx(320.0)
-
- async def test_find_one_or_fail_derived_all(self, async_product_class):
- p = await self._insert(async_product_class, "H", 60.0, 3)
- result = await async_product_class.find_one_or_fail(p.id, derived="all")
- assert result.discounted_price == pytest.approx(54.0)
- assert result.total_value == pytest.approx(180.0)
-
-
-class TestAsyncDerivedFieldFormA:
- """Tests for Form A declaration: ClassVar[DerivedField] = DerivedField(...)."""
-
- async def test_form_a_fields_registered(self, async_product_form_a_class):
- assert "discounted_price" in async_product_form_a_class.__derived_fields__
- assert "total_value" in async_product_form_a_class.__derived_fields__
-
- async def test_form_a_query(self, async_product_form_a_class):
- p = async_product_form_a_class(name="FA", price=100.0, quantity=3)
- await p.save()
- results = await async_product_form_a_class.find_all(derived=True)
- assert results[0].discounted_price == pytest.approx(90.0)
- assert results[0].total_value == pytest.approx(300.0)
-
- async def test_form_a_source_id_mapping(self, async_product_form_a_class):
- df = async_product_form_a_class.__derived_fields__["discounted_price"]
- assert df._source_id is not None
- assert async_product_form_a_class.__derived_field_names__[df._source_id] == "discounted_price"
-
-
-class TestAsyncDerivedFieldDictForm:
- """Tests for derived=dict form."""
-
- async def _insert(self, Model, name, price, quantity):
- p = Model(name=name, price=price, quantity=quantity)
- await p.save()
- return p
-
- async def test_derived_dict_with_lambda(self, async_product_class):
- await self._insert(async_product_class, "D1", 100.0, 4)
- results = await async_product_class.find_all(
- derived={
- "my_discount": lambda d: ArithmeticOperation(
- dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.8)
- )
- }
- )
- assert results[0].__dict__["my_discount"] == pytest.approx(80.0)
-
- async def test_derived_dict_with_derived_field_instance(self, async_product_class):
- await self._insert(async_product_class, "D2", 50.0, 2)
- df = async_product_class.__derived_fields__["total_value"]
- results = await async_product_class.find_all(
- derived={"tv": df}
- )
- assert results[0].__dict__["tv"] == pytest.approx(100.0)
-
-
- async def test_derived_dict_with_expression_object(self, async_product_class):
- await self._insert(async_product_class, "D3", 80.0, 5)
- dialect = async_product_class.backend().dialect
- expr = ArithmeticOperation(
- dialect, "mul", Column(dialect, "price"), Literal(dialect, 0.5)
- )
- results = await async_product_class.find_all(
- derived={"half_price": expr}
- )
- assert results[0].__dict__["half_price"] == pytest.approx(40.0)
-
-
-class TestAsyncDerivedFieldLookupByInstance:
- """Tests for derived=[DerivedField instance] form."""
-
- async def _insert(self, Model, name, price, quantity):
- p = Model(name=name, price=price, quantity=quantity)
- await p.save()
- return p
-
- async def test_lookup_by_derived_field_instance(self, async_product_class):
- await self._insert(async_product_class, "L1", 200.0, 1)
- df = async_product_class.__derived_fields__["discounted_price"]
- results = await async_product_class.find_all(derived=[df])
- assert results[0].discounted_price == pytest.approx(180.0)
-
-
-class TestAsyncExtraDerived:
-
- async def _insert(self, Model, name, price, quantity):
- p = Model(name=name, price=price, quantity=quantity)
- await p.save()
- return p
-
- async def test_extra_derived_basic(self, async_product_class):
- await self._insert(async_product_class, "F", 100.0, 10)
- results = await async_product_class.find_all(
- extra_derived={
- "triple_price": lambda d: ArithmeticOperation(
- dialect, "mul", Column(dialect, d, "price"), Literal(d, 3)
- )
- }
- )
- assert len(results) == 1
- assert results[0].__dict__["triple_price"] == pytest.approx(300.0)
-
- async def test_extra_derived_conflict_raises(self, async_product_class):
- await self._insert(async_product_class, "G", 50.0, 2)
- with pytest.raises(ValueError, match="conflicts with a declared derived field"):
- await async_product_class.find_all(
- extra_derived={
- "discounted_price": lambda d: ArithmeticOperation(
- dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.5)
- )
- }
- )
-
- async def test_derived_and_extra_derived_together(self, async_product_class):
- await self._insert(async_product_class, "H", 40.0, 5)
- results = await async_product_class.find_all(
- derived=True,
- extra_derived={
- "double_qty": lambda d: ArithmeticOperation(
- dialect, "mul", Column(dialect, d, "quantity"), Literal(d, 2)
- )
- }
- )
- assert results[0].discounted_price == pytest.approx(36.0)
- assert results[0].total_value == pytest.approx(200.0)
- assert results[0].__dict__["double_qty"] == pytest.approx(10.0)
-
-
-class TestAsyncDerivedFieldWithProxy:
- """Tests for DerivedField using FieldProxy in expressions."""
-
- async def _insert(self, Model, name, price, quantity):
- p = Model(name=name, price=price, quantity=quantity)
- await p.save()
- return p
-
- async def test_proxy_derived_query(self, async_product_with_proxy_class):
- await self._insert(async_product_with_proxy_class, "P1", 100.0, 4)
- results = await async_product_with_proxy_class.find_all(derived=True)
- assert results[0].discounted_price == pytest.approx(90.0)
- assert results[0].total_value == pytest.approx(400.0)
-
- async def test_proxy_derived_all_fields(self, async_product_with_proxy_class):
- await self._insert(async_product_with_proxy_class, "P2", 200.0, 3)
- results = await async_product_with_proxy_class.find_all(
- derived=["discounted_price", "total_value"]
- )
- assert results[0].discounted_price == pytest.approx(180.0)
- assert results[0].total_value == pytest.approx(600.0)
-
- async def test_proxy_derived_not_in_model_fields(self, async_product_with_proxy_class):
- assert "discounted_price" not in async_product_with_proxy_class.model_fields
- assert "total_value" not in async_product_with_proxy_class.model_fields
-
- async def test_proxy_derived_not_in_dirty_fields(self, async_product_with_proxy_class):
- await self._insert(async_product_with_proxy_class, "P3", 50.0, 2)
- instance = (await async_product_with_proxy_class.find_all(derived=True))[0]
- instance.__dict__["discounted_price"] = 999.0
- assert "discounted_price" not in instance.dirty_fields
-
- async def test_proxy_derived_read_only(self, async_product_with_proxy_class):
- await self._insert(async_product_with_proxy_class, "P4", 80.0, 1)
- instance = (await async_product_with_proxy_class.find_all(derived=True))[0]
- with pytest.raises(AttributeError):
- instance.discounted_price = 123.0
-
- async def test_proxy_derived_not_saved_to_db(self, async_product_with_proxy_class):
- p = await self._insert(async_product_with_proxy_class, "P5", 60.0, 2)
- instance = await async_product_with_proxy_class.find_one(p.id, derived=True)
- assert instance.discounted_price == pytest.approx(54.0)
- instance.name = "P5_modified"
- await instance.save()
- fresh = await async_product_with_proxy_class.find_one(p.id, derived=True)
- assert fresh.name == "P5_modified"
- assert fresh.discounted_price == pytest.approx(54.0)
-
-
-class TestAsyncDerivedFieldWithUseColumnAndAdapter:
- """Tests for DerivedField with UseColumn and UseAdapter annotations."""
-
- async def _insert(self, Model, name, price, quantity):
- p = Model(name=name, price=price, quantity=quantity)
- await p.save()
- return p
-
- async def test_use_column_alias_in_select(self, async_product_with_column_and_adapter_class):
- """UseColumn controls the SELECT alias; result maps back to Python field name."""
- await self._insert(async_product_with_column_and_adapter_class, "UC1", 100.0, 5)
- results = await async_product_with_column_and_adapter_class.find_all(derived=True)
- # discounted_price has UseColumn("disc") — alias is "disc" in SQL,
- # but the value is accessible via the Python attribute name
- assert results[0].discounted_price == pytest.approx(90.0)
- assert results[0].total_int == 500
-
- async def test_use_adapter_from_database(self, async_product_with_column_and_adapter_class):
- """UseAdapter applies from_database conversion on the derived field value."""
- await self._insert(async_product_with_column_and_adapter_class, "UA1", 33.3, 3)
- results = await async_product_with_column_and_adapter_class.find_all(derived=["total_int"])
- # 33.3 * 3 = 99.9, adapter rounds to int → 100
- assert results[0].total_int == 100
- assert isinstance(results[0].total_int, int)
-
- async def test_use_column_field_not_in_model_fields(self, async_product_with_column_and_adapter_class):
- assert "discounted_price" not in async_product_with_column_and_adapter_class.model_fields
- assert "total_int" not in async_product_with_column_and_adapter_class.model_fields
-
- async def test_use_column_column_name_stored(self, async_product_with_column_and_adapter_class):
- df = async_product_with_column_and_adapter_class.__derived_fields__["discounted_price"]
- assert df.column_name == "disc"
-
- async def test_use_adapter_stored(self, async_product_with_column_and_adapter_class):
- df = async_product_with_column_and_adapter_class.__derived_fields__["total_int"]
- assert df.adapter is not None
-
- async def test_use_column_and_adapter_together(self, async_product_with_column_and_adapter_class):
- """Both UseColumn and UseAdapter can coexist on the same derived field."""
- await self._insert(async_product_with_column_and_adapter_class, "CA1", 50.0, 4)
- results = await async_product_with_column_and_adapter_class.find_all(
- derived=["discounted_price", "total_int"]
- )
- assert results[0].discounted_price == pytest.approx(45.0)
- assert results[0].total_int == 200
-
-
-class TestAsyncDerivedFieldColumnConflict:
- """Tests that column name conflicts between regular and derived fields are detected."""
-
- async def test_use_column_conflict_raises(self):
- """UseColumn on derived field must not duplicate a regular field's column name."""
- with pytest.raises(TypeError, match="conflicts with a regular field's column name"):
- class ConflictModel(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "conflict"
-
- id: Optional[int] = None
- discount_rate: Annotated[float, UseColumn("disc")]
- discounted: ClassVar[Annotated[float, DerivedField(
- lambda d: ArithmeticOperation(
- dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.9)
- ),
- ), UseColumn("disc")]]
-
- async def test_use_column_no_conflict_different_names(self):
- """Different column names should not conflict."""
- class NoConflict(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "no_conflict"
-
- id: Optional[int] = None
- discount_rate: Annotated[float, UseColumn("rate")]
- discounted: ClassVar[Annotated[float, DerivedField(
- lambda d: ArithmeticOperation(
- dialect, "mul", Column(dialect, d, "price"), Literal(d, 0.9)
- ),
- ), UseColumn("disc")]]
-
- assert NoConflict.__derived_fields__["discounted"].column_name == "disc"
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures.py
index a35d9746..2bb1a933 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures.py
@@ -3,4 +3,3 @@
Bridge file for example basic fixtures tests from the testsuite.
"""
from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures_async import * # noqa: F403
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures_async.py
index cef55fc3..60d8d3e9 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures_async.py
@@ -1,3 +1,5 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_example_basic_fixtures_async.py
"""Bridge file for async feature.basic.fields.test_example_basic_fixtures_async tests."""
from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures_async import * # noqa: F401, F403
+
+from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping.py
index 87b920c3..360f1ed6 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping.py
@@ -21,5 +21,3 @@
# The test classes contain the actual test cases.
from rhosocial.activerecord.testsuite.feature.basic.fields.test_field_column_mapping import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.fields.test_field_column_mapping_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping_async.py
index d46911b2..27561fb7 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping_async.py
@@ -1,3 +1,5 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_field_column_mapping_async.py
"""Bridge file for async feature.basic.fields.test_field_column_mapping_async tests."""
from rhosocial.activerecord.testsuite.feature.basic.fields.test_field_column_mapping_async import * # noqa: F401, F403
+
+from rhosocial.activerecord.testsuite.feature.basic.fields.test_field_column_mapping_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields.py
deleted file mode 100644
index 13b13fb8..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/basic/test_fields.py
-"""
-Basic Fields Test Module for postgres backend.
-
-This module imports and runs the shared tests from the testsuite package,
-ensuring postgres backend compatibility.
-"""
-# IMPORTANT: These imports are essential for pytest to work correctly.
-# Even though they may be flagged as "unused" by some IDEs or linters,
-# they must not be removed. They are the mechanism by which pytest discovers
-# the fixtures and the tests from the external testsuite package.
-
-# Although the root conftest.py sets up the environment, explicitly importing
-# the fixtures here makes the dependency clear and can help with test discovery
-# in some IDEs. These fixtures are defined in the testsuite package and are
-# parameterized to run against the scenarios defined in `providers/scenarios.py`.
-from rhosocial.activerecord.testsuite.feature.basic.conftest import (
- type_test_model, # noqa: F401
- async_type_test_model # noqa: F401
-)
-
-# Import shared tests from testsuite package
-from rhosocial.activerecord.testsuite.feature.basic.fields.test_fields import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.fields.test_fields_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py
deleted file mode 100644
index 2dace749..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/basic/fields/test_fields_async.py
-"""Bridge file for async feature.basic.fields.test_fields_async tests."""
-from rhosocial.activerecord.testsuite.feature.basic.fields.test_fields_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/conftest.py
new file mode 100644
index 00000000..b31eb03a
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/conftest.py
@@ -0,0 +1,4 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/conftest.py
+"""Use the shared ``basic/nopk`` minimal test set."""
+
+from rhosocial.activerecord.testsuite.feature.basic.nopk.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models.py
index ec0a3c2a..2abc20b6 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models.py
@@ -1,4 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models.py
"""Bridge file for the testsuite keyless model contract (sync and async)."""
from rhosocial.activerecord.testsuite.feature.basic.nopk.test_keyless_models import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.nopk.test_keyless_models_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models_async.py
new file mode 100644
index 00000000..002d1a36
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/nopk/test_keyless_models_async.py
@@ -0,0 +1 @@
+from rhosocial.activerecord.testsuite.feature.basic.nopk.test_keyless_models_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/conftest.py
new file mode 100644
index 00000000..fefb63b6
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/conftest.py
@@ -0,0 +1,4 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/conftest.py
+"""Use the shared ``basic/readonly`` minimal test set."""
+
+from rhosocial.activerecord.testsuite.feature.basic.readonly.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models.py
index f9b39047..a8f07aea 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models.py
@@ -1,4 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models.py
"""Bridge file for the testsuite read-only model contract (sync and async)."""
from rhosocial.activerecord.testsuite.feature.basic.readonly.test_readonly_models import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.readonly.test_readonly_models_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models_async.py
new file mode 100644
index 00000000..bc6ebf7a
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/readonly/test_readonly_models_async.py
@@ -0,0 +1 @@
+from rhosocial.activerecord.testsuite.feature.basic.readonly.test_readonly_models_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/test_basic_mapped_models.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/test_basic_mapped_models.py
deleted file mode 100644
index 6601e6ad..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/test_basic_mapped_models.py
+++ /dev/null
@@ -1,20 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/basic/test_basic_mapped_models.py
-"""
-This module serves as a bridge to execute the generic basic mapped models tests
-defined in the `rhosocial-activerecord-testsuite` package against the PostgreSQL backend.
-
-The tests are dynamically parametrized with PostgreSQL-specific fixtures.
-"""
-
-# IMPORTANT:
-# The following imports are essential for the test suite to discover and run the tests.
-# The fixtures are defined in the `conftest.py` of the testsuite and are implemented
-# by the provider in the current backend (`tests/providers/basic.py`).
-
-# The `basic_model_fixtures` is a fixture that provides the necessary setup for the tests.
-from rhosocial.activerecord.testsuite.feature.basic.conftest import mapped_models_fixtures # noqa: F401
-
-# The `TestBasicMappedModels` class contains the actual test cases.
-from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/conftest.py
new file mode 100644
index 00000000..07a37fb2
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/conftest.py
@@ -0,0 +1,4 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/conftest.py
+"""Use the shared ``basic/type_adapter`` minimal test set."""
+
+from rhosocial.activerecord.testsuite.feature.basic.type_adapter.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter.py
index d6108e4f..db332eac 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter.py
@@ -14,5 +14,3 @@
# Import all tests from the generic testsuite file.
from rhosocial.activerecord.testsuite.feature.basic.type_adapter.test_type_adapter import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.type_adapter.test_type_adapter_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter_async.py
index 533df4fa..7294139e 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter_async.py
@@ -1,3 +1,5 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/type_adapter/test_type_adapter_async.py
"""Bridge file for async feature.basic.type_adapter.test_type_adapter_async tests."""
from rhosocial.activerecord.testsuite.feature.basic.type_adapter.test_type_adapter_async import * # noqa: F401, F403
+
+from rhosocial.activerecord.testsuite.feature.basic.type_adapter.test_type_adapter_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types/conftest.py
new file mode 100644
index 00000000..dc28256c
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types/conftest.py
@@ -0,0 +1,4 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/types/conftest.py
+"""Use the shared ``basic/types`` test set."""
+
+from rhosocial.activerecord.testsuite.feature.basic.types.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants.py
new file mode 100644
index 00000000..099a7b6a
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants.py
+"""Bridge for the shared ``basic/types`` test module.
+
+The test logic lives in ``rhosocial-activerecord-testsuite``; this file
+only makes its tests discoverable in this backend's test run. Do not
+remove the star import -- it is the discovery mechanism.
+"""
+
+from rhosocial.activerecord.testsuite.feature.basic.types.test_type_variants import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants_async.py
new file mode 100644
index 00000000..9314f5aa
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants_async.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/types/test_type_variants_async.py
+"""Bridge for the shared ``basic/types`` test module.
+
+The test logic lives in ``rhosocial-activerecord-testsuite``; this file
+only makes its tests discoverable in this backend's test run. Do not
+remove the star import -- it is the discovery mechanism.
+"""
+
+from rhosocial.activerecord.testsuite.feature.basic.types.test_type_variants_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py
new file mode 100644
index 00000000..ca2e4294
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py
@@ -0,0 +1,107 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/conftest.py
+"""Use the shared ``basic/types_complex`` test set, gated on PostGIS.
+
+The shared fixture declares its geometry column through ``CustomType``, which
+PostgreSQL renders verbatim: DDL *builds* even when PostGIS is absent, so the
+shared capability gate (which only skips when DDL building fails) never fires
+and ``CREATE TABLE`` raises ``type "geometry" does not exist`` on a plain
+server. This backend bridge adds the missing capability gate locally:
+
+* the shared ``schema`` fixture is autouse, so every test in the group builds
+ the GEOMETRY table at setup. We override it as opt-in so declaration-only
+ tests keep running on servers without PostGIS;
+* the tests that actually build or use the table are skipped with a named
+ reason when the scenario's server has no ``geometry`` type. The catalog is
+ queried directly: a server can advertise PostGIS as installable while no
+ database actually has the type, which the extension-name probe cannot tell.
+"""
+
+import re
+from functools import lru_cache
+from pathlib import Path
+
+import pytest
+
+import support.postgres
+from rhosocial.activerecord.backend.options import ExecutionOptions
+from rhosocial.activerecord.backend.schema import StatementType
+from rhosocial.activerecord.testsuite.feature.basic.fixtures.operations import (
+ create_schema,
+ drop_schema,
+)
+from rhosocial.activerecord.testsuite.feature.basic.fixtures.types_complex_models import (
+ COMPLEX_FIXTURES,
+)
+from rhosocial.activerecord.testsuite.feature.basic.types_complex.conftest import * # noqa: F401,F403
+from rhosocial.activerecord.testsuite.feature.basic.types_complex.conftest import (
+ _unsupported_reason,
+)
+
+_SKIP_REASON = "geometry type not available on this server (PostGIS required)"
+
+_GEOMETRY_TYPE_SQL = "SELECT 1 FROM pg_type WHERE typname = 'geometry' LIMIT 1"
+
+
+@lru_cache(maxsize=None)
+def _geometry_type_available(scenario_name: str) -> bool:
+ """Whether the scenario's server actually has a ``geometry`` type.
+
+ Ask the catalog, not the extension name: PostGIS can be advertised as
+ installable while the type is missing from the database the tests run in.
+ Probe ``template1`` because the per-directory test database is created
+ from it with no explicit TEMPLATE, so the type's presence there decides
+ whether the test tables can use it.
+ """
+ scenario = support.postgres.scenario(scenario_name)
+ backend = scenario.backend_class(connection_config=scenario.make_config("template1"))
+ try:
+ backend.connect()
+ try:
+ result = backend.execute(
+ _GEOMETRY_TYPE_SQL, (), options=ExecutionOptions(stmt_type=StatementType.DQL)
+ )
+ return bool(result.data)
+ finally:
+ backend.disconnect()
+ except Exception:
+ # A probe we could not perform is not evidence that the type is absent.
+ # Leave the test to run so a real connection problem surfaces normally.
+ return True
+
+
+@pytest.fixture(scope="function")
+def schema(database):
+ """Opt-in override of the shared autouse fixture.
+
+ Declaration-only tests must not build the GEOMETRY table at setup: on a
+ server without PostGIS that would make them error before they can assert
+ anything. Tests that need the tables request this fixture (directly or
+ through the ``complex_*_class`` fixtures) as before.
+ """
+ why = _unsupported_reason(database.dialect)
+ if why is not None:
+ pytest.skip(why)
+ create_schema(database, COMPLEX_FIXTURES)
+ yield
+ drop_schema(database, COMPLEX_FIXTURES)
+
+
+def pytest_collection_modifyitems(config, items):
+ """Skip the PostGIS-dependent tests on scenarios without PostGIS."""
+ here = Path(__file__).resolve().parent
+ for item in items:
+ path = Path(str(item.fspath)).resolve()
+ if here not in path.parents:
+ continue
+ # Only tests that build or use the tables request ``schema`` (directly
+ # or through the complex_*_class fixtures). Declaration-only tests do
+ # not, so they keep running on servers without PostGIS.
+ if "schema" not in item.fixturenames:
+ continue
+ match = re.search(r"\[([^\]]+)\]\s*$", item.name)
+ if match is None:
+ # No scenario in the node id: let the test run rather than
+ # guessing about a server we have not identified.
+ continue
+ if not _geometry_type_available(match.group(1)):
+ item.add_marker(pytest.mark.skip(reason=_SKIP_REASON))
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants.py
new file mode 100644
index 00000000..66eca43b
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants.py
+"""Bridge for the shared ``basic/types_complex`` test module.
+
+The test logic lives in ``rhosocial-activerecord-testsuite``; this file
+only makes its tests discoverable in this backend's test run. Do not
+remove the star import -- it is the discovery mechanism.
+"""
+
+from rhosocial.activerecord.testsuite.feature.basic.types_complex.test_complex_variants import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants_async.py
new file mode 100644
index 00000000..3981f7b7
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants_async.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/types_complex/test_complex_variants_async.py
+"""Bridge for the shared ``basic/types_complex`` test module.
+
+The test logic lives in ``rhosocial-activerecord-testsuite``; this file
+only makes its tests discoverable in this backend's test run. Do not
+remove the star import -- it is the discovery mechanism.
+"""
+
+from rhosocial.activerecord.testsuite.feature.basic.types_complex.test_complex_variants_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py
new file mode 100644
index 00000000..ca697a6c
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py
@@ -0,0 +1,28 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/conftest.py
+"""Use the shared ``basic/types_long_content`` test set.
+
+The shared ``LongRow`` / ``AsyncLongRow`` fixtures declare ``id: Optional[int]``
+but no ``__primary_key__``. Since the primary-key-declaration refactor, a bare
+``ActiveRecord`` subclass is keyless (``primary_key() is None``), so ``save()``
+no longer writes back the generated id and ``find_one()`` refuses to address
+the row. PostgreSQL is one of the few dialects that renders all four content
+concepts (text/blob/json/xml), so this group actually runs its round-trip tests
+here and is the only backend affected.
+
+The declaration belongs in the shared fixture, but until it is added there the
+postgres bridge restores it locally. Setting the class attribute (rather than
+subclassing) keeps the shared fixtures and the imported test module operating
+on the very same model objects.
+"""
+
+from rhosocial.activerecord.testsuite.feature.basic.types_long_content.conftest import * # noqa: F401,F403
+from rhosocial.activerecord.testsuite.feature.basic.fixtures.types_long_content_models import (
+ AsyncLongRow,
+ LongRow,
+)
+
+for _long_row_class in (LongRow, AsyncLongRow):
+ if _long_row_class.__primary_key__ is None:
+ _long_row_class.__primary_key__ = "id"
+
+del _long_row_class
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content.py
new file mode 100644
index 00000000..9ca9373e
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content.py
+"""Bridge for the shared ``basic/types_long_content`` test module.
+
+The test logic lives in ``rhosocial-activerecord-testsuite``; this file
+only makes its tests discoverable in this backend's test run. Do not
+remove the star import -- it is the discovery mechanism.
+"""
+
+from rhosocial.activerecord.testsuite.feature.basic.types_long_content.test_long_content import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content_async.py
new file mode 100644
index 00000000..a0a6d0f6
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content_async.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/types_long_content/test_long_content_async.py
+"""Bridge for the shared ``basic/types_long_content`` test module.
+
+The test logic lives in ``rhosocial-activerecord-testsuite``; this file
+only makes its tests discoverable in this backend's test run. Do not
+remove the star import -- it is the discovery mechanism.
+"""
+
+from rhosocial.activerecord.testsuite.feature.basic.types_long_content.test_long_content_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/conftest.py
new file mode 100644
index 00000000..af0b63da
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/conftest.py
@@ -0,0 +1,4 @@
+# tests/rhosocial/activerecord_postgres_test/feature/basic/validation/conftest.py
+"""Use the shared ``basic/validation`` minimal test set."""
+
+from rhosocial.activerecord.testsuite.feature.basic.validation.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation.py
index 03fc5eeb..a136f7f1 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation.py
@@ -14,5 +14,3 @@
)
from rhosocial.activerecord.testsuite.feature.basic.validation.test_pydantic_native_validation import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.validation.test_pydantic_native_validation_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation_async.py
index 1b5019de..62465994 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation_async.py
@@ -1,3 +1,5 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_pydantic_native_validation_async.py
"""Bridge file for async feature.basic.validation.test_pydantic_native_validation_async tests."""
from rhosocial.activerecord.testsuite.feature.basic.validation.test_pydantic_native_validation_async import * # noqa: F401, F403
+
+from rhosocial.activerecord.testsuite.feature.basic.validation.test_pydantic_native_validation_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation.py
index 2c2cd094..41de15ba 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation.py
@@ -21,5 +21,3 @@
# Import shared tests from testsuite package
from rhosocial.activerecord.testsuite.feature.basic.validation.test_validation import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.validation.test_validation_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation_async.py
index df784d78..9b25cb87 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation_async.py
@@ -1,3 +1,5 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/validation/test_validation_async.py
"""Bridge file for async feature.basic.validation.test_validation_async tests."""
from rhosocial.activerecord.testsuite.feature.basic.validation.test_validation_async import * # noqa: F401, F403
+
+from rhosocial.activerecord.testsuite.feature.basic.validation.test_validation_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management.py
index a5150e06..4486e093 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management.py
@@ -8,5 +8,3 @@
user_class_for_worker, # noqa: F401
)
from rhosocial.activerecord.testsuite.feature.basic.worker.test_connection_management import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.worker.test_connection_management_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management_async.py
index 3340c392..48a29cea 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management_async.py
@@ -1,3 +1,5 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_connection_management_async.py
"""Bridge file for async feature.basic.worker.test_connection_management_async tests."""
from rhosocial.activerecord.testsuite.feature.basic.worker.test_connection_management_async import * # noqa: F401, F403
+
+from rhosocial.activerecord.testsuite.feature.basic.worker.test_connection_management_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud.py
index 287d0828..c75a4e8c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud.py
@@ -9,5 +9,3 @@
async_user_class_for_worker, # noqa: F401
)
from rhosocial.activerecord.testsuite.feature.basic.worker.test_parallel_crud import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.worker.test_parallel_crud_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud_async.py
index 62eedf04..dce3b9dc 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud_async.py
@@ -1,3 +1,5 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_parallel_crud_async.py
"""Bridge file for async feature.basic.worker.test_parallel_crud_async tests."""
from rhosocial.activerecord.testsuite.feature.basic.worker.test_parallel_crud_async import * # noqa: F401, F403
+
+from rhosocial.activerecord.testsuite.feature.basic.worker.test_parallel_crud_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle.py
index 7df4d9df..53d0a0d0 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle.py
@@ -8,5 +8,3 @@
user_class_for_worker, # noqa: F401
)
from rhosocial.activerecord.testsuite.feature.basic.worker.test_worker_pool_lifecycle import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.basic.worker.test_worker_pool_lifecycle_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle_async.py b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle_async.py
index 15ccdd00..67029291 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle_async.py
@@ -1,3 +1,5 @@
# tests/rhosocial/activerecord_postgres_test/feature/basic/worker/test_worker_pool_lifecycle_async.py
"""Bridge file for async feature.basic.worker.test_worker_pool_lifecycle_async tests."""
from rhosocial.activerecord.testsuite.feature.basic.worker.test_worker_pool_lifecycle_async import * # noqa: F401, F403
+
+from rhosocial.activerecord.testsuite.feature.basic.worker.test_worker_pool_lifecycle_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py
deleted file mode 100644
index 0cc3dba5..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/conftest.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.conftest import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk.py
deleted file mode 100644
index 508723af..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_bulk import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk_async.py
deleted file mode 100644
index 93522c88..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_bulk_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_bulk_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml.py
deleted file mode 100644
index daf79d05..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_dml import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml_async.py
deleted file mode 100644
index 43214f10..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dml_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_dml_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql.py
deleted file mode 100644
index df9f8d98..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_dql import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql_async.py
deleted file mode 100644
index 1a0e1d77..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_dql_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_dql_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only.py
deleted file mode 100644
index 7b9befb3..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_read_only import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only_async.py
deleted file mode 100644
index d8668b1c..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_read_only_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_read_only_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte.py
deleted file mode 100644
index 253caa54..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_set_cte import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte_async.py
deleted file mode 100644
index b60ecaff..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_set_cte_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_set_cte_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete.py
deleted file mode 100644
index 5fe311b2..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_soft_delete import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete_async.py
deleted file mode 100644
index 21ef6585..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_soft_delete_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_soft_delete_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation.py
deleted file mode 100644
index aa055ff4..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_validation import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation_async.py
deleted file mode 100644
index 28c97f34..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/cli/test_cli_validation_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.cli.test_cli_validation_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/conftest.py
new file mode 100644
index 00000000..7308beeb
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/conftest.py
@@ -0,0 +1,16 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/conftest.py
+"""Bridge the shared ``feature/cli`` contracts with a dedicated database.
+
+The testsuite ``feature/cli`` conftest hardcodes the database name ``test_cli``;
+the backend's own ``feature/cli`` subset also uses that shared fixture. To keep
+the two directories' parallel subsets isolated, override the database name here
+with a unique one derived from this directory.
+"""
+from rhosocial.activerecord.testsuite.feature.cli.conftest import * # noqa: F401,F403
+import pytest
+
+
+@pytest.fixture(scope="session")
+def database_config(backend_scenario):
+ name = "test_cli_contracts"
+ return backend_scenario, backend_scenario.make_config(name), name
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk.py
new file mode 100644
index 00000000..efad951f
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_bulk import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk_async.py
new file mode 100644
index 00000000..1c2ea125
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_bulk_async.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_bulk_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml.py
new file mode 100644
index 00000000..29b48f46
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_dml import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml_async.py
new file mode 100644
index 00000000..8f77750b
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dml_async.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_dml_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql.py
new file mode 100644
index 00000000..8ae62862
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_dql import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql_async.py
new file mode 100644
index 00000000..f541e116
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_dql_async.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_dql_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate.py
new file mode 100644
index 00000000..c3cb89de
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate.py
+"""Bridge to the shared ``feature/cli`` migrate contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_migrate import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate_async.py
new file mode 100644
index 00000000..e966c21b
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_migrate_async.py
+"""Bridge to the shared ``feature/cli`` migrate contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_migrate_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only.py
new file mode 100644
index 00000000..5e238906
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_read_only import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only_async.py
new file mode 100644
index 00000000..fb9b984f
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_read_only_async.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_read_only_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte.py
new file mode 100644
index 00000000..2f6ad010
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_set_cte import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte_async.py
new file mode 100644
index 00000000..f3743fb3
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_set_cte_async.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_set_cte_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete.py
new file mode 100644
index 00000000..7b0a0dd3
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_soft_delete import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete_async.py
new file mode 100644
index 00000000..bc5d2bb6
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_soft_delete_async.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_soft_delete_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation.py
new file mode 100644
index 00000000..122d30bb
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_validation import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation_async.py
new file mode 100644
index 00000000..1246ad64
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cli_contracts/test_cli_validation_async.py
+"""Bridge to the shared ``feature/cli`` contract."""
+from rhosocial.activerecord.testsuite.feature.cli.test_cli_validation_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py
index 540b149e..f6afccec 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py
@@ -1,138 +1,79 @@
# tests/rhosocial/activerecord_postgres_test/feature/connection/conftest.py
-"""
-Pytest configuration for connection pool tests.
+"""L2 backend fixtures for the connection-pool tests.
+
+The pool fixtures own their connections: each creates the directory's database
+for the scenario it runs under and hands out PostgreSQL backends from it. The
+concurrency tables are created and dropped by the table fixtures through that
+pool, from the definitions in ``pool_definitions.py``.
-This module provides fixtures for testing connection pools with PostgreSQL backends.
+``database_config`` declares the directory's identity (scenario, configuration
+and database name). It exists for the xdist grouping contract: a scenario's
+tests for one directory stay on one worker, while different scenarios are
+different databases and may run in parallel.
"""
+from rhosocial.activerecord.testsuite.pytest_plugin import Declaration
-import os
-from typing import Dict, Any, Generator
+from functools import partial
+from pathlib import Path
+from typing import Generator
import pytest
import pytest_asyncio
-import yaml
-from rhosocial.activerecord.backend.impl.postgres.backend.async_backend import AsyncPostgresBackend
-from rhosocial.activerecord.backend.impl.postgres.backend import PostgresBackend
-from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig
+from rhosocial.activerecord.backend.options import ExecutionOptions
+from rhosocial.activerecord.backend.schema import StatementType
from rhosocial.activerecord.connection.pool import (
- PoolConfig,
- BackendPool,
AsyncBackendPool,
+ BackendPool,
+ PoolConfig,
)
+from pool_definitions import (
+ AsyncConcurrentTestPostsDefinition,
+ AsyncConcurrentTestUsersDefinition,
+ ConcurrentTestPostsDefinition,
+ ConcurrentTestUsersDefinition,
+)
-# --- Scenario Loading Logic ---
-
-SCENARIO_MAP: Dict[str, Dict[str, Any]] = {}
-
-
-def register_scenario(name: str, config: Dict[str, Any]):
- SCENARIO_MAP[name] = config
-
-
-def _load_scenarios_from_config():
- """Load scenarios from a configuration file."""
- config_path = None
- env_config_path = os.getenv("POSTGRES_SCENARIOS_CONFIG_PATH")
-
- if env_config_path and os.path.exists(env_config_path):
- config_path = env_config_path
- else:
- default_path = os.path.join(
- os.path.dirname(__file__),
- "../../../../config",
- "postgres_scenarios.yaml"
- )
- if os.path.exists(default_path):
- config_path = default_path
- elif env_config_path:
- print(f"Warning: Scenario file specified in POSTGRES_SCENARIOS_CONFIG_PATH not found: {env_config_path}")
- return
-
- if not config_path:
- raise FileNotFoundError(
- "No PostgreSQL scenarios configuration file found. "
- "Set POSTGRES_SCENARIOS_CONFIG_PATH or place postgres_scenarios.yaml in tests/config."
- )
-
- try:
- with open(config_path, 'r', encoding='utf-8') as f:
- config_data = yaml.safe_load(f)
-
- if 'scenarios' not in config_data:
- raise ValueError(f"Configuration file {config_path} does not contain 'scenarios' key")
-
- for scenario_name, config in config_data['scenarios'].items():
- if config:
- register_scenario(scenario_name, config)
-
- except ImportError:
- raise ImportError("PyYAML is required to load scenario configuration files") # noqa: B904
-
-
-_load_scenarios_from_config()
-
-
-def get_scenario_config(name: str) -> Dict[str, Any]:
- if name not in SCENARIO_MAP:
- if SCENARIO_MAP:
- name = next(iter(SCENARIO_MAP))
- else:
- raise ValueError("No scenarios registered or enabled")
- config_dict = SCENARIO_MAP[name].copy()
- # Apply the pooled database name so parallel workers never share a schema.
- from providers.pooling import resolve_database_name
-
- pooled_db = resolve_database_name(name)
- if pooled_db:
- config_dict["database"] = pooled_db
- return config_dict
+DDL = ExecutionOptions(stmt_type=StatementType.DDL)
-def get_scenario_names():
- return list(SCENARIO_MAP.keys())
+def _database_name() -> str:
+ """Database name from this directory's namespace (below ``feature``)."""
+ parts = Path(__file__).parent.parts
+ start = parts.index("feature") + 1
+ return "test_" + "_".join(parts[start:])
-# --- Pool Fixtures ---
-def create_postgres_backend_factory(config_dict: Dict[str, Any]):
- """Create a factory function that produces PostgresBackend instances."""
- def factory():
- config = PostgresConnectionConfig(**config_dict)
- backend = PostgresBackend(connection_config=config)
- backend.connect()
- return backend
- return factory
+# This directory owns a database shared by all its tests within a scenario;
+# pin them to one worker so setup/teardown never races on the same database.
+DECLARATION = Declaration(
+ uses_database=True,
+ parallel=True,
+ purpose="Directory-owned PostgreSQL database shared by this test group.",
+)
-def create_async_postgres_backend_factory(config_dict: Dict[str, Any]):
- """Create a factory function that produces AsyncPostgresBackend instances."""
- def factory():
- config = PostgresConnectionConfig(**config_dict)
- backend = AsyncPostgresBackend(connection_config=config)
- # Note: connect() will be called by the pool when needed
- return backend
- return factory
+@pytest.fixture(scope="session")
+def database_config(backend_scenario):
+ """The scenario, its connection configuration, and the directory database name."""
+ name = _database_name()
+ return backend_scenario, backend_scenario.make_config(name), name
@pytest.fixture(scope="function")
-def postgres_pool() -> Generator[BackendPool, None, None]:
+def postgres_pool(database_config) -> Generator[BackendPool, None, None]:
"""Create a BackendPool with PostgreSQL backends for testing."""
- scenario_names = get_scenario_names()
- if not scenario_names:
- pytest.skip("No PostgreSQL scenarios configured")
-
- config_dict = get_scenario_config(scenario_names[0])
- config_dict.pop('enabled', None)
-
+ scenario, config, name = database_config
+ scenario.reset_database(name)
pool_config = PoolConfig(
min_size=1,
max_size=5,
timeout=30.0,
validate_on_borrow=True,
validation_query="SELECT 1",
- backend_factory=create_postgres_backend_factory(config_dict),
+ backend_factory=partial(scenario.backend_class, connection_config=config),
)
pool = BackendPool.create(pool_config)
@@ -141,22 +82,17 @@ def postgres_pool() -> Generator[BackendPool, None, None]:
@pytest_asyncio.fixture(scope="function")
-async def async_postgres_pool() -> AsyncBackendPool:
+async def async_postgres_pool(database_config) -> AsyncBackendPool:
"""Create an AsyncBackendPool with PostgreSQL backends for testing."""
- scenario_names = get_scenario_names()
- if not scenario_names:
- pytest.skip("No PostgreSQL scenarios configured")
-
- config_dict = get_scenario_config(scenario_names[0])
- config_dict.pop('enabled', None)
-
+ scenario, config, name = database_config
+ scenario.reset_database(name)
pool_config = PoolConfig(
min_size=1,
max_size=5,
timeout=30.0,
validate_on_borrow=True,
validation_query="SELECT 1",
- backend_factory=create_async_postgres_backend_factory(config_dict),
+ backend_factory=partial(scenario.async_backend_class, connection_config=config),
)
pool = await AsyncBackendPool.create(pool_config)
@@ -165,21 +101,16 @@ async def async_postgres_pool() -> AsyncBackendPool:
@pytest.fixture(scope="function")
-def postgres_pool_large() -> Generator[BackendPool, None, None]:
+def postgres_pool_large(database_config) -> Generator[BackendPool, None, None]:
"""Create a larger BackendPool for stress testing."""
- scenario_names = get_scenario_names()
- if not scenario_names:
- pytest.skip("No PostgreSQL scenarios configured")
-
- config_dict = get_scenario_config(scenario_names[0])
- config_dict.pop('enabled', None)
-
+ scenario, config, name = database_config
+ scenario.reset_database(name)
pool_config = PoolConfig(
min_size=2,
max_size=10,
timeout=60.0,
validate_on_borrow=False, # Faster for stress tests
- backend_factory=create_postgres_backend_factory(config_dict),
+ backend_factory=partial(scenario.backend_class, connection_config=config),
)
pool = BackendPool.create(pool_config)
@@ -188,21 +119,16 @@ def postgres_pool_large() -> Generator[BackendPool, None, None]:
@pytest_asyncio.fixture(scope="function")
-async def async_postgres_pool_large() -> AsyncBackendPool:
+async def async_postgres_pool_large(database_config) -> AsyncBackendPool:
"""Create a larger AsyncBackendPool for stress testing."""
- scenario_names = get_scenario_names()
- if not scenario_names:
- pytest.skip("No PostgreSQL scenarios configured")
-
- config_dict = get_scenario_config(scenario_names[0])
- config_dict.pop('enabled', None)
-
+ scenario, config, name = database_config
+ scenario.reset_database(name)
pool_config = PoolConfig(
min_size=2,
max_size=10,
timeout=60.0,
validate_on_borrow=False,
- backend_factory=create_async_postgres_backend_factory(config_dict),
+ backend_factory=partial(scenario.async_backend_class, connection_config=config),
)
pool = await AsyncBackendPool.create(pool_config)
@@ -212,63 +138,44 @@ async def async_postgres_pool_large() -> AsyncBackendPool:
# --- Table Setup Fixtures ---
+
@pytest.fixture(scope="function")
def postgres_pool_with_tables(postgres_pool: BackendPool) -> Generator[BackendPool, None, None]:
"""Create a pool with test tables initialized."""
+ definitions = (
+ ConcurrentTestPostsDefinition,
+ ConcurrentTestUsersDefinition,
+ )
with postgres_pool.connection() as backend:
- backend.execute("DROP TABLE IF EXISTS concurrent_test_users")
- backend.execute("DROP TABLE IF EXISTS concurrent_test_posts")
- backend.execute("""
- CREATE TABLE concurrent_test_users (
- id SERIAL PRIMARY KEY,
- thread_id INTEGER,
- name VARCHAR(255),
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- )
- """)
- backend.execute("""
- CREATE TABLE concurrent_test_posts (
- id SERIAL PRIMARY KEY,
- thread_id INTEGER,
- user_id INTEGER,
- title VARCHAR(255),
- content TEXT
- )
- """)
+ fixtures = [definition(backend.dialect) for definition in definitions]
+ for fixture in fixtures:
+ backend.execute(*fixture.drop_table.to_sql(), options=DDL)
+ backend.execute(*fixture.create_table.to_sql(), options=DDL)
yield postgres_pool
with postgres_pool.connection() as backend:
- backend.execute("DROP TABLE IF EXISTS concurrent_test_posts")
- backend.execute("DROP TABLE IF EXISTS concurrent_test_users")
+ for fixture in reversed(fixtures):
+ backend.execute(*fixture.drop_table.to_sql(), options=DDL)
@pytest_asyncio.fixture(scope="function")
-async def async_postgres_pool_with_tables(async_postgres_pool: AsyncBackendPool) -> AsyncBackendPool:
+async def async_postgres_pool_with_tables(
+ async_postgres_pool: AsyncBackendPool,
+) -> AsyncBackendPool:
"""Create an async pool with test tables initialized."""
+ definitions = (
+ AsyncConcurrentTestPostsDefinition,
+ AsyncConcurrentTestUsersDefinition,
+ )
async with async_postgres_pool.connection() as backend:
- await backend.execute("DROP TABLE IF EXISTS concurrent_test_users")
- await backend.execute("DROP TABLE IF EXISTS concurrent_test_posts")
- await backend.execute("""
- CREATE TABLE concurrent_test_users (
- id SERIAL PRIMARY KEY,
- task_id INTEGER,
- name VARCHAR(255),
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- )
- """)
- await backend.execute("""
- CREATE TABLE concurrent_test_posts (
- id SERIAL PRIMARY KEY,
- task_id INTEGER,
- user_id INTEGER,
- title VARCHAR(255),
- content TEXT
- )
- """)
+ fixtures = [definition(backend.dialect) for definition in definitions]
+ for fixture in fixtures:
+ await backend.execute(*fixture.drop_table.to_sql(), options=DDL)
+ await backend.execute(*fixture.create_table.to_sql(), options=DDL)
yield async_postgres_pool
async with async_postgres_pool.connection() as backend:
- await backend.execute("DROP TABLE IF EXISTS concurrent_test_posts")
- await backend.execute("DROP TABLE IF EXISTS concurrent_test_users")
+ for fixture in reversed(fixtures):
+ await backend.execute(*fixture.drop_table.to_sql(), options=DDL)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py b/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py
new file mode 100644
index 00000000..44ccaada
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py
@@ -0,0 +1,146 @@
+# tests/rhosocial/activerecord_postgres_test/feature/connection/pool_definitions.py
+"""The connection-pool tests' own tables.
+
+The concurrent tests create and drop these tables through the pool itself, so
+their DDL belongs here rather than in the conftest or in a test body: a
+definition class receives only a ``dialect`` and knows nothing about backends,
+databases, connection pools or execution.
+
+The sync and async test sets each use their own pair of tables, and the only
+difference between the two pairs is the column naming the worker
+(``thread_id`` for threads, ``task_id`` for asyncio tasks).
+
+The primary keys are declared with PostgreSQL's own ``SERIAL`` type class, so
+the DDL the tables get is the same ``SERIAL PRIMARY KEY`` the inline SQL used to
+spell; no SQL text is written here.
+"""
+
+from rhosocial.activerecord.backend.expression import (
+ ColumnConstraint as Constraint,
+ ColumnDefinition as Column,
+ CreateTableStatement as CreateTable,
+ DropTableStatement as DropTable,
+ current_timestamp,
+)
+from rhosocial.activerecord.backend.expression.objects import Table
+from rhosocial.activerecord.backend.expression.statements import (
+ ColumnDefaultConstraint as Default,
+ ColumnPrimaryKeyConstraint as PrimaryKey,
+)
+from rhosocial.activerecord.backend.expression.types import (
+ IntegerType as Int,
+ TextType as Text,
+ TimestampType,
+ VarCharType as VarChar,
+)
+from rhosocial.activerecord.backend.impl.postgres.expression.types import (
+ PostgresSerialType,
+)
+from rhosocial.activerecord.testsuite.feature.query.fixtures.definitions import supports_drop_if_exists
+
+
+class Definition:
+ """Base class for the pool tests' table definitions."""
+
+ table_name = ""
+
+ def __init__(self, dialect):
+ self.dialect = dialect
+ self.create_table = CreateTable(
+ self.dialect,
+ table=Table(self.dialect, self.table_name),
+ columns=self.columns(),
+ )
+ self.drop_table = DropTable(
+ self.dialect,
+ table=Table(self.dialect, self.table_name),
+ if_exists=supports_drop_if_exists(self.dialect),
+ )
+
+ def columns(self):
+ raise NotImplementedError
+
+ def column(self, name, sql_type, constraints=None):
+ return Column(self.dialect, name, sql_type, constraints=constraints or [])
+
+ def auto_pk(self, name="id"):
+ return self.column(
+ name,
+ PostgresSerialType(self.dialect),
+ [
+ Constraint(
+ self.dialect,
+ branch=PrimaryKey(self.dialect),
+ )
+ ],
+ )
+
+ def created_at(self, name="created_at"):
+ return self.column(
+ name,
+ TimestampType(self.dialect),
+ [
+ Constraint(
+ self.dialect,
+ branch=Default(self.dialect, current_timestamp(self.dialect)),
+ )
+ ],
+ )
+
+
+class ConcurrentTestUsersDefinition(Definition):
+ """The synchronized users table."""
+
+ table_name = "concurrent_test_users"
+
+ def columns(self):
+ return [
+ self.auto_pk(),
+ self.column("thread_id", Int(self.dialect)),
+ self.column("name", VarChar(self.dialect, 255)),
+ self.created_at(),
+ ]
+
+
+class ConcurrentTestPostsDefinition(Definition):
+ """The synchronized posts table."""
+
+ table_name = "concurrent_test_posts"
+
+ def columns(self):
+ return [
+ self.auto_pk(),
+ self.column("thread_id", Int(self.dialect)),
+ self.column("user_id", Int(self.dialect)),
+ self.column("title", VarChar(self.dialect, 255)),
+ self.column("content", Text(self.dialect)),
+ ]
+
+
+class AsyncConcurrentTestUsersDefinition(Definition):
+ """The asyncio users table."""
+
+ table_name = "concurrent_test_users"
+
+ def columns(self):
+ return [
+ self.auto_pk(),
+ self.column("task_id", Int(self.dialect)),
+ self.column("name", VarChar(self.dialect, 255)),
+ self.created_at(),
+ ]
+
+
+class AsyncConcurrentTestPostsDefinition(Definition):
+ """The asyncio posts table."""
+
+ table_name = "concurrent_test_posts"
+
+ def columns(self):
+ return [
+ self.auto_pk(),
+ self.column("task_id", Int(self.dialect)),
+ self.column("user_id", Int(self.dialect)),
+ self.column("title", VarChar(self.dialect, 255)),
+ self.column("content", Text(self.dialect)),
+ ]
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/core/conftest.py
new file mode 100644
index 00000000..bb848484
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/core/conftest.py
@@ -0,0 +1,2 @@
+# tests/rhosocial/activerecord_postgres_test/feature/core/conftest.py
+from rhosocial.activerecord_postgres_test.feature.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/test_features.py b/tests/rhosocial/activerecord_postgres_test/feature/core/test_features.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/test_features.py
rename to tests/rhosocial/activerecord_postgres_test/feature/core/test_features.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/test_features_async.py b/tests/rhosocial/activerecord_postgres_test/feature/core/test_features_async.py
similarity index 100%
rename from tests/rhosocial/activerecord_postgres_test/feature/test_features_async.py
rename to tests/rhosocial/activerecord_postgres_test/feature/core/test_features_async.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cte/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/cte/conftest.py
new file mode 100644
index 00000000..90e9e46d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cte/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cte/conftest.py
+"""Use the shared ``cte`` minimal test set."""
+from rhosocial.activerecord.testsuite.feature.cte.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte.py b/tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte.py
new file mode 100644
index 00000000..064547d3
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte.py
+"""
+Bridge file for composite PK CTE query tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.cte.test_composite_pk_cte import * # noqa: F403
+except ImportError:
+ pytest.skip("composite_pk testsuite not available", allow_module_level=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte_async.py b/tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte_async.py
new file mode 100644
index 00000000..a506d773
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte_async.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/cte/test_composite_pk_cte_async.py
+"""
+Bridge file for composite PK async CTE query tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.cte.test_composite_pk_cte_async import * # noqa: F403
+except ImportError:
+ pytest.skip("composite_pk testsuite not available", allow_module_level=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/conftest.py
new file mode 100644
index 00000000..8def55d1
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/ddl/conftest.py
+"""Bridge fixture configuration for the shared DDL contract group."""
+from rhosocial.activerecord.testsuite.feature.ddl.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/conftest.py
new file mode 100644
index 00000000..fe34b5ec
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/ddl/core/conftest.py
+"""Bridge fixture configuration for the shared DDL core contracts."""
+from rhosocial.activerecord.testsuite.feature.ddl.core.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_ddl_source_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_ddl_source_contract.py
new file mode 100644
index 00000000..1762533e
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_ddl_source_contract.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_ddl_source_contract.py
+"""Bridge to the shared DDL contract."""
+from rhosocial.activerecord.testsuite.feature.ddl.core.test_ddl_source_contract import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation.py
new file mode 100644
index 00000000..2daa54e2
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation.py
+"""Bridge to the shared DDL contract."""
+from rhosocial.activerecord.testsuite.feature.ddl.core.test_derivation import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation_async.py
new file mode 100644
index 00000000..62b929e5
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_derivation_async.py
+"""Bridge to the shared DDL contract."""
+from rhosocial.activerecord.testsuite.feature.ddl.core.test_derivation_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_migration_function_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_migration_function_contract.py
new file mode 100644
index 00000000..2342440f
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_migration_function_contract.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_migration_function_contract.py
+"""Bridge to the shared DDL contract."""
+from rhosocial.activerecord.testsuite.feature.ddl.core.test_migration_function_contract import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_statement_derivation.py b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_statement_derivation.py
new file mode 100644
index 00000000..f9e30c4c
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_statement_derivation.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/ddl/core/test_statement_derivation.py
+"""Bridge to the shared DDL contract."""
+from rhosocial.activerecord.testsuite.feature.ddl.core.test_statement_derivation import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py
deleted file mode 100644
index 412a154d..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/events/conftest.py
-"""
-Pytest configuration for events feature tests.
-
-This file imports fixtures from the corresponding testsuite, making them
-available to the tests in this directory.
-"""
-from rhosocial.activerecord.testsuite.feature.events.conftest import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models.py b/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models.py
deleted file mode 100644
index 7c6d3a30..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models.py
-"""
-This file defines the generic ActiveRecord model classes used by the events tests.
-
-These models are "generic" because they define the data structure and validation
-rules (using Pydantic), but they are not tied to any specific database backend.
-The backend-specific provider is responsible for taking these classes and
-configuring them with a live database connection at test time.
-"""
-from typing import Optional, Dict, List, Tuple
-from datetime import datetime
-
-from pydantic import Field
-
-from rhosocial.activerecord.interface import ModelEvent
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin
-
-
-class EventTestModel(IntegerPKMixin, TimestampMixin, ActiveRecord):
- """A model class for testing event mechanisms"""
- @classmethod
- def table_name(cls):
- return "event_tests"
-
- id: Optional[int] = None
- name: str
- status: str = Field(default="draft")
- revision: int = Field(default=1)
- content: Optional[str] = None
-
- def __init__(self, **data):
- super().__init__(**data)
- self._event_logs = [] # Used to record event triggering history
-
- def log_event(self, event: ModelEvent, **kwargs):
- """Record the trigger history of events"""
- self._event_logs.append((event, kwargs))
-
- def get_event_logs(self) -> List[Tuple[ModelEvent, Dict]]:
- """Get the event history"""
- return self._event_logs.copy()
-
- def clear_event_logs(self):
- """Empty the history of events"""
- self._event_logs.clear()
-
-
-class EventTrackingModel(IntegerPKMixin, ActiveRecord):
- """A model for testing event tracking functionality."""
- @classmethod
- def table_name(cls):
- return "event_tracking_models"
-
- title: str
- content: str
- view_count: int = 0
- last_viewed_at: Optional[datetime] = None
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py310.py b/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py310.py
deleted file mode 100644
index bd3ee5e0..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py310.py
+++ /dev/null
@@ -1,69 +0,0 @@
-# src/rhosocial/activerecord/testsuite/feature/events/fixtures/models_py310.py
-"""
-Python 3.10+ fixture model definitions for events tests.
-
-This file contains model classes using Python 3.10+ syntax features:
-- `X | Y` syntax instead of `Optional[X]` or `Union[X, Y]`
-- `Type | None` instead of `Optional[Type]`
-
-Note: This file should only be imported and used in Python 3.10+ environments.
-"""
-from typing import Dict
-from datetime import datetime
-
-from pydantic import Field
-
-from rhosocial.activerecord.interface import ModelEvent
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin
-
-
-# Declare that this module requires Python 3.10+
-__requires_python__ = (3, 10)
-
-
-class EventTestModel(IntegerPKMixin, TimestampMixin, ActiveRecord):
- """A model class for testing event mechanisms.
-
- Python 3.10+ version using | syntax instead of Optional.
- """
- @classmethod
- def table_name(cls):
- return "event_tests"
-
- id: int | None = None
- name: str
- status: str = Field(default="draft")
- revision: int = Field(default=1)
- content: str | None = None
-
- def __init__(self, **data):
- super().__init__(**data)
- self._event_logs: list[tuple[ModelEvent, Dict]] = [] # Used to record event triggering history
-
- def log_event(self, event: ModelEvent, **kwargs):
- """Record the trigger history of events"""
- self._event_logs.append((event, kwargs))
-
- def get_event_logs(self) -> list[tuple[ModelEvent, Dict]]:
- """Get the event history"""
- return self._event_logs.copy()
-
- def clear_event_logs(self):
- """Empty the history of events"""
- self._event_logs.clear()
-
-
-class EventTrackingModel(IntegerPKMixin, ActiveRecord):
- """A model for testing event tracking functionality.
-
- Python 3.10+ version using | syntax instead of Optional.
- """
- @classmethod
- def table_name(cls):
- return "event_tracking_models"
-
- title: str
- content: str
- view_count: int = 0
- last_viewed_at: datetime | None = None
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py311.py b/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py311.py
deleted file mode 100644
index 786f4f32..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py311.py
+++ /dev/null
@@ -1,88 +0,0 @@
-# src/rhosocial/activerecord/testsuite/feature/events/fixtures/models_py311.py
-"""
-Python 3.11+ fixture model definitions for events tests.
-
-This file contains model classes using Python 3.11+ syntax features:
-- `Self` type for methods that return an instance of the same class
-- `X | Y` syntax (inherited from 3.10+)
-
-Note: This file should only be imported and used in Python 3.11+ environments.
-"""
-from __future__ import annotations
-
-from typing import Dict, Self
-from datetime import datetime
-
-from pydantic import Field
-
-from rhosocial.activerecord.interface import ModelEvent
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin
-
-
-# Declare that this module requires Python 3.11+
-__requires_python__ = (3, 11)
-
-
-class EventTestModel(IntegerPKMixin, TimestampMixin, ActiveRecord):
- """A model class for testing event mechanisms.
-
- Python 3.11+ version using | syntax and Self type.
- """
- @classmethod
- def table_name(cls):
- return "event_tests"
-
- id: int | None = None
- name: str
- status: str = Field(default="draft")
- revision: int = Field(default=1)
- content: str | None = None
-
- def __init__(self, **data):
- super().__init__(**data)
- self._event_logs: list[tuple[ModelEvent, Dict]] = [] # Used to record event triggering history
-
- def log_event(self, event: ModelEvent, **kwargs):
- """Record the trigger history of events"""
- self._event_logs.append((event, kwargs))
-
- def get_event_logs(self) -> list[tuple[ModelEvent, Dict]]:
- """Get the event history"""
- return self._event_logs.copy()
-
- def clear_event_logs(self) -> Self:
- """Empty the history of events and return self for chaining."""
- self._event_logs.clear()
- return self
-
- def set_status(self, new_status: str) -> Self:
- """Set status and return self for chaining."""
- self.status = new_status
- return self
-
- def increment_revision(self) -> Self:
- """Increment revision and return self for chaining."""
- self.revision += 1
- return self
-
-
-class EventTrackingModel(IntegerPKMixin, ActiveRecord):
- """A model for testing event tracking functionality.
-
- Python 3.11+ version using | syntax and Self type.
- """
- @classmethod
- def table_name(cls):
- return "event_tracking_models"
-
- title: str
- content: str
- view_count: int = 0
- last_viewed_at: datetime | None = None
-
- def record_view(self) -> Self:
- """Record a view and return self for chaining."""
- self.view_count += 1
- self.last_viewed_at = datetime.now()
- return self
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py312.py b/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py312.py
deleted file mode 100644
index 9196e1a0..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/events/fixtures/models_py312.py
+++ /dev/null
@@ -1,89 +0,0 @@
-# src/rhosocial/activerecord/testsuite/feature/events/fixtures/models_py312.py
-"""
-Python 3.12+ fixture model definitions for events tests.
-
-This file contains model classes using Python 3.12+ syntax features:
-- `@override` decorator for inheritance safety
-- `Self` type for methods that return an instance of the same class
-- `X | Y` syntax (inherited from 3.10+)
-
-Note: This file should only be imported and used in Python 3.12+ environments.
-"""
-from __future__ import annotations
-
-from typing import Dict, Self
-from datetime import datetime
-
-from pydantic import Field
-
-from rhosocial.activerecord.interface import ModelEvent
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin
-
-
-# Declare that this module requires Python 3.12+
-__requires_python__ = (3, 12)
-
-
-class EventTestModel(IntegerPKMixin, TimestampMixin, ActiveRecord):
- """A model class for testing event mechanisms.
-
- Python 3.12+ version using | syntax, Self type, and @override.
- """
- @classmethod
- def table_name(cls):
- return "event_tests"
-
- id: int | None = None
- name: str
- status: str = Field(default="draft")
- revision: int = Field(default=1)
- content: str | None = None
-
- def __init__(self, **data):
- super().__init__(**data)
- self._event_logs: list[tuple[ModelEvent, Dict]] = [] # Used to record event triggering history
-
- def log_event(self, event: ModelEvent, **kwargs):
- """Record the trigger history of events"""
- self._event_logs.append((event, kwargs))
-
- def get_event_logs(self) -> list[tuple[ModelEvent, Dict]]:
- """Get the event history"""
- return self._event_logs.copy()
-
- def clear_event_logs(self) -> Self:
- """Empty the history of events and return self for chaining."""
- self._event_logs.clear()
- return self
-
- def set_status(self, new_status: str) -> Self:
- """Set status and return self for chaining."""
- self.status = new_status
- return self
-
- def increment_revision(self) -> Self:
- """Increment revision and return self for chaining."""
- self.revision += 1
- return self
-
-
-class EventTrackingModel(IntegerPKMixin, ActiveRecord):
- """A model for testing event tracking functionality.
-
- Python 3.12+ version using | syntax, Self type, and @override.
- """
- @classmethod
- def table_name(cls):
- return "event_tracking_models"
-
- title: str
- content: str
- view_count: int = 0
- last_viewed_at: datetime | None = None
-
- def record_view(self) -> Self:
- """Record a view and return self for chaining."""
- self.view_count += 1
- self.last_viewed_at = datetime.now()
- return self
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_test_models.sql b/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_test_models.sql
deleted file mode 100644
index 010b55f6..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_test_models.sql
+++ /dev/null
@@ -1,20 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_test_models.sql
--- Schema for EventTestModel
-CREATE TABLE event_test_models (
- id SERIAL PRIMARY KEY,
- name VARCHAR(255) NOT NULL,
- status VARCHAR(50) DEFAULT 'draft',
- revision INTEGER DEFAULT 1,
- content TEXT,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
-);
-
--- Schema for EventTrackingModel
-CREATE TABLE event_tracking_models (
- id SERIAL PRIMARY KEY,
- title VARCHAR(255) NOT NULL,
- content TEXT,
- view_count INTEGER DEFAULT 0,
- last_viewed_at TIMESTAMP WITH TIME ZONE
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tests.sql b/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tests.sql
deleted file mode 100644
index 85cff134..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tests.sql
+++ /dev/null
@@ -1,11 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tests.sql
--- Schema for EventTestModel
-CREATE TABLE event_tests (
- id SERIAL PRIMARY KEY,
- name VARCHAR(255) NOT NULL,
- status VARCHAR(50) DEFAULT 'draft',
- revision INTEGER DEFAULT 1,
- content TEXT,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tracking_models.sql b/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tracking_models.sql
deleted file mode 100644
index 2e189ed9..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tracking_models.sql
+++ /dev/null
@@ -1,9 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/events/schema/event_tracking_models.sql
--- Schema for EventTrackingModel
-CREATE TABLE event_tracking_models (
- id SERIAL PRIMARY KEY,
- title VARCHAR(255) NOT NULL,
- content TEXT,
- view_count INTEGER DEFAULT 0,
- last_viewed_at TIMESTAMP WITH TIME ZONE
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers.py b/tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers.py
deleted file mode 100644
index 5964c8ba..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers.py
-"""
-Event Handler Test Module for PostgreSQL backend.
-
-This module imports and runs the shared tests from the testsuite package,
-ensuring PostgreSQL backend compatibility.
-"""
-# IMPORTANT: These imports are essential for pytest to work correctly.
-# Even though they may be flagged as "unused" by some IDEs or linters,
-# they must not be removed. They are the mechanism by which pytest discovers
-# the fixtures and the tests from the external testsuite package.
-
-# Although the root conftest.py sets up the environment, explicitly importing
-# the fixtures here makes the dependency clear and can help with test discovery
-# in some IDEs. These fixtures are defined in the testsuite package and are
-# parameterized to run against the scenarios defined in `providers/scenarios.py`.
-from rhosocial.activerecord.testsuite.feature.events.conftest import (
- event_model, # noqa: F401
- event_tracking_model, # Assuming event_tracking_model is also needed here # noqa: F401
-)
-
-# Import shared tests from testsuite package
-from rhosocial.activerecord.testsuite.feature.events.test_handlers import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.events.test_handlers_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers_async.py b/tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers_async.py
deleted file mode 100644
index 6b946f79..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/events/test_handlers_async.py
-"""Bridge file for async feature.events.test_handlers_async tests."""
-from rhosocial.activerecord.testsuite.feature.events.test_handlers_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle.py b/tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle.py
deleted file mode 100644
index 43bb6d83..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle.py
-"""
-Event Lifecycle Test Module for PostgreSQL backend.
-
-This module imports and runs the shared tests from the testsuite package,
-ensuring PostgreSQL backend compatibility.
-"""
-# IMPORTANT: These imports are essential for pytest to work correctly.
-# Even though they may be flagged as "unused" by some IDEs or linters,
-# they must not be removed. They are the mechanism by which pytest discovers
-# the fixtures and the tests from the external testsuite package.
-
-# Although the root conftest.py sets up the environment, explicitly importing
-# the fixtures here makes the dependency clear and can help with test discovery
-# in some IDEs. These fixtures are defined in the testsuite package and are
-# parameterized to run against the scenarios defined in `providers/scenarios.py`.
-from rhosocial.activerecord.testsuite.feature.events.conftest import (
- event_model, # noqa: F401
- event_tracking_model, # Assuming event_tracking_model is also needed here # noqa: F401
-)
-
-# Import shared tests from testsuite package
-from rhosocial.activerecord.testsuite.feature.events.test_lifecycle import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.events.test_lifecycle_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle_async.py b/tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle_async.py
deleted file mode 100644
index 94312c2a..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/events/test_lifecycle_async.py
-"""Bridge file for async feature.events.test_lifecycle_async tests."""
-from rhosocial.activerecord.testsuite.feature.events.test_lifecycle_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/interface/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/interface/conftest.py
deleted file mode 100644
index 52d35dc0..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/interface/conftest.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/interface/conftest.py
-"""
-Pytest configuration for interface tests.
-
-This file imports fixtures from the corresponding testsuite, making them
-available to the tests in this directory.
-"""
-from rhosocial.activerecord.testsuite.feature.interface.conftest import * # noqa: F403
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py b/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py
deleted file mode 100644
index 48cf1235..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py
+++ /dev/null
@@ -1,7 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict.py
-"""
-Bridge file for ThreadSafeDict interface tests from the testsuite.
-"""
-
-from rhosocial.activerecord.testsuite.feature.interface.test_threadsafe_dict import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.interface.test_threadsafe_dict_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py b/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py
deleted file mode 100644
index b5e43962..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/interface/test_threadsafe_dict_async.py
-"""Bridge file for async feature.interface.test_threadsafe_dict_async tests."""
-from rhosocial.activerecord.testsuite.feature.interface.test_threadsafe_dict_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/logging/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/logging/conftest.py
new file mode 100644
index 00000000..396228d5
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/logging/conftest.py
@@ -0,0 +1,6 @@
+# tests/rhosocial/activerecord_postgres_test/feature/logging/conftest.py
+"""The logging tests are unit-level: this directory needs no database tables.
+
+The shared suite has no ``logging`` fixture group, so there is nothing to
+import and no ``prepare`` / ``teardown`` group to declare.
+"""
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py
deleted file mode 100644
index afd426f8..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/mixins/conftest.py
-"""
-Pytest configuration for mixins feature tests.
-
-This file imports fixtures from the corresponding testsuite, making them
-available to the tests in this directory.
-"""
-from rhosocial.activerecord.testsuite.feature.mixins.conftest import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models.py
deleted file mode 100644
index 01fbcba0..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models.py
+++ /dev/null
@@ -1,61 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models.py
-"""
-This file defines the generic ActiveRecord model classes used by the mixins tests.
-
-These models are "generic" because they define the data structure and validation
-rules (using Pydantic), but they are not tied to any specific database backend.
-The backend-specific provider is responsible for taking these classes and
-configuring them with a live database connection at test time.
-"""
-from typing import Optional
-from datetime import datetime # noqa: F401
-
-from pydantic import Field
-
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin
-
-
-class TimestampedPost(IntegerPKMixin, TimestampMixin, ActiveRecord):
- """Blog post model with timestamps"""
- @classmethod
- def table_name(cls):
- return "timestamped_posts"
-
- id: Optional[int] = None
- title: str
- content: str
-
-
-class VersionedProduct(IntegerPKMixin, OptimisticLockMixin, ActiveRecord):
- """Product model with optimistic locking"""
- @classmethod
- def table_name(cls):
- return "versioned_products"
-
- id: Optional[int] = None
- name: str
- price: float = Field(default=0.0)
-
-
-class Task(IntegerPKMixin, SoftDeleteMixin, ActiveRecord):
- """Task model supporting soft deletion"""
- @classmethod
- def table_name(cls):
- return "tasks"
-
- id: Optional[int] = None
- title: str
- is_completed: bool = Field(default=False)
-
-
-class CombinedArticle(IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin, ActiveRecord):
- """Article model combining all mixins"""
- @classmethod
- def table_name(cls):
- return "combined_articles"
-
- id: Optional[int] = None
- title: str
- content: str
- status: str = Field(default="draft")
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py310.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py310.py
deleted file mode 100644
index b7d0778e..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py310.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# src/rhosocial/activerecord/testsuite/feature/mixins/fixtures/models_py310.py
-"""
-Python 3.10+ fixture model definitions for mixins tests.
-
-This file contains model classes using Python 3.10+ syntax features:
-- `X | Y` syntax instead of `Optional[X]` or `Union[X, Y]`
-- `Type | None` instead of `Optional[Type]`
-
-Note: This file should only be imported and used in Python 3.10+ environments.
-"""
-
-from pydantic import Field
-
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin
-
-
-# Declare that this module requires Python 3.10+
-__requires_python__ = (3, 10)
-
-
-class TimestampedPost(IntegerPKMixin, TimestampMixin, ActiveRecord):
- """Blog post model with timestamps.
-
- Python 3.10+ version using | syntax instead of Optional.
- """
- @classmethod
- def table_name(cls):
- return "timestamped_posts"
-
- id: int | None = None
- title: str
- content: str
-
-
-class VersionedProduct(IntegerPKMixin, OptimisticLockMixin, ActiveRecord):
- """Product model with optimistic locking.
-
- Python 3.10+ version using | syntax instead of Optional.
- """
- @classmethod
- def table_name(cls):
- return "versioned_products"
-
- id: int | None = None
- name: str
- price: float = Field(default=0.0)
-
-
-class Task(IntegerPKMixin, SoftDeleteMixin, ActiveRecord):
- """Task model supporting soft deletion.
-
- Python 3.10+ version using | syntax instead of Optional.
- """
- @classmethod
- def table_name(cls):
- return "tasks"
-
- id: int | None = None
- title: str
- is_completed: bool = Field(default=False)
-
-
-class CombinedArticle(IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin, ActiveRecord):
- """Article model combining all mixins.
-
- Python 3.10+ version using | syntax instead of Optional.
- """
- @classmethod
- def table_name(cls):
- return "combined_articles"
-
- id: int | None = None
- title: str
- content: str
- status: str = Field(default="draft")
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py311.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py311.py
deleted file mode 100644
index 978afa7f..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py311.py
+++ /dev/null
@@ -1,109 +0,0 @@
-# src/rhosocial/activerecord/testsuite/feature/mixins/fixtures/models_py311.py
-"""
-Python 3.11+ fixture model definitions for mixins tests.
-
-This file contains model classes using Python 3.11+ syntax features:
-- `Self` type for methods that return an instance of the same class
-- `X | Y` syntax (inherited from 3.10+)
-
-Note: This file should only be imported and used in Python 3.11+ environments.
-"""
-from __future__ import annotations
-
-from typing import Self
-
-from pydantic import Field
-
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin
-
-
-# Declare that this module requires Python 3.11+
-__requires_python__ = (3, 11)
-
-
-class TimestampedPost(IntegerPKMixin, TimestampMixin, ActiveRecord):
- """Blog post model with timestamps.
-
- Python 3.11+ version using | syntax and Self type.
- """
- @classmethod
- def table_name(cls):
- return "timestamped_posts"
-
- id: int | None = None
- title: str
- content: str
-
- def update_content(self, new_content: str) -> Self:
- """Update content and return self for chaining."""
- self.content = new_content
- return self
-
-
-class VersionedProduct(IntegerPKMixin, OptimisticLockMixin, ActiveRecord):
- """Product model with optimistic locking.
-
- Python 3.11+ version using | syntax and Self type.
- """
- @classmethod
- def table_name(cls):
- return "versioned_products"
-
- id: int | None = None
- name: str
- price: float = Field(default=0.0)
-
- def set_price(self, new_price: float) -> Self:
- """Set price and return self for chaining."""
- self.price = new_price
- return self
-
-
-class Task(IntegerPKMixin, SoftDeleteMixin, ActiveRecord):
- """Task model supporting soft deletion.
-
- Python 3.11+ version using | syntax and Self type.
- """
- @classmethod
- def table_name(cls):
- return "tasks"
-
- id: int | None = None
- title: str
- is_completed: bool = Field(default=False)
-
- def complete(self) -> Self:
- """Mark task as completed and return self for chaining."""
- self.is_completed = True
- return self
-
- def uncomplete(self) -> Self:
- """Mark task as not completed and return self for chaining."""
- self.is_completed = False
- return self
-
-
-class CombinedArticle(IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin, ActiveRecord):
- """Article model combining all mixins.
-
- Python 3.11+ version using | syntax and Self type.
- """
- @classmethod
- def table_name(cls):
- return "combined_articles"
-
- id: int | None = None
- title: str
- content: str
- status: str = Field(default="draft")
-
- def publish(self) -> Self:
- """Publish article and return self for chaining."""
- self.status = "published"
- return self
-
- def archive(self) -> Self:
- """Archive article and return self for chaining."""
- self.status = "archived"
- return self
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py312.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py312.py
deleted file mode 100644
index 176fabe4..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/fixtures/models_py312.py
+++ /dev/null
@@ -1,134 +0,0 @@
-# src/rhosocial/activerecord/testsuite/feature/mixins/fixtures/models_py312.py
-"""
-Python 3.12+ fixture model definitions for mixins tests.
-
-This file contains model classes using Python 3.12+ syntax features:
-- `@override` decorator for inheritance safety
-- `Self` type for methods that return an instance of the same class
-- `X | Y` syntax (inherited from 3.10+)
-
-Note: This file should only be imported and used in Python 3.12+ environments.
-"""
-from __future__ import annotations
-
-from typing import Self, override
-
-from pydantic import Field
-
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.field import IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin
-
-
-# Declare that this module requires Python 3.12+
-__requires_python__ = (3, 12)
-
-
-class TimestampedPost(IntegerPKMixin, TimestampMixin, ActiveRecord):
- """Blog post model with timestamps.
-
- Python 3.12+ version using | syntax, Self type, and @override.
- """
- @classmethod
- def table_name(cls):
- return "timestamped_posts"
-
- id: int | None = None
- title: str
- content: str
-
- @override
- def save(self, **kwargs) -> Self:
- """Save the post and return self for chaining."""
- super().save(**kwargs)
- return self
-
- def update_content(self, new_content: str) -> Self:
- """Update content and return self for chaining."""
- self.content = new_content
- return self
-
-
-class VersionedProduct(IntegerPKMixin, OptimisticLockMixin, ActiveRecord):
- """Product model with optimistic locking.
-
- Python 3.12+ version using | syntax, Self type, and @override.
- """
- @classmethod
- def table_name(cls):
- return "versioned_products"
-
- id: int | None = None
- name: str
- price: float = Field(default=0.0)
-
- @override
- def save(self, **kwargs) -> Self:
- """Save the product and return self for chaining."""
- super().save(**kwargs)
- return self
-
- def set_price(self, new_price: float) -> Self:
- """Set price and return self for chaining."""
- self.price = new_price
- return self
-
-
-class Task(IntegerPKMixin, SoftDeleteMixin, ActiveRecord):
- """Task model supporting soft deletion.
-
- Python 3.12+ version using | syntax, Self type, and @override.
- """
- @classmethod
- def table_name(cls):
- return "tasks"
-
- id: int | None = None
- title: str
- is_completed: bool = Field(default=False)
-
- @override
- def save(self, **kwargs) -> Self:
- """Save the task and return self for chaining."""
- super().save(**kwargs)
- return self
-
- def complete(self) -> Self:
- """Mark task as completed and return self for chaining."""
- self.is_completed = True
- return self
-
- def uncomplete(self) -> Self:
- """Mark task as not completed and return self for chaining."""
- self.is_completed = False
- return self
-
-
-class CombinedArticle(IntegerPKMixin, TimestampMixin, OptimisticLockMixin, SoftDeleteMixin, ActiveRecord):
- """Article model combining all mixins.
-
- Python 3.12+ version using | syntax, Self type, and @override.
- """
- @classmethod
- def table_name(cls):
- return "combined_articles"
-
- id: int | None = None
- title: str
- content: str
- status: str = Field(default="draft")
-
- @override
- def save(self, **kwargs) -> Self:
- """Save the article and return self for chaining."""
- super().save(**kwargs)
- return self
-
- def publish(self) -> Self:
- """Publish article and return self for chaining."""
- self.status = "published"
- return self
-
- def archive(self) -> Self:
- """Archive article and return self for chaining."""
- self.status = "archived"
- return self
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/interfaces.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/interfaces.py
deleted file mode 100644
index 9ef97023..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/interfaces.py
+++ /dev/null
@@ -1,67 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/mixins/interfaces.py
-"""
-This file defines the interface (or contract) that a backend's test provider
-must adhere to for the "mixins" feature group.
-
-By defining a standard interface, the generic tests in the testsuite can rely on
-these methods being available, regardless of which database backend is actually
-running the tests. Each backend must provide a concrete class that implements
-these abstract methods.
-"""
-from abc import ABC, abstractmethod
-from typing import Type, List
-from rhosocial.activerecord.model import ActiveRecord
-
-
-class IMixinsProvider(ABC):
- """
- The interface for the provider of the 'mixins' feature tests.
- """
-
- @abstractmethod
- def get_test_scenarios(self) -> List[str]:
- """
- Should return a list of scenario names (e.g., ['memory', 'file'])
- that this backend supports for this test group.
- """
- pass
-
- @abstractmethod
- def setup_timestamped_post_model(self, scenario_name: str) -> Type[ActiveRecord]:
- """
- Should prepare the testing environment for the timestamped post model under a
- given scenario and return the configured model class.
- """
- pass
-
- @abstractmethod
- def setup_versioned_product_model(self, scenario_name: str) -> Type[ActiveRecord]:
- """
- Should prepare the testing environment for the versioned product model under a
- given scenario and return the configured model class.
- """
- pass
-
- @abstractmethod
- def setup_task_model(self, scenario_name: str) -> Type[ActiveRecord]:
- """
- Should prepare the testing environment for the task model under a
- given scenario and return the configured model class.
- """
- pass
-
- @abstractmethod
- def setup_combined_article_model(self, scenario_name: str) -> Type[ActiveRecord]:
- """
- Should prepare the testing environment for the combined article model under a
- given scenario and return the configured model class.
- """
- pass
-
- @abstractmethod
- def cleanup_after_test(self, scenario_name: str):
- """
- Should perform any necessary cleanup after a test has run, such as
- deleting temporary database files.
- """
- pass
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/articles.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/articles.sql
deleted file mode 100644
index d2d29952..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/articles.sql
+++ /dev/null
@@ -1,12 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/articles.sql
--- Schema for Article (mapped from CombinedArticle)
-CREATE TABLE articles (
- id SERIAL PRIMARY KEY,
- title VARCHAR(255) NOT NULL,
- content TEXT,
- status VARCHAR(50) DEFAULT 'draft',
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- version INTEGER DEFAULT 1,
- deleted_at TIMESTAMP WITH TIME ZONE
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/combined_articles.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/combined_articles.sql
deleted file mode 100644
index 42de407a..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/combined_articles.sql
+++ /dev/null
@@ -1,12 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/combined_articles.sql
--- Schema for CombinedArticle
-CREATE TABLE combined_articles (
- id SERIAL PRIMARY KEY,
- title VARCHAR(255) NOT NULL,
- content TEXT,
- status VARCHAR(50) DEFAULT 'draft',
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- version INTEGER DEFAULT 1,
- deleted_at TIMESTAMP WITH TIME ZONE
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/comments.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/comments.sql
deleted file mode 100644
index 5df75274..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/comments.sql
+++ /dev/null
@@ -1,12 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/comments.sql
--- Schema for Comment (used with Article)
-CREATE TABLE comments (
- id SERIAL PRIMARY KEY,
- title VARCHAR(255),
- content TEXT,
- article_id INTEGER,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- version INTEGER DEFAULT 1,
- deleted_at TIMESTAMP WITH TIME ZONE
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/optimistic_lock_test_models.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/optimistic_lock_test_models.sql
deleted file mode 100644
index 7fbddbea..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/optimistic_lock_test_models.sql
+++ /dev/null
@@ -1,8 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/optimistic_lock_test_models.sql
--- Schema for OptimisticLockTestModel (mapped from VersionedProduct)
-CREATE TABLE optimistic_lock_test_models (
- id SERIAL PRIMARY KEY,
- name VARCHAR(255) NOT NULL,
- price DECIMAL(10,2) DEFAULT 0.00,
- version INTEGER DEFAULT 1
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/soft_delete_test_models.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/soft_delete_test_models.sql
deleted file mode 100644
index 68c1cf48..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/soft_delete_test_models.sql
+++ /dev/null
@@ -1,8 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/soft_delete_test_models.sql
--- Schema for SoftDeleteTestModel (mapped from Task)
-CREATE TABLE soft_delete_test_models (
- id SERIAL PRIMARY KEY,
- title VARCHAR(255) NOT NULL,
- is_completed BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMP WITH TIME ZONE
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/tasks.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/tasks.sql
deleted file mode 100644
index b73628c3..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/tasks.sql
+++ /dev/null
@@ -1,8 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/tasks.sql
--- Schema for Task
-CREATE TABLE tasks (
- id SERIAL PRIMARY KEY,
- title VARCHAR(255) NOT NULL,
- is_completed BOOLEAN DEFAULT FALSE,
- deleted_at TIMESTAMP WITH TIME ZONE
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamped_posts.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamped_posts.sql
deleted file mode 100644
index 71e783f1..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamped_posts.sql
+++ /dev/null
@@ -1,9 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamped_posts.sql
--- Schema for TimestampedPost
-CREATE TABLE timestamped_posts (
- id SERIAL PRIMARY KEY,
- title VARCHAR(255) NOT NULL,
- content TEXT,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamps_test_models.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamps_test_models.sql
deleted file mode 100644
index 34932300..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamps_test_models.sql
+++ /dev/null
@@ -1,9 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/timestamps_test_models.sql
--- Schema for TimestampsTestModel (mapped from TimestampedPost)
-CREATE TABLE timestamps_test_models (
- id SERIAL PRIMARY KEY,
- title VARCHAR(255) NOT NULL,
- content TEXT,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/versioned_products.sql b/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/versioned_products.sql
deleted file mode 100644
index 969b8d4d..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/versioned_products.sql
+++ /dev/null
@@ -1,8 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/mixins/schema/versioned_products.sql
--- Schema for VersionedProduct
-CREATE TABLE versioned_products (
- id SERIAL PRIMARY KEY,
- name VARCHAR(255) NOT NULL,
- price DECIMAL(10,2) DEFAULT 0.00,
- version INTEGER DEFAULT 1
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles.py
deleted file mode 100644
index c0c81379..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles.py
+++ /dev/null
@@ -1,11 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles.py
-"""
-Test combined articles functionality for PostgreSQL backend.
-
-This module imports and runs the shared tests from the testsuite package,
-ensuring PostgreSQL backend compatibility.
-"""
-# Import shared tests from testsuite package
-from rhosocial.activerecord.testsuite.feature.mixins.test_combined_articles import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.mixins.test_combined_articles_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles_async.py
deleted file mode 100644
index 1dc7d5c5..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_combined_articles_async.py
-"""Bridge file for async feature.mixins.test_combined_articles_async tests."""
-from rhosocial.activerecord.testsuite.feature.mixins.test_combined_articles_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock.py
deleted file mode 100644
index be5611e5..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock.py
+++ /dev/null
@@ -1,11 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock.py
-"""
-Test optimistic lock functionality for PostgreSQL backend.
-
-This module imports and runs the shared tests from the testsuite package,
-ensuring PostgreSQL backend compatibility.
-"""
-# Import shared tests from testsuite package
-from rhosocial.activerecord.testsuite.feature.mixins.test_optimistic_lock import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.mixins.test_optimistic_lock_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock_async.py
deleted file mode 100644
index 4c233401..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_optimistic_lock_async.py
-"""Bridge file for async feature.mixins.test_optimistic_lock_async tests."""
-from rhosocial.activerecord.testsuite.feature.mixins.test_optimistic_lock_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete.py
deleted file mode 100644
index 40a34336..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete.py
+++ /dev/null
@@ -1,11 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete.py
-"""
-Test soft delete functionality for PostgreSQL backend.
-
-This module imports and runs the shared tests from the testsuite package,
-ensuring PostgreSQL backend compatibility.
-"""
-# Import shared tests from testsuite package
-from rhosocial.activerecord.testsuite.feature.mixins.test_soft_delete import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.mixins.test_soft_delete_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete_async.py
deleted file mode 100644
index 14371fd5..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_soft_delete_async.py
-"""Bridge file for async feature.mixins.test_soft_delete_async tests."""
-from rhosocial.activerecord.testsuite.feature.mixins.test_soft_delete_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps.py
deleted file mode 100644
index 64344372..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps.py
+++ /dev/null
@@ -1,11 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps.py
-"""
-Test timestamp functionality for PostgreSQL backend.
-
-This module imports and runs the shared tests from the testsuite package,
-ensuring PostgreSQL backend compatibility.
-"""
-# Import shared tests from testsuite package
-from rhosocial.activerecord.testsuite.feature.mixins.test_timestamps import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.mixins.test_timestamps_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps_async.py b/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps_async.py
deleted file mode 100644
index 0260c373..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/mixins/test_timestamps_async.py
-"""Bridge file for async feature.mixins.test_timestamps_async tests."""
-from rhosocial.activerecord.testsuite.feature.mixins.test_timestamps_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/README.md b/tests/rhosocial/activerecord_postgres_test/feature/query/README.md
new file mode 100644
index 00000000..446745b8
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/README.md
@@ -0,0 +1,5 @@
+# query tests
+
+Placeholder - describe this directory's scope, fixtures and parallelism declaration.
+
+See [feature tests](../README.md) and [tests/README.md](../../../../README.md).
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py
new file mode 100644
index 00000000..cc950f64
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/conftest.py
+"""Bridge to the shared ``query/aggregate`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.aggregate.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py
index deae3685..afc1f88c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py
@@ -1,10 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_active_query_aggregate.py
-"""
-Bridge file for ActiveQuery aggregate tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate.py
+"""Bridge to the shared ``query/aggregate`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py
index c3568677..5b2406b6 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_active_query_aggregate_async.py
-"""Bridge file for async feature.query.aggregate.test_active_query_aggregate_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/aggregate`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.aggregate.test_active_query_aggregate_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py
index 525ba49a..2dea45b3 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py
@@ -1,10 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_aggregate_queries.py
-"""
-Bridge file for aggregate queries tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries.py
+"""Bridge to the shared ``query/aggregate`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py
index df180f44..c839fa53 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/aggregate/test_aggregate_queries_async.py
-"""Bridge file for async feature.query.aggregate.test_aggregate_queries_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/aggregate`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.aggregate.test_aggregate_queries_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py
new file mode 100644
index 00000000..064db239
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/basic/conftest.py
+"""Use the shared ``query/basic`` minimal test set."""
+from rhosocial.activerecord.testsuite.feature.query.basic.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic.py
deleted file mode 100644
index 9baba06b..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_active_query_basic.py
-"""
-Bridge file for ActiveQuery basic tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.basic.test_active_query_basic import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.basic.test_active_query_basic_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py
deleted file mode 100644
index 4bc013b4..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_active_query_basic_async.py
-"""Bridge file for async feature.query.basic.test_active_query_basic_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.basic.test_active_query_basic_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic.py
deleted file mode 100644
index e2f69cef..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_basic.py
-"""
-Bridge file for basic tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.basic.test_basic import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.basic.test_basic_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py
deleted file mode 100644
index 55d0570f..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_basic_async.py
-"""Bridge file for async feature.query.basic.test_basic_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.basic.test_basic_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py
deleted file mode 100644
index 20bd64fb..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query.py
-"""
-Bridge file for composite PK query tests from the testsuite.
-"""
-from rhosocial.activerecord.testsuite.feature.query.basic.test_composite_pk_query import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.basic.test_composite_pk_query_async import * # noqa: F403
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py
index a4d65b87..2208833e 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py
@@ -1,3 +1,9 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_composite_pk_query_async.py
-"""Bridge file for async feature.query.basic.test_composite_pk_query_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.basic.test_composite_pk_query_async import * # noqa: F401, F403
+"""
+Bridge file for composite PK async ActiveQuery tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.query.basic.test_composite_pk_query_async import * # noqa: F403
+except ImportError:
+ pytest.skip("composite_pk testsuite not available", allow_module_level=True)
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py
deleted file mode 100644
index cc8fd3a4..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py
+++ /dev/null
@@ -1,4 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_find_one_or_create.py
-"""Bridge file for the testsuite natural-key find_one_or_create contract."""
-from rhosocial.activerecord.testsuite.feature.query.basic.test_find_one_or_create import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.basic.test_find_one_or_create_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries.py
deleted file mode 100644
index 1fda7a9b..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_queries.py
-"""
-Bridge file for synchronous query tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.basic.test_queries import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries_async.py
deleted file mode 100644
index 8e53f6fe..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/basic/test_queries_async.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_queries_async.py
-"""
-Bridge file for async queries tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.basic.test_queries_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py
new file mode 100644
index 00000000..98495f49
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py
@@ -0,0 +1,74 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/collation/conftest.py
+"""L2 backend fixtures for the PostgreSQL-only collation test set.
+
+These tests are backend-specific, so the fixture group lives here rather than
+in the shared suite; the table definition still comes from the query topic.
+
+- ``database``: one database per directory (session scope, emptied at start);
+- ``schema``: the ``searchable_items`` table, dropped and recreated for every
+ test (function scope), so each test starts from an empty table.
+"""
+from rhosocial.activerecord.testsuite.pytest_plugin import Declaration
+
+from pathlib import Path
+
+import pytest
+
+from rhosocial.activerecord.backend.options import ExecutionOptions
+from rhosocial.activerecord.backend.schema import StatementType
+from rhosocial.activerecord.testsuite.feature.query.conftest import * # noqa: F401,F403
+from rhosocial.activerecord.testsuite.feature.query.fixtures.definitions import (
+ SearchableItemsDefinition,
+)
+
+DDL = ExecutionOptions(stmt_type=StatementType.DDL)
+
+DEFINITIONS = (SearchableItemsDefinition,)
+
+
+def _database_name() -> str:
+ """Database name from this directory's namespace (below ``feature``)."""
+ parts = Path(__file__).parent.parts
+ start = parts.index("feature") + 1
+ return "test_" + "_".join(parts[start:])
+
+
+
+
+# This directory owns a database shared by all its tests within a scenario;
+# pin them to one worker so setup/teardown never races on the same database.
+DECLARATION = Declaration(
+ # This scope opens a database; the plugin enforces this declaration.
+ uses_database=True,
+ parallel=True,
+ purpose="Directory-owned PostgreSQL database shared by this test group.",
+)
+
+@pytest.fixture(scope="session")
+def database_config(backend_scenario):
+ """The scenario, its connection configuration, and the database name."""
+ name = _database_name()
+ return backend_scenario, backend_scenario.make_config(name), name
+
+
+@pytest.fixture(scope="session")
+def database(database_config):
+ """The directory's database, prepared once and left for later files."""
+ scenario, config, name = database_config
+ scenario.reset_database(name)
+ backend = scenario.backend_class(connection_config=config)
+ backend.connect()
+ backend.introspect_and_adapt()
+ yield backend
+ backend.disconnect()
+
+
+@pytest.fixture(scope="function", autouse=True)
+def schema(database):
+ """Drop and recreate the table this directory uses, before every test."""
+ fixtures = [definition(database.dialect) for definition in DEFINITIONS]
+ for fixture in fixtures:
+ database.execute(*fixture.create_table.to_sql(), options=DDL)
+ yield
+ for fixture in reversed(fixtures):
+ database.execute(*fixture.drop_table.to_sql(), options=DDL)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py
index 070acde9..8d381eed 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py
@@ -1,8 +1,8 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/conftest.py
-"""
-Pytest configuration for query feature tests.
+"""Pytest configuration for query feature tests.
This file imports fixtures from the corresponding testsuite, making them
available to the tests in this directory.
"""
-from rhosocial.activerecord.testsuite.feature.query.conftest import * # noqa: F403
+
+from rhosocial.activerecord.testsuite.feature.query.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py
index e3dcb692..54004cff 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py
@@ -1,8 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/connection/conftest.py
-"""
-Pytest configuration for query connection pool feature tests.
-
-This file imports fixtures from the corresponding testsuite, making them
-available to the tests in this directory.
-"""
-from rhosocial.activerecord.testsuite.feature.query.connection.conftest import * # noqa: F403
+"""Bridge to the shared ``query/connection`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.connection.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py
index 9fb3d2f7..48580637 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py
@@ -1,16 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context.py
-"""
-ActiveQuery Context Test Module for PostgreSQL backend.
-
-This module imports and runs the shared tests from the testsuite package,
-ensuring PostgreSQL backend compatibility for ActiveQuery connection pool context awareness.
-"""
-from rhosocial.activerecord.testsuite.feature.query.connection.conftest import (
- sync_pool_and_model, # noqa: F401
- async_pool_and_model, # noqa: F401
-)
-
-# Import shared tests from testsuite package
-from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context_async import * # noqa: F403
-
+"""Bridge to the shared ``query/connection`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py
index cd8c61c6..85450915 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_active_query_context_async.py
-"""Bridge file for async feature.query.connection.test_active_query_context_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/connection`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py
index 0b1e6153..acc4c346 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py
@@ -1,16 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context.py
-"""
-CTEQuery Context Test Module for PostgreSQL backend.
-
-This module imports and runs the shared tests from the testsuite package,
-ensuring PostgreSQL backend compatibility for CTEQuery connection pool context awareness.
-"""
-from rhosocial.activerecord.testsuite.feature.query.connection.conftest import (
- sync_pool_and_model, # noqa: F401
- async_pool_and_model, # noqa: F401
-)
-
-# Import shared tests from testsuite package
-from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context_async import * # noqa: F403
-
+"""Bridge to the shared ``query/connection`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py
index e8b21313..29fc0273 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_cte_query_context_async.py
-"""Bridge file for async feature.query.connection.test_cte_query_context_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/connection`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py
index ef0d192a..b916ccfa 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py
@@ -1,16 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context.py
-"""
-SetOperationQuery Context Test Module for PostgreSQL backend.
-
-This module imports and runs the shared tests from the testsuite package,
-ensuring PostgreSQL backend compatibility for SetOperationQuery connection pool context awareness.
-"""
-from rhosocial.activerecord.testsuite.feature.query.connection.conftest import (
- sync_pool_and_model, # noqa: F401
- async_pool_and_model, # noqa: F401
-)
-
-# Import shared tests from testsuite package
-from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context_async import * # noqa: F403
-
+"""Bridge to the shared ``query/connection`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py
index 9bc0e34e..1dc25e75 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/connection/test_set_operation_context_async.py
-"""Bridge file for async feature.query.connection.test_set_operation_context_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/connection`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility.py
deleted file mode 100644
index b234b681..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_cross_database_compatibility.py
-"""
-Bridge file for cross-database compatibility tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.cross_database.test_cross_database_compatibility import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.cross_database.test_cross_database_compatibility_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py
deleted file mode 100644
index 1c8d2108..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/cross_database/test_cross_database_compatibility_async.py
-"""Bridge file for async feature.query.cross_database.test_cross_database_compatibility_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.cross_database.test_cross_database_compatibility_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/conftest.py
new file mode 100644
index 00000000..5f738de9
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/conftest.py
+"""Bridge to the shared ``query/cross_schema`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.cross_schema.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join.py
new file mode 100644
index 00000000..7a81840f
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join.py
+"""Bridge to the shared ``query/cross_schema`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.cross_schema.test_cross_schema_join import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join_async.py
new file mode 100644
index 00000000..0c35215d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_cross_schema_join_async.py
+"""Bridge to the shared ``query/cross_schema`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.cross_schema.test_cross_schema_join_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema.py
new file mode 100644
index 00000000..76107087
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema.py
+"""Bridge to the shared ``query/cross_schema`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.cross_schema.test_mixed_schema import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_async.py
new file mode 100644
index 00000000..9326cf8e
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_async.py
+"""Bridge to the shared ``query/cross_schema`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.cross_schema.test_mixed_schema_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_qualifiers.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_qualifiers.py
new file mode 100644
index 00000000..70dd696d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_qualifiers.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/cross_schema/test_mixed_schema_qualifiers.py
+"""Bridge to the shared ``query/cross_schema`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.cross_schema.test_mixed_schema_qualifiers import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py
deleted file mode 100644
index 986a6c4a..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte.py
-"""
-Bridge file for composite PK CTE tests from the testsuite.
-"""
-from rhosocial.activerecord.testsuite.feature.query.cte.test_composite_pk_cte import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.cte.test_composite_pk_cte_async import * # noqa: F403
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py
deleted file mode 100644
index 46972049..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_composite_pk_cte_async.py
-"""Bridge file for async feature.query.cte.test_composite_pk_cte_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.cte.test_composite_pk_cte_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query.py
deleted file mode 100644
index 6298688f..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_cte_query_active_query.py
-"""
-Bridge file for cte_query_active_query tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_active_query import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_active_query_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py
deleted file mode 100644
index 3429c45a..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_active_query_async.py
-"""Bridge file for async feature.query.cte.test_cte_query_active_query_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_active_query_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation.py
deleted file mode 100644
index 686d8fc6..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_cte_query_set_operation.py
-"""
-Bridge file for cte_query_set_operation tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_set_operation import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_set_operation_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py
deleted file mode 100644
index 4bf171be..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/cte/test_cte_query_set_operation_async.py
-"""Bridge file for async feature.query.cte.test_cte_query_set_operation_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.cte.test_cte_query_set_operation_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py
new file mode 100644
index 00000000..1a31ac71
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/conftest.py
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py
index a7c1e676..47a2ab61 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py
@@ -1,7 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_eager_loading_caching.py
-"""
-Bridge file for eager loading caching tests.
-"""
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching import * # noqa: F401, F403
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching.py
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py
index f946bcec..6887dd0d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_caching_async.py
-"""Bridge file for async feature.query.eager_loading.test_eager_loading_caching_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_caching_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py
index 09efb41a..85acb036 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py
@@ -1,7 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_eager_loading_nested.py
-"""
-Bridge file for eager loading nested tests.
-"""
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested import * # noqa: F401, F403
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested.py
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py
index b7921aa6..39b6672b 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_nested_async.py
-"""Bridge file for async feature.query.eager_loading.test_eager_loading_nested_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_nested_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py
index 7b5ca3cd..deae767c 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py
@@ -1,2 +1,3 @@
-"""Bridge file for sync eager loading scenario tests."""
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_scenarios import * # noqa: F401, F403
+# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios.py
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_scenarios import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py
index 64cae900..0687f716 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py
@@ -1,5 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_eager_loading_scenarios_async.py
-"""
-Bridge file for async eager loading scenario tests.
-"""
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_scenarios_async import * # noqa: F401, F403
+# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_scenarios_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py
index 7571dafa..6eeff6a6 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py
@@ -1,7 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_eager_loading_with_all.py
-"""
-Bridge file for eager loading with_all tests.
-"""
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all import * # noqa: F401, F403
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all.py
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py
index 197ae5d6..83f4c9f8 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_all_async.py
-"""Bridge file for async feature.query.eager_loading.test_eager_loading_with_all_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_all_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py
index c55cb6f8..2576b488 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py
@@ -1,7 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_eager_loading_with_modifier.py
-"""
-Bridge file for eager loading with_modifier tests.
-"""
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier import * # noqa: F401, F403
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier.py
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py
index c558e117..be23ceea 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py
-"""Bridge file for async feature.query.eager_loading.test_eager_loading_with_modifier_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_modifier_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py
index 8dc3de43..fcb72fe7 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py
@@ -1,7 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_eager_loading_with_one.py
-"""
-Bridge file for eager loading with_one tests.
-"""
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one import * # noqa: F401, F403
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one.py
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py
index 1ad43fb7..a964468d 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/eager_loading/test_eager_loading_with_one_async.py
-"""Bridge file for async feature.query.eager_loading.test_eager_loading_with_one_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_with_one_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py
new file mode 100644
index 00000000..7fb5d45e
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/conftest.py
+"""Bridge to the shared ``query/error_handling`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.error_handling.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py
index 88f48f2c..6cb01aff 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py
@@ -1,10 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_error_handling.py
-"""
-Bridge file for error_handling tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling.py
+"""Bridge to the shared ``query/error_handling`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py
index ef91b73c..0e35d381 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/error_handling/test_error_handling_async.py
-"""Bridge file for async feature.query.error_handling.test_error_handling_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/error_handling`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py
new file mode 100644
index 00000000..4f98e988
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/joins/conftest.py
+"""Use the shared ``query/joins`` minimal test set."""
+from rhosocial.activerecord.testsuite.feature.query.joins.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join.py
deleted file mode 100644
index 90eb3a08..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_active_query_join.py
-"""
-Bridge file for ActiveQuery join tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.joins.test_active_query_join import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.joins.test_active_query_join_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py
deleted file mode 100644
index 63a0b532..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_active_query_join_async.py
-"""Bridge file for async feature.query.joins.test_active_query_join_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.joins.test_active_query_join_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins.py
deleted file mode 100644
index a775027d..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_joins.py
-"""
-Bridge file for joins tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.joins.test_joins import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.joins.test_joins_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py
deleted file mode 100644
index f5710f45..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/joins/test_joins_async.py
-"""Bridge file for async feature.query.joins.test_joins_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.joins.test_joins_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/json/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/json/conftest.py
new file mode 100644
index 00000000..8b173d48
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/json/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/json/conftest.py
+"""Bridge to the shared ``query/json`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.json.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/json/test_json_probe_honesty.py b/tests/rhosocial/activerecord_postgres_test/feature/query/json/test_json_probe_honesty.py
new file mode 100644
index 00000000..843c2e99
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/json/test_json_probe_honesty.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/json/test_json_probe_honesty.py
+"""Bridge to the shared ``query/json`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.json.test_json_probe_honesty import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py
new file mode 100644
index 00000000..e45e0ff2
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/logging/conftest.py
+"""Bridge to the shared ``query/logging`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.logging.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py
index 5087c2ed..ba17b876 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py
@@ -1,10 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_logging_data_summarization.py
-"""
-Bridge file for logging data summarization tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization.py
+"""Bridge to the shared ``query/logging`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py
index 1f9e0aa4..6d1211b9 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/logging/test_logging_data_summarization_async.py
-"""Bridge file for async feature.query.logging.test_logging_data_summarization_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/logging`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.logging.test_logging_data_summarization_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py
new file mode 100644
index 00000000..b1830f22
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/optimization/conftest.py
+"""Bridge to the shared ``query/optimization`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.optimization.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py
index 115d70f0..5e9726e0 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py
@@ -1,10 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_query_optimization.py
-"""
-Bridge file for query_optimization tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization.py
+"""Bridge to the shared ``query/optimization`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py
index 9688b94b..a7ce0389 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/optimization/test_query_optimization_async.py
-"""Bridge file for async feature.query.optimization.test_query_optimization_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/optimization`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.optimization.test_query_optimization_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py
new file mode 100644
index 00000000..3190e2f0
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/conftest.py
+"""Bridge to the shared ``query/range_queries`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.range_queries.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py
index 8498bb08..9b900a81 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py
@@ -1,10 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_active_query_range.py
-"""
-Bridge file for ActiveQuery range tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range.py
+"""Bridge to the shared ``query/range_queries`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py
index 667a3718..9068d462 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_active_query_range_async.py
-"""Bridge file for async feature.query.range_queries.test_active_query_range_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/range_queries`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.range_queries.test_active_query_range_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py
index fb8bc85e..7923c145 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py
@@ -1,10 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_range_queries.py
-"""
-Bridge file for range_queries tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries.py
+"""Bridge to the shared ``query/range_queries`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py
index c6ef096e..2a20daee 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_queries_async.py
-"""Bridge file for async feature.query.range_queries.test_range_queries_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/range_queries`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_queries_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py
index ef05c44b..f5ba66d9 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py
@@ -1,10 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_range_query_detailed.py
-"""
-Bridge file for range_query_detailed tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed.py
+"""Bridge to the shared ``query/range_queries`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py
index df8937fe..4e3c8a53 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/range_queries/test_range_query_detailed_async.py
-"""Bridge file for async feature.query.range_queries.test_range_query_detailed_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/range_queries`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.range_queries.test_range_query_detailed_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/README.md b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/README.md
new file mode 100644
index 00000000..43a6c447
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/README.md
@@ -0,0 +1,13 @@
+# query/relation tests (sqlite bridge)
+
+SQLite bridge for the shared `feature/query/relation` testsuite topic. This
+directory was moved from `feature/relation/` and merged with the old
+`feature/query/relations/` bridge group, mirroring the testsuite source tree.
+
+- `conftest.py` — star-imports `testsuite.feature.query.relation.conftest`.
+- `core/` — sqlite-local relation tests (unchanged).
+- `ordering/` — bridge to `testsuite.feature.query.relation.ordering`.
+- `legacy/` — the merged old `query/relations` real-database `with_()` integration
+ tests (`test_with_integration.py`) plus a self-contained L2 conftest.
+
+See [feature tests](../README.md) and [tests/README.md](../../../../README.md).
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base.py
new file mode 100644
index 00000000..8c53d9b7
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base.py
+"""Bridge to the shared ``query/relation/base`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.base.test_base import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base_async.py
new file mode 100644
index 00000000..98f20887
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_base_async.py
+"""Bridge to the shared ``query/relation/base`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.base.test_base_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces.py
new file mode 100644
index 00000000..9523448a
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces.py
+"""Bridge to the shared ``query/relation/base`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.base.test_interfaces import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces_async.py
new file mode 100644
index 00000000..edd832d2
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/base/test_interfaces_async.py
+"""Bridge to the shared ``query/relation/base`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.base.test_interfaces_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/conftest.py
new file mode 100644
index 00000000..bd9707ac
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/conftest.py
+"""Bridge fixture configuration for ``query/relation/boundary``."""
+from rhosocial.activerecord.testsuite.feature.query.relation.boundary.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary.py
new file mode 100644
index 00000000..2a17cd04
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary.py
+"""Bridge to the shared ``query/relation/boundary`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.boundary.test_boundary import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary_async.py
new file mode 100644
index 00000000..2d7194bf
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/boundary/test_boundary_async.py
+"""Bridge to the shared ``query/relation/boundary`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.boundary.test_boundary_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache.py
new file mode 100644
index 00000000..026b8ecf
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache.py
+"""Bridge to the shared ``query/relation/cache`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.cache.test_cache import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_async.py
new file mode 100644
index 00000000..d1e84e64
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_async.py
+"""Bridge to the shared ``query/relation/cache`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.cache.test_cache_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing.py
new file mode 100644
index 00000000..9f8a1024
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing.py
+"""Bridge to the shared ``query/relation/cache`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.cache.test_cache_clearing import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing_async.py
new file mode 100644
index 00000000..5659ca9d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/cache/test_cache_clearing_async.py
+"""Bridge to the shared ``query/relation/cache`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.cache.test_cache_clearing_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/conftest.py
new file mode 100644
index 00000000..6659724d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/conftest.py
@@ -0,0 +1,7 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/conftest.py
+"""Fixtures for the relation feature tests.
+
+The topic conftest supplies the fixtures and the minimal test set for this
+directory's database.
+"""
+from rhosocial.activerecord.testsuite.feature.query.relation.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/conftest.py
new file mode 100644
index 00000000..d5509296
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/conftest.py
+"""Bridge fixture configuration for ``query/relation/derived``."""
+from rhosocial.activerecord.testsuite.feature.query.relation.derived.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field.py
new file mode 100644
index 00000000..c9d699fc
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field.py
+"""Bridge to the shared ``query/relation/derived`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.derived.test_relation_derived_field import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_async.py
new file mode 100644
index 00000000..ffa45448
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_async.py
+"""Bridge to the shared ``query/relation/derived`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.derived.test_relation_derived_field_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json.py
new file mode 100644
index 00000000..669b35f7
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json.py
+"""Bridge to the shared ``query/relation/derived`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.derived.test_relation_derived_field_json import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json_async.py
new file mode 100644
index 00000000..01d4e3fd
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/derived/test_relation_derived_field_json_async.py
+"""Bridge to the shared ``query/relation/derived`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.derived.test_relation_derived_field_json_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat.py
new file mode 100644
index 00000000..5492e7d9
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat.py
+"""Bridge to the shared ``query/relation/descriptors`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.descriptors.test_descriptor_compat import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat_async.py
new file mode 100644
index 00000000..7046b9c1
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptor_compat_async.py
+"""Bridge to the shared ``query/relation/descriptors`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.descriptors.test_descriptor_compat_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors.py
new file mode 100644
index 00000000..4680b79e
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors.py
+"""Bridge to the shared ``query/relation/descriptors`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.descriptors.test_descriptors import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors_async.py
new file mode 100644
index 00000000..8453205d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/descriptors/test_descriptors_async.py
+"""Bridge to the shared ``query/relation/descriptors`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.descriptors.test_descriptors_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/conftest.py
new file mode 100644
index 00000000..0fb01806
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/conftest.py
+"""Bridge fixture configuration for ``query/relation/eager_loading``."""
+from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access.py
new file mode 100644
index 00000000..e917abc6
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access.py
+"""Bridge to the shared ``query/relation/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.test_nested_relationship_access import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py
new file mode 100644
index 00000000..0ddbee16
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py
+"""Bridge to the shared ``query/relation/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.test_nested_relationship_access_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method.py
new file mode 100644
index 00000000..bba49cda
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method.py
+"""Bridge to the shared ``query/relation/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.test_with_method import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method_async.py
new file mode 100644
index 00000000..de9291c2
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/eager_loading/test_with_method_async.py
+"""Bridge to the shared ``query/relation/eager_loading`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.test_with_method_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/conftest.py
new file mode 100644
index 00000000..4c527dd7
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/conftest.py
+"""Bridge fixture configuration for ``query/relation/integration``."""
+from rhosocial.activerecord.testsuite.feature.query.relation.integration.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration.py
new file mode 100644
index 00000000..172739d1
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration.py
+"""Bridge to the shared ``query/relation/integration`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.integration.test_integration import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration_async.py
new file mode 100644
index 00000000..7444cb98
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/integration/test_integration_async.py
+"""Bridge to the shared ``query/relation/integration`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.integration.test_integration_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation.py
new file mode 100644
index 00000000..3b6dbd70
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation.py
+"""Bridge to the shared ``query/relation/legacy`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.legacy.test_relational_validation import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation_async.py
new file mode 100644
index 00000000..ef7690c2
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/legacy/test_relational_validation_async.py
+"""Bridge to the shared ``query/relation/legacy`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.legacy.test_relational_validation_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/conftest.py
new file mode 100644
index 00000000..ace3ff66
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/conftest.py
+"""Bridge fixture configuration for ``query/relation/modifiers``."""
+from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior.py
new file mode 100644
index 00000000..c47df05d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior.py
+"""Bridge to the shared ``query/relation/modifiers`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.test_modifier_behavior import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior_async.py
new file mode 100644
index 00000000..c06be888
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_behavior_async.py
+"""Bridge to the shared ``query/relation/modifiers`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.test_modifier_behavior_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning.py
new file mode 100644
index 00000000..42ba6f55
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning.py
+"""Bridge to the shared ``query/relation/modifiers`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.test_modifier_warning import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning_async.py
new file mode 100644
index 00000000..483c0640
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/modifiers/test_modifier_warning_async.py
+"""Bridge to the shared ``query/relation/modifiers`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.test_modifier_warning_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/conftest.py
new file mode 100644
index 00000000..36582d90
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/conftest.py
+"""Use the shared ``relation/ordering`` minimal test set."""
+from rhosocial.activerecord.testsuite.feature.query.relation.ordering.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by.py
new file mode 100644
index 00000000..3e437b46
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by.py
+"""Bridge to the shared ``query/relation/ordering`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.ordering.test_has_many_order_by import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_async.py
new file mode 100644
index 00000000..93b05c4d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/ordering/test_has_many_order_by_async.py
+"""Bridge to the shared ``query/relation/ordering`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.ordering.test_has_many_order_by_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/conftest.py
new file mode 100644
index 00000000..bc562cbd
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/conftest.py
+"""Bridge fixture configuration for ``query/relation/validation``."""
+from rhosocial.activerecord.testsuite.feature.query.relation.validation.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation.py
new file mode 100644
index 00000000..4d02bfcd
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation.py
+"""Bridge to the shared ``query/relation/validation`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.validation.test_path_validation import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation_async.py
new file mode 100644
index 00000000..2bef540c
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_path_validation_async.py
+"""Bridge to the shared ``query/relation/validation`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.validation.test_path_validation_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator.py
new file mode 100644
index 00000000..f45cf228
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator.py
+"""Bridge to the shared ``query/relation/validation`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.validation.test_validator import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator_async.py
new file mode 100644
index 00000000..dca12bab
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/relation/validation/test_validator_async.py
+"""Bridge to the shared ``query/relation/validation`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.relation.validation.test_validator_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation.py
deleted file mode 100644
index abd6a3f4..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_relational_validation.py
-"""
-Bridge file for relational_validation tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.relations.test_relational_validation import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.relations.test_relational_validation_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py
deleted file mode 100644
index 9276ed3a..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relational_validation_async.py
-"""Bridge file for async feature.query.relations.test_relational_validation_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.relations.test_relational_validation_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic.py
deleted file mode 100644
index 7a2a089e..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_relations_basic.py
-"""
-Bridge file for relations_basic tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_basic import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_basic_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py
deleted file mode 100644
index 6ff408c0..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_basic_async.py
-"""Bridge file for async feature.query.relations.test_relations_basic_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_basic_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with.py
deleted file mode 100644
index 8e7d2338..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with.py
+++ /dev/null
@@ -1,5 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_relations_with_sync.py
-"""
-Bridge file for sync relation 'with' tests.
-"""
-from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_with import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with_async.py
deleted file mode 100644
index 8057becf..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/relations/test_relations_with_async.py
+++ /dev/null
@@ -1,5 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_relations_with_async.py
-"""
-Bridge file for async relation 'with' tests.
-"""
-from rhosocial.activerecord.testsuite.feature.query.relations.test_relations_with_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/comments.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/comments.sql
deleted file mode 100644
index 5747fb2e..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/comments.sql
+++ /dev/null
@@ -1,11 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/query/schema/comments.sql
--- Schema for Comment model
-CREATE TABLE comments (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL,
- post_id INTEGER NOT NULL,
- content TEXT NOT NULL,
- is_hidden BOOLEAN NOT NULL DEFAULT FALSE,
- created_at TIMESTAMP WITH TIME ZONE,
- updated_at TIMESTAMP WITH TIME ZONE
-);
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_order_items.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_order_items.sql
deleted file mode 100644
index ac4139ac..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_order_items.sql
+++ /dev/null
@@ -1,13 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_order_items.sql
--- Schema for ExtendedOrderItem
-CREATE TABLE extended_order_items (
- id SERIAL PRIMARY KEY,
- order_id INTEGER NOT NULL,
- product_name VARCHAR(255) NOT NULL,
- quantity INTEGER NOT NULL DEFAULT 1,
- price DECIMAL(10,2) NOT NULL,
- category VARCHAR(255),
- region VARCHAR(50),
- created_at TIMESTAMP WITH TIME ZONE,
- updated_at TIMESTAMP WITH TIME ZONE
-);
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_orders.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_orders.sql
deleted file mode 100644
index 78886085..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_orders.sql
+++ /dev/null
@@ -1,18 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/query/schema/extended_orders.sql
--- Schema for ExtendedOrder
-CREATE TABLE extended_orders (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL,
- order_number VARCHAR(255) NOT NULL,
- total_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00,
- status VARCHAR(50) NOT NULL DEFAULT 'pending',
- priority VARCHAR(50) NOT NULL DEFAULT 'medium',
- region VARCHAR(50) NOT NULL DEFAULT 'default',
- category VARCHAR(255),
- product VARCHAR(255),
- department VARCHAR(255),
- year VARCHAR(10),
- quarter VARCHAR(10),
- created_at TIMESTAMP WITH TIME ZONE,
- updated_at TIMESTAMP WITH TIME ZONE
-);
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/json_users.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/json_users.sql
deleted file mode 100644
index 8934c8fd..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/json_users.sql
+++ /dev/null
@@ -1,18 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/query/schema/json_users.sql
--- Schema for JsonUser model
-CREATE TABLE json_users (
- id SERIAL PRIMARY KEY,
- username VARCHAR(255) NOT NULL,
- email VARCHAR(255) NOT NULL,
- age INTEGER,
- created_at TIMESTAMP WITH TIME ZONE,
- updated_at TIMESTAMP WITH TIME ZONE,
- -- JSONB fields for JSON testing
- settings JSONB,
- tags JSONB,
- profile JSONB,
- roles JSONB,
- scores JSONB,
- subscription JSONB,
- preferences JSONB
-);
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/nodes.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/nodes.sql
deleted file mode 100644
index 2ee019b1..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/nodes.sql
+++ /dev/null
@@ -1,10 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/query/schema/nodes.sql
--- Schema for Nodes (for tree/CTE tests)
-CREATE TABLE nodes (
- id SERIAL PRIMARY KEY,
- name VARCHAR(255) NOT NULL,
- parent_id INTEGER,
- value DECIMAL(10,2) NOT NULL DEFAULT 0.00,
- created_at TIMESTAMP WITH TIME ZONE,
- updated_at TIMESTAMP WITH TIME ZONE
-);
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/order_items.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/order_items.sql
deleted file mode 100644
index 32e90279..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/order_items.sql
+++ /dev/null
@@ -1,12 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/query/schema/order_items.sql
--- Schema for OrderItem model
-CREATE TABLE order_items (
- id SERIAL PRIMARY KEY,
- order_id INTEGER NOT NULL,
- product_name VARCHAR(255) NOT NULL,
- quantity INTEGER NOT NULL DEFAULT 1,
- unit_price DECIMAL(10,2) NOT NULL,
- subtotal DECIMAL(10,2) NOT NULL DEFAULT 0.00,
- created_at TIMESTAMP WITH TIME ZONE,
- updated_at TIMESTAMP WITH TIME ZONE
-);
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/orders.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/orders.sql
deleted file mode 100644
index 8eededd9..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/orders.sql
+++ /dev/null
@@ -1,11 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/query/schema/orders.sql
--- Schema for Order model
-CREATE TABLE orders (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL,
- order_number VARCHAR(255) NOT NULL,
- total_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00,
- status VARCHAR(50) NOT NULL DEFAULT 'pending',
- created_at TIMESTAMP WITH TIME ZONE,
- updated_at TIMESTAMP WITH TIME ZONE
-);
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/posts.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/posts.sql
deleted file mode 100644
index 25a30933..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/posts.sql
+++ /dev/null
@@ -1,11 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/query/schema/posts.sql
--- Schema for Post model
-CREATE TABLE posts (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL,
- title VARCHAR(255) NOT NULL,
- content TEXT,
- status VARCHAR(50) NOT NULL DEFAULT 'published',
- created_at TIMESTAMP WITH TIME ZONE,
- updated_at TIMESTAMP WITH TIME ZONE
-);
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/profiles.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/profiles.sql
deleted file mode 100644
index 6b40e508..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/profiles.sql
+++ /dev/null
@@ -1,10 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/query/schema/profiles.sql
--- Schema for Profile model
-CREATE TABLE profiles (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL REFERENCES users(id),
- bio TEXT,
- avatar_url VARCHAR(512),
- created_at TIMESTAMP(6),
- updated_at TIMESTAMP(6)
-);
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/searchable_items.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/searchable_items.sql
deleted file mode 100644
index 4a3b59bc..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/searchable_items.sql
+++ /dev/null
@@ -1,9 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/query/schema/searchable_items.sql
-
-CREATE TABLE "searchable_items" (
- "id" SERIAL PRIMARY KEY,
- "name" VARCHAR(255),
- "tags" TEXT,
- "created_at" TIMESTAMP,
- "updated_at" TIMESTAMP
-);
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/users.sql b/tests/rhosocial/activerecord_postgres_test/feature/query/schema/users.sql
deleted file mode 100644
index 4b41d485..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/schema/users.sql
+++ /dev/null
@@ -1,12 +0,0 @@
--- tests/rhosocial/activerecord_postgres_test/feature/query/schema/users.sql
--- Schema for User model
-CREATE TABLE users (
- id SERIAL PRIMARY KEY,
- username VARCHAR(255) NOT NULL,
- email VARCHAR(255) NOT NULL,
- age INTEGER,
- balance DECIMAL(10,2) NOT NULL DEFAULT 0.00,
- is_active BOOLEAN NOT NULL DEFAULT TRUE,
- created_at TIMESTAMP WITH TIME ZONE,
- updated_at TIMESTAMP WITH TIME ZONE
-);
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation.py
deleted file mode 100644
index d3981b53..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_active_query_set_operation.py
-"""
-Bridge file for ActiveQuery set operation tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.set_operations.test_active_query_set_operation import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.set_operations.test_active_query_set_operation_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py
deleted file mode 100644
index 97e7fa6f..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_active_query_set_operation_async.py
-"""Bridge file for async feature.query.set_operations.test_active_query_set_operation_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.set_operations.test_active_query_set_operation_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py
deleted file mode 100644
index 8cf2e58c..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation.py
-"""
-Bridge file for composite PK set operation tests from the testsuite.
-"""
-from rhosocial.activerecord.testsuite.feature.query.set_operations.test_composite_pk_set_operation import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.set_operations.test_composite_pk_set_operation_async import * # noqa: F403
\ No newline at end of file
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py
deleted file mode 100644
index fe46fbee..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_composite_pk_set_operation_async.py
-"""Bridge file for async feature.query.set_operations.test_composite_pk_set_operation_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.set_operations.test_composite_pk_set_operation_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation.py
deleted file mode 100644
index a23ca1b3..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_set_operation.py
-"""
-Bridge file for set_operation tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.set_operations.test_set_operation import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.set_operations.test_set_operation_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py
deleted file mode 100644
index 20f605cb..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/set_operations/test_set_operation_async.py
-"""Bridge file for async feature.query.set_operations.test_set_operation_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.set_operations.test_set_operation_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py
new file mode 100644
index 00000000..64242303
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/special/conftest.py
+"""Bridge to the shared ``query/special`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.special.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py
index 162cb400..c4517c6a 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py
@@ -1,10 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_example_query_fixtures.py
-"""
-Bridge file for example_query_fixtures tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures.py
+"""Bridge to the shared ``query/special`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py
index aa20fa09..ed6f09fd 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/special/test_example_query_fixtures_async.py
-"""Bridge file for async feature.query.special.test_example_query_fixtures_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/special`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.special.test_example_query_fixtures_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py
index eb4efe6f..dce47161 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py
@@ -1,10 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_special_queries.py
-"""
-Bridge file for special_queries tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries.py
+"""Bridge to the shared ``query/special`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py
index 4bba9f80..ff00a9f9 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/special/test_special_queries_async.py
-"""Bridge file for async feature.query.special.test_special_queries_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/special`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.special.test_special_queries_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py
new file mode 100644
index 00000000..a529658e
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/conftest.py
+"""Bridge fixture configuration for ``query/typed_column``."""
+from rhosocial.activerecord.testsuite.feature.query.typed_column.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_column_operations_core.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_column_operations_core.py
new file mode 100644
index 00000000..6575f54d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_column_operations_core.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_column_operations_core.py
+"""Bridge to the shared ``query/typed_column`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.typed_column.test_column_operations_core import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_enum_capability_contracts.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_enum_capability_contracts.py
new file mode 100644
index 00000000..98d9ef0b
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_enum_capability_contracts.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_enum_capability_contracts.py
+"""Bridge to the shared ``query/typed_column`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.typed_column.test_enum_capability_contracts import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py
new file mode 100644
index 00000000..b7980f2a
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_protocol_guarantees.py
+"""Bridge to the shared ``query/typed_column`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.typed_column.test_protocol_guarantees import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py
index 318177ec..312864ea 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py
@@ -1,2 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_seconds_between_contract.py
+"""Bridge to the shared ``query/typed_column`` contract."""
from rhosocial.activerecord.testsuite.feature.query.typed_column.test_seconds_between_contract import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_typed_column_contracts.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_typed_column_contracts.py
new file mode 100644
index 00000000..4fcfb115
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_typed_column_contracts.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_typed_column_contracts.py
+"""Bridge to the shared ``query/typed_column`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.typed_column.test_typed_column_contracts import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_uuid_capability_contracts.py b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_uuid_capability_contracts.py
new file mode 100644
index 00000000..b40310a0
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_uuid_capability_contracts.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/typed_column/test_uuid_capability_contracts.py
+"""Bridge to the shared ``query/typed_column`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.typed_column.test_uuid_capability_contracts import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py
new file mode 100644
index 00000000..1997d42d
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/conftest.py
+"""Bridge to the shared ``query/window_functions`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.window_functions.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py
index 54ee5de3..145b1b45 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py
@@ -1,10 +1,3 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/test_window_functions.py
-"""
-Bridge file for window_functions tests from the testsuite.
-
-This file imports the generic tests from the testsuite package and makes them
-discoverable by pytest in this project's test run.
-"""
-from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions_async import * # noqa: F403
-
+# tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions.py
+"""Bridge to the shared ``query/window_functions`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py
index f69a0000..e58c9295 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/window_functions/test_window_functions_async.py
-"""Bridge file for async feature.query.window_functions.test_window_functions_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/window_functions`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.window_functions.test_window_functions_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py
index e9cd5de9..3077deb7 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py
@@ -1,8 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/worker/conftest.py
-"""
-Pytest configuration for query worker tests.
-
-This file imports fixtures from the corresponding testsuite, making them
-available to the tests in this directory.
-"""
-from rhosocial.activerecord.testsuite.feature.query.worker.conftest import * # noqa: F403
\ No newline at end of file
+"""Bridge to the shared ``query/worker`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.worker.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py
index f7927c07..05ff3f56 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py
@@ -1,13 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries.py
-"""
-Bridge file for parallel queries worker tests.
-
-Imports tests from testsuite and makes them discoverable by pytest.
-"""
-from rhosocial.activerecord.testsuite.feature.query.worker.conftest import (
- order_fixtures_for_worker, # noqa: F401
- async_order_fixtures_for_worker, # noqa: F401
-)
-from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries_async import * # noqa: F403
-
+"""Bridge to the shared ``query/worker`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py
index 326c49d9..ac9b92b1 100644
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py
@@ -1,3 +1,3 @@
# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_parallel_queries_async.py
-"""Bridge file for async feature.query.worker.test_parallel_queries_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries_async import * # noqa: F401, F403
+"""Bridge to the shared ``query/worker`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_query_worker_transaction_isolation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_query_worker_transaction_isolation.py
deleted file mode 100644
index f32643b9..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_query_worker_transaction_isolation.py
+++ /dev/null
@@ -1,7 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_query_worker_transaction_isolation.py
-"""
-Bridge file for transaction isolation tests.
-
-Imports tests from testsuite and makes them discoverable by pytest.
-"""
-from rhosocial.activerecord.testsuite.feature.query.worker.test_transaction_isolation import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py
deleted file mode 100644
index f73efd1c..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_transaction_isolation_async.py
-"""Bridge file for async feature.query.worker.test_transaction_isolation_async tests."""
-from rhosocial.activerecord.testsuite.feature.query.worker.test_transaction_isolation_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation.py
new file mode 100644
index 00000000..ab42dc10
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation.py.py
+"""Bridge to the shared ``query/worker`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.worker.test_transaction_isolation import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation_async.py
new file mode 100644
index 00000000..b99d28b9
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation_async.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query/worker/test_worker_transaction_isolation_async.py_async.py
+"""Bridge to the shared ``query/worker`` contract."""
+from rhosocial.activerecord.testsuite.feature.query.worker.test_transaction_isolation_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/conftest.py
new file mode 100644
index 00000000..87988fd2
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query_integration/conftest.py
+"""Use the shared ``query_integration`` combination fixture set."""
+from rhosocial.activerecord.testsuite.feature.query_integration.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation.py
new file mode 100644
index 00000000..97198cc0
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation.py
+"""
+Bridge file for ActiveQuery + SetOperationQuery combination tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.query_integration.test_active_query_set_operation import * # noqa: F403
+except ImportError:
+ pytest.skip("ActiveQuery + SetOperationQuery testsuite not available", allow_module_level=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation_async.py
new file mode 100644
index 00000000..204ae10f
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation_async.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_active_query_set_operation_async.py
+"""
+Bridge file for async ActiveQuery + SetOperationQuery combination tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.query_integration.test_active_query_set_operation_async import * # noqa: F403
+except ImportError:
+ pytest.skip("async ActiveQuery + SetOperationQuery testsuite not available", allow_module_level=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query.py
new file mode 100644
index 00000000..38080e2a
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query.py
+"""
+Bridge file for CTEQuery + ActiveQuery combination tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.query_integration.test_cte_query_active_query import * # noqa: F403
+except ImportError:
+ pytest.skip("CTEQuery + ActiveQuery testsuite not available", allow_module_level=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query_async.py
new file mode 100644
index 00000000..cf4a17e8
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query_async.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_active_query_async.py
+"""
+Bridge file for async CTEQuery + ActiveQuery combination tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.query_integration.test_cte_query_active_query_async import * # noqa: F403
+except ImportError:
+ pytest.skip("async CTEQuery + ActiveQuery testsuite not available", allow_module_level=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation.py
new file mode 100644
index 00000000..91893bd5
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation.py
+"""
+Bridge file for CTEQuery + SetOperationQuery combination tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.query_integration.test_cte_query_set_operation import * # noqa: F403
+except ImportError:
+ pytest.skip("CTEQuery + SetOperationQuery testsuite not available", allow_module_level=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation_async.py
new file mode 100644
index 00000000..80776fc2
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation_async.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/query_integration/test_cte_query_set_operation_async.py
+"""
+Bridge file for async CTEQuery + SetOperationQuery combination tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.query_integration.test_cte_query_set_operation_async import * # noqa: F403
+except ImportError:
+ pytest.skip("async CTEQuery + SetOperationQuery testsuite not available", allow_module_level=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base.py
deleted file mode 100644
index 1fb8802b..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""
-Tests for relation base functionality.
-Imports tests from the standardized testsuite.
-"""
-from rhosocial.activerecord.testsuite.feature.relation.base.test_base import TestRelationDescriptor # noqa: F401
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base_async.py
deleted file mode 100644
index 5259aa4a..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_base_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.base.test_base_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces.py
deleted file mode 100644
index dce937f9..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""
-Tests for relation interfaces.
-Imports tests from the standardized testsuite.
-"""
-from rhosocial.activerecord.testsuite.feature.relation.base.test_interfaces import TestRelationInterfaces # noqa: F401
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces_async.py
deleted file mode 100644
index 688ea916..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/base/test_interfaces_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.base.test_interfaces_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary.py
deleted file mode 100644
index 0efbbf89..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.boundary.test_boundary import * # noqa: F401,F403
-from rhosocial.activerecord.testsuite.feature.relation.boundary.test_boundary_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary_async.py
deleted file mode 100644
index 591af194..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/boundary/test_boundary_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.boundary.test_boundary_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache.py
deleted file mode 100644
index 7e97b7cd..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Test bridge for relation cache functionality.
-
-This test file runs the relation cache tests from the testsuite using the PostgreSQL backend.
-"""
-import pytest # noqa: F401
-
-
-# Import the test classes from the testsuite
-from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache import TestRelationCache # noqa: F401
-
-
-# This will cause pytest to run all the tests in the imported class
-# The tests will use the fixtures and providers configured in conftest.py
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_async.py
deleted file mode 100644
index 33f8eccb..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing.py
deleted file mode 100644
index ae990e84..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache_clearing import * # noqa: F401,F403
-from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache_clearing_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py
deleted file mode 100644
index e5e95b6a..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/relation/cache/test_cache_clearing_async.py
-"""Bridge file for async feature.relation.cache.test_cache_clearing_async tests."""
-from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache_clearing_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py
deleted file mode 100644
index 77f688a5..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/relation/conftest.py
-"""
-Pytest configuration for relation feature tests.
-
-This file imports fixtures from the corresponding testsuite, making them
-available to the tests in this directory.
-"""
-from rhosocial.activerecord.testsuite.feature.relation.conftest import * # noqa: F403
-
-import pytest_asyncio
-
-
-@pytest_asyncio.fixture(scope="function")
-async def async_user_class(async_user_post_comment_classes):
- user, _, _ = async_user_post_comment_classes
- return user
-
-
-@pytest_asyncio.fixture(scope="function")
-async def async_post_class(async_user_post_comment_classes):
- _, post, _ = async_user_post_comment_classes
- return post
-
-
-@pytest_asyncio.fixture(scope="function")
-async def async_comment_class(async_user_post_comment_classes):
- _, _, comment = async_user_post_comment_classes
- return comment
-
-
-@pytest_asyncio.fixture(scope="function", params=SCENARIO_PARAMS_ASYNC) # noqa: F405
-async def async_user_post_comment_classes(request):
- from rhosocial.activerecord.testsuite.core.registry import get_provider_registry
-
- scenario = request.param
- provider_registry = get_provider_registry()
- provider_class = provider_registry.get_provider(PROVIDER_KEY_ASYNC) # noqa: F405
- provider = provider_class()
- user = await provider.setup_user_model(scenario)
- post = await provider.setup_post_model(scenario)
- comment = await provider.setup_comment_model(scenario)
- yield user, post, comment
- await provider.cleanup_after_test(scenario)
-
-
-@pytest_asyncio.fixture(scope="function", params=SCENARIO_PARAMS_ASYNC) # noqa: F405
-async def async_relation_boundary_context(request):
- from rhosocial.activerecord.testsuite.core.registry import get_provider_registry
-
- scenario = request.param
- provider_registry = get_provider_registry()
- provider_class = provider_registry.get_provider(PROVIDER_KEY_ASYNC) # noqa: F405
- provider = provider_class()
- owner, profile, post = await provider.setup_relation_boundary_fixtures(scenario)
- yield provider, scenario, owner, profile, post
- await provider.cleanup_after_test(scenario)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json.py
deleted file mode 100644
index a9d9b50b..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json import * # noqa: F401,F403
-from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json_async.py
deleted file mode 100644
index 0bf8a6d2..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_derived_field_json_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field.py
deleted file mode 100644
index b43dbfb2..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field.py
-"""Bridge file for sync feature.relation.derived.test_derived_field tests."""
-from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field_async.py
deleted file mode 100644
index c26f8585..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/relation/derived/test_relation_derived_field_async.py
-"""Bridge file for async feature.relation.derived.test_derived_field_async tests."""
-from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat.py
deleted file mode 100644
index 09df177d..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat.py
+++ /dev/null
@@ -1,4 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/relation/test_descriptor_compat.py
-
-from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptor_compat import * # noqa: F401,F403
-from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptor_compat_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py
deleted file mode 100644
index 53052583..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptor_compat_async.py
-"""Bridge file for async feature.relation.descriptors.test_descriptor_compat_async tests."""
-from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptor_compat_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors.py
deleted file mode 100644
index 9622ce84..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""
-Tests for relation descriptor functionality.
-Imports tests from the standardized testsuite.
-"""
-from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptors import TestRelationDescriptors # noqa: F401
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors_async.py
deleted file mode 100644
index b10f32f3..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/descriptors/test_descriptors_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/relation/test_descriptors_async.py
-
-from rhosocial.activerecord.testsuite.feature.relation.descriptors.test_descriptors_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access.py
deleted file mode 100644
index f9447d3a..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""
-Tests for nested relationship access functionality.
-Imports tests from the standardized testsuite.
-"""
-from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_nested_relationship_access import TestNestedRelationshipAccess # noqa: E501, F401
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access_async.py
deleted file mode 100644
index 6ea7cbbe..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_nested_relationship_access_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_nested_relationship_access_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method.py
deleted file mode 100644
index a1ce8686..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_with_method import * # noqa: F401,F403
-from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_with_method_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method_async.py
deleted file mode 100644
index a2c28563..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/eager_loading/test_with_method_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_with_method_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models.py
deleted file mode 100644
index 3dd75e19..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models.py
+++ /dev/null
@@ -1,420 +0,0 @@
-# src/rhosocial/activerecord/testsuite/feature/relation/fixtures/models.py
-"""
-Relation model fixtures for the testsuite.
-
-This module provides model classes for testing relation features:
-- Employee/Department: Basic BelongsTo/HasMany relations
-- Author/Book/Chapter/Profile: Nested relations with HasOne
-- User/Post/Comment: Relations with FieldProxy, DerivedField, and JSON fields
-"""
-from typing import Optional, ClassVar
-
-from typing_extensions import Annotated
-
-from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord
-from rhosocial.activerecord.base import DerivedField, FieldProxy
-from rhosocial.activerecord.backend.expression import Column, Literal
-from rhosocial.activerecord.backend.expression.functions import (
- json_extract_text, length, coalesce
-)
-from rhosocial.activerecord.relation.descriptors import BelongsTo, HasMany, HasOne
-from rhosocial.activerecord.relation.async_descriptors import AsyncBelongsTo, AsyncHasMany, AsyncHasOne
-
-
-# ── Basic Relation Models ────────────────────────────────
-
-class Employee(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "employees"
-
- id: Optional[int] = None
- username: str
- department_id: int
-
- department: ClassVar[BelongsTo["Department"]] = BelongsTo(
- foreign_key="department_id",
- inverse_of="employees"
- )
-
-
-class Department(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "departments"
-
- id: Optional[int] = None
- name: str
- description: str = ""
-
- employees: ClassVar[HasMany["Employee"]] = HasMany(
- foreign_key="department_id",
- inverse_of="department"
- )
-
-
-class Author(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "authors"
-
- id: Optional[int] = None
- name: str
-
- books: ClassVar[HasMany["Book"]] = HasMany(
- foreign_key="author_id",
- inverse_of="author"
- )
- profile: ClassVar[HasOne["Profile"]] = HasOne(
- foreign_key="author_id",
- inverse_of="author"
- )
-
-
-class Book(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "books"
-
- id: Optional[int] = None
- title: str
- author_id: int
-
- author: ClassVar[BelongsTo["Author"]] = BelongsTo(
- foreign_key="author_id",
- inverse_of="books"
- )
- chapters: ClassVar[HasMany["Chapter"]] = HasMany(
- foreign_key="book_id",
- inverse_of="book"
- )
-
-
-class Chapter(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "chapters"
-
- id: Optional[int] = None
- title: str
- book_id: int
-
- book: ClassVar[BelongsTo["Book"]] = BelongsTo(
- foreign_key="book_id",
- inverse_of="chapters"
- )
-
-
-class Profile(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "profiles"
-
- id: Optional[int] = None
- bio: str
- author_id: int
-
- author: ClassVar[BelongsTo["Author"]] = BelongsTo(
- foreign_key="author_id",
- inverse_of="profile"
- )
-
-
-# ── Advanced Relation Models (with FieldProxy, DerivedField, JSON) ──
-
-class User(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "users"
-
- c: ClassVar[FieldProxy] = FieldProxy()
- id: Optional[int] = None
- name: str
- email: Optional[str] = None
- settings: Optional[str] = None # JSON: {"language": "zh-CN", "theme": "dark"}
-
- # DerivedField: display name (coalesce email to name)
- display_name: ClassVar[Annotated[str, DerivedField(
- lambda d: coalesce(d, Column(dialect, d, "email"), Column(dialect, d, "name")),
- )]]
-
- # DerivedField (JSON): extract language preference
- language: ClassVar[Annotated[str, DerivedField(
- lambda d: json_extract_text(d, Column(dialect, d, "settings"), "$.language"),
- )]]
-
- # DerivedField (JSON): extract theme preference
- theme: ClassVar[Annotated[str, DerivedField(
- lambda d: json_extract_text(d, Column(dialect, d, "settings"), "$.theme"),
- )]]
-
- # Relation
- posts: ClassVar[HasMany["Post"]] = HasMany(
- foreign_key="user_id",
- inverse_of="user"
- )
-
-
-class Post(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "posts"
-
- c: ClassVar[FieldProxy] = FieldProxy()
- id: Optional[int] = None
- title: str
- body: str
- user_id: int
- view_count: int = 0
- metadata: Optional[str] = None # JSON: {"tags": ["python", "orm"], "source": "blog"}
-
- # DerivedField: title length using FieldProxy
- title_length: ClassVar[Annotated[int, DerivedField(
- lambda d: length(d, Post.c.title),
- )]]
-
- # DerivedField: hotness score
- hotness: ClassVar[Annotated[int, DerivedField(
- lambda d: ArithmeticOperation(dialect, "add", Column(dialect, d, "view_count"), Literal(d, 1)),
- )]]
-
- # DerivedField (JSON): first tag from metadata
- first_tag: ClassVar[Annotated[str, DerivedField(
- lambda d: json_extract_text(d, Column(dialect, d, "metadata"), "$.tags[0]"),
- )]]
-
- # DerivedField (JSON): source from metadata
- source: ClassVar[Annotated[str, DerivedField(
- lambda d: json_extract_text(d, Column(dialect, d, "metadata"), "$.source"),
- )]]
-
- # Relations
- user: ClassVar[BelongsTo["User"]] = BelongsTo(
- foreign_key="user_id",
- inverse_of="posts"
- )
- comments: ClassVar[HasMany["Comment"]] = HasMany(
- foreign_key="post_id",
- inverse_of="post"
- )
-
-
-class Comment(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "comments"
-
- c: ClassVar[FieldProxy] = FieldProxy()
- id: Optional[int] = None
- body: str
- post_id: int
- meta: Optional[str] = None # JSON: {"platform": "web", "device": "mobile"}
-
- # DerivedField: body length using FieldProxy
- body_length: ClassVar[Annotated[int, DerivedField(
- lambda d: length(d, Comment.c.body),
- )]]
-
- # DerivedField (JSON): platform from meta
- platform: ClassVar[Annotated[str, DerivedField(
- lambda d: json_extract_text(d, Column(dialect, d, "meta"), "$.platform"),
- )]]
-
- # Relation
- post: ClassVar[BelongsTo["Post"]] = BelongsTo(
- foreign_key="post_id",
- inverse_of="comments"
- )
-
-
-# ── Async Models ─────────────────────────────────────────
-
-class AsyncUser(AsyncActiveRecord):
- @classmethod
- def table_name(cls):
- return "users"
-
- c: ClassVar[FieldProxy] = FieldProxy()
- id: Optional[int] = None
- name: str
- email: Optional[str] = None
- settings: Optional[str] = None
-
- display_name: ClassVar[Annotated[str, DerivedField(
- lambda d: coalesce(d, Column(dialect, d, "email"), Column(dialect, d, "name")),
- )]]
-
- language: ClassVar[Annotated[str, DerivedField(
- lambda d: json_extract_text(d, Column(dialect, d, "settings"), "$.language"),
- )]]
-
- theme: ClassVar[Annotated[str, DerivedField(
- lambda d: json_extract_text(d, Column(dialect, d, "settings"), "$.theme"),
- )]]
-
- posts: ClassVar[AsyncHasMany["AsyncPost"]] = AsyncHasMany(
- foreign_key="user_id",
- inverse_of="user"
- )
-
-
-class AsyncPost(AsyncActiveRecord):
- @classmethod
- def table_name(cls):
- return "posts"
-
- c: ClassVar[FieldProxy] = FieldProxy()
- id: Optional[int] = None
- title: str
- body: str
- user_id: int
- view_count: int = 0
- metadata: Optional[str] = None
-
- title_length: ClassVar[Annotated[int, DerivedField(
- lambda d: length(d, AsyncPost.c.title),
- )]]
-
- hotness: ClassVar[Annotated[int, DerivedField(
- lambda d: ArithmeticOperation(dialect, "add", Column(dialect, d, "view_count"), Literal(d, 1)),
- )]]
-
- first_tag: ClassVar[Annotated[str, DerivedField(
- lambda d: json_extract_text(d, Column(dialect, d, "metadata"), "$.tags[0]"),
- )]]
-
- source: ClassVar[Annotated[str, DerivedField(
- lambda d: json_extract_text(d, Column(dialect, d, "metadata"), "$.source"),
- )]]
-
- user: ClassVar[AsyncBelongsTo["AsyncUser"]] = AsyncBelongsTo(
- foreign_key="user_id",
- inverse_of="posts"
- )
- comments: ClassVar[AsyncHasMany["AsyncComment"]] = AsyncHasMany(
- foreign_key="post_id",
- inverse_of="post"
- )
-
-
-class AsyncComment(AsyncActiveRecord):
- @classmethod
- def table_name(cls):
- return "comments"
-
- c: ClassVar[FieldProxy] = FieldProxy()
- id: Optional[int] = None
- body: str
- post_id: int
- meta: Optional[str] = None
-
- body_length: ClassVar[Annotated[int, DerivedField(
- lambda d: length(d, AsyncComment.c.body),
- )]]
-
- platform: ClassVar[Annotated[str, DerivedField(
- lambda d: json_extract_text(d, Column(dialect, d, "meta"), "$.platform"),
- )]]
-
- post: ClassVar[AsyncBelongsTo["AsyncPost"]] = AsyncBelongsTo(
- foreign_key="post_id",
- inverse_of="comments"
- )
-
-
-# ── Relation Boundary Models ──────────────────────────────
-
-class BoundaryOwner(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "relation_boundary_owners"
-
- id: Optional[int] = None
- name: str
-
- profile: ClassVar[HasOne["BoundaryProfile"]] = HasOne(
- foreign_key="owner_id",
- inverse_of="owner"
- )
- posts: ClassVar[HasMany["BoundaryPost"]] = HasMany(
- foreign_key="owner_id",
- inverse_of="owner"
- )
-
-
-class BoundaryProfile(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "relation_boundary_profiles"
-
- id: Optional[int] = None
- bio: str
- owner_id: Optional[int] = None
-
- owner: ClassVar[BelongsTo["BoundaryOwner"]] = BelongsTo(
- foreign_key="owner_id",
- inverse_of="profile"
- )
-
-
-class BoundaryPost(ActiveRecord):
- @classmethod
- def table_name(cls):
- return "relation_boundary_posts"
-
- id: Optional[int] = None
- title: str
- owner_id: Optional[int] = None
-
- owner: ClassVar[BelongsTo["BoundaryOwner"]] = BelongsTo(
- foreign_key="owner_id",
- inverse_of="posts"
- )
-
-
-class AsyncBoundaryOwner(AsyncActiveRecord):
- @classmethod
- def table_name(cls):
- return "relation_boundary_owners"
-
- id: Optional[int] = None
- name: str
-
- profile: ClassVar[AsyncHasOne["AsyncBoundaryProfile"]] = AsyncHasOne(
- foreign_key="owner_id",
- inverse_of="owner"
- )
- posts: ClassVar[AsyncHasMany["AsyncBoundaryPost"]] = AsyncHasMany(
- foreign_key="owner_id",
- inverse_of="owner"
- )
-
-
-class AsyncBoundaryProfile(AsyncActiveRecord):
- @classmethod
- def table_name(cls):
- return "relation_boundary_profiles"
-
- id: Optional[int] = None
- bio: str
- owner_id: Optional[int] = None
-
- owner: ClassVar[AsyncBelongsTo["AsyncBoundaryOwner"]] = AsyncBelongsTo(
- foreign_key="owner_id",
- inverse_of="profile"
- )
-
-
-class AsyncBoundaryPost(AsyncActiveRecord):
- @classmethod
- def table_name(cls):
- return "relation_boundary_posts"
-
- id: Optional[int] = None
- title: str
- owner_id: Optional[int] = None
-
- owner: ClassVar[AsyncBelongsTo["AsyncBoundaryOwner"]] = AsyncBelongsTo(
- foreign_key="owner_id",
- inverse_of="posts"
- )
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py310.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py310.py
deleted file mode 100644
index e91bf2c1..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py310.py
+++ /dev/null
@@ -1,144 +0,0 @@
-# src/rhosocial/activerecord/testsuite/feature/relation/fixtures/models_py310.py
-"""
-Python 3.10+ fixture model definitions for relation tests.
-
-This file contains model classes using Python 3.10+ syntax features:
-- `X | Y` syntax instead of `Optional[X]` or `Union[X, Y]`
-
-Note: This file should only be imported and used in Python 3.10+ environments.
-"""
-from typing import ClassVar
-
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.relation.descriptors import BelongsTo, HasMany, HasOne
-
-
-# Declare that this module requires Python 3.10+
-__requires_python__ = (3, 10)
-
-
-class Employee(ActiveRecord):
- """Employee model with department relation.
-
- Python 3.10+ version.
- """
- @classmethod
- def table_name(cls):
- return "employees"
-
- id: int | None = None
- username: str
- department_id: int
-
- # Define the relation to department
- department: ClassVar[BelongsTo["Department"]] = BelongsTo(
- foreign_key="department_id",
- inverse_of="employees"
- )
-
-
-class Department(ActiveRecord):
- """Department model with employees relation.
-
- Python 3.10+ version.
- """
- @classmethod
- def table_name(cls):
- return "departments"
-
- id: int | None = None
- name: str
- description: str = ""
-
- # Define the relation to employees
- employees: ClassVar[HasMany["Employee"]] = HasMany(
- foreign_key="department_id",
- inverse_of="department"
- )
-
-
-class Author(ActiveRecord):
- """Author model with books and profile relations.
-
- Python 3.10+ version.
- """
- @classmethod
- def table_name(cls):
- return "authors"
-
- id: int | None = None
- name: str
-
- # Relations
- books: ClassVar[HasMany["Book"]] = HasMany(
- foreign_key="author_id",
- inverse_of="author"
- )
- profile: ClassVar[HasOne["Profile"]] = HasOne(
- foreign_key="author_id",
- inverse_of="author"
- )
-
-
-class Book(ActiveRecord):
- """Book model with author and chapters relations.
-
- Python 3.10+ version.
- """
- @classmethod
- def table_name(cls):
- return "books"
-
- id: int | None = None
- title: str
- author_id: int
-
- # Relations
- author: ClassVar[BelongsTo["Author"]] = BelongsTo(
- foreign_key="author_id",
- inverse_of="books"
- )
- chapters: ClassVar[HasMany["Chapter"]] = HasMany(
- foreign_key="book_id",
- inverse_of="book"
- )
-
-
-class Chapter(ActiveRecord):
- """Chapter model with book relation.
-
- Python 3.10+ version.
- """
- @classmethod
- def table_name(cls):
- return "chapters"
-
- id: int | None = None
- title: str
- book_id: int
-
- # Relations
- book: ClassVar[BelongsTo["Book"]] = BelongsTo(
- foreign_key="book_id",
- inverse_of="chapters"
- )
-
-
-class Profile(ActiveRecord):
- """Profile model with author relation.
-
- Python 3.10+ version.
- """
- @classmethod
- def table_name(cls):
- return "profiles"
-
- id: int | None = None
- bio: str
- author_id: int
-
- # Relations
- author: ClassVar[BelongsTo["Author"]] = BelongsTo(
- foreign_key="author_id",
- inverse_of="profile"
- )
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py311.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py311.py
deleted file mode 100644
index ea692f3c..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py311.py
+++ /dev/null
@@ -1,177 +0,0 @@
-# src/rhosocial/activerecord/testsuite/feature/relation/fixtures/models_py311.py
-"""
-Python 3.11+ fixture model definitions for relation tests.
-
-This file contains model classes using Python 3.11+ syntax features:
-- `Self` type for methods that return an instance of the same class
-- `X | Y` syntax (inherited from 3.10+)
-
-Note: This file should only be imported and used in Python 3.11+ environments.
-"""
-from __future__ import annotations
-
-from typing import ClassVar, Self
-
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.relation.descriptors import BelongsTo, HasMany, HasOne
-
-
-# Declare that this module requires Python 3.11+
-__requires_python__ = (3, 11)
-
-
-class Employee(ActiveRecord):
- """Employee model with department relation.
-
- Python 3.11+ version using | syntax and Self type.
- """
- @classmethod
- def table_name(cls):
- return "employees"
-
- id: int | None = None
- username: str
- department_id: int
-
- # Define the relation to department
- department: ClassVar[BelongsTo["Department"]] = BelongsTo(
- foreign_key="department_id",
- inverse_of="employees"
- )
-
- def transfer_to(self, new_department_id: int) -> Self:
- """Transfer employee to another department and return self for chaining."""
- self.department_id = new_department_id
- return self
-
-
-class Department(ActiveRecord):
- """Department model with employees relation.
-
- Python 3.11+ version using | syntax and Self type.
- """
- @classmethod
- def table_name(cls):
- return "departments"
-
- id: int | None = None
- name: str
- description: str = ""
-
- # Define the relation to employees
- employees: ClassVar[HasMany["Employee"]] = HasMany(
- foreign_key="department_id",
- inverse_of="department"
- )
-
- def set_description(self, new_description: str) -> Self:
- """Set description and return self for chaining."""
- self.description = new_description
- return self
-
-
-class Author(ActiveRecord):
- """Author model with books and profile relations.
-
- Python 3.11+ version using | syntax and Self type.
- """
- @classmethod
- def table_name(cls):
- return "authors"
-
- id: int | None = None
- name: str
-
- # Relations
- books: ClassVar[HasMany["Book"]] = HasMany(
- foreign_key="author_id",
- inverse_of="author"
- )
- profile: ClassVar[HasOne["Profile"]] = HasOne(
- foreign_key="author_id",
- inverse_of="author"
- )
-
- def rename(self, new_name: str) -> Self:
- """Rename author and return self for chaining."""
- self.name = new_name
- return self
-
-
-class Book(ActiveRecord):
- """Book model with author and chapters relations.
-
- Python 3.11+ version using | syntax and Self type.
- """
- @classmethod
- def table_name(cls):
- return "books"
-
- id: int | None = None
- title: str
- author_id: int
-
- # Relations
- author: ClassVar[BelongsTo["Author"]] = BelongsTo(
- foreign_key="author_id",
- inverse_of="books"
- )
- chapters: ClassVar[HasMany["Chapter"]] = HasMany(
- foreign_key="book_id",
- inverse_of="book"
- )
-
- def retitle(self, new_title: str) -> Self:
- """Change book title and return self for chaining."""
- self.title = new_title
- return self
-
-
-class Chapter(ActiveRecord):
- """Chapter model with book relation.
-
- Python 3.11+ version using | syntax and Self type.
- """
- @classmethod
- def table_name(cls):
- return "chapters"
-
- id: int | None = None
- title: str
- book_id: int
-
- # Relations
- book: ClassVar[BelongsTo["Book"]] = BelongsTo(
- foreign_key="book_id",
- inverse_of="chapters"
- )
-
- def rename(self, new_title: str) -> Self:
- """Rename chapter and return self for chaining."""
- self.title = new_title
- return self
-
-
-class Profile(ActiveRecord):
- """Profile model with author relation.
-
- Python 3.11+ version using | syntax and Self type.
- """
- @classmethod
- def table_name(cls):
- return "profiles"
-
- id: int | None = None
- bio: str
- author_id: int
-
- # Relations
- author: ClassVar[BelongsTo["Author"]] = BelongsTo(
- foreign_key="author_id",
- inverse_of="profile"
- )
-
- def update_bio(self, new_bio: str) -> Self:
- """Update bio and return self for chaining."""
- self.bio = new_bio
- return self
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py312.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py312.py
deleted file mode 100644
index 75a3906f..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/fixtures/models_py312.py
+++ /dev/null
@@ -1,214 +0,0 @@
-# src/rhosocial/activerecord/testsuite/feature/relation/fixtures/models_py312.py
-"""
-Python 3.12+ fixture model definitions for relation tests.
-
-This file contains model classes using Python 3.12+ syntax features:
-- `@override` decorator for inheritance safety
-- `Self` type for methods that return an instance of the same class
-- `X | Y` syntax (inherited from 3.10+)
-
-Note: This file should only be imported and used in Python 3.12+ environments.
-"""
-from __future__ import annotations
-
-from typing import ClassVar, Self, override
-
-from rhosocial.activerecord.model import ActiveRecord
-from rhosocial.activerecord.relation.descriptors import BelongsTo, HasMany, HasOne
-
-
-# Declare that this module requires Python 3.12+
-__requires_python__ = (3, 12)
-
-
-class Employee(ActiveRecord):
- """Employee model with department relation.
-
- Python 3.12+ version using | syntax, Self type, and @override.
- """
- @classmethod
- def table_name(cls):
- return "employees"
-
- id: int | None = None
- username: str
- department_id: int
-
- # Define the relation to department
- department: ClassVar[BelongsTo["Department"]] = BelongsTo(
- foreign_key="department_id",
- inverse_of="employees"
- )
-
- @override
- def save(self, **kwargs) -> Self:
- """Save the employee and return self for chaining."""
- super().save(**kwargs)
- return self
-
- def transfer_to(self, new_department_id: int) -> Self:
- """Transfer employee to another department and return self for chaining."""
- self.department_id = new_department_id
- return self
-
-
-class Department(ActiveRecord):
- """Department model with employees relation.
-
- Python 3.12+ version using | syntax, Self type, and @override.
- """
- @classmethod
- def table_name(cls):
- return "departments"
-
- id: int | None = None
- name: str
- description: str = ""
-
- # Define the relation to employees
- employees: ClassVar[HasMany["Employee"]] = HasMany(
- foreign_key="department_id",
- inverse_of="department"
- )
-
- @override
- def save(self, **kwargs) -> Self:
- """Save the department and return self for chaining."""
- super().save(**kwargs)
- return self
-
- def set_description(self, new_description: str) -> Self:
- """Set description and return self for chaining."""
- self.description = new_description
- return self
-
-
-class Author(ActiveRecord):
- """Author model with books and profile relations.
-
- Python 3.12+ version using | syntax, Self type, and @override.
- """
- @classmethod
- def table_name(cls):
- return "authors"
-
- id: int | None = None
- name: str
-
- # Relations
- books: ClassVar[HasMany["Book"]] = HasMany(
- foreign_key="author_id",
- inverse_of="author"
- )
- profile: ClassVar[HasOne["Profile"]] = HasOne(
- foreign_key="author_id",
- inverse_of="author"
- )
-
- @override
- def save(self, **kwargs) -> Self:
- """Save the author and return self for chaining."""
- super().save(**kwargs)
- return self
-
- def rename(self, new_name: str) -> Self:
- """Rename author and return self for chaining."""
- self.name = new_name
- return self
-
-
-class Book(ActiveRecord):
- """Book model with author and chapters relations.
-
- Python 3.12+ version using | syntax, Self type, and @override.
- """
- @classmethod
- def table_name(cls):
- return "books"
-
- id: int | None = None
- title: str
- author_id: int
-
- # Relations
- author: ClassVar[BelongsTo["Author"]] = BelongsTo(
- foreign_key="author_id",
- inverse_of="books"
- )
- chapters: ClassVar[HasMany["Chapter"]] = HasMany(
- foreign_key="book_id",
- inverse_of="book"
- )
-
- @override
- def save(self, **kwargs) -> Self:
- """Save the book and return self for chaining."""
- super().save(**kwargs)
- return self
-
- def retitle(self, new_title: str) -> Self:
- """Change book title and return self for chaining."""
- self.title = new_title
- return self
-
-
-class Chapter(ActiveRecord):
- """Chapter model with book relation.
-
- Python 3.12+ version using | syntax, Self type, and @override.
- """
- @classmethod
- def table_name(cls):
- return "chapters"
-
- id: int | None = None
- title: str
- book_id: int
-
- # Relations
- book: ClassVar[BelongsTo["Book"]] = BelongsTo(
- foreign_key="book_id",
- inverse_of="chapters"
- )
-
- @override
- def save(self, **kwargs) -> Self:
- """Save the chapter and return self for chaining."""
- super().save(**kwargs)
- return self
-
- def rename(self, new_title: str) -> Self:
- """Rename chapter and return self for chaining."""
- self.title = new_title
- return self
-
-
-class Profile(ActiveRecord):
- """Profile model with author relation.
-
- Python 3.12+ version using | syntax, Self type, and @override.
- """
- @classmethod
- def table_name(cls):
- return "profiles"
-
- id: int | None = None
- bio: str
- author_id: int
-
- # Relations
- author: ClassVar[BelongsTo["Author"]] = BelongsTo(
- foreign_key="author_id",
- inverse_of="profile"
- )
-
- @override
- def save(self, **kwargs) -> Self:
- """Save the profile and return self for chaining."""
- super().save(**kwargs)
- return self
-
- def update_bio(self, new_bio: str) -> Self:
- """Update bio and return self for chaining."""
- self.bio = new_bio
- return self
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration.py
deleted file mode 100644
index eb3e57d4..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration import * # noqa: F401,F403
-from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration_async.py
deleted file mode 100644
index ef9b2e02..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/integration/test_integration_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior.py
deleted file mode 100644
index 8fc621f3..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_behavior import * # noqa: F401,F403
-from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_behavior_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior_async.py
deleted file mode 100644
index 797fa5e3..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_behavior_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_behavior_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning.py
deleted file mode 100644
index 2b7b7bc8..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_warning import * # noqa: F401,F403
-from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_warning_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning_async.py
deleted file mode 100644
index 6e884253..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/modifiers/test_modifier_warning_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.modifiers.test_modifier_warning_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py
deleted file mode 100644
index c3ba5e03..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py
+++ /dev/null
@@ -1,4 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/relation/ordering/test_has_many_order_by.py
-"""Bridge file for the testsuite ordered HasMany contract (sync and async)."""
-from rhosocial.activerecord.testsuite.feature.relation.ordering.test_has_many_order_by import * # noqa: F403
-from rhosocial.activerecord.testsuite.feature.relation.ordering.test_has_many_order_by_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation.py
deleted file mode 100644
index b2b0a150..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.validation.test_path_validation import * # noqa: F401,F403
-from rhosocial.activerecord.testsuite.feature.relation.validation.test_path_validation_async import * # noqa: F403
-
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation_async.py
deleted file mode 100644
index b492478f..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_path_validation_async.py
+++ /dev/null
@@ -1 +0,0 @@
-from rhosocial.activerecord.testsuite.feature.relation.validation.test_path_validation_async import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator.py
deleted file mode 100644
index 47df6d4e..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator.py
+++ /dev/null
@@ -1,4 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/relation/test_validator.py
-
-from rhosocial.activerecord.testsuite.feature.relation.validation.test_validator import * # noqa: F401,F403
-from rhosocial.activerecord.testsuite.feature.relation.validation.test_validator_async import * # noqa: F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py b/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py
deleted file mode 100644
index 799baf9f..00000000
--- a/tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# tests/rhosocial/activerecord_postgres_test/feature/relation/validation/test_validator_async.py
-"""Bridge file for async feature.relation.validation.test_validator_async tests."""
-from rhosocial.activerecord.testsuite.feature.relation.validation.test_validator_async import * # noqa: F401, F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/setop/conftest.py b/tests/rhosocial/activerecord_postgres_test/feature/setop/conftest.py
new file mode 100644
index 00000000..30262f20
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/setop/conftest.py
@@ -0,0 +1,3 @@
+# tests/rhosocial/activerecord_postgres_test/feature/setop/conftest.py
+"""Use the shared ``setop`` minimal test set."""
+from rhosocial.activerecord.testsuite.feature.setop.conftest import * # noqa: F401,F403
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation.py
new file mode 100644
index 00000000..24ed5f06
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation.py
+"""
+Bridge file for composite PK sync set operation tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.setop.test_composite_pk_set_operation import * # noqa: F403
+except ImportError:
+ pytest.skip("composite_pk testsuite not available", allow_module_level=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation_async.py
new file mode 100644
index 00000000..87348f0a
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation_async.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/setop/test_composite_pk_set_operation_async.py
+"""
+Bridge file for composite PK async set operation tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.setop.test_composite_pk_set_operation_async import * # noqa: F403
+except ImportError:
+ pytest.skip("composite_pk testsuite not available", allow_module_level=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation.py b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation.py
new file mode 100644
index 00000000..35a7809f
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation.py
+"""
+Bridge file for sync set operation tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.setop.test_set_operation import * # noqa: F403
+except ImportError:
+ pytest.skip("setop testsuite not available", allow_module_level=True)
diff --git a/tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation_async.py b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation_async.py
new file mode 100644
index 00000000..d3d071c1
--- /dev/null
+++ b/tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation_async.py
@@ -0,0 +1,9 @@
+# tests/rhosocial/activerecord_postgres_test/feature/setop/test_set_operation_async.py
+"""
+Bridge file for async set operation tests from the testsuite.
+"""
+import pytest
+try:
+ from rhosocial.activerecord.testsuite.feature.setop.test_set_operation_async import * # noqa: F403
+except ImportError:
+ pytest.skip("setop testsuite not available", allow_module_level=True)
diff --git a/tests/rhosocial/activerecord_test/feature/backend/cli/test_cli_blackbox.py b/tests/rhosocial/activerecord_test/feature/backend/cli/test_cli_blackbox.py
index 210f89ad..2405a988 100644
--- a/tests/rhosocial/activerecord_test/feature/backend/cli/test_cli_blackbox.py
+++ b/tests/rhosocial/activerecord_test/feature/backend/cli/test_cli_blackbox.py
@@ -8,7 +8,7 @@
import pytest
from rhosocial.activerecord.backend.impl.postgres.__main__ import main
-from providers.scenarios import get_scenario_raw
+from support.postgres import get_scenario_raw
import socket
COMMANDS = [
diff --git a/tests/support/__init__.py b/tests/support/__init__.py
new file mode 100644
index 00000000..3ad07961
--- /dev/null
+++ b/tests/support/__init__.py
@@ -0,0 +1,2 @@
+# tests/support/__init__.py
+"""Backend declarations and test helpers that are not fixtures."""
diff --git a/tests/support/postgres.py b/tests/support/postgres.py
new file mode 100644
index 00000000..5d91b735
--- /dev/null
+++ b/tests/support/postgres.py
@@ -0,0 +1,131 @@
+# tests/support/postgres.py
+"""The PostgreSQL backend's test scenarios.
+
+The scenario file holds server connection parameters only; the logical database
+name comes from the test directory and is injected here. PostgreSQL is a
+server backend, so a scenario maps to one database on one server.
+
+Maintenance work (dropping and creating databases, server-level checks) runs on
+the ``postgres`` database every PostgreSQL instance ships with, because a
+connection cannot drop the database it is currently using.
+"""
+
+import os
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Dict
+
+import yaml
+
+from rhosocial.activerecord.backend.impl.postgres.backend import (
+ AsyncPostgresBackend,
+ PostgresBackend,
+)
+from rhosocial.activerecord.backend.impl.postgres.config import PostgresConnectionConfig
+from rhosocial.activerecord.backend.options import ExecutionOptions
+from rhosocial.activerecord.backend.schema import StatementType
+
+CONFIG_PATH = Path(
+ os.environ.get("POSTGRES_SCENARIOS_CONFIG_PATH")
+ or Path(__file__).resolve().parents[1] / "config" / "postgres_scenarios.yaml"
+)
+
+# The scenario file describes a server, never a database: the logical name is
+# derived from the test directory. A ``database`` key, if present, is dropped.
+# ``enabled`` is a scenario toggle, not a connection parameter.
+SERVER_ONLY_KEYS = ("database", "enabled")
+
+# The database every PostgreSQL server has, used for server-level connections.
+MAINTENANCE_DATABASE = "postgres"
+
+DDL_OPTIONS = ExecutionOptions(stmt_type=StatementType.DDL)
+
+
+def _load_scenarios(path: Path = CONFIG_PATH) -> Dict[str, Dict[str, Any]]:
+ """Load one server-parameter dict per scenario from the YAML file."""
+ with open(path, "r", encoding="utf-8") as file:
+ data = yaml.safe_load(file) or {}
+ entries = data.get("scenarios")
+ if not entries:
+ raise ValueError(f"{path} defines no scenarios")
+ return {
+ name: {key: value for key, value in entry.items() if key not in SERVER_ONLY_KEYS}
+ for name, entry in entries.items()
+ }
+
+
+SCENARIO_MAP = _load_scenarios()
+SCENARIOS = tuple(SCENARIO_MAP)
+
+
+def _identifier(name: str) -> str:
+ """Quote a PostgreSQL identifier (database names come from the testsuite)."""
+ return '"' + name.replace('"', '""') + '"'
+
+
+@dataclass(frozen=True)
+class PostgresScenario:
+ """One PostgreSQL test scenario: a server plus the backend classes."""
+
+ name: str
+ server: Dict[str, Any]
+ backend_class: Any = PostgresBackend
+ async_backend_class: Any = AsyncPostgresBackend
+ maintenance_database: str = "postgres"
+
+ def make_config(self, database: str) -> PostgresConnectionConfig:
+ """Return the connection configuration for this database on this server."""
+ return PostgresConnectionConfig(**self.server, database=database)
+
+ def reset_database(self, database: str) -> None:
+ """Drop and recreate ``database`` on this scenario's server."""
+ backend = self.backend_class(
+ connection_config=PostgresConnectionConfig(**self.server, database=MAINTENANCE_DATABASE)
+ )
+ backend.connect()
+ try:
+ backend.execute(
+ f"DROP DATABASE IF EXISTS {_identifier(database)}",
+ (),
+ options=DDL_OPTIONS,
+ )
+ backend.execute(
+ f"CREATE DATABASE {_identifier(database)}",
+ (),
+ options=DDL_OPTIONS,
+ )
+ finally:
+ backend.disconnect()
+
+
+def scenario(name: str) -> PostgresScenario:
+ """Return the scenario called ``name``."""
+ try:
+ server = SCENARIO_MAP[name]
+ except KeyError:
+ raise KeyError(f"Unknown PostgreSQL scenario: {name}") from None
+ return PostgresScenario(name, server)
+
+
+def get_enabled_scenarios():
+ """Return the scenarios this backend enables, as a name -> server map."""
+ return {name: dict(server) for name, server in SCENARIO_MAP.items()}
+
+
+def get_scenario(name: str):
+ """Return ``(backend_class, config)`` for a benchmark database."""
+ current = scenario(name)
+ current.reset_database("test_benchmark")
+ return current.backend_class, current.make_config("test_benchmark")
+
+
+def get_scenario_raw(name: str):
+ """Return ``(backend_class, config)`` for a server-level connection.
+
+ Falls back to the first configured scenario when CI enables only one.
+ """
+ resolved = name if name in SCENARIO_MAP else next(iter(SCENARIO_MAP), None)
+ if resolved is None:
+ raise KeyError("No %s scenario configured" % name)
+ current = scenario(resolved)
+ return current.backend_class, current.make_config(MAINTENANCE_DATABASE)