Skip to content

feat(sqlserver): declaration-driven DDL and shared testsuite contracts - #18

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

vistart merged 69 commits into
release/v1.0.0.dev3from
feature/activerecord-ddl

Conversation

@vistart

@vistart vistart commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Description

SQL Server-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, expression-built DDL, primary-key declarations restored/identity preserved on backend-local and native-type models (including long-content models), stale render pins and id-column expressions corrected after the auto-increment refactor; portable migrate CLI contracts bridged.
  • Dialect / types: scalar EXISTS rendered as T-SQL CASE WHEN, paging ORDER BY synthesised as an expression rather than by replacing SQL; bare Decimal/datetime get lossless suggested columns; the suggested data-type table with the substitute_data_types hook rename and the six complex families (durations as intervals); native-type tests, neutral-type bridges, adapter read-hook keywords, database-assigned column protocol, and removal of the superseded spatial adapter.
  • Tests: the SQL Server test tree moves to the rebuilt testsuite's directory-owned databases, declaration-driven fixtures and parallel units — DDLSource, query/relation/typed_column, restructured query topics, feature CLI, and shared benchmarks are bridged. Added live and offline CLI (info/query/status) tests, status-introspector coverage and backend-local deep EXPLAIN construction tests; shared real-DB EXPLAIN contracts and driver-unsupported cases are explicitly skipped.
  • 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, 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 and refactor commits as part of the feature.)

Breaking Change

  • Yes
  • No

feat(sqlserver)!: directory-owned fixtures and expression DDL: the connection test directory now owns its database via session database_config, pool fixtures depend on it with xdist grouping, and inline CREATE TABLE strings moved to dialect-only definition classes in pool_definitions.py; query/core gains real L2 fixtures with testsuite definition classes. These are internal test-fixture changes with no public API impact. The superseded spatial adapter is also removed.

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 #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, postgres, mariadb, 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 / SQL Server matrix. Development commits added live and offline CLI tests, status-introspector coverage, backend-local deep EXPLAIN construction tests and the shared contract bridges listed above; unsupported contracts are gated by capability checks.

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, mysql, postgres and mariadb were 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.

- connection: session database_config (test_connection), the four pool fixtures
  depend on it (xdist grouping), inline CREATE TABLE strings moved into
  pool_definitions.py (dialect-only definition classes)
- query/core: real L2 fixtures with the testsuite definition classes
- tests: 10 passed (connection, -n 2 loadgroup verified), 6 passed + 2 skipped
  (query/core, unchanged skips)
…lacing SQL

OFFSET/FETCH without an ORDER BY was repaired by rewriting the rendered SQL
string (str.replace / +=), which the formatting rules forbid and which broke
the statement when the ORDER BY reference was a bind parameter. The preamble
is now an OrderByClause over a scalar subquery, handed to the generic
formatter; the restored method only composes clauses. Also drops the unused
typing import.
…klog)

The previous commit ran 'git add -A' over the worktree and swept in trees
that were untracked before it: the native-type directory, its raw schema and
models, plus a few adapter-phase test files. They are not part of this
migration's scope, they are not on the directory-owned fixtures yet, and they
fail (rowversion, xml, datetimeoffset). Removing them from the index keeps
the working copies where they are; the backlog is recorded in the stage
report instead of being hidden by a red CI.
Core's type rules walk every DataType subclass and require the tuple a class
declares to name arguments its __init__ actually takes, and the shared
tuples to be the shared objects rather than copies. Three declarations broke
both rules; the defect only shows when this package is imported, which is why
core's CI (core + testsuite only) never saw it:

* SQLServerNVarCharMaxType inherited LENGTH_PARAMETERS while its __init__ takes
  no length -- and MAX is not a width, so it declares no parameters;
* SQLServerTinyIntType inherited UNSIGNED_PARAMETERS while its signedness is
  fixed (no T-SQL spelling of TINYINT is signed), so there is no knob to name;
* SQLServerVarBinaryType wrote a literal ("length",) instead of the shared
  LENGTH_PARAMETERS, which makes its declarations unequal to their siblings.
Core added the probe-only `DatabaseAssignedColumnSupport` protocol, and the
dialect conformance test requires every generic protocol to be classified as
implemented or deliberately not implemented. The backend answers on its dialect
class, never in a mixin: the mixins here are paired with their own protocols,
and a method a paired protocol does not declare fails the reverse-coverage
check.

