Skip to content

feat(postgres): declaration-driven DDL and shared testsuite contracts - #72

Merged
vistart merged 81 commits into
release/v1.0.0.dev17from
feature/activerecord-ddl
Nov 20, 2026
Merged

vistart merged 81 commits into
release/v1.0.0.dev17from
feature/activerecord-ddl

Conversation

@vistart

@vistart vistart commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Description

PostgreSQL-backend side of the coordinated feature/activerecord-ddl work. It brings the backend onto the rebuilt shared testsuite and core DDL/migration contracts, and adds backend-specific migration documentation.

What changed:

  • DDL / migration: backend-specific migration guide and runnable examples; auto-increment suggestions and field generators, with SERIAL used on every server version and the capability probe moved onto the dialect (skips decided by dialect probes rather than version tuples); expression-built DDL and primary-key identity restoration for long-content models; portable migrate CLI contracts bridged.
  • Types / adapters: answer all 24 column entries with no refusals and name the server's own column classes; PostGIS gets its own ST_* column class, hstore key predicates, vector distance operators, text-search match/rank, multirange and range operators, bit-string bitwise operators and geometric built-ins; range wrappers are kept out of the extras table. Added the data-type suggestions with the substitute_data_types hook rename, the typed-column contract in CI, neutral and network-address adapters (including macaddr8 and psycopg multiranges), and jsonpath registration.
  • Tests: the PostgreSQL test tree moves to the rebuilt testsuite's directory-owned databases, declaration-driven fixtures and parallel scopes — DDLSource, query/relation/typed_column, restructured query topics, feature CLI, and shared benchmarks are bridged. Added live and offline CLI (info/query/introspect/status) tests and backend-local deep EXPLAIN tests rewritten without RawSQL; PostGIS/complex-geometry cases are gated on availability.
  • Docs / CI: README restructured into the 6-section template with version badge, backend docs chapters built out, migration guide added. CI test scope restructured for the new layout, coverage narrowed to this package, stable postgres:19 image adopted, and dependencies pinned to the merged releases: testsuite release/v1.0.0.dev17 and core release/v1.0.0.dev30.

Dependencies: core >=1.0.0.dev30,<2.0.0 and the shared testsuite release/v1.0.0.dev17 (both merged in the coordinated series).

Adds # (issue): N/A

Type of change

  • feat: A new feature
  • docs: Documentation only changes (if related to the new feature)
  • perf: A code change that improves performance (if part of the feature)
  • test: Adding missing tests or correcting existing tests (for the new feature)
  • chore: Changes to the build process or auxiliary tools/libraries (test-suite tooling)
  • ci: Changes to our CI configuration files and scripts (if related to the new feature)
  • build: Changes that affect the build system or external dependencies (if related to the new feature)
  • revert: Reverts a previous commit

(Also includes fix commits as part of the feature.)

Breaking Change

  • Yes
  • No

feat(postgres)!: directory-owned fixtures and expression DDL: basic/core, query/collation and connection test directories now own their databases and build tables per test from dialect-only definition classes; no raw SQL remains there, and connection-pool tables moved into pool_definitions.py (keeping SERIAL). This changes the backend's internal test-fixture layout, with no public API impact.

Applicable rhosocial-activerecord Version Range: >=1.0.0.dev30,<2.0.0

Related Repositories/Packages

Part of the coordinated feature/activerecord-ddl series; every repo's work is based on its own latest release/* branch:

  • rhosocial/python-activerecord-testsuite — rebuilt suite merged as PR feat(postgres): add schema namespace support for PostgreSQL backend #33 on release/v1.0.0.dev17.
  • rhosocial/python-activerecord (core) — DDL/migration APIs merged as PR #141 on release/v1.0.0.dev30.
  • The other eight backends: mysql, mariadb, sqlserver, oracle, snowflake, clickhouse, bigquery, firebird — each with its own coordinated PR.

