Repository navigation
feat(postgres): declaration-driven DDL and shared testsuite contracts - #72
Merged
Merged
Conversation
- 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.
|
Codecov Report❌ Patch coverage is 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Description
PostgreSQL-backend side of the coordinated
feature/activerecord-ddlwork. It brings the backend onto the rebuilt shared testsuite and core DDL/migration contracts, and adds backend-specific migration documentation.What changed:
SERIALused 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; portablemigrateCLI contracts bridged.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 thesubstitute_data_typeshook rename, the typed-column contract in CI, neutral and network-address adapters (including macaddr8 and psycopg multiranges), and jsonpath registration.postgres:19image adopted, and dependencies pinned to the merged releases: testsuiterelease/v1.0.0.dev17and corerelease/v1.0.0.dev30.Dependencies: core
>=1.0.0.dev30,<2.0.0and the shared testsuiterelease/v1.0.0.dev17(both merged in the coordinated series).Adds # (issue): N/A
Type of change
feat: A new featuredocs: 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
fixcommits as part of the feature.)Breaking Change
feat(postgres)!: directory-owned fixtures and expression DDL:basic/core,query/collationandconnectiontest 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 intopool_definitions.py(keepingSERIAL). This changes the backend's internal test-fixture layout, with no public API impact.Applicable
rhosocial-activerecordVersion Range:>=1.0.0.dev30,<2.0.0Related Repositories/Packages
Part of the coordinated
feature/activerecord-ddlseries; every repo's work is based on its own latestrelease/*branch:rhosocial/python-activerecord-testsuite— rebuilt suite merged as PR feat(postgres): add schema namespace support for PostgreSQL backend #33 onrelease/v1.0.0.dev17.rhosocial/python-activerecord(core) — DDL/migration APIs merged as PR #141 onrelease/v1.0.0.dev30.Testing
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
README.md, etc.).changelog.d/<issue_number>.<type>.md). — to be added after the PR number is assigned.Additional Notes
Part of the cross-repository
feature/activerecord-ddlmerge 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.