The answer is the capability, not the mechanism: the engine supplies an
integer column's value on INSERT when the caller omits it, however that dialect
spells it. The docstring names the mechanism so the answer can be checked
against the grammar.
The previous commit staged the directory rather than the two files it meant to
change, and an untracked `test_get_type_adapters.py` from the adapter work came
along. That file is not part of this change and is not on the directory-owned
fixtures yet, so it is removed from the index and left in the working tree; the
backlog lives in the migration plan, not inside a commit wearing a different
label.
…ument

Core's type rules require the tuple a class declares to name arguments its
constructor actually takes; `SQLServerTinyIntType` fixed `unsigned=True` without
exposing the keyword, so its inherited `("unsigned",)` named nothing.

The keyword is now accepted and the value stays pinned: `unsigned=False` is
refused by name, because no T-SQL spelling of TINYINT is signed. `identity()`
therefore still records the signedness, the comparison against a signed
`TinyIntType` still differs, and the declaration surface stays honest.

The repository's own test pinned `TypeError` for the flip (the keyword did not
exist); it now pins `ValueError` with the reason, which is the accurate refusal
for a value the backend cannot render.
…d hook's keywords

New test surface: the neutral-type contract bridges under ``feature/adapters``
(and their async copies), the adapter inventory test, the JSON codec hooks,
and the native families -- BIT, JSON kept as text, XML, ROWVERSION/TIMESTAMP,
MONEY, HIERARCHYID, DATETIMEOFFSET and UNIQUEIDENTIFIER.  Each native module
owns the tables it needs, so a failure names the family.

Three test-side facts the suite recorded wrongly, fixed here:

* the DDL loader stripped comment lines *after* splitting on ``;``, so the
  ROWVERSION note ("only one such column per table") cut a statement in half
  and left the tail to be parsed as SQL;
* the S3 "foreign value" literals were not ``N``-prefixed, so a non-ASCII
  document was flattened by the server's VARCHAR collation before the column
  ever saw it;
* a double-encoded JSON document cannot satisfy a ``dict`` field, and the test
  now asserts that the model refuses it -- detection, not silent acceptance.

``SQLServer*Adapter.from_database`` accepts ``**kwargs``, the base class's
signature: that is how the read hook receives the field's declared annotation,
which lets a backend tell a field that refuses ``None`` from an ``Optional``
one when the driver stores one database value for two Python types.

Verified locally against SQL Server 2022: native 52 passed / 2 xfailed,
neutral bridges 20 passed, inventory and JSON hooks 71 passed.
CI on every SQL Server image failed a model's first ``save()`` with
"Connection is busy with results for another command": the table had just
been created on the same connection, and pyodbc keeps the server's DDL
messages as pending results, so the save's next statement was refused.

The table is now created and dropped on a dedicated connection, and the drop
only runs when the table exists -- ``DROP TABLE IF EXISTS`` on a missing
table answers with a message of its own.  The test's connection stays clean
for the model and the literal-SQL probes.
…rker

Only directories whose path contained both ``backend`` and ``execute`` were
pinned to a single xdist worker, so the native adapter directory -- and every
other ``feature/backend`` directory that creates its own tables -- could run
from several workers at once.  Each worker resets the directory's database,
which starts with ``ALTER DATABASE ... SINGLE_USER WITH ROLLBACK IMMEDIATE``
and ``DROP DATABASE``: one worker evicts the other's session while it is
running.

The pin now follows the rule the docstring states rather than an ``execute``
path fragment: every ``feature/backend`` directory except ``construct``
(which opens no database) runs in one worker.
Every failing native test was the *first* statement of a freshly connected
backend: "Connection is busy with results for another command".  The backend
closes its connection after each test, and pyodbc's connection pool -- on by
default -- hands that physical connection to the next test together with
whatever result sets are still pending on it.  SQL Server answers some DDL
with informational messages, so the pooled connection carries them into the
next test's first statement.

``pyodbc.pooling`` is now off in the test support, so each backend gets a
clean physical connection.  It is a test-process switch, not a server or
production-backend change.
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.
SQLServerSpatialAdapter declared its pairs against string driver names (str: ['geography', 'geometry']), which the type-keyed registry can never look up, so it was unreachable. SQLServerGeometryAdapter supersedes it and already covers both column kinds: it takes geography=True and defaults the SRID to 4326 for that case. The class and its seven tests go; the surviving suite keeps failing exactly the same 22 pre-existing cases as before the deletion.
…titute hook