Testing

  • I have added new tests to cover my changes.
  • I have updated existing tests to reflect my changes.
  • All existing tests pass. (Full local suite intentionally skipped; validation is delegated to remote CI per project policy.)
  • This change has been tested on [specify backend/DB versions].

Test Plan:

Local full-suite execution skipped per AGENTS.md (full tests run in CI only). CI will run the suite across the Python / PostgreSQL matrix, including PostGIS-gated cases. Development commits added live and offline CLI tests, deep EXPLAIN tests and the shared contract bridges listed above; unsupported or unavailable features are gated by dialect probes.

Checklist

  • My code follows the project's code style guidelines.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have made corresponding changes to the documentation (Docstrings, README.md, etc.).
  • My changes generate no new warnings.
  • I have added a Changelog fragment (changelog.d/<issue_number>.<type>.md). — to be added after the PR number is assigned.
  • I have verified that my changes do not introduce SQL injection vulnerabilities.
  • I have checked for potential performance regressions.

Additional Notes

Part of the cross-repository feature/activerecord-ddl merge series: testsuite, core and mysql were merged/opened first; this backend PR follows, with the remaining backends to follow. No local branch merges are performed — all merges happen on GitHub after CI passes.

- basic/core, query/collation and connection now own their databases
  (session database_config/database) and build their tables per test from
  dialect-only definition classes; no raw SQL remains in those directories
- the connection pool tables moved into pool_definitions.py (SERIAL preserved)
- the neutral-adapter work and the benchmark relation fixture are included
int4multirange does not exist on servers older than 14, so the ranges fixture
could not create its table. The class now skips with the server version named;
no type substitution is made.
int4multirange needs PostgreSQL 14 and xid8 needs 13, so the wrapped-scalars
and multirange tables cannot be created on older servers. Each table now
carries its minimum version and the class is skipped with the server version
in the reason instead of failing in fixture setup.
The native fixture decides whether its table can be created by asking the
dialect's own switches (supports_multirange_type, supports_xid8_type) instead
of comparing server versions in the test; the skip reason names the switch
that answered. Corrects the hand-written version table in 43fd18d.
…ion tuples

Six test files compared get_server_version() with a hard-coded floor to decide
whether to run. They now ask the dialect's own support switches:

- macaddr8 -> supports_data_type_postgres_macaddr8 (existed, >= 10)
- pg_lsn -> supports_data_type_postgres_pg_lsn, gated at 9.4 (the probe was an
  always-true stub, which made the lsn test's skip unreachable)
- pg_lsn addition (14) -> new supports_pg_lsn_addition probe
- bit_count (14) -> new supports_bit_count probe
- partitioned-table primary key (11) -> new supports_partitioned_table_primary_key
  probe, plus its protocol declaration
- multirange family in native_ranges -> supports_multirange()

No assertion was weakened; the only behavioural difference is that 'no' now
comes from the dialect instead of from a number the test wrote down.
ubuntu-latest moved to 24.04, where actions/setup-python can no longer find
Python 3.8/3.9, so those jobs failed at the setup step before any test ran.
The core repository already solves this by pinning the old interpreter rows
to ubuntu-22.04 while the rest ride ubuntu-latest; this applies the same
pattern here.
native_json_xml carries a jsonpath column, which PostgreSQL 12 introduced.
The directory already asks the dialect for its type switches, but this table
was missing from the list, so PG 10 and PG 11 failed while creating the
table (jsonpath does not exist) instead of skipping the family.

The probe (supports_data_type_postgres_jsonpath) already existed and answers
>= 12; only the conftest entry was missing.
…ersion

A declaration says "the database assigns this integer". PostgreSQL's spelling
of that is SERIAL -- a pseudo-type whose backing sequence supplies the value --
and it predates the SQL-standard identity clause. Its observable behaviour on
INSERT is the one the request asks about, so it is the single spelling used
from 9 through 19, which also removes the version boundary that used to make
PostgreSQL 9 refuse the request.

What changed:

* `is_auto_increment=True` on a PRIMARY KEY compiles to SMALLSERIAL / SERIAL /
  BIGSERIAL by the column's width, instead of a GENERATED ... AS IDENTITY
  clause; the constraint contributes no clause of its own any more;
* a width SERIAL does not have is refused by name rather than approximated
  (an auto-increment text column has no PostgreSQL spelling);
* `supports_database_assigned_integer_column()` answers True while
  `supports_auto_increment_column()` stays False, which is the point of the
  two probes: the capability exists, the MySQL token does not;
* the SERIAL type probe now documents the three differences from
  AUTO_INCREMENT, including the one that is not operationally equivalent
  (an explicit larger key raises the MySQL counter to max + 1 and leaves a
  sequence untouched).

Explicit `IdentityClause` remains available to a caller that asks for the
SQL-standard form.

Verified: 11 DDL tests (including all three widths, a refused text column cycle
and the explicit SERIAL path) and 18 sequence/identity execution tests pass;
an unbound ColumnDefinition renders SERIAL under an adapted PostgreSQL 9
dialect.
The capability probe was declared in `PostgresAutoIncrementMixin`, whose
protocol (`PostgresAutoIncrementSupport`) restates it method for method, so the
reverse-coverage test rightly flagged a method the protocol does not declare.
Probe-only capabilities follow the `TransactionalDDLSupport` pattern instead:
the protocol declares it and the dialect answers it. The method therefore moves
to `PostgresDialect`, next to the other probe-only answers, and the generic
`DatabaseAssignedColumnSupport` joins the protocol list the conformance test
classifies.

Verified: 575 tests across the dialect conformance and auto-increment DDL files
pass.
One runner for every row was wrong in both directions: ubuntu-latest no longer
carries Python 3.8/3.9, and the newest interpreters belong on the newest image,
not on the same one as the middle band. The matrix now states the mapping per
row, and runs-on reads it:

* 3.8 / 3.9 -> ubuntu-22.04 (the only image that still has them)
* 3.10 - 3.13 -> ubuntu-24.04
* 3.14 / 3.15, free-threaded included -> ubuntu-26.04
The test branched on `supports_identity_column()` and expected `NOT_RENDERED`
below PostgreSQL 10. That was true while the flag routed through the identity
clause; it now renders a SERIAL type, which exists on every version, so the
server accepts the declaration regardless of the identity probe.

Verified against PostgreSQL 18 locally; the PostgreSQL 9 row is what this
changes, and its job is the one that failed.
`native_network` carries a `macaddr8` column, which PostgreSQL 10 introduced.
The directory already asks the dialect for its type switches, but this table was
missing from the list, so PostgreSQL 9 failed while creating the table
(`type "macaddr8" does not exist`) instead of skipping the family. The probe
(`supports_data_type_postgres_macaddr8`) already answered >= 10; only the
conftest entry was missing, the same way `jsonpath` was.

Verified locally: the native network file, 6 passed on PostgreSQL 18.
The shared suite keeps the composite-key contract in its own directory now;
the bridge follows the module.  No test content changes.
``testsuite.fixture_types`` (and, for this backend, ``database_name``) moved
out of the ``testsuite.core`` package; the test helpers import them from their
new location.  No test behaviour changes.
Core's FieldAdapterMixin now calls adapter.from_database(value, target,
original_type=<field annotation>) so an adapter can tell '' from NULL for
fields that admit None.  The public contract carries **kwargs for exactly
this, and the adapters that inherit BaseSQLTypeAdapter already tolerate it;
the standalone postgres adapters declared the narrow signature and raised
TypeError the first time a model field was read back.  Every standalone
from_database now takes **kwargs, matching the MySQL adapters.
Six adapters existed but were never registered: XML, jsonpath, bit string, PostGIS, pgvector and hstore. Each keys on its own wrapper type (PostgresXML, PostgresJsonPath, PostgresBitString, PostgresGeometry, PostgresVector, PostgresHstore), so registering them cannot shadow a core Python type -- the note claiming a str->str conflict described an older shape of these adapters and is gone.