suggested_data_types answers every framework-modelled Python type in SQL Server's own words: BIT for a boolean, INT/FLOAT(53)/DECIMAL for the numbers, NVARCHAR(255) for text and VARBINARY(MAX) for bytes, DATE/TIME/DATETIME2(3) for the temporal family, UNIQUEIDENTIFIER for a UUID, NVARCHAR(MAX) for a document and the four sequence entries. The server has no interval and no array type, so timedelta is carried as text and the containers share the JSON text column. The six complex families name the text carriers their neutral adapters already write, because no DataType class of this backend names the CLR geometry types yet. No key answers None.

The substitution table keeps its meaning under substitute_data_types. The failures left in this repo are the column-class half (the six family entries core now models) and the expression roundtrip matrix, neither of which this change touches.
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.
…an interval

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.
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.
…acts

The contract lives in this repository, not in the shared testsuite: backend
functionality is tested by its own backend. Core concepts are discovered
rather than listed, so a future concept cannot slip past a stale list.

For each declared version the tests assert that every concept is either
rendered or substituted, that substitute keys are disjoint from rendered
keys, that values are DataType subclasses, and that each substitute actually
renders (parameter-carrying substitutes use a documented minimum instance).
D10: every format_data_type_<name> has a supports_data_type_<name> probe and
vice versa, supports_data_types() names only formatter-bearing concepts, and a
formatter missing from the supported map must be explained by an explicit
False probe (a version gate), never by silence.

The contract lives in this repository; backend functionality is not tested in
the shared testsuite.
A bare DECIMAL is DECIMAL(18,0) on SQL Server and DATETIME2(3) keeps only
milliseconds, so bare Decimal/datetime fields rounded 10.99 to 11 and lost
the microsecond of a written datetime. Recommend DECIMAL(18,4) and
DATETIME2(6) so those fields round-trip through the shared basic tests.
Bridge types, types_complex and types_long_content so the bare/annotated contracts run against this backend.
Bridge the shared X1-X6 field-expression contracts so they run against this backend.
The shared testsuite deleted test_fields{,_async} along with the TypeCase/TypeTestModel fixtures.
Cancel all non-basic testsuite feature test bridges; backend-owned tests and benchmark imports stay.
根 conftest 声明 parallel=False 并删除 legacy xdist_group 分组钩子;execute/ 各目录及 adapters/native 声明 parallel=True 接管按目录串行;construct 纯渲染目录不声明,继承无限制并行。
Point pool_definitions at feature.query.fixtures.definitions; give backend-specific test_expressions.py unique basenames so pytest does not collide with the new basic/expressions group.
Core now raises UnsupportedDataTypeError (a TypeError subclass) for a concept the dialect neither renders nor substitutes; the roundtrip pins expected the exact TypeError.
…erver

Register crud/query/transaction/mixin benchmark implementations backed by
SQL Server scenarios, deriving DDL from the model via the expression system.
Add a single-process benchmark job with a SQL Server service, ODBC driver,
scenario config and a GITHUB_STEP_SUMMARY conclusion block.
@vistart vistart self-assigned this Nov 20, 2026
@vistart vistart added the enhancement New feature or request label Nov 20, 2026
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
D Security Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

@codecov

codecov Bot commented Nov 20, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.44186% with 27 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.16%. Comparing base (b1be045) to head (7c76864).
⚠️ Report is 2 commits behind head on release/v1.0.0.dev3.

Files with missing lines Patch % Lines
...al/activerecord/backend/impl/sqlserver/adapters.py 82.63% 19 Missing and 6 partials ⚠️
...ial/activerecord/backend/impl/sqlserver/dialect.py 91.66% 1 Missing ⚠️
...ord/backend/impl/sqlserver/mixins/backend_mixin.py 95.45% 1 Missing ⚠️
Additional details and impacted files
@@                   Coverage Diff                   @@
##           release/v1.0.0.dev3      #18      +/-   ##
=======================================================
+ Coverage                78.97%   85.16%   +6.18%     
=======================================================
  Files                      148      151       +3     
  Lines                     9818    10118     +300     
  Branches                  1536     1580      +44     
=======================================================
+ Hits                      7754     8617     +863     
+ Misses                    1504     1058     -446     
+ Partials                   560      443     -117     
Flag Coverage Δ
python-3.14 85.16% <87.44%> (+6.18%) ⬆️
sqlserver-2025 85.16% <87.44%> (+6.18%) ⬆️
unittests 85.16% <87.44%> (+6.18%) ⬆️

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 1a18415 into release/v1.0.0.dev3 Nov 20, 2026
13 of 14 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