The hstore adapter also accepts a plain dict; that pair is deliberately not registered, because (dict, str) would take every dict in the backend away from the JSON adapter. Coverage of a backend's own types does not displace the core ones.
…ltiranges

PostgresNetworkAddressAdapter existed twice; the live one is in network_address.py (the package exports it), so base.py's copy was unreachable and its batch methods had never run. PostgresJSONBAdapter existed twice as well: base.py's carries the batch overrides and is the one the package exports, while json.py's was a shorter copy that only the tests imported. json.py now re-exports base.py's class, so one implementation answers to the name.

PostgresMultirangeAdapter imported Multirange from psycopg.types.range, where psycopg 3.2+ no longer keeps it; the ImportError was swallowed and a native multirange value could never be read. The import now points at psycopg.types.multirange.

Tests cover the two batch paths, the psycopg Range/Multirange read paths, the tuple/bounds refusals and the enum option guards. The adapter package's coverage rises from 87% to 91%; base.py 75% -> 100%, range.py 78% -> 98%.
… paths

Both directions in bulk, the absent values, the MAC bytes input, and the named refusals for an unsupported type. network_address.py rises from 81% to 97%; what is left is the two ImportError branches that no environment reaches.
Per family: the pass-through of an already-neutral value, the named refusal of a wrong shape, the option guards (declared bit length, literal spelling, element-type hints), and the range literal parser's own error contract (brackets, quotes, truncated and empty literals, the normalised infinite bound).

neutral.py rises from 83% to 95% and the adapter package to 96%. The two branches left -- a dangling escape and an unescaped quote inside a quoted bound -- are unreachable through the literal path, because the splitter rejects both shapes before the unquoting step runs.
…itute hook

suggested_data_types now carries PostgreSQL's own answer for every framework-modelled Python type: TEXT for text (one unbounded tier), JSONB for a document, native arrays for the sequence entries, TIMESTAMP(3) by default, and the server's GEOMETRY/VARBIT/MACADDR words for three complex families. Vector, Range and Multirange name the text carrier their neutral adapters already write, because a bare annotation does not say the dimension or the element type; the field that wants the native type declares it with UseSqlType.

The old substitution table keeps its meaning under the name the replan gives it, substitute_data_types.
…table

Thirty-seven value classes the framework does not model now have a declaration: the server's geometric family, its text-search and jsonpath types, the object identifiers (OID, the reg* aliases, XID/XID8/CID/TID), money, hstore, XML, LSN, the PostGIS and pgvector wrappers, and the MAC variants. Entries whose native spelling needs a parameter the annotation does not carry (a vector's dimension, a range's subtype) name the text their adapters write.

A bare field annotated with one of these used to fail as 'declares no SQL type' even though the adapter and the type class both existed; this is the table the derivation falls back to for them.
The table behind a bare field's declaration now has a shared contract: every framework-modelled type is answered with a renderable declaration and nothing answers None, the backend's own value classes are disjoint from that list and render too, and each call returns a fresh dict. It runs against this backend's dialect through the usual thin bridge.
The new adapter-existence contract caught two entries that had no adapter on a default backend: PostgresRange and PostgresMultirange are adapted only in the CUSTOM/BOTH range modes, so suggesting a declaration for them built a column nothing could write. The wrappers are dropped from the table and the reason is written down where the entry used to be.

The contract itself is added beside the adapter inventory: every extra value class must have an adapter registered, because a suggestion the adapter cannot carry is worse than a refusal.
The six families core now models -- geometry, vector, bit string, range,
multirange, MAC address -- get a class in this backend's table instead of a
hole. Their classes promise only the column surface (alias, null tests,
casting, collation), which every backend can execute on whatever storage it
picks, so the answer costs no false promise.

A duration now answers IntervalColumn rather than NumericColumn: a span is not
a number of its own family, and the class promises no arithmetic.

The per-entry answers and their reasons were updated together with the table;
the protocol conformance file's "eighteen" wording now says twenty-four.
…xtras table

Twelve PostgreSQL-named column classes (geometry, vector, range, multirange,
bit string, text search, jsonpath, hstore, xml, macaddr, money, identifiers,
lsn) give this server's values a home for its own operations and a name a
field can pass to UseColumnType.

POSTGRES_EXTRA_COLUMN_TYPES keys 35 of them by the value class they answer
for, mirroring the extra data-type table. PostgresRange/PostgresMultirange
stay out for the reason recorded there: their adapters only register in the
CUSTOM/BOTH range modes, so a default backend cannot write the value. The
classes exist and can be declared explicitly once the adapter is in place.

The extras table is disjoint from the twenty-four common entries, every
answer builds and renders, and a field annotated with Point resolves to the
PostgreSQL geometry class without a declaration.
The shared file now covers the extras table as well -- class answers,
disjoint keys, constructibility and a fresh copy -- so this backend
reports a malformed or overlapping extras entry as its own failure
rather than leaving it to a later query.
…ators

distance_to (<->) is offered on every geometry value; contains (@>), contained_by
(<@) and overlaps (&&) live on PostgresAreaGeometryColumn, because a point has no
@> -- a live probe against 18.6 refused it. The extras table now keys box,
polygon and circle to the narrower class so a Point field cannot offer an
operator the server would refuse.

Render assertions plus a live round-trip on postgres-18 (point distance, and
contains/contained_by/overlaps on a polygon) both pass.
bit_and/bit_or/bit_xor (#, not ^), bit_not, BIT_LENGTH (not the generic LENGTH),
BIT_COUNT and the two shifts are thin façades over the existing bit_string
functions. Render assertions plus a live round-trip on postgres-18.6 pass.
contains/contained_by/overlaps and is_empty/lower/upper are thin façades over
functions/range.py, each gated on supports_range_operators() or
supports_range_functions(). A 9.1 dialect now fails loudly by capability name
instead of rendering an operator the server would refuse.

Render assertions and gates pass; a live int4range round-trip on postgres-18.6
returns the expected answers for all six operations.
Register CRUD/query/transaction/mixin benchmark implementations with the
shared testsuite registry via tests/benchmark/providers.py and conftest.py.
Scenarios derive from support.postgres with a fresh database per run; DDL is
derived from the model via create_table_statement (no hand-built SQL).
Enable -p tests.benchmark.providers in the benchmark job's testsuite pytest
command so the generic contracts register before collection.
@sonarqubecloud

Copy link
Copy Markdown

@vistart vistart self-assigned this Nov 20, 2026
@vistart vistart added the enhancement New feature or request label Nov 20, 2026
@codecov

codecov Bot commented Nov 20, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.69154% with 37 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.35%. Comparing base (03c1bcd) to head (e132c2b).

Files with missing lines Patch % Lines
...verecord/backend/impl/postgres/adapters/neutral.py 92.58% 18 Missing and 11 partials ⚠️
...verecord/backend/impl/postgres/mixins/ddl_table.py 50.00% 5 Missing ⚠️
...cial/activerecord/backend/impl/postgres/dialect.py 75.00% 1 Missing ⚠️
...d/backend/impl/postgres/protocols/ddl/partition.py 50.00% 1 Missing ⚠️
...backend/impl/postgres/protocols/types/data_type.py 50.00% 1 Missing ⚠️
Additional details and impacted files
@@                   Coverage Diff                    @@
##           release/v1.0.0.dev17      #72      +/-   ##
========================================================
+ Coverage                 78.58%   83.35%   +4.77%     
========================================================
  Files                       360      364       +4     
  Lines                     19399    19999     +600     
  Branches                   3183     3288     +105     
========================================================
+ Hits                      15244    16670    +1426     
+ Misses                     3017     2333     -684     
+ Partials                   1138      996     -142     
Flag Coverage Δ
postgres-18 83.35% <94.69%> (+4.77%) ⬆️
python-3.14 83.35% <94.69%> (+4.77%) ⬆️
unittests 83.35% <94.69%> (+4.77%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@vistart
vistart merged commit 2d0c60e into release/v1.0.0.dev17 Nov 20, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant