diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d2b2af66..0542675e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,9 +18,144 @@ permissions: contents: read jobs: + benchmark-sqlserver: + name: Run benchmarks with Python 3.14 and SQL Server 2025 + runs-on: ubuntu-24.04 + permissions: + contents: read + + services: + sqlserver: + image: mcr.microsoft.com/mssql/server:2025-latest + env: + ACCEPT_EULA: Y + MSSQL_SA_PASSWORD: Password123! + ports: + - 1443:1433 + options: >- + --name sqlserver + --health-cmd "/opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P 'Password123!' -Q 'SELECT 1' -N -C || exit 1" + --health-interval 10s + --health-timeout 5s + --health-retries 15 + + steps: + - name: Check out the repository + uses: actions/checkout@v6 + + - name: Set up Python 3.14 + uses: actions/setup-python@v6 + with: + python-version: "3.14" + + - name: Install ODBC Driver 18 for SQL Server + run: | + curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - + curl https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/prod.list | sudo tee /etc/apt/sources.list.d/mssql-release.list + sudo apt-get update + sudo ACCEPT_EULA=Y apt-get install -y msodbcsql18 unixodbc-dev + + - name: Install activerecord and testsuite from PyPI + run: | + pip install "rhosocial-activerecord @ git+https://github.com/rhosocial/python-activerecord.git@release/v1.0.0.dev30" # NOSONAR + pip install "rhosocial-activerecord-testsuite @ git+https://github.com/rhosocial/python-activerecord-testsuite.git@release/v1.0.0.dev17" # NOSONAR + + - name: Install dependencies + run: | + pip install -r requirements.txt + pip install -r requirements-dev.txt + + - name: Create test database + run: | + python -c " + import pyodbc + + connection_string = ( + 'DRIVER={ODBC Driver 18 for SQL Server};' + 'SERVER=localhost,1443;' + 'DATABASE=master;' + 'UID=sa;' + 'PWD=Password123!;' + 'TrustServerCertificate=yes;' + 'Encrypt=no;' + ) + + conn = pyodbc.connect(connection_string, autocommit=True) + cursor = conn.cursor() + cursor.execute('CREATE DATABASE test_db') + print('Successfully created test_db') + cursor.close() + conn.close() + " + + - name: Create SQL Server scenario config + run: | + cat > sqlserver_scenarios.yaml << EOF + scenarios: + sqlserver_2025: + host: localhost + port: 1443 + database: test_db + username: sa + password: Password123! + driver: "ODBC Driver 18 for SQL Server" + encrypt: false + trust_server_certificate: true + autocommit: true + EOF + echo "SQLSERVER_SCENARIOS_CONFIG_PATH=$(pwd)/sqlserver_scenarios.yaml" >> $GITHUB_ENV + + - name: Run benchmark suite + run: | + set -o pipefail + export PYTHONPATH=src:tests + TESTSUITE_DIR=$(python - <<'PY' + import pathlib + import rhosocial.activerecord.testsuite as testsuite + + print(pathlib.Path(testsuite.__file__).parent) + PY + ) + python -m pytest \ + -p tests.benchmark.providers \ + --rootdir=. \ + --confcutdir=. \ + "$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" \ + -m benchmark \ + --benchmark-size=small \ + --benchmark-sort=mean \ + --tb=short | tee -a benchmark-output.txt + + - name: Write benchmark conclusion + if: always() + run: | + { + echo "## Python 3.14 / SQL Server 2025 Benchmark Conclusion" + echo + echo "- Python: 3.14" + echo "- SQL Server: 2025" + echo "- Scope: shared testsuite benchmarks (crud/query/transaction/mixin) via registered SQL Server providers" + echo "- Size: small" + echo "- Result: benchmark job fails only when benchmark execution or correctness checks fail." + echo + echo '```text' + grep -A 120 "benchmark:" benchmark-output.txt || cat benchmark-output.txt + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + test-py39-sqlserver2022: name: Run tests with Python 3.9 and SQL Server 2022 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 services: sqlserver: image: mcr.microsoft.com/mssql/server:2022-latest @@ -106,11 +241,11 @@ jobs: run: | export PYTHONPATH=src:tests python tests/enable_read_committed_snapshot.py || true - python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x + python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x --ignore=tests/benchmark --ignore=tests/rhosocial/activerecord_sqlserver_test/feature/connection test-py39-sqlserver2017: name: Run tests with Python 3.9 and SQL Server 2017 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 services: sqlserver: image: mcr.microsoft.com/mssql/server:2017-latest @@ -196,11 +331,11 @@ jobs: run: | export PYTHONPATH=src:tests python tests/enable_read_committed_snapshot.py || true - python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x + python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x --ignore=tests/benchmark --ignore=tests/rhosocial/activerecord_sqlserver_test/feature/connection test-py310-sqlserver2019: name: Run tests with Python 3.10 and SQL Server 2019 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 services: sqlserver: image: mcr.microsoft.com/mssql/server:2019-latest @@ -286,11 +421,11 @@ jobs: run: | export PYTHONPATH=src:tests python tests/enable_read_committed_snapshot.py || true - python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x + python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x --ignore=tests/benchmark --ignore=tests/rhosocial/activerecord_sqlserver_test/feature/connection test-py311-sqlserver2019: name: Run tests with Python 3.11 and SQL Server 2019 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 services: sqlserver: image: mcr.microsoft.com/mssql/server:2019-latest @@ -376,11 +511,11 @@ jobs: run: | export PYTHONPATH=src:tests python tests/enable_read_committed_snapshot.py || true - python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x + python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x --ignore=tests/benchmark --ignore=tests/rhosocial/activerecord_sqlserver_test/feature/connection test-py312-sqlserver2025: name: Run tests with Python 3.12 and SQL Server 2025 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 services: sqlserver: image: mcr.microsoft.com/mssql/server:2025-latest @@ -466,11 +601,11 @@ jobs: run: | export PYTHONPATH=src:tests python tests/enable_read_committed_snapshot.py || true - python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x + python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x --ignore=tests/benchmark --ignore=tests/rhosocial/activerecord_sqlserver_test/feature/connection test-py313-sqlserver2022: name: Run tests with Python 3.13 and SQL Server 2022 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 services: sqlserver: image: mcr.microsoft.com/mssql/server:2022-latest @@ -556,11 +691,11 @@ jobs: run: | export PYTHONPATH=src:tests python tests/enable_read_committed_snapshot.py || true - python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x + python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x --ignore=tests/benchmark --ignore=tests/rhosocial/activerecord_sqlserver_test/feature/connection test-py313t-sqlserver2019: name: Run tests with Python 3.13t (free-threaded) and SQL Server 2019 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 continue-on-error: true services: sqlserver: @@ -647,11 +782,11 @@ jobs: run: | export PYTHONPATH=src:tests python tests/enable_read_committed_snapshot.py || true - python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x + python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x --ignore=tests/benchmark --ignore=tests/rhosocial/activerecord_sqlserver_test/feature/connection test-py314-sqlserver2025: name: Run tests with Python 3.14 and SQL Server 2025 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 services: sqlserver: image: mcr.microsoft.com/mssql/server:2025-latest @@ -737,7 +872,7 @@ jobs: run: | export PYTHONPATH=src:tests python tests/enable_read_committed_snapshot.py || true - python -m pytest tests/ --tb=short -n 8 --dist=loadgroup --cov=src/rhosocial --cov-branch --cov-report=xml + python -m pytest tests/ --tb=short -n 8 --dist=loadgroup --cov=rhosocial.activerecord.backend.impl.sqlserver --cov-branch --cov-report=xml --ignore=tests/benchmark --ignore=tests/rhosocial/activerecord_sqlserver_test/feature/connection - name: Upload coverage to Codecov uses: codecov/codecov-action@v5 @@ -750,7 +885,7 @@ jobs: test-py314t-sqlserver2022: name: Run tests with Python 3.14t (free-threaded) and SQL Server 2022 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 services: sqlserver: image: mcr.microsoft.com/mssql/server:2022-latest @@ -836,4 +971,4 @@ jobs: run: | export PYTHONPATH=src:tests python tests/enable_read_committed_snapshot.py || true - python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x + python -m pytest tests/ -n 8 --dist=loadgroup --tb=short -x --ignore=tests/benchmark --ignore=tests/rhosocial/activerecord_sqlserver_test/feature/connection diff --git a/README.md b/README.md index c7d96a65..29f72d23 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,11 @@ + # rhosocial-activerecord-sqlserver ($\rho_{\mathbf{AR}\text{-sqlserver}}$) [![PyPI version](https://badge.fury.io/py/rhosocial-activerecord-sqlserver.svg)](https://badge.fury.io/py/rhosocial-activerecord-sqlserver) [![Python](https://img.shields.io/pypi/pyversions/rhosocial-activerecord-sqlserver.svg)](https://pypi.org/project/rhosocial-activerecord-sqlserver/) [![Tests](https://github.com/rhosocial/python-activerecord-sqlserver/actions/workflows/test.yml/badge.svg)](https://github.com/rhosocial/python-activerecord-sqlserver/actions) [![Coverage Status](https://codecov.io/gh/rhosocial/python-activerecord-sqlserver/branch/main/graph/badge.svg)](https://app.codecov.io/gh/rhosocial/python-activerecord-sqlserver/tree/main) +[![Supported SQL Server versions](https://img.shields.io/badge/SQLServer-2017%7C2019%7C2022%7C2025-blue?logo=microsoftsqlserver)](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/README.md) [![Apache 2.0 License](https://img.shields.io/github/license/rhosocial/python-activerecord-sqlserver.svg)](https://github.com/rhosocial/python-activerecord-sqlserver/blob/main/LICENSE)
@@ -12,60 +14,57 @@

OUTPUT clause · Temporal tables · SQL Graph · Sync & async

-This is a backend implementation for [rhosocial-activerecord](https://github.com/rhosocial/python-activerecord). -It cannot be used standalone. +This is the Microsoft SQL Server backend for [rhosocial-activerecord](https://github.com/rhosocial/python-activerecord). It cannot be used standalone. -## Requirements +**Keywords:** sql-server, mssql, odbc, pyodbc, orm, activerecord, pydantic, python, async, type-safe - +## Why This Project? -_b69f713_ +SQL Server is a mainstay of enterprise data platforms, yet working with it usually means hand-writing T-SQL or adopting an ORM that hides the database. This backend brings the same small, intuitive ActiveRecord API — a class is a table, an instance is a row — to SQL Server, with full type safety and native sync–async parity. -- **Python**: `>=3.9` -- **Core**: `rhosocial-activerecord>=1.0.0.dev0,<2.0.0` -- **Driver**: `pyodbc>=5.3.0` (with an installed ODBC Driver 17+) -- **CI-tested server versions**: 2017, 2019, 2022, 2025 -- **Published**: PyPI `1.0.0.dev2` +It speaks SQL Server on its own terms. DML that returns affected rows uses the `OUTPUT` clause, temporal queries use `FOR SYSTEM_TIME`, and capabilities such as SQL Graph, memory-optimized tables and columnstore appear only on the server versions that support them. You keep one consistent API and still see the exact T-SQL through `.to_sql()` before anything runs. -`pyodbc` 5.3.0 ships no cp315 wheel — the source tarball only, with no -`Python :: 3.15` classifier declaring support — so a 3.15 leg would fail at -install while pip compiles the driver. Adding one awaits a `pyodbc` release, -not anything in this repository. +## Quick Start -## Installation +### Installation ```bash pip install rhosocial-activerecord-sqlserver ``` -## Quick Start +Requires Python 3.9+, `pyodbc>=5.3.0`, an installed ODBC Driver 17+ and a reachable SQL Server instance. + +### End-to-End Example ```python -from typing import ClassVar, Optional +"""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.impl.sqlserver.backend import SQLServerBackend from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig -from rhosocial.activerecord.backend.expression import CreateTableStatement -from rhosocial.activerecord.backend.expression.statements import ( - ColumnConstraint, - ColumnDefinition, - ColumnPrimaryKeyConstraint, -) -from rhosocial.activerecord.backend.expression.types import IntegerType, VarCharType +from rhosocial.activerecord.backend.expression.types import VarCharType +from rhosocial.activerecord.field import DefaultTimestampMixin, IntegerPKMixin from rhosocial.activerecord.model import ActiveRecord -class User(ActiveRecord): - __table_name__ = "users" +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[int] = None - name: str - email: str + c: ClassVar[FieldProxy] = FieldProxy() # enables User.c. expressions - c: ClassVar[FieldProxy] = FieldProxy() + @classmethod + def table_name(cls) -> str: + return "users" +# Configure the backend and create the table from the model declaration User.configure( SQLServerConnectionConfig( host="localhost", @@ -73,200 +72,66 @@ User.configure( database="myapp", username="sa", password="YourStrong!Passw0rd", - driver="{ODBC Driver 17 for SQL Server}", + driver="ODBC Driver 17 for SQL Server", ), SQLServerBackend, ) +User.create_table() -dialect = User.__backend__.dialect -User.__backend__.execute(*CreateTableStatement( - dialect, - "users", - columns=[ - ColumnDefinition( - dialect, "id", IntegerType(dialect), - constraints=[ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - )], - ), - ColumnDefinition(dialect, "name", VarCharType(dialect, 100)), - ColumnDefinition(dialect, "email", VarCharType(dialect, 255)), - ], -).to_sql()) - -user = User(name="Alice", email="alice@example.com") -user.save() -rows = User.query().where(User.c.email == "alice@example.com").all() -``` - -### Async - -`AsyncSQLServerBackend` exposes the same API. Method names are identical; add -`await`. - -```python -from rhosocial.activerecord.backend.impl.sqlserver.backend import AsyncSQLServerBackend -from rhosocial.activerecord.model import AsyncActiveRecord - +# Create +alice = User(name="Alice", email="alice@example.com", age=30) +alice.save() +print(alice.id) # database-assigned integer primary key -class User(AsyncActiveRecord): - ... +# Query with type-safe expressions +adults = User.query().where(User.c.age >= 18).all() +print([user.name for user in adults]) - -User.configure(config, AsyncSQLServerBackend) -rows = await User.query().where(User.c.email == "alice@example.com").all() +# 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] >= ? (18,) ``` -## SQL Server-Specific Features +> **Async parity:** use `AsyncActiveRecord` with `AsyncSQLServerBackend` — same method names, same patterns, just add `await`. -### `OUTPUT` instead of `RETURNING` +## Project Architecture -SQL Server has no `RETURNING`; the equivalent is the `OUTPUT` clause, which -the backend emits for DML that needs to return the affected row. +Models and field proxies are declared once against the core `ActiveRecord` API; this backend binds them to SQL Server's dialect and the `pyodbc` driver. Query structure and T-SQL generation are decoupled: nothing is rendered until an explicit `.to_sql()` call, so you can preview and verify every statement before it runs. The sync (`SQLServerBackend`) and async (`AsyncSQLServerBackend`) implementations are native and share the same method names. -### Temporal tables +For the full picture, start with the [core library documentation](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/README.md). -Query historical state with `FOR SYSTEM_TIME`. The table must already be -declared as a system-versioned temporal table; the backend does not add the -`PERIOD FOR` clause for you. +**SQL Server highlights.** `OUTPUT` for returning affected rows, `FOR SYSTEM_TIME` for temporal tables, SQL Graph, memory-optimized and columnstore tables, and version-gated features. See [Database introspection](docs/en_US/introspection/README.md) and [Table partitioning](docs/en_US/ddl/partition.md) for the SQL Server-specific details. -```python -User.query().where( - "id = ? FOR SYSTEM_TIME AS OF ?", - (1, "2026-06-30T12:00:00"), -).all() -``` +## Backend Support & Progress -### Memory-optimized and columnstore tables +This package supports SQL Server **2017, 2019, 2022 and 2025**. Capabilities are gated by the detected server version, so a feature appears only where the server supports it (for example SQL Graph from 2017 and `columnstore_order` from 2022). Connectivity uses `pyodbc` with an installed ODBC Driver 17+. -Set through the DDL expression's table options, not a model attribute: - -```python -from rhosocial.activerecord.backend.impl.sqlserver.expression import ( - SQLServerCreateTableOptions, -) - -CreateTableStatement( - dialect, - "sessions", - columns=[...], - table_options=SQLServerCreateTableOptions(dialect, memory_optimized=True), -) -``` +It ships as a separate package from the core `rhosocial-activerecord` library; add it to any project using that library and configure models with `SQLServerBackend`. The core library and its documentation describe ActiveRecord itself. -### Signed seconds between two instants +> **⚠️ Development Stage:** This project is under active development. APIs may change, and some features are not yet production-ready. -`seconds_between(start, end)` answers `end - start` in seconds, keeping the -sign and the fraction. SQL Server has no interval subtraction, so the backend -counts milliseconds with `DATEDIFF_BIG` and divides by `1000.0`: - -```python -from rhosocial.activerecord.backend.expression import ( - Column, - seconds_between, -) - -elapsed = seconds_between(dialect, Column(dialect, "started_at"), - Column(dialect, "ended_at")).as_("seconds") -# DATEDIFF_BIG(MILLISECOND, [started_at], [ended_at]) / 1000.0 AS [seconds] -``` - -`DATEDIFF_BIG` rather than `DATEDIFF` because a millisecond count overflows a -32-bit `int` after about 24 days; the result is exact to a millisecond, which -is the resolution of `DATEDIFF_BIG`, not of `datetime2`. The function arrived -in SQL Server 2016; a server below that floor refuses the expression, and -`supports_functions()["seconds_between"]` reports `False`. An `end` earlier -than `start` subtracts to a negative value with no extra sign handling. - -### Partitioned tables - -SQL Server partitioning is a partition function plus a partition scheme plus a -table built `ON ()` -- not a `PARTITION BY` clause. The DDL -expressions cover `CREATE PARTITION FUNCTION` / `SCHEME`, `SPLIT RANGE`, -`MERGE RANGE`, `SWITCH`, `NEXT USED` and the two drops, and the maintenance -executor provides `ensure`, `list`, `retention_boundaries`, `drop_or_merge`, -`drop_before` and `validate` with sync and async forms. There is no -subpartitioning, and a partition is removed by merging its boundary, never by -dropping it. - -See [Table partitioning](docs/partition.md) for the model, examples and the -maintenance contract. - -## Version Gates - -Gates below are the versions at which this backend's own `supports_*` -switch returns `True`, probed at 10, 11, 12, 13, 14, 15, 16. -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 | -|---|---| -| 11 (2012) | `create_sequence`, `drop_sequence`, `nonclustered_columnstore`, `offset_fetch`, `order_by_in_subquery`, `try_cast`, `try_convert`, `window_frame_clause` | -| 12 (2014) | `clustered_columnstore`, `memory_optimized_table_types`, `memory_optimized_tables` | -| 13 (2016) | `drop_type_if_exists`, `if_exists_table`, `if_exists_view`, `index_if_exists`, `json_table`, `json_type`, `system_versioning`, `temporal_tables` | -| 14 (2017) | `graph_pseudo_columns`, `graph_table_kind`, `sql_graph` | -| 15 (2019) | `edge_constraints`, `for_update_skip_locked`, `graph_path_aggregates`, `readpast`, `shortest_path` | -| 16 (2022) | `columnstore_order` | - -## Known Limitations - -- **No connection pooling.** `pool_size` and `pool_timeout` are accepted by - the config class but not consumed; `connect()` opens one persistent - connection. -- **No native arrays, and no JSON *type*.** JSON is reachable through - functions (`JSON_VALUE`, `JSON_QUERY`) on 2016+, not through a column - type, and `supports_json_type` gates on that. -- **No generic partition verbs.** Table partitioning exists through - partition functions and schemes (`supports_table_partitioning`, - `supports_partition_function`, `supports_partition_scheme`, - `supports_split_partition`, `supports_merge_partition` and - `supports_switch_partition` are `True` on 2008+), but the generic - `add_partition`, `drop_partition`, `attach_partition`, `detach_partition`, - `truncate_partition` and `reorganize_partition` switches stay `False`: - SQL Server spells those operations differently or not at all. - `supports_subpartitioning()` is `False` at every version -- SQL Server has - no subpartitions. A model does not take a `__partition__` attribute; - partition state is managed by the backend helper in - [docs/partition.md](docs/partition.md). -- Also unsupported: `alter_type`, `constraint_enforced`, `create_or_replace_view`, - `deferrable_*`, `fetch_with_ties`, `fk_match`, `returning_alias`, - `returning_wildcard`, `set_type`, `transaction_mode`. - -## Testing - -Tests require a reachable SQL Server instance and must run serially. - -```bash -export PYTHONPATH=src:tests -.venv3.14-ubuntu26.04/bin/pytest tests/ -``` +## Documentation -The shared contract suite lives in -[python-activerecord-testsuite](https://github.com/rhosocial/python-activerecord-testsuite): +### Contributing -```bash -PYTHONPATH=tests .venv3.14-ubuntu26.04/bin/pytest \ - ../python-activerecord-testsuite/src/rhosocial/activerecord/testsuite/feature/ -``` - -## Documentation +We welcome contributions! Please see [CONTRIBUTING.md](https://github.com/rhosocial/python-activerecord/blob/main/CONTRIBUTING.md) for guidelines. -[Database introspection](docs/introspection.md) states what this backend -answers, where each answer comes from, and the version floors that decide -whether it can be asked at all. [Table partitioning](docs/partition.md) -describes SQL Server's function/scheme model, the DDL expressions and the -maintenance helper. +### License -Backend notes live in [.claude/architecture.md](.claude/architecture.md) and -[.claude/testing.md](.claude/testing.md); core library documentation is at -[python-activerecord/docs](https://github.com/rhosocial/python-activerecord/tree/main/docs). +[Apache License 2.0](LICENSE) — Copyright © 2026 [vistart](https://github.com/vistart) -## Contributing +### Documentation -See [CONTRIBUTING.md](https://github.com/rhosocial/python-activerecord/blob/main/CONTRIBUTING.md). +* **[Backend documentation home](docs/en_US/README.md)** — full table of contents for this backend's docs +* **[Core library documentation](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/README.md)** — the full documentation table of contents +* **[Database introspection](docs/en_US/introspection/README.md)** — what this backend answers, where each answer comes from, and the version floors that decide whether it can be asked +* **[Table partitioning](docs/en_US/ddl/partition.md)** — SQL Server's function/scheme model, DDL expressions and the maintenance helper +* **[Runnable examples](docs/examples/README.md)** — connection, DDL and introspection scripts using this backend's classes +* **[Backend architecture notes](.claude/architecture.md)** and **[testing notes](.claude/testing.md)** — backend-specific design and test setup -## License +--- -[Apache License 2.0](LICENSE) — Copyright © 2026 [vistart](https://github.com/vistart) +
+

Built with ❤️ by the rhosocial team

+

GitHub · Documentation · PyPI

+
diff --git a/changelog.d/18.added.md b/changelog.d/18.added.md new file mode 100644 index 00000000..3903cdb0 --- /dev/null +++ b/changelog.d/18.added.md @@ -0,0 +1 @@ +Add SQL Server-side DDL and migration support: auto-increment suggestions and field generators, expression-built DDL with restored primary-key identity, T-SQL `CASE WHEN` rendering for scalar `EXISTS` and expression-synthesised paging `ORDER BY`, lossless suggested columns for `Decimal`/`datetime`, the suggested data-type table with the `substitute_data_types` hook and six complex families, native-type tests, neutral-type bridges, the database-assigned column protocol, a backend migration guide with examples, live and offline CLI tests, backend-local deep EXPLAIN construction 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/18.changed.md b/changelog.d/18.changed.md new file mode 100644 index 00000000..945d2c93 --- /dev/null +++ b/changelog.d/18.changed.md @@ -0,0 +1 @@ +Change the SQL Server backend's internal test layout to directory-owned databases with dialect-only definition classes (connection pool definitions and `query/core` L2 fixtures), and remove the superseded spatial adapter. These are internal changes with no public API impact. diff --git a/changelog.d/8.changed.md b/changelog.d/8.changed.md index 67581f1a..9b5b74d8 100644 --- a/changelog.d/8.changed.md +++ b/changelog.d/8.changed.md @@ -1 +1 @@ -Rework suggested_data_types() into a documented answer to "concepts SQL Server cannot spell, and what it stores instead": the keys are exactly the core types this dialect does not render (binary and varbinary as BlobType, interval as BigIntType, array and jsonb as JsonType, enum as VarCharType, timetz as TimeType, and uuid under this backend's own SQLServerUniqueIdentifierType, because T-SQL writes UNIQUEIDENTIFIER and the dispatch key has to be a word this backend can produce), while xml and timestamptz stay out of the table because the server has native types for them. Follow the core's renames of DateTimeColumn to TimestampColumn and DateTimeSupport to TimestampSupport, and migrate the tests to the rebuilt DDL-source accessors (column_type() / columns_type() become column_data_type() / columns_data_type()) and to building predicates, DDL check conditions and index conditions as explicit nodes now that the bare Column offers no operators. +Rework substitute_data_types() into a documented answer to "concepts SQL Server cannot spell, and what it stores instead": the keys are exactly the core types this dialect does not render (binary and varbinary as BlobType, interval as BigIntType, array and jsonb as JsonType, enum as VarCharType, timetz as TimeType, and uuid under this backend's own SQLServerUniqueIdentifierType, because T-SQL writes UNIQUEIDENTIFIER and the dispatch key has to be a word this backend can produce), while xml and timestamptz stay out of the table because the server has native types for them. Follow the core's renames of DateTimeColumn to TimestampColumn and DateTimeSupport to TimestampSupport, and migrate the tests to the rebuilt DDL-source accessors (column_type() / columns_type() become column_data_type() / columns_data_type()) and to building predicates, DDL check conditions and index conditions as explicit nodes now that the bare Column offers no operators. diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..d95c0d6d --- /dev/null +++ b/docs/README.md @@ -0,0 +1,29 @@ + +# rhosocial-activerecord-sqlserver Documentation + +This is the documentation for the SQL Server backend of +[rhosocial-activerecord](https://github.com/rhosocial/python-activerecord). It +covers only what is specific to SQL Server — connection and configuration, the +native types and dialect, introspection, partitioning, transactions, capability +gates and testing. For the framework itself (models, fields, queries, relations, +migrations), see the [core library documentation](https://github.com/rhosocial/python-activerecord/tree/main/docs/en_US). + +## Languages + +| Language | Documentation | +|----------|---------------| +| English | [en_US/README.md](en_US/README.md) | +| 中文 | [zh_CN/README.md](zh_CN/README.md) | + +> The English tree is the primary one; the `zh_CN` tree currently carries the +> migration guide. The GitBook summary lives under `en_US/`. + +## Quick links + +- [Documentation home / table of contents](en_US/README.md) +- [GitBook summary](en_US/SUMMARY.md) +- [Runnable examples](examples/README.md) +- [Migration guide](en_US/migration/README.md) / [迁移指南(中文)](zh_CN/migration/README.md) +- [Migration examples](examples/migration/README.md) +- [Database introspection](en_US/introspection/README.md) +- [Table partitioning](en_US/ddl/partition.md) diff --git a/docs/en_US/README.md b/docs/en_US/README.md new file mode 100644 index 00000000..8c1e8489 --- /dev/null +++ b/docs/en_US/README.md @@ -0,0 +1,69 @@ +# rhosocial-activerecord SQL Server Backend Documentation + +> 🤖 **AI Learning Assistant**: Key concepts in this documentation are marked +> with 💡 AI Prompt. When you encounter concepts you don't understand, you can +> ask the AI assistant directly. + +> **Example:** "Why does this backend gate SQL Graph on the server version, and +> how do I preview the T-SQL before it runs?" + +> 📖 **Scope**: These pages describe **this backend only** — where SQL Server +> differs, what it supports, and how it is configured and tested. The +> ActiveRecord model, field and query-building contract belongs to the +> [core library documentation](https://github.com/rhosocial/python-activerecord/tree/main/docs/en_US) +> and is not repeated here. + +## Table of Contents + +1. **[Introduction](introduction/README.md)** + * **[Backend overview](introduction/README.md)**: what this backend is, how it is layered, and when to use it + * **[Relationship with the core library](introduction/README.md#relationship-with-the-core-library)**: what the backend adds and what stays in core + * **[Supported versions](introduction/README.md#supported-versions)**: SQL Server 2017 / 2019 / 2022 / 2025; Python 3.9+ + +2. **[Installation & Configuration](installation/installation.md)** + * **[Installation](installation/installation.md)**: `pip` install, `pyodbc` and the ODBC driver + * **[Connection configuration](installation/configuration.md)**: host, port, database, authentication, driver + * **[Encryption & certificates](installation/configuration.md#encryption--tls)**: `encrypt`, `trust_server_certificate`, client certificates + * **[Timeouts & connection pool](installation/configuration.md#timeouts--connection-pool)**: connection/query timeouts and ODBC pooling + +3. **[Getting Started](getting_started/quick_start.md)** + * **[Quick start](getting_started/quick_start.md)**: a declarative model end to end + * **[Runnable examples](../examples/README.md)**: connection, DDL and introspection scripts + +4. **[Modeling](modeling/field_types.md)** + * **[SQL Server field types](modeling/field_types.md)**: `NVARCHAR`, `NCHAR`, `NVARCHAR(MAX)`, `VARBINARY`, `XML`, `UNIQUEIDENTIFIER`, `BIT`, `TINYINT` and more + +5. **[DDL Operations](ddl/create_table.md)** + * **[Creating tables](ddl/create_table.md)**: models to tables, IDENTITY, constraints and indexes + * **[Partitioning](ddl/partition.md)**: functions, schemes, `SPLIT`/`MERGE`/`SWITCH` and the maintenance helper + * **[Advanced objects](ddl/advanced_objects.md)**: temporal tables, SQL Graph, columnstore, memory-optimized tables and sequences + +6. **[Migrations](migration/README.md)** + * **[Migrations on SQL Server](migration/README.md)**: backend configuration, transactional DDL, version gating and CLI wiring (the system itself is in the core docs) + * **[Migration examples](../examples/migration/README.md)**: function-style and class-style examples using this backend + +7. **[Querying](querying/output_and_merge.md)** + * **[OUTPUT and RETURNING](querying/output_and_merge.md)**: returning affected rows from DML + * **[MERGE and pagination](querying/output_and_merge.md#merge-and-pagination)**: upsert, `OFFSET ... FETCH`, hints + +8. **[Transaction Support](transactions/README.md)** + * **[Isolation levels](transactions/README.md#isolation-levels)**: including `SNAPSHOT` + * **[Savepoints](transactions/README.md#savepoints)**: nested transactions via `SAVE TRANSACTION` + * **[Deadlocks & retries](transactions/README.md#deadlocks-and-retries)**: error mapping and retry guidance + +9. **[Introspection](introspection/README.md)** + * **[Database introspection](introspection/README.md)**: catalogue sources, capability answers, operational and data families, CLI types + +10. **[Capabilities](capabilities/README.md)** + * **[Capability gates](capabilities/README.md)**: how `supports_*` switches and version floors work + * **[Version floor reference](capabilities/README.md#version-floor-reference)**: which feature appears on which server + +11. **[Command Line](cli/README.md)** + * **[CLI usage](cli/README.md)**: `info`, `query`, `status` and `introspect` + +12. **[Testing](testing/README.md)** + * **[Test configuration](testing/README.md)**: PYTHONPATH, provider registration, local SQL Server via Docker + * **[Local scope](testing/README.md#local-test-scope)**: targeted checks only; full matrix on CI + +> 📖 **Core Library Documentation**: To learn about the complete ActiveRecord +> framework, 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..83a6cd38 --- /dev/null +++ b/docs/en_US/SUMMARY.md @@ -0,0 +1,58 @@ +# Table of Contents + +* [rhosocial-activerecord SQL Server Backend Documentation](README.md) + +## Introduction + +* [Backend overview](introduction/README.md) +* [Supported versions](introduction/README.md#supported-versions) +* [Relationship with the core library](introduction/README.md#relationship-with-the-core-library) + +## Installation & Configuration + +* [Installation](installation/installation.md) +* [Connection configuration](installation/configuration.md) + +## Getting Started + +* [Quick start](getting_started/quick_start.md) +* [Runnable examples](../examples/README.md) + +## Modeling + +* [SQL Server field types](modeling/field_types.md) + +## DDL + +* [Creating tables](ddl/create_table.md) +* [Partitioning](ddl/partition.md) +* [Advanced objects](ddl/advanced_objects.md) + +## Migrations + +* [Migrations on SQL Server](migration/README.md) +* [Migration examples](../examples/migration/README.md) + +## Querying + +* [OUTPUT and MERGE](querying/output_and_merge.md) + +## Transactions + +* [Transactions, isolation and savepoints](transactions/README.md) + +## Introspection + +* [Database introspection](introspection/README.md) + +## Capabilities + +* [Capability gates and version floors](capabilities/README.md) + +## Command Line + +* [CLI usage](cli/README.md) + +## Testing + +* [Test configuration](testing/README.md) diff --git a/docs/en_US/capabilities/README.md b/docs/en_US/capabilities/README.md new file mode 100644 index 00000000..1632f4f1 --- /dev/null +++ b/docs/en_US/capabilities/README.md @@ -0,0 +1,77 @@ +# Capability Gates + +The dialect exposes a large family of `supports_*` switches. They are the +backend's answer to "can this be asked of / rendered for the server in front of +us?". This page explains how they behave; the feature chapters list which ones +matter for each area. + +## How gates work + +1. **Capability questions are about the server, not the product.** A probe may + consult the detected server version (`version_at_least(...)` against the + constants in `mixins/version_constants.py`), or it may be a fixed statement + about what this backend implements. `backend.introspect_and_adapt()` refreshes + the detected version so version-gated probes answer for the server actually + reached. The CLI calls it on entry; code that gates on a probe should too. +2. **A `False` answer means "this question cannot be asked here"**, not "the + answer was empty or zero". It is distinct from an empty list, which is the + answer to a question that *was* asked and had nothing to report. Callers can + take a fallback knowingly. +3. **Gates do not test grants.** Two introspection DMVs need `VIEW DATABASE + STATE` / `VIEW SERVER STATE`; without them the engine answers a short list + or nothing at all, not an error. The probe answers `True` because the server + can answer — not because this login may ask. + +A gate that opens only means a statement renders and the server accepts it; it +says nothing about the shape or cost of the answer. The introspection page +states the price of each family it describes. + +## Two kinds of `False` + +- **Version floors** — the feature exists in SQL Server only from a certain + release. E.g. `supports_object_dependencies()` is `True` from 2008; + `supports_column_value_sample()` from 2012 because its `OFFSET ... FETCH` + cap needs that parser. +- **Permanent statements about the engine** — e.g. `supports_table_stats()` + and `supports_ddl_extraction()` are `False` on every release: the counters + are keyed per index (not per table), and the engine has no per-object DDL + retrieval call. `supports_json_table()` is `False` even on recent releases + because this backend's route is `OPENJSON`, not `JSON_TABLE`. +- **Syntax decisions** — `supports_nulls_first_last()` and + `supports_fetch_with_ties()` are `False` because SQL Server has no such + syntax in those positions; `supports_subpartitioning()`, + `supports_add_partition()` and `supports_drop_partition()` are `False` + because partitioning here uses `SPLIT` / `MERGE` / `SWITCH` + (see [Partitioning](../ddl/partition.md)). + +## Version floor reference + +| Feature / gate | Floor | What happens below it | +|----------------|-------|-----------------------| +| DMV-based gates (`runtime`, `index-stats`, `unused-indexes`) | 2005 (9.0) | probe `False`; CLI exits 2 without sending a statement | +| `supports_object_dependencies()` | 2008 (10.0) | probe `False`; CLI exits 2 | +| `supports_column_value_sample()` | 2012 (11.0) | probe `False`; CLI exits 2 | +| JSON functions (`supports_json_type()`) | 2016 (13.x) | probe `False` | +| Temporal tables (`supports_system_versioning()`) | 2016 (13.x) | gate closed | +| SQL Graph (node/edge, pseudo-columns) | 2017 (14.x) | gate closed | +| Graph shortest path / path aggregates; `READPAST` skip-locked | 2019 (15.x) | gate closed | +| Columnstore `ORDER (...)` | 2022 (16.x) | gate closed | +| `table-stats`, `ddl`, `extensions`, `json_table` | never | probe `False` on every release | + +All tested releases (2017–2025) are past the 2005/2008/2012/2016 floors; the +2017, 2019 and 2022 floors narrow what the earlier tested releases can render. + +## Probing from code + +```python +backend.introspect_and_adapt() + +if backend.dialect.supports_unused_indexes_detection(): + for index in backend.introspector.list_unused_indexes(): + print(f"{index.table_name}.{index.index_name}") +else: + ... # take the fallback knowingly +``` + +The full introspection probe table, including which answers are backend-local +or newly added, is in [Database introspection](../introspection/README.md). diff --git a/docs/en_US/cli/README.md b/docs/en_US/cli/README.md new file mode 100644 index 00000000..b7bc5868 --- /dev/null +++ b/docs/en_US/cli/README.md @@ -0,0 +1,66 @@ +# Command Line + +The backend installs the `rhosocial-activerecord-sqlserver` script and can also +be invoked as a module: + +```bash +python -m rhosocial.activerecord.backend.impl.sqlserver +``` + +Commands are registered under `cli/`: `info`, `query`, `status`, and the large +`introspect` family, plus named-connection, named-query and named-procedure +helpers. + +## Connection flags + +Connection parameters can be flags or environment variables: + +| Flag | Environment variable | Default | +|------|----------------------|---------| +| `--host` | `SQLSERVER_HOST` | `localhost` | +| `--port` | `SQLSERVER_PORT` | `1433` | +| `--database` | `SQLSERVER_DATABASE` | required for introspection | +| `--user` / `--username` | `SQLSERVER_USERNAME` | `sa` | +| `--password` | `SQLSERVER_PASSWORD` | empty | +| `--driver` | `SQLSERVER_DRIVER` | `ODBC Driver 18 for SQL Server` | + +`--trusted-connection` switches to Windows authentication. `--ssl` selects +`auto`, `require`, `verify-ca`, `verify-full` or `disabled`; +`--encrypt` / `--no-encrypt` and +`--trust-server-certificate` / `--no-trust-server-certificate` override it. +A named connection profile (`--named-connection`) may stand in for `--database`. +`--async` runs the same command through `AsyncSQLServerBackend`. + +## Introspection + +```bash +# Schema and tables +python -m rhosocial.activerecord.backend.impl.sqlserver introspect schemas --database mydb +python -m rhosocial.activerecord.backend.impl.sqlserver introspect tables --database mydb +python -m rhosocial.activerecord.backend.impl.sqlserver introspect columns orders --database mydb + +# Operational readings and exact data profiles +python -m rhosocial.activerecord.backend.impl.sqlserver introspect unused-indexes --database mydb +python -m rhosocial.activerecord.backend.impl.sqlserver introspect runtime --database mydb +python -m rhosocial.activerecord.backend.impl.sqlserver introspect column-profiles orders --database mydb +``` + +Every introspect type is gated on its `supports_*` probe: a refused family exits +**2** with "not supported by this server" before a statement is sent. DDL +extraction is not offered at all because the probe is permanently `False`. +Output formats are `-o table` (default, rich), `json`, `csv` and `tsv`, with +`--rich-ascii` for plain table borders. + +The complete list of introspection types, their name arguments and exit-code +rules is in [Database introspection](../introspection/README.md#command-line-introspection). + +## Other commands + +- `info` — connection and server information (name, version, collation, edition). +- `query` — run a statement and render results in the chosen output format. +- `status` — report the connected server's capabilities and settings. +- `named-connection`, `named-query`, `named-procedure` — manage and run saved + definitions; see the `examples/cli` and `examples/named_*` scripts in the + repository's `src/.../examples/` tree. + +> 💡 *AI prompt: "Why does the CLI refuse a capability-gated family with exit code 2 rather than printing an empty table?"* diff --git a/docs/en_US/ddl/advanced_objects.md b/docs/en_US/ddl/advanced_objects.md new file mode 100644 index 00000000..dfaee326 --- /dev/null +++ b/docs/en_US/ddl/advanced_objects.md @@ -0,0 +1,80 @@ +# Advanced Objects + +SQL Server presents several object families that have no portable equivalent. +This backend exposes them as expressions and gates each one on the connected +server's version. The contract for how gates work is in +[Capability gates](../capabilities/README.md); this page is the catalogue of +what is gated. + +## Version-gated feature map + +| Feature | Gate | Floor | +|---------|------|-------| +| System-versioned temporal tables | `supports_system_versioning()` | SQL Server 2016 (13.x) | +| SQL Graph (node/edge tables) | `supports_sql_graph()` | 2017 (14.x) | +| Shortest path / graph path aggregates | `supports_shortest_path()`, `supports_graph_path_aggregates()` | 2019 (15.x) | +| Nonclustered columnstore index | `supports_nonclustered_columnstore()` | 2012 (11.x) | +| Clustered columnstore index | `supports_clustered_columnstore()` | 2014 (12.x) | +| `ORDER (...)` in a columnstore index | `supports_columnstore_order()` | 2022 (16.x) | +| Sequences | `supports_sequence()` and friends | 2012 (11.x) | +| User-defined types (incl. CLR, memory-optimized table types) | `supports_type_objects()` family | varies | + +Every release this repository tests against — 2017, 2019, 2022 and 2025 — is +past the 2012/2014/2016 floors, so those gates are open there; the 2017, 2019 +and 2022 floors narrow what the earlier tested releases can render. + +## Temporal tables + +A system-versioned table keeps a history table and is queried with +`FOR SYSTEM_TIME`. Expressions live in `expression/temporal.py`; the dialect's +`supports_system_versioning()` answers from the 2016 floor. Queries are built +through the mixin in `mixins/temporal.py` rather than raw text. + +```python +# The capability is asked of the connected server, not hard-coded +if backend.dialect.supports_system_versioning(): + ... # render a SYSTEM_VERSIONING / FOR SYSTEM_TIME expression +``` + +## SQL Graph + +Node and edge tables, `$node_id` / `$edge_id` pseudo-columns, `MATCH` pattern +matching and `SHORTEST_PATH` are available from SQL Server 2017 (2019 for the +path functions). The protocol surface is in `protocols/graph.py` and +`mixins/graph.py`, with expressions in `expression/graph.py`: + +- `supports_sql_graph()`, `supports_graph_table_kind()`, + `supports_graph_pseudo_columns()` +- `supports_shortest_path()`, `supports_graph_path_aggregates()`, + `supports_edge_constraints()` + +## Columnstore and memory-optimized tables + +The columnstore expressions (`expression/columnstore.py`) render clustered and +nonclustered columnstore indexes, with the `ORDER` clause gated to 2022. +Memory-optimized tables are gated by `supports_memory_optimized_tables()` and +belong to the `WITH (MEMORY_OPTIMIZED = ON, ...)` family. These are storage +choices — the model declaration stays the same; the DDL expression changes. + +## Sequences and user-defined types + +`CREATE/ALTER/DROP SEQUENCE` support is in `mixins/sequence.py`, gated to 2012, +with a few sequence-as-data-type and validation clauses gated to 2016. +User-defined types (alias, table, CLR and memory-optimized table types) are +covered by `mixins/ddl_type.py` and the `protocols/type.py` capability surface +(`supports_create_type`, `supports_clr_user_defined_type`, +`supports_memory_optimized_table_types`, and so on). Introspection for these +objects is described in [Database introspection](../introspection/README.md). + +## Other SQL Server DDL surfaces + +- **Views** — indexed views, `WITH CHECK OPTION`, `CREATE OR ALTER`, and + `SELECT INTO`; see the `supports_*` answers in `mixins/ddl_view.py`. +- **Fulltext** — fulltext catalogs and indexes (`protocols/fulltext.py`, + `mixins/index.py`). +- **Generated columns** — stored and virtual computed columns + (`mixins/generated_column.py`). +- **Triggers and routines** — DDL and introspection under `expression/ddl/` + and `mixins/trigger.py` / `mixins/routine.py`. + +> 💡 *AI prompt: "How does the backend decide whether a feature can be rendered, and why is that decision made at connect time rather than import time?"* diff --git a/docs/en_US/ddl/create_table.md b/docs/en_US/ddl/create_table.md new file mode 100644 index 00000000..85f2fdb7 --- /dev/null +++ b/docs/en_US/ddl/create_table.md @@ -0,0 +1,128 @@ +# Creating Tables + +There are two ways to create schema on this backend: + +1. **From a declarative model** — `Model.create_table()` renders DDL from the + model's field declarations (see [Quick start](../getting_started/quick_start.md)). +2. **From expression nodes** — build `CreateTableStatement` directly when you + need precise control over types, identity and constraints. This is the style + used by the backend's own DDL examples. + +Both end in the dialect rendering T-SQL; call `.to_sql()` first to preview it. + +## Expression-based DDL + +```python +from rhosocial.activerecord.backend.expression import ( + ColumnConstraint, + ColumnDefinition, + CreateTableStatement, + DropTableStatement, +) +from rhosocial.activerecord.backend.expression.objects import Table +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts +from rhosocial.activerecord.backend.expression.statements.ddl_table import ( + ColumnNotNullConstraint, + ColumnPrimaryKeyConstraint, + ColumnUniqueConstraint, + IndexDefinition, +) +from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType + +config = SQLServerConnectionConfig( + host="localhost", database="myapp", username="sa", password="secret", + driver="ODBC Driver 18 for SQL Server", +) +backend = SQLServerBackend(connection_config=config) +backend.connect() +dialect = backend.dialect + +id_type, id_attrs = auto_increment_parts(dialect, "INT") + +columns = [ + ColumnDefinition( + name="id", + data_type=id_type, # INT + attributes=id_attrs, # IDENTITY(1,1) + constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))], + ), + ColumnDefinition( + name="name", + data_type="NVARCHAR(100)", + constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))], + ), + ColumnDefinition( + name="email", + data_type="NVARCHAR(200)", + constraints=[ColumnConstraint(dialect, branch=ColumnUniqueConstraint(dialect))], + ), + ColumnDefinition(name="created_at", data_type="DATETIME2"), +] + +indexes = [IndexDefinition(name="idx_users_email", columns=["email"])] + +create = CreateTableStatement( + dialect=dialect, + table=Table(dialect, "users"), + columns=columns, + indexes=indexes, + if_not_exists=True, +) +sql, params = create.to_sql() +backend.execute(sql, params, options=ExecutionOptions(stmt_type=StatementType.DDL)) +``` + +Rendered shape: + +```sql +CREATE TABLE [users] ( + [id] INT IDENTITY(1,1) NOT NULL PRIMARY KEY, + [name] NVARCHAR(100) NOT NULL, + [email] NVARCHAR(200) UNIQUE, + [created_at] DATETIME2 +); +CREATE INDEX [idx_users_email] ON [users] ([email]); +``` + +## IDENTITY and generated keys + +`auto_increment_parts(dialect, "INT")` returns the pair `(type, attributes)`: +the base integer type and the `IDENTITY(1,1)` column attribute. This split +mirrors how SQL Server models identity — it is a column property, not a type. +A model using `IntegerPKMixin` goes through the same path automatically. + +See [SQL Server field types](../modeling/field_types.md) for server-maintained +columns (`ROWVERSION`) that must instead be excluded from writes. + +## Constraints and indexes + +- Primary key, `NOT NULL` and `UNIQUE` column constraints render as inline or + table constraints. +- Indexes are declared with `IndexDefinition`. SQL Server-specific index kinds + are also available as expressions (filtered, fulltext, columnstore, XML, + spatial); see [Advanced objects](advanced_objects.md). +- Which DDL clauses are legal is expressed by `supports_*` switches — for + example `supports_drop_table_cascade()` is `False` because SQL Server has no + `DROP TABLE ... CASCADE`, and `supports_table_partitioning()` is `True`. + +## Dropping / altering + +```python +drop = DropTableStatement(dialect=dialect, table=Table(dialect, "users"), if_exists=True) +sql, params = drop.to_sql() +backend.execute(sql, params, options=ExecutionOptions(stmt_type=StatementType.DDL)) +``` + +`ALTER TABLE` support is implemented by a modifier with explicit feature +answers: adding and dropping columns are supported; `ADD COLUMN IF NOT EXISTS`, +`DROP COLUMN IF EXISTS` and `DROP CONSTRAINT IF EXISTS` are **not** (SQL Server +has no such clause) and answer `False`. + +## Next steps + +- [Partitioning](partition.md) — functions, schemes and maintenance +- [Advanced objects](advanced_objects.md) — temporal tables, graph, columnstore, sequences +- [OUTPUT and MERGE](../querying/output_and_merge.md) — returning rows from DML diff --git a/docs/partition.md b/docs/en_US/ddl/partition.md similarity index 99% rename from docs/partition.md rename to docs/en_US/ddl/partition.md index 1c375520..f8ece22f 100644 --- a/docs/partition.md +++ b/docs/en_US/ddl/partition.md @@ -247,7 +247,7 @@ partition to absorb its neighbour. ## Live coverage -`tests/.../feature/backend/test_sqlserver_partition_live.py` exercises +`tests/.../feature/backend/execute/partition/test_partition_live.py` exercises `CREATE PARTITION FUNCTION` / `SCHEME`, `SPLIT RANGE`, `MERGE RANGE`, `SWITCH` and catalogue reads against the SQL Server 2022 image in `docker-compose.yml`. It skips -- rather than passes -- when no scenario is configured or the server diff --git a/docs/en_US/getting_started/quick_start.md b/docs/en_US/getting_started/quick_start.md new file mode 100644 index 00000000..eba8b17c --- /dev/null +++ b/docs/en_US/getting_started/quick_start.md @@ -0,0 +1,107 @@ +# Quick Start + +This page shows a complete, SQL Server-backed declarative model. It focuses on +the wiring that is specific to this backend; the meaning of `ActiveRecord`, +field mixins and the query API belongs to the +[core documentation](https://github.com/rhosocial/python-activerecord/tree/main/docs/en_US). + +```python +from typing import Annotated, ClassVar + +from rhosocial.activerecord.base import FieldProxy, UseSqlType +from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig +from rhosocial.activerecord.backend.expression.types import VarCharType +from rhosocial.activerecord.field import DefaultTimestampMixin, IntegerPKMixin +from rhosocial.activerecord.model import ActiveRecord + + +class User( + IntegerPKMixin, # auto-increment integer primary key `id` + DefaultTimestampMixin, # injects `created_at` / `updated_at` + ActiveRecord, # persistence, query builder, relations +): + name: Annotated[str, UseSqlType(VarCharType(length=100))] + email: Annotated[str, UseSqlType(VarCharType(length=255))] + age: int = 0 + + c: ClassVar[FieldProxy] = FieldProxy() # enables User.c. expressions + + @classmethod + def table_name(cls) -> str: + return "users" + + +# Bind the model to SQL Server and create the table from the declaration +User.configure( + SQLServerConnectionConfig( + host="localhost", + port=1433, + database="myapp", + username="sa", + password="YourStrong!Passw0rd", + driver="ODBC Driver 17 for SQL Server", + ), + SQLServerBackend, +) +User.create_table() + +# Create +alice = User(name="Alice", email="alice@example.com", age=30) +alice.save() +print(alice.id) # database-assigned integer primary key + +# Query with type-safe expressions +adults = User.query().where(User.c.age >= 18).all() +print([user.name for user in adults]) + +# Preview the generated T-SQL without executing it +sql, params = User.query().where(User.c.age >= 18).to_sql() +print(sql, params) +# SELECT ... FROM [users] WHERE [users].[age] >= ? (18,) +``` + +> 💡 *AI prompt: "Why does `configure()` take both a config and a backend class? What does `create_table()` generate for an `IntegerPKMixin` key on SQL Server?"* + +## What is SQL Server-specific here + +- **`IntegerPKMixin` → `INT IDENTITY`.** A server-assigned integer key is + rendered as SQL Server `IDENTITY`, and DML that returns it uses the `OUTPUT` + clause. See [Creating tables](../ddl/create_table.md) and + [OUTPUT and MERGE](../querying/output_and_merge.md). +- **Unicode text.** For `NVARCHAR` rather than the collation-dependent + `VARCHAR`, pin the field to a `SQLServerNVarCharType`. See + [SQL Server field types](../modeling/field_types.md). +- **Bracket quoting.** Identifiers render as `[users]` / `[age]`, and the + parameter placeholder is `?` (filled by `pyodbc`). +- **Version gates.** Advanced features appear only when the connected server + supports them; see [Capability gates](../capabilities/README.md). + +## Async parity + +Use `AsyncActiveRecord` with `AsyncSQLServerBackend`. The method names are the +same; add `await`: + +```python +from rhosocial.activerecord.model import AsyncActiveRecord +from rhosocial.activerecord.backend.impl.sqlserver.backend.async_backend import AsyncSQLServerBackend + +class AsyncUser(IntegerPKMixin, AsyncActiveRecord): + c: ClassVar[FieldProxy] = FieldProxy() + name: str + + @classmethod + def table_name(cls) -> str: + return "users" + +AsyncUser.configure(config, AsyncSQLServerBackend) +user = AsyncUser(name="Alice") +await user.save() +``` + +## Runnable scripts + +Three complete scripts live under [`docs/examples/`](../../examples/README.md): +connection/configuration, declarative-model CRUD, and +introspection/partitioning. They are syntax-checked but require a reachable SQL +Server to run. diff --git a/docs/en_US/installation/configuration.md b/docs/en_US/installation/configuration.md new file mode 100644 index 00000000..70bcedd2 --- /dev/null +++ b/docs/en_US/installation/configuration.md @@ -0,0 +1,134 @@ +# Connection Configuration + +All connection settings live on `SQLServerConnectionConfig`, which subclasses +core's `ConnectionConfig`. It is passed to `SQLServerBackend` (or +`AsyncSQLServerBackend`) as `connection_config=`. + +```python +from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig + +config = SQLServerConnectionConfig( + host="localhost", + port=1433, + database="myapp", + username="sa", + password="YourStrong!Passw0rd", + driver="ODBC Driver 18 for SQL Server", +) +backend = SQLServerBackend(connection_config=config) +backend.connect() +``` + +## Authentication + +Two modes are supported: + +```python +# SQL Server Authentication +config = SQLServerConnectionConfig( + host="db.example.com", database="myapp", + username="app_user", password="secret", +) + +# Windows / integrated authentication +config = SQLServerConnectionConfig( + host="db.example.com", database="myapp", + trusted_connection=True, +) +``` + +`validate_config()` enforces that either `trusted_connection=True` or both +`username` and `password` are supplied. The `repr` masks the password, so a +config can be logged safely. + +## Connection string fields + +`build_connection_string()` produces a semicolon-delimited ODBC string. The +fields map as follows: + +| Field | Default | ODBC key / effect | +|-------|---------|-------------------| +| `host` | `localhost` | `SERVER=host,port` (a `(localdb)...` host is emitted verbatim) | +| `port` | `1433` | combined with `host` | +| `database` | `""` | `DATABASE=` | +| `username` / `password` | `None` | `UID=` / `PWD=` when not using trusted connection | +| `trusted_connection` | `False` | `Trusted_Connection=yes` | +| `driver` | `ODBC Driver 17 for SQL Server` | `DRIVER={...}` | +| `encrypt` | `True` | `Encrypt=yes/no` (omitted for legacy drivers) | +| `trust_server_certificate` | `False` | `TrustServerCertificate=yes/no` | +| `timeout` | `30` | `Connection Timeout=` | +| `charset` | `UTF-8` | `CharacterSet=` when not UTF-8 | +| `options` | `{}` | extra `key=value` pairs appended verbatim | + +Legacy drivers (`SQL Server`, `SQL Server Native Client 11.0`) do not accept the +`Encrypt`/`TrustServerCertificate` keywords, so those two entries are skipped +for them. + +## Encryption & TLS + +Encryption defaults on (`encrypt=True`) and certificate validation defaults to +strict (`trust_server_certificate=False`). A development database using a +self-signed certificate usually needs: + +```python +config = SQLServerConnectionConfig( + host="localhost", database="dev", username="sa", password="secret", + driver="ODBC Driver 18 for SQL Server", + encrypt=True, + trust_server_certificate=True, # disables server-certificate validation +) +``` + +> ⚠️ `trust_server_certificate=True` together with `encrypt=True` emits a +> `UserWarning`: it disables certificate validation and is not recommended for +> production. + +Mutual TLS and hostname overrides are supported through: + +| Field | Purpose | +|-------|---------| +| `client_certificate` | filesystem path to a PEM/PFX client certificate | +| `client_key` | filesystem path to the client key (requires `client_certificate`) | +| `client_key_password` | password for the client key | +| `host_name_in_certificate` | name to match against the server certificate when it differs from `host` | + +These are paths and settings the ODBC driver reads itself, not certificate +material held by the backend. `validate_config()` rejects a `client_key` +without a `client_certificate`. + +The CLI exposes the same knobs as `--ssl` (`auto`, `require`, `verify-ca`, +`verify-full`, `disabled`), with `--encrypt`/`--no-encrypt` and +`--trust-server-certificate`/`--no-trust-server-certificate` taking precedence. + +## Timeouts & connection pool + +| Field | Default | Meaning | +|-------|---------|---------| +| `timeout` | `30` | connection timeout, seconds | +| `query_timeout` | `0` | per-query timeout, seconds (`0` = no limit) | +| `autocommit` | `True` | initial autocommit mode | +| `pool_size` | `5` | ODBC connection pool size | +| `pool_timeout` | `30` | pool checkout timeout, seconds | +| `deployment_target` | `"sqlserver"` | label used by capability gates | + +`pool_size` / `pool_timeout` are passed through as ODBC pool settings; the +driver and connection manager handle the actual pooling. + +## Named connection profiles (CLI) + +For CLI use, connection parameters can be supplied as flags or environment +variables: + +| Flag | Environment variable | Default | +|------|----------------------|---------| +| `--host` | `SQLSERVER_HOST` | `localhost` | +| `--port` | `SQLSERVER_PORT` | `1433` | +| `--database` | `SQLSERVER_DATABASE` | required for introspection | +| `--user` / `--username` | `SQLSERVER_USERNAME` | `sa` | +| `--password` | `SQLSERVER_PASSWORD` | empty | +| `--driver` | `SQLSERVER_DRIVER` | `ODBC Driver 18 for SQL Server` | +| `--trusted-connection` | — | Windows authentication | + +A named connection profile (`--named-connection`) can stand in for `--database`. +See [CLI usage](../cli/README.md). diff --git a/docs/en_US/installation/installation.md b/docs/en_US/installation/installation.md new file mode 100644 index 00000000..57f815c0 --- /dev/null +++ b/docs/en_US/installation/installation.md @@ -0,0 +1,60 @@ +# Installation + +## Package + +```bash +pip install rhosocial-activerecord-sqlserver +``` + +The package installs into the `rhosocial.activerecord.backend.impl.sqlserver` +namespace. It depends on `pyodbc >= 5.3.0` and a compatible release of the core +`rhosocial-activerecord` library. When developing against a local checkout of a +sibling package, install it by explicit local path rather than relying on a +published version from an index, so that the editable source tree is the one +actually imported. + +## Prerequisites + +| Requirement | Notes | +|-------------|-------| +| Python | 3.9 or newer | +| SQL Server | 2017, 2019, 2022 or 2025 | +| ODBC driver | Microsoft ODBC Driver 17 or 18 for SQL Server, installed on the client | +| `pyodbc` | `>= 5.3.0`, installed as a dependency | + +The ODBC driver is a **system** component, not a Python package: `pyodbc` only +loads it by name. Verify that the driver is present before debugging Python +code — an incorrect or missing driver name is the most common connection +failure. On the connection config the default is `ODBC Driver 17 for SQL +Server`; override `driver` if you installed Driver 18. See +[Connection configuration](configuration.md). + +### Async support + +The sync backend uses `pyodbc`. For `AsyncSQLServerBackend`, install the async +extra, which pulls in `aioodbc`: + +```bash +pip install "rhosocial-activerecord-sqlserver[async]" +``` + +## Verify the install + +A syntax-and-import check needs no database: + +```bash +python -c "from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend; print(SQLServerBackend)" +python -c "from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig; print(SQLServerConnectionConfig)" +``` + +To confirm the driver name your machine can actually load: + +```python +import pyodbc +print(pyodbc.drivers()) # look for "ODBC Driver 17/18 for SQL Server" +``` + +## Next steps + +- [Connection configuration](configuration.md) — authentication, encryption, timeouts, pooling +- [Quick start](../getting_started/quick_start.md) — a declarative model end to end diff --git a/docs/en_US/introduction/README.md b/docs/en_US/introduction/README.md new file mode 100644 index 00000000..d8fb2192 --- /dev/null +++ b/docs/en_US/introduction/README.md @@ -0,0 +1,82 @@ +# Backend Overview + +`rhosocial-activerecord-sqlserver` is the Microsoft SQL Server backend for +[rhosocial-activerecord](https://github.com/rhosocial/python-activerecord). It +binds the framework's ActiveRecord models and query builder to SQL Server's +dialect and to the `pyodbc` driver. It cannot be used standalone — it is an +add-on to the core library. + +The backend speaks SQL Server on its own terms instead of flattening it to a +lowest-common-denominator SQL: DML that returns affected rows uses `OUTPUT`, +temporal queries use `FOR SYSTEM_TIME`, schema objects are named with +`[...]-quoted identifiers, and server-specific features (SQL Graph, +memory-optimized tables, columnstore, partitioning) appear only on the versions +that support them. You keep a single API and can still preview the exact T-SQL +through `.to_sql()` before anything runs. + +> 💡 *AI prompt: "What does it mean that this backend renders native T-SQL rather than portable SQL? How can I see the statement before it is executed?"* + +## Design principles + +1. **Backend implementation** — extends the core Expression–Dialect–Backend + layering with SQL Server-specific dialect, expressions, types, adapters and + mixins. Query structure is built as expression nodes; the dialect renders + them to T-SQL only when `.to_sql()` is called. +2. **Driver** — uses `pyodbc` for connectivity. Async support is provided by + `aioodbc` through `AsyncSQLServerBackend`, with the same method names as the + sync backend (add `await`). +3. **Namespace package** — installs under + `rhosocial.activerecord.backend.impl.sqlserver` as part of the core library's + PEP 420 namespace. +4. **Capability negotiation** — a broad set of `supports_*` switches, many of + them version-gated against the connected server, decide whether a feature + can be rendered. See [Capability gates](../capabilities/README.md). + +## Relationship with the core library + +The core library owns the ActiveRecord abstraction: declaring a `Model`, its +fields and mixins, defining relations, building queries and expressions, and +the introspection/partition *contracts*. This backend owns the SQL Server side +of those contracts: + +| Concern | Core library | This backend | +|---------|--------------|--------------| +| Model declaration, fields, mixins, relations | ✅ | — (reused as-is) | +| Query builder and expression nodes | ✅ | SQL Server expression subclasses and dialect rendering | +| Native type mapping | core type classes | `SQLServer*Type` variants (e.g. `SQLServerNVarCharType`) and adapters | +| Connection configuration | `ConnectionConfig` base | `SQLServerConnectionConfig` (ODBC string, auth, encryption) | +| CRUD / DDL / DML execution | backend protocol | `SQLServerBackend` / `AsyncSQLServerBackend` | +| Introspection contract and result types | ✅ | catalogue queries against `sys.*` / `INFORMATION_SCHEMA`, capability answers | +| Partitioning contract, plan and retention protocol | ✅ | `SQLServerPartitionPlan`, `SQLServerPartitionMaintenance`, partition expressions | +| Transactions | `TransactionManager` | `SQLServerTransactionManager` (SNAPSHOT, savepoints) | + +A declarative model is written once against core's `ActiveRecord` API and then +bound to this backend. See [Quick start](../getting_started/quick_start.md) and +the [runnable examples](../../examples/README.md). + +## Supported versions + +| Item | Value | +|------|-------| +| SQL Server | **2017, 2019, 2022, 2025** (tested in CI) | +| Python | **3.9+** (see `pyproject.toml`) | +| Driver | `pyodbc >= 5.3.0`; ODBC Driver **17+** (18 recommended) | +| Core library | `rhosocial-activerecord >= 1.0.0.dev30, < 2.0.0` | + +Version detection happens at connect time. `backend.introspect_and_adapt()` +refreshes the detected version so version-gated probes answer for the server +actually reached, rather than for a construction-time assumption. The backend's +internal floor constants reach back to 2005 for a few legacy capabilities, but +the releases this repository tests against are 2017–2025, all of which are past +the relevant gates. The capability chapter lists the floors that matter in +practice. + +> ⚠️ **Development stage**: this package is under active development. APIs may +> change and some features are not yet production-ready. + +## Where to go next + +- [Installation and configuration](../installation/installation.md) +- [Quick start with a declarative model](../getting_started/quick_start.md) +- [SQL Server-specific field types](../modeling/field_types.md) +- [Database introspection](../introspection/README.md) diff --git a/docs/introspection.md b/docs/en_US/introspection/README.md similarity index 100% rename from docs/introspection.md rename to docs/en_US/introspection/README.md diff --git a/docs/en_US/migration/README.md b/docs/en_US/migration/README.md new file mode 100644 index 00000000..b6ab4272 --- /dev/null +++ b/docs/en_US/migration/README.md @@ -0,0 +1,145 @@ +# Migrations on SQL Server + +> 📖 **Scope**: This page covers **only what is specific to running ActiveRecord migrations on this backend** — configuring the SQL Server (pyodbc) backend, transactional DDL behaviour, version gating, and how the two authoring APIs are wired to this backend's CLI. +> +> The migration **system itself** — the two APIs, vocabulary, ordering and dependency validation, version records, dry-run capture, the exception hierarchy, and the core `migrate` CLI — belongs to the [core migration chapter](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md). It is **not** restated here. Read that chapter first if you are new to migrations. +> +> All examples on this page and in [docs/examples/migration/](../../examples/migration/README.md) use SQL Server. + +Contents: + +1. [Configuring the backend](#1-configuring-the-backend) +2. [Transactional DDL on SQL Server](#2-transactional-ddl-on-sql-server) +3. [Version-gated features and types](#3-version-gated-features-and-types) +4. [Function-style migrations (`run_migration_group`)](#4-function-style-migrations-run_migration_group) +5. [Class-style migrations and the `named-migration` CLI](#5-class-style-migrations-and-the-named-migration-cli) +6. [Local examples](#6-local-examples) + +> 💡 **AI Prompt**: "I have an `@migration`-decorated function. Show me how to run it as a dry run against SQL Server, then for real, without re-explaining how the migration system works." + +## 1. Configuring the backend + +A migration uses the same backend and connection config as any other operation. Construct `SQLServerConnectionConfig`, pass it to `SQLServerBackend`, connect, and refresh the detected server version: + +```python +from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig + +config = SQLServerConnectionConfig( + host="localhost", + port=1433, + database="myapp", + username="sa", + password="...", # or trusted_connection=True + driver="ODBC Driver 18 for SQL Server", +) +backend = SQLServerBackend(connection_config=config) +backend.connect() +backend.introspect_and_adapt() # refresh the detected version before any version gate +``` + +Backend-specific points: + +- The synchronous path uses `pyodbc` via `SQLServerBackend`; the asynchronous path uses `aioodbc` via `AsyncSQLServerBackend` and `run_migration_group_async()`. See [Connection configuration](../installation/configuration.md) for the full config surface, including Windows authentication, ODBC drivers and TLS. +- Do not hard-code credentials. The examples read connection details from `SQLSERVER_*` environment variables; the CLI accepts `--named-connection` for the same purpose. +- Call `backend.introspect_and_adapt()` before rendering version-gated DDL in application code. Gates consult the *detected* server version, and a stale version answers for the wrong floor. This backend's CLI does it on entry; a script must do it itself. +- Leave the connection's `autocommit` setting at its default. Transaction boundaries for a migration group are decided by `transaction_mode` (next section), not by the connection-level flag. + +## 2. Transactional DDL on SQL Server + +**SQL Server supports transactional DDL in general.** Ordinary schema statements — `CREATE TABLE`, `ALTER TABLE`, `DROP TABLE`, `CREATE INDEX` and the like — participate in a user transaction and are rolled back when it rolls back. Consequently the migration group's default `TransactionMode.AUTO` gives you an atomic group on this backend: a failure part-way through applies nothing and writes no version record. The SQL Server dialect has no `supports_transactional_ddl()` override, so the runner reports DDL as transactional (the default), which matches this behaviour. + +Caveats that matter when authoring migrations here: + +- **Not every statement may appear inside an explicit transaction.** Server- and database-scoped operations such as `CREATE DATABASE`, `DROP DATABASE`, `RESTORE DATABASE` and several `DBCC` commands are rejected inside a transaction. Keep such statements out of a migration group, or run them explicitly outside one; do not assume that "DDL is transactional" makes every `CREATE ...` safe. +- **Long DDL takes locks.** A migration can block on an exclusive schema lock. Bound the run with `query_timeout` on the connection config (default `0` means no limit) instead of relying on a client-side timeout. +- **`SNAPSHOT` is not automatic.** If you select snapshot isolation for a migration transaction, the database must already have `ALLOW_SNAPSHOT_ISOLATION ON`; this backend does not change that setting for you. See [Transactions](../transactions/README.md) for isolation mapping, savepoints and deadlock retries. + +The meaning of `TransactionMode.AUTO` / `STEP` / `NONE`, version-record writes, and the failure metadata (`transactional_ddl`, `executed`, ...) are described in the core chapter; this page only states what those modes *do* on SQL Server. + +## 3. Version-gated features and types + +The dialect answers capability questions with `supports_*` probes and `version_at_least(...)`, using the constants in `mixins/version_constants.py`. A few floors that commonly affect DDL: + +- sequences — 2012 (`SQL_SERVER_2012`) +- JSON functions / `supports_json_type()` — 2016 (`SQL_SERVER_2016`) +- temporal tables / `supports_system_versioning()` — 2016 +- SQL Graph (node/edge tables) / `supports_sql_graph()` — 2017 (`SQL_SERVER_2017`) +- graph shortest path — 2019 (`SQL_SERVER_2019`) +- `ORDER (...)` on columnstore indexes — 2022 (`SQL_SERVER_2022`) + +Check the gate **before** generating version-gated DDL; a closed gate means the expression will not render (or raises `UnsupportedFeatureError`, surfaced by the migration layer as `MigrationDialectError`): + +```python +from rhosocial.activerecord.backend.impl.sqlserver.mixins.version_constants import SQL_SERVER_2016 + +backend.introspect_and_adapt() +dialect = backend.dialect + +if dialect.supports_system_versioning() and dialect.version_at_least(SQL_SERVER_2016): + ... # safe to emit version-gated DDL +else: + ... # take a deliberate fallback, or fail deliberately +``` + +Note that a gate answers whether the *server* can be asked, not whether this login has grants. See [Capability gates](../capabilities/README.md) for the full floor table and the distinction between a closed gate, a version floor, and a permanently unsupported statement. + +## 4. Function-style migrations (`run_migration_group`) + +New work should use the function-style API. This backend contributes only the connection and dialect; the decorator, group runner, record store, ordering rules and dry-run semantics are all core features documented in the [core migration chapter](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md). + +The minimal SQL Server shape is: + +```python +@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)) + + +backend = SQLServerBackend(connection_config=config) +backend.connect() +backend.introspect_and_adapt() + +# dry run — renders T-SQL through this backend's dialect, writes nothing +preview = run_migration_group(backend, [f"{__name__}:create_users"], dry_run=True) +print(preview.dry_run_sql, preview.dry_run_total) + +# real run — applies the DDL inside a transaction and writes a version record +result = run_migration_group(backend, [f"{__name__}:create_users"], record_store=store) +``` + +Because DDL is rendered by this backend's dialect, the dry-run SQL you inspect is the actual T-SQL that would run — including `[bracketed]` identifiers, `IDENTITY(1,1)` and this server's type spelling. There is no backend-specific dry-run flag; `dry_run=True` is the same core option described in the core chapter. + +A complete, syntax-checked script is [`01_function_migration.py`](../../examples/migration/01_function_migration.py). + +## 5. Class-style migrations and the `named-migration` CLI + +The class-style (`NamedMigration`) path is maintained for compatibility. This backend wires it into its own CLI through [`cli/named_migration.py`](../../../src/rhosocial/activerecord/backend/impl/sqlserver/cli/named_migration.py): the subcommand builds `SQLServerBackend` from the shared connection arguments and calls `introspect_and_adapt()` before delegating to core's `handle_named_migration`. + +```bash +python -m rhosocial.activerecord.backend.impl.sqlserver named-migration \ + myapp.migrations.v001.CreateUsersTable \ + --host localhost --database myapp --user sa --password '...' \ + --direction up --record-store ./migrations.json --dry-run +``` + +The parser takes a **dotted** `module.Class` qualified name (not the `module:function` form of the function API) plus `--direction up|down`, `--record-store`, `--dry-run`, `--describe`, `--list`, `--param KEY=VALUE`, `--all`, `--single-transaction` and `--async`. Connection may also come from `--named-connection`. `--single-transaction` wraps a whole batch and writes records only after the final commit — useful precisely because SQL Server can roll ordinary DDL back. + +Two wiring rules worth repeating here: + +- Passing a `NamedMigration` class FQN to the *function-style* API (`run_migration_group`, or the core `migrate` CLI) is an error with a hint to use this backend's `named-migration` command. Use the matching API from the [core comparison table](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md#1-two-apis-two-entry-points). +- For `MigrationRunner` (class API), `dry_run_sql` is assembled from the named-expression callback only; the function-style runner captures both statement paths. This is a core-level caveat, noted again so it is not missed when choosing an API. + +A complete class-style demo is [`02_named_migration.py`](../../examples/migration/02_named_migration.py). + +## 6. Local examples + +| Script | Demonstrates | +|---|---| +| [`01_function_migration.py`](../../examples/migration/01_function_migration.py) | SQL Server config + `@migration` + `run_migration_group`: dry run → real UP → DOWN with a `JSONFileMigrationRecordStore` | +| [`02_named_migration.py`](../../examples/migration/02_named_migration.py) | a `NamedMigration` subclass driven by `MigrationRunner` on SQL Server, plus the `named-migration` CLI wiring | + +These scripts are syntax-checked but require a reachable SQL Server to execute; see [docs/examples/README.md](../../examples/README.md) for the connection environment variables. diff --git a/docs/en_US/modeling/field_types.md b/docs/en_US/modeling/field_types.md new file mode 100644 index 00000000..31b84b67 --- /dev/null +++ b/docs/en_US/modeling/field_types.md @@ -0,0 +1,116 @@ +# SQL Server Field Types + +The core library defines the portable type classes. This backend adds SQL +Server's own types where no portable spelling exists, and supplies adapters for +values the driver does not return as a native Python type. This page lists the +backend-specific side only; see the core docs for how `UseSqlType` and field +declarations work in general. + +## Why backend-specific types exist + +Core's string types deliberately have no character-set dimension. SQL Server's +national-character types therefore get their own classes rather than being +treated as aliases: `NVARCHAR` stores UCS-2/UTF-16, while `VARCHAR` follows the +database collation's code page. They are not interchangeable. + +The SQL Server type classes live in +`rhosocial.activerecord.backend.impl.sqlserver.expression.types` and carry a +reserved `KIND_RESERVED = ("SQLServer",)` marker. + +| Backend type class | SQL type | Notes | +|--------------------|----------|-------| +| `SQLServerNVarCharType` | `NVARCHAR(n)` | variable-length Unicode string | +| `SQLServerNCharType` | `NCHAR(n)` | fixed-length, blank-padded Unicode string | +| `SQLServerNVarCharMaxType` | `NVARCHAR(MAX)` | unbounded Unicode string (lifts the 8000-byte cap) | +| `SQLServerVarBinaryType` | `VARBINARY(n)` | variable-length binary | +| `SQLServerVarBinaryMaxType` | `VARBINARY(MAX)` | unbounded binary | +| `SQLServerImageType` | `IMAGE` | legacy large binary (deprecated by SQL Server) | +| `SQLServerXmlType` | `XML` | native XML, carried as text | +| `SQLServerTinyIntType` | `TINYINT` | 0–255 integer | +| `SQLServerBitType` | `BIT` | SQL Server's boolean; note it is a boolean, not a bit string | +| `SQLServerUniqueIdentifierType` | `UNIQUEIDENTIFIER` | native GUID, maps to `uuid.UUID` | + +Pin a type on a field with the core `UseSqlType` annotation: + +```python +from typing import Annotated, ClassVar +from rhosocial.activerecord.base import FieldProxy, UseSqlType +from rhosocial.activerecord.model import ActiveRecord +from rhosocial.activerecord.backend.impl.sqlserver.expression.types import SQLServerNVarCharType + +class Article(ActiveRecord): + c: ClassVar[FieldProxy] = FieldProxy() + title: Annotated[str, UseSqlType(SQLServerNVarCharType(length=200))] + + @classmethod + def table_name(cls) -> str: + return "articles" +``` + +## Native types reached through adapters + +Some SQL Server column families need an adapter to convert between the driver's +value and a Python type. The backend ships these in +`rhosocial.activerecord.backend.impl.sqlserver.adapters`: + +| SQL Server type | Python carrier | Adapter | +|-----------------|----------------|---------| +| `MONEY`, `SMALLMONEY` | `decimal.Decimal` | default suggestion (never `float`) | +| `DATETIMEOFFSET` | `datetime.datetime` | `SQLServerDateTimeOffsetAdapter` | +| `XML` | `str` | `SQLServerXMLAdapter` | +| `HIERARCHYID` | `str` | `SQLServerHierarchyIdAdapter` | +| `GEOMETRY`, `GEOGRAPHY` | `Geometry` | `SQLServerGeometryAdapter` (`geography=True` for geography) | +| `UNIQUEIDENTIFIER` | `uuid.UUID` | default suggestion | +| `ROWVERSION` / `TIMESTAMP` | `bytes` | generated column excluded from DML | +| `JSON` | stored as `NVARCHAR(MAX)` text, carried as `dict` | default suggestion — SQL Server has no JSON type | + +An adapter is pinned with `UseAdapter`: + +```python +import uuid +from datetime import datetime +from typing import Annotated, ClassVar, Optional + +from rhosocial.activerecord.base import FieldProxy, UseAdapter +from rhosocial.activerecord.backend.impl.sqlserver.adapters import ( + SQLServerDateTimeOffsetAdapter, + SQLServerXMLAdapter, +) +from rhosocial.activerecord.model import ActiveRecord + +class Event(ActiveRecord): + c: ClassVar[FieldProxy] = FieldProxy() + dto: Annotated[Optional[datetime], UseAdapter(SQLServerDateTimeOffsetAdapter(), datetime)] + doc: Annotated[Optional[str], UseAdapter(SQLServerXMLAdapter(), str)] + uid: Optional[uuid.UUID] = None + + @classmethod + def table_name(cls) -> str: + return "events" +``` + +> 💡 *AI prompt: "Why is money mapped to Decimal instead of float, and why does ROWVERSION appear as bytes that the backend never writes?"* + +## Server-generated columns + +`ROWVERSION` (and its synonym `TIMESTAMP`) is maintained by the server: SQL +Server refuses an explicit value. Declare such fields as generated so the +INSERT/UPDATE column lists skip them: + +```python +class Document(ActiveRecord): + __table_generated_columns__ = ("rv",) + rv: Optional[bytes] = None +``` + +Likewise, a caller-supplied key that happens to be an `INT` (not `IDENTITY`) +must be marked as application-assigned with a `UseFieldGenerator` so core keeps +it in the INSERT rather than expecting the server to fill it. + +## Type suggestion and capability probes + +The dialect merges a suggestion table mapping Python types to preferred SQL +Server types, and exposes `supports_data_type_sqlserver_*` probes (for example +`supports_data_type_sqlserver_nvarchar`, `..._xml`, `..._uniqueidentifier`). +These are capability statements about the backend, useful when generating DDL +or validating a model before it reaches the server. diff --git a/docs/en_US/querying/output_and_merge.md b/docs/en_US/querying/output_and_merge.md new file mode 100644 index 00000000..5d827e3c --- /dev/null +++ b/docs/en_US/querying/output_and_merge.md @@ -0,0 +1,85 @@ +# OUTPUT, MERGE and Query Dialect + +This chapter covers the parts of DML and SELECT where SQL Server's dialect +differs from portable SQL. Core's query builder is unchanged; what differs is +the T-SQL the dialect renders and a handful of capability answers. + +## OUTPUT / RETURNING + +SQL Server returns affected rows with the `OUTPUT` clause. The backend declares +`supports_output_clause() == True` and renders DML through the OUTPUT path, so a +`RETURNING`-style call maps onto native T-SQL rather than a second SELECT. + +Expressions live in `expression/output.py` and `expression/dml.py`, with the +mixin in `mixins/output.py` / `mixins/returning.py`. A typical statement returns +the inserted identity value: + +```sql +INSERT INTO [users] ([name]) OUTPUT INSERTED.[id] VALUES (?); +``` + +```python +sql, params = insert_expr.to_sql() # preview before running +result = backend.execute(sql, params, options=dml_options) +print(result.data) # rows projected by OUTPUT +``` + +> 💡 *AI prompt: "Why does the backend use OUTPUT to return generated keys, and how does that differ from running a second SELECT?"* + +## MERGE + +`supports_merge_statement()` is `True` — SQL Server has had `MERGE` since 2008. +The `merge` mixin and `expression/` support `MERGE ... WHEN MATCHED / WHEN NOT +MATCHED`, with backend-local extras `supports_merge_output()` and +`supports_merge_holdlock()` controlling whether `OUTPUT` and the `HOLDLOCK` +hint can be attached. `MERGE` is the backend's native upsert route. + +## Locking + +SQL Server has no `FOR UPDATE` syntax, but the backend still answers +`supports_for_update() == True`: it renders row locks as table hints. + +```sql +SELECT ... FROM [users] WITH (UPDLOCK, ROWLOCK); +``` + +`skip_locked` adds `READPAST` and is gated to SQL Server 2019+ via +`supports_for_update_skip_locked()`. A lock strength other than `UPDATE` raises +`UnsupportedFeatureError` at render time; the refusal names the SQL phrase it +cannot express. + +## Pagination + +`format_limit_offset()` renders `OFFSET ... FETCH NEXT ... ROWS ONLY` (with the +required `ORDER BY`), gated to SQL Server 2012+. Two portability flags are +explicitly `False`: + +- `supports_fetch_with_ties()` — `WITH TIES` exists only with `TOP`, not with + `OFFSET FETCH`. +- `supports_nulls_first_last()` — SQL Server has no `NULLS FIRST` / `NULLS LAST` + syntax. + +`TOP`, `TABLESAMPLE`, `PIVOT` / `UNPIVOT`, window functions, CTEs (including +recursive), grouping sets, lateral constructs and set operations are all part +of the dialect; the corresponding `supports_*` answers live in the mixins. + +## JSON, XML and functions + +- **JSON is stored as text** (`NVARCHAR(MAX)`); there is no native JSON column + type. `supports_json_type()` answers from the 2016 floor because that is when + the JSON *functions* arrive. +- There is no `->` operator: JSON extraction renders as `JSON_VALUE(col, 'path')`. +- `supports_json_table()` is **`False`** even on recent servers. The formatter + refuses unconditionally and points at `OPENJSON`, which is fully implemented + as `SQLServerOpenJsonExpression`. Advertising `JSON_TABLE` would promise a + statement the backend cannot render. +- `XML`, `HIERARCHYID`, spatial and math/string/date functions are supplied as + native expressions under `expression/` and `functions/`. + +## Query hints and diagnostics + +`WITH (...)` table hints, `OPTION (...)` query hints and `INDEX` / `FORCESEEK` +style hints are available through `mixins/table_hint.py` and +`expression/option_hint.py`. `EXPLAIN` maps to execution-plan output, with +`supports_explain_analyze()` / `supports_explain_format()` answering for the +supported forms. diff --git a/docs/en_US/testing/README.md b/docs/en_US/testing/README.md new file mode 100644 index 00000000..fce9028b --- /dev/null +++ b/docs/en_US/testing/README.md @@ -0,0 +1,72 @@ +# Testing + +Test commands and provider registration for the family of projects are defined +centrally in the core repository's `testing.md`. This page records only the SQL +Server-specific facts: the driver, the local server image and the scope of +tests you are expected to run locally. + +## Environment + +| Item | Value | +|------|-------| +| Python | 3.14 (default for the local venv) | +| Driver | `pyodbc` (+ ODBC Driver 17/18) | +| Local server | SQL Server 2022 image in `docker-compose.yml` | +| Async | `aioodbc`; the suite runs isolation/transaction tests through both paths | + +Bring up a local server with the repository's Compose file, then let the +fixtures point at it. Connection parameters for tests come from environment +variables such as `SQLSERVER_HOST`, `SQLSERVER_PORT`, `SQLSERVER_DATABASE`, +`SQLSERVER_USERNAME`, `SQLSERVER_PASSWORD` and `SQLSERVER_DRIVER`. + +## Running tests + +The suite needs the `tests/` directory on `PYTHONPATH` so that the provider +registry is importable: + +```bash +$env:PYTHONPATH = 'src;tests' +pytest tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct -q +``` + +Use the repository's `/test`, `/test-feature ` and `/lint` shortcuts +where available. Tests are organised by feature (`backend/construct`, +`backend/execute`, `connection`, `logging`, `adapters`, and so on); the +`providers/` registration supplies the backend to the shared testsuite. + +## Live vs offline tests + +- **Offline** suites replace catalogue reads with canned rows and assert every + rendered statement. They need no database and are the default local check. +- **Live** tests (for example the partition coverage under + `feature/backend/execute/partition/test_partition_live.py`) exercise + `CREATE PARTITION FUNCTION` / `SCHEME`, `SPLIT`, `MERGE`, `SWITCH` and + catalogue reads against the SQL Server 2022 image. A live test **skips — + rather than passes —** when no scenario is configured or the server cannot be + reached, so a skipped live test is not evidence that the feature works. + +## Local test scope + +> ⚠️ **Never run the full suite locally.** A single `pytest tests/` collection +> takes minutes and conflicts with the task time budget. Full-matrix testing +> belongs to remote CI. + +Local runs are limited to targeted checks within the task at hand: + +- importing a single module; +- asserting a signature or a single behaviour; +- a single test file or a single test case; +- `python -m py_compile` on changed example scripts. + +The `docs/examples/` scripts are syntax-checked this way. They are not executed +locally because no SQL Server is available to the documentation build; their +import paths and model declarations are nevertheless written against this +backend's real classes. + +## Sibling testsuite installation + +When wiring the shared testsuite for local cross-repo integration, install it by explicit local +path rather than relying on a published version from an index — a published +version may be older and lack modules the current backend expects. Install +sibling packages the same way so the editable source tree, not a stale +published wheel, is what gets imported. diff --git a/docs/en_US/transactions/README.md b/docs/en_US/transactions/README.md new file mode 100644 index 00000000..efd04356 --- /dev/null +++ b/docs/en_US/transactions/README.md @@ -0,0 +1,69 @@ +# Transactions + +SQL Server transactions are handled by `SQLServerTransactionManager` (and its +async counterpart). It extends core's `TransactionManager` with SNAPSHOT +isolation, `SAVE TRANSACTION` savepoints and SQL Server-specific isolation +mapping. The core transaction protocol is described in the core docs; this page +covers only this backend's portion. + +```python +with backend.transaction(): + user = User(name="Alice") + user.save() + # commit on normal exit, rollback on exception +``` + +## Isolation levels + +The backend defines `SQLServerIsolationLevel` with five values and maps core's +`IsolationLevel` onto them: + +| `SQLServerIsolationLevel` | Core mapping | Notes | +|---------------------------|--------------|-------| +| `READ_UNCOMMITTED` | `IsolationLevel.READ_UNCOMMITTED` | | +| `READ_COMMITTED` | `IsolationLevel.READ_COMMITTED` | SQL Server default | +| `REPEATABLE_READ` | `IsolationLevel.REPEATABLE_READ` | | +| `SERIALIZABLE` | `IsolationLevel.SERIALIZABLE` | | +| `SNAPSHOT` | — (backend-specific) | row-versioning isolation | + +`SNAPSHOT` has no portable equivalent, so it is selected with the dedicated +`snapshot=True` argument on `begin()` (or the corresponding transaction +context option). When a level is chosen, the manager emits +`SET TRANSACTION ISOLATION LEVEL ` before the real `BEGIN TRANSACTION`. +`SNAPSHOT` requires `ALLOW_SNAPSHOT_ISOLATION ON` on the database — a server +setting the backend does not change on the caller's behalf. + +> 💡 *AI prompt: "What extra database setting must be enabled before SNAPSHOT isolation works, and why is it not the backend's job to enable it?"* + +## Savepoints + +Nested transactions use SQL Server's `SAVE TRANSACTION` syntax rather than a new +`BEGIN`. The manager tracks active savepoint names and supports: + +- `savepoint(name=None)` — create one (an auto name `sp_N` is generated when + none is given); +- `rollback(savepoint=name)` — roll back to it via `ROLLBACK TRANSACTION name`; +- release — a no-op on SQL Server, since savepoints need no explicit release. + +Creating a savepoint outside an active transaction raises `TransactionError`. +A repeated name is rejected. Only the `UPDATE` lock strength is supported by +the locking mixin (see [OUTPUT, MERGE and Query Dialect](../querying/output_and_merge.md)). + +## Deadlocks and retries + +SQL Server errors are translated from `pyodbc` exceptions into the framework's +error hierarchy by `error_mapping.py`; the async path has the same mapping. +Deadlocks and timeouts therefore surface as framework errors that callers can +catch and retry at the unit-of-work level. Keep retry logic around the whole +transaction context — re-running a half-completed unit of work is only safe when +the transaction rolled back cleanly. + +`query_timeout` on the connection config (default `0`, no limit) bounds how long +a statement may run; see [Connection configuration](../installation/configuration.md#timeouts--connection-pool). + +## Async parity + +`AsyncSQLServerTransactionManager` mirrors the sync manager using `aioodbc`. +Isolation levels, savepoints and the snapshot flag behave identically; only +`await` differs. The backend's test suite runs the same isolation-effect tests +through both paths. diff --git a/docs/examples/01_connection_and_config.py b/docs/examples/01_connection_and_config.py new file mode 100644 index 00000000..a5bcb03f --- /dev/null +++ b/docs/examples/01_connection_and_config.py @@ -0,0 +1,56 @@ +# docs/examples/01_connection_and_config.py +"""Connect to SQL Server and inspect what the backend can do. + +Run with a reachable SQL Server; see docs/examples/README.md for the +environment variables used for connection details. +""" +import os + +from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig + + +def make_config() -> SQLServerConnectionConfig: + """Build the connection config used by this example.""" + return SQLServerConnectionConfig( + host=os.environ.get("SQLSERVER_HOST", "localhost"), + port=int(os.environ.get("SQLSERVER_PORT", "1433")), + database=os.environ.get("SQLSERVER_DATABASE", "test_db"), + username=os.environ.get("SQLSERVER_USERNAME", "sa"), + password=os.environ.get("SQLSERVER_PASSWORD", ""), + driver=os.environ.get("SQLSERVER_DRIVER", "ODBC Driver 18 for SQL Server"), + encrypt=os.environ.get("SQLSERVER_ENCRYPT", "true").lower() == "true", + trust_server_certificate=( + os.environ.get("SQLSERVER_TRUST_SERVER_CERTIFICATE", "false").lower() == "true" + ), + ) + + +def main() -> None: + config = make_config() + + # __repr__ masks the password; show that, not the raw connection string. + print("Config:", repr(config)) + print("ODBC driver:", config.driver) + + backend = SQLServerBackend(connection_config=config) + backend.connect() + try: + # Refresh the detected server version so version-gated probes answer + # for the server actually reached. + backend.introspect_and_adapt() + + dialect = backend.dialect + print("Dialect:", dialect.name) + print("Server version:", dialect.get_server_version()) + print("Introspection supported:", dialect.supports_introspection()) + print("SQL Graph supported:", dialect.supports_sql_graph()) + print("Temporal tables supported:", dialect.supports_system_versioning()) + print("DDL extraction supported:", dialect.supports_ddl_extraction()) + finally: + backend.disconnect() + print("Disconnected.") + + +if __name__ == "__main__": + main() diff --git a/docs/examples/02_declarative_model_crud.py b/docs/examples/02_declarative_model_crud.py new file mode 100644 index 00000000..ac44f094 --- /dev/null +++ b/docs/examples/02_declarative_model_crud.py @@ -0,0 +1,68 @@ +# docs/examples/02_declarative_model_crud.py +"""Declarative ActiveRecord model backed by SQL Server. + +This script binds a model to this backend, creates its table, saves a row and +runs a typed query. It also previews the generated T-SQL without executing it. +Run against a scratch database (see docs/examples/README.md). +""" +import os +from typing import Annotated, ClassVar + +from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig +from rhosocial.activerecord.backend.impl.sqlserver.expression.types import SQLServerNVarCharType +from rhosocial.activerecord.base import FieldProxy, UseSqlType +from rhosocial.activerecord.field import DefaultTimestampMixin, IntegerPKMixin +from rhosocial.activerecord.model import ActiveRecord + + +class User(IntegerPKMixin, DefaultTimestampMixin, ActiveRecord): + """A SQL Server-backed model using Unicode text columns. + + ``IntegerPKMixin`` renders the auto-increment key as ``INT IDENTITY`` on + this backend, and ``SQLServerNVarCharType`` pins the columns to ``NVARCHAR`` + rather than the collation-dependent ``VARCHAR``. + """ + + c: ClassVar[FieldProxy] = FieldProxy() + + name: Annotated[str, UseSqlType(SQLServerNVarCharType(length=100))] + email: Annotated[str, UseSqlType(SQLServerNVarCharType(length=255))] + age: int = 0 + + @classmethod + def table_name(cls) -> str: + return "example_users" + + +def main() -> None: + config = SQLServerConnectionConfig( + host=os.environ.get("SQLSERVER_HOST", "localhost"), + port=int(os.environ.get("SQLSERVER_PORT", "1433")), + database=os.environ.get("SQLSERVER_DATABASE", "test_db"), + username=os.environ.get("SQLSERVER_USERNAME", "sa"), + password=os.environ.get("SQLSERVER_PASSWORD", ""), + driver=os.environ.get("SQLSERVER_DRIVER", "ODBC Driver 18 for SQL Server"), + ) + + # Bind the model to this backend and create the table from the declaration. + User.configure(config, SQLServerBackend) + User.create_table() + + # Create: the key is assigned by SQL Server and returned via OUTPUT. + alice = User(name="Alice", email="alice@example.com", age=30) + alice.save() + print("Inserted id:", alice.id) + + # Query with the type-safe field proxy. + adults = User.query().where(User.c.age >= 18).all() + print("Adults:", [user.name for user in adults]) + + # Preview the generated T-SQL before it runs. + sql, params = User.query().where(User.c.age >= 18).to_sql() + print("SQL:", sql) + print("Params:", params) + + +if __name__ == "__main__": + main() diff --git a/docs/examples/03_introspection_and_partition.py b/docs/examples/03_introspection_and_partition.py new file mode 100644 index 00000000..f914a8f4 --- /dev/null +++ b/docs/examples/03_introspection_and_partition.py @@ -0,0 +1,89 @@ +# docs/examples/03_introspection_and_partition.py +"""Introspect a SQL Server database and preview partition maintenance. + +All partition operations here use dry runs, so the script reads the catalogue +but does not change schema. Run against a scratch database (see +docs/examples/README.md). +""" +import os +from datetime import date + +from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig +from rhosocial.activerecord.backend.impl.sqlserver.partition import ( + SQLServerPartitionMaintenance, + SQLServerPartitionPlan, +) + + +def make_backend() -> SQLServerBackend: + config = SQLServerConnectionConfig( + host=os.environ.get("SQLSERVER_HOST", "localhost"), + port=int(os.environ.get("SQLSERVER_PORT", "1433")), + database=os.environ.get("SQLSERVER_DATABASE", "test_db"), + username=os.environ.get("SQLSERVER_USERNAME", "sa"), + password=os.environ.get("SQLSERVER_PASSWORD", ""), + driver=os.environ.get("SQLSERVER_DRIVER", "ODBC Driver 18 for SQL Server"), + ) + backend = SQLServerBackend(connection_config=config) + backend.connect() + backend.introspect_and_adapt() + return backend + + +def show_introspection(backend: SQLServerBackend) -> None: + introspector = backend.introspector + + info = introspector.get_database_info() + print("Database:", info.name, info.version, info.collation) + + for schema in introspector.list_schemas(): + print("Schema:", schema.name, "owner:", schema.owner) + + for table in introspector.list_tables(): + print("Table:", table.name, table.table_type.value) + + for column in introspector.list_columns("example_users"): + print("Column:", column.name, column.data_type_full, column.nullable.value) + + if backend.dialect.supports_unused_indexes_detection(): + for index in introspector.list_unused_indexes(): + print("Unused index:", f"{index.table_name}.{index.index_name}") + + +def show_partition_plan(backend: SQLServerBackend) -> None: + plan = SQLServerPartitionPlan( + function="pf_example_logs", + data_type="DATE", + boundaries=(date(2026, 1, 1), date(2026, 2, 1), date(2026, 3, 1)), + scheme="ps_example_logs", + all_filegroup="PRIMARY", + ) + maintenance = SQLServerPartitionMaintenance(backend) + + # Catalogue report: functions, schemes, tables and per-partition ranges. + report = maintenance.list(plan, table="example_logs", schema="dbo") + print("Partition functions:", report.functions) + print("Ranges:", report.ranges) + + # Checks only; never repairs. + report = maintenance.validate(plan, table="example_logs", schema="dbo") + print("Issues:", report.issues) + + # Render the SPLIT statements without executing them (SQL Server DDL + # auto-commits, so a dry run is the safe way to review the plan). + report = maintenance.ensure(plan, dry_run=True) + print("Planned operations:", report.operations) + + +def main() -> None: + backend = make_backend() + try: + show_introspection(backend) + show_partition_plan(backend) + finally: + backend.disconnect() + + +if __name__ == "__main__": + main() diff --git a/docs/examples/README.md b/docs/examples/README.md new file mode 100644 index 00000000..8cdc8630 --- /dev/null +++ b/docs/examples/README.md @@ -0,0 +1,38 @@ +# Runnable Examples + +Three small scripts show this backend's classes and SQL Server-specific +behaviour. They are **syntax-checked** with `python -m py_compile` but are not +executed by the documentation build: a reachable SQL Server is required. + +They use environment variables for connection details, so no credentials are +hard-coded: + +| Variable | Meaning | Default used here | +|----------|---------|-------------------| +| `SQLSERVER_HOST` | server host | `localhost` | +| `SQLSERVER_PORT` | server port | `1433` | +| `SQLSERVER_DATABASE` | database | `test_db` | +| `SQLSERVER_USERNAME` / `SQLSERVER_PASSWORD` | SQL authentication | `sa` / empty | +| `SQLSERVER_DRIVER` | ODBC driver name | `ODBC Driver 18 for SQL Server` | + +Run a script from the repository root: + +```bash +$env:SQLSERVER_DATABASE = 'demo' +python docs/examples/01_connection_and_config.py +``` + +> ⚠️ Use a scratch database. The DDL example creates and drops a table. + +## Scripts + +| Script | What it demonstrates | +|--------|----------------------| +| [`01_connection_and_config.py`](01_connection_and_config.py) | `SQLServerConnectionConfig`, ODBC connection string, connect/disconnect, version-aware capability probing | +| [`02_declarative_model_crud.py`](02_declarative_model_crud.py) | declarative `ActiveRecord` model bound with `configure(..., SQLServerBackend)`, `create_table`, `save`, typed queries, SQL preview | +| [`03_introspection_and_partition.py`](03_introspection_and_partition.py) | `backend.introspector` catalogue reads, capability gates, `SQLServerPartitionPlan` and `SQLServerPartitionMaintenance` | + +Migration-specific scripts live in their own folder: +[migration examples](migration/README.md) (function-style and class-style, +using this backend's SQL Server config). For the theory behind the general +scripts, see the [en_US documentation](../en_US/README.md). diff --git a/docs/examples/migration/01_function_migration.py b/docs/examples/migration/01_function_migration.py new file mode 100644 index 00000000..b76bc1db --- /dev/null +++ b/docs/examples/migration/01_function_migration.py @@ -0,0 +1,101 @@ +# docs/examples/migration/01_function_migration.py +"""Function-style migrations on SQL Server: dry run -> UP -> DOWN. + +Requires a reachable SQL Server (see docs/examples/README.md for the +connection environment variables). Uses this backend's own config/backend +classes and a JSONFileMigrationRecordStore. The migration system itself is +documented in the core migration chapter. +""" +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.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig +from rhosocial.activerecord.backend.migration import ( + MigrationDirection, + migration, + run_migration_group, +) +from rhosocial.activerecord.backend.migration.record import JSONFileMigrationRecordStore +from rhosocial.activerecord.model import ActiveRecord + + +# ActiveRecord already mixes in MigrationMixin, so create_table_statement() +# and drop_table_statement() are available on every model. +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))] + + +@migration("v001_create_users", description="create the initial users table on SQL Server") +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)) + + +def make_config() -> SQLServerConnectionConfig: + """Build the connection config for this example from environment variables.""" + return SQLServerConnectionConfig( + host=os.environ.get("SQLSERVER_HOST", "localhost"), + port=int(os.environ.get("SQLSERVER_PORT", "1433")), + database=os.environ.get("SQLSERVER_DATABASE", "test_db"), + username=os.environ.get("SQLSERVER_USERNAME", "sa"), + password=os.environ.get("SQLSERVER_PASSWORD", ""), + driver=os.environ.get("SQLSERVER_DRIVER", "ODBC Driver 18 for SQL Server"), + trust_server_certificate=( + os.environ.get("SQLSERVER_TRUST_SERVER_CERTIFICATE", "false").lower() == "true" + ), + ) + + +def main() -> None: + rec_path = tempfile.mktemp(suffix=".json") + backend = SQLServerBackend(connection_config=make_config()) + backend.connect() + try: + # Version gates consult the detected server version; refresh it first. + backend.introspect_and_adapt() + print("Server version:", backend.dialect.get_server_version()) + + store = JSONFileMigrationRecordStore(rec_path) + fqn = f"{__name__}:create_users" + + # 1) dry run — renders T-SQL through this backend's dialect, writes nothing + preview = run_migration_group(backend, [fqn], 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 — applies the DDL inside a transaction and writes a record + up = run_migration_group(backend, [fqn], record_store=store) + print("\n== UP ==") + print(" applied:", up.applied, "versions:", up.versions) + print(" records written:", up.records_written) + print(" applied versions:", [r.version for r in store.get_applied()]) + + # 3) DOWN — rolls back and clears the applied version + down = run_migration_group( + backend, [fqn], 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..b1dcad4c --- /dev/null +++ b/docs/examples/migration/02_named_migration.py @@ -0,0 +1,98 @@ +# docs/examples/migration/02_named_migration.py +"""Class-style migration on SQL Server, driven by MigrationRunner. + +The migration system itself is documented in the core migration chapter; +this script only shows the SQL Server wiring. The same class is what this +backend's `named-migration` command resolves by its dotted qualified name: + + python -m rhosocial.activerecord.backend.impl.sqlserver named-migration \ + myapp.migrations.CreateUsers \ + --database myapp --direction up --record-store migrations.json + +Requires a reachable SQL Server (see docs/examples/README.md for the +connection environment variables). +""" +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.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig +from rhosocial.activerecord.backend.migration import ( + JSONFileMigrationRecordStore, + MigrationContext, + MigrationDirection, + MigrationRunner, + NamedMigration, +) +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 CreateUsers(NamedMigration): + """A single class-style migration; the version is its unique identifier.""" + + version = "v001_create_users" + + def up(self, ctx: MigrationContext) -> None: + ctx.apply(User.create_table_statement(backend=ctx.backend)) + + def down(self, ctx: MigrationContext) -> None: + ctx.apply(User.drop_table_statement(if_exists=True, backend=ctx.backend)) + + +def make_config() -> SQLServerConnectionConfig: + """Build the connection config for this example from environment variables.""" + return SQLServerConnectionConfig( + host=os.environ.get("SQLSERVER_HOST", "localhost"), + port=int(os.environ.get("SQLSERVER_PORT", "1433")), + database=os.environ.get("SQLSERVER_DATABASE", "test_db"), + username=os.environ.get("SQLSERVER_USERNAME", "sa"), + password=os.environ.get("SQLSERVER_PASSWORD", ""), + driver=os.environ.get("SQLSERVER_DRIVER", "ODBC Driver 18 for SQL Server"), + trust_server_certificate=( + os.environ.get("SQLSERVER_TRUST_SERVER_CERTIFICATE", "false").lower() == "true" + ), + ) + + +def main() -> None: + rec_path = tempfile.mktemp(suffix=".json") + backend = SQLServerBackend(connection_config=make_config()) + backend.connect() + try: + # Version gates consult the detected server version; refresh it first. + backend.introspect_and_adapt() + + store = JSONFileMigrationRecordStore(rec_path) + # NamedMigration FQNs are dotted: module.Class (not module:function). + fqn = f"{__name__}.CreateUsers" + runner = MigrationRunner(fqn) + + up = runner.run(backend, MigrationDirection.UP, record_store=store) + print("== UP ==") + print(" version:", up.version, "success:", up.success) + print(" applied versions:", [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 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/README.md b/docs/examples/migration/README.md new file mode 100644 index 00000000..a53c9aeb --- /dev/null +++ b/docs/examples/migration/README.md @@ -0,0 +1,28 @@ +# Migration Examples (SQL Server) + +Runnable-style examples for migrations on the SQL Server backend. The +migration **system** is documented in the +[core migration chapter](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md); +the SQL Server-specific concerns are in +[docs/en_US/migration/](../../en_US/migration/README.md) ([中文](../../zh_CN/migration/README.md)). + +These scripts are **syntax-checked** with `python -m py_compile` but are not +executed by the documentation build: a reachable SQL Server is required. They +read connection details from the `SQLSERVER_*` environment variables described +in [docs/examples/README.md](../README.md), so no credentials are hard-coded. + +Run a script from the repository root: + +```bash +$env:SQLSERVER_DATABASE = 'demo' +python docs/examples/migration/01_function_migration.py +``` + +> ⚠️ Use a scratch database. The examples create and drop a table. + +## Scripts + +| Script | Demonstrates | +|---|---| +| [`01_function_migration.py`](01_function_migration.py) | `SQLServerConnectionConfig` + `SQLServerBackend`, `@migration` with `ctx.apply()`, and `run_migration_group`: dry run → real UP → DOWN with a `JSONFileMigrationRecordStore` | +| [`02_named_migration.py`](02_named_migration.py) | a `NamedMigration` subclass driven by `MigrationRunner` on SQL Server, plus the `named-migration` CLI wiring | diff --git a/docs/zh_CN/README.md b/docs/zh_CN/README.md new file mode 100644 index 00000000..2624e17c --- /dev/null +++ b/docs/zh_CN/README.md @@ -0,0 +1,12 @@ + +# rhosocial-activerecord-sqlserver 文档(中文) + +本页介绍 SQL Server 后端特有的内容。ActiveRecord 框架本身(模型、字段、查询、关系、迁移)属于[核心库文档](https://github.com/rhosocial/python-activerecord/tree/main/docs/zh_CN),此处不再重复。 + +## 目录 + +1. **[迁移](migration/README.md)** + * **[SQL Server 上的迁移](migration/README.md)**: 后端配置、事务性 DDL、版本门控以及 CLI 接线(迁移系统本身见核心文档) + * **迁移示例**: [英文示例索引](../examples/migration/README.md) + +> 📖 当前中文树仅包含上述页面;其余章节请先参阅 [英文文档](../en_US/README.md)。 diff --git a/docs/zh_CN/migration/README.md b/docs/zh_CN/migration/README.md new file mode 100644 index 00000000..39685557 --- /dev/null +++ b/docs/zh_CN/migration/README.md @@ -0,0 +1,157 @@ +# SQL Server 上的迁移 + +> 📖 **范围**:本页**仅介绍在本后端上运行 ActiveRecord 迁移时特有的内容** —— 配置 SQL Server(pyodbc)后端、事务性 DDL 行为、版本门控,以及两种编写 API 如何接入本后端的 CLI。 +> +> 迁移**系统本身** —— 两套 API、术语、排序与依赖校验、版本记录、试运行的 SQL 捕获、异常层级以及核心的 `migrate` CLI —— 属于[核心库迁移章节](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md)。此处**不再重复**。如果你刚接触迁移,请先阅读该章节。 +> +> 本页及[docs/examples/migration/](../../examples/migration/README.md)中的所有示例均使用 SQL Server。 + +目录: + +1. [配置后端](#1-configuring-the-backend) +2. [SQL Server 上的事务性 DDL](#2-transactional-ddl-on-sql-server) +3. [版本门控的特性与类型](#3-version-gated-features-and-types) +4. [函数式迁移(run_migration_group)](#4-function-style-migrations-run_migration_group) +5. [类式迁移与 named-migration CLI](#5-class-style-migrations-and-the-named-migration-cli) +6. [本地示例](#6-local-examples) + +> 💡 **AI 提示词:** "我有一个由 `@migration` 装饰的函数。请演示如何针对 SQL Server 先以试运行(dry run)方式执行它,再真正执行它,但不要重复讲解迁移系统的工作原理。" + + + +## 1. 配置后端 + +迁移与任何其他操作使用相同的后端和连接配置。构造 `SQLServerConnectionConfig`,将其传给 `SQLServerBackend`,建立连接,并刷新检测到的服务器版本: + +```python +from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig + +config = SQLServerConnectionConfig( + host="localhost", + port=1433, + database="myapp", + username="sa", + password="...", # or trusted_connection=True + driver="ODBC Driver 18 for SQL Server", +) +backend = SQLServerBackend(connection_config=config) +backend.connect() +backend.introspect_and_adapt() # refresh the detected version before any version gate +``` + +本后端特有的要点: + +- 同步路径通过 `SQLServerBackend` 使用 `pyodbc`;异步路径通过 `AsyncSQLServerBackend` 使用 `aioodbc`,并配合 `run_migration_group_async()`。完整的配置接口(包括 Windows 身份验证、ODBC 驱动与 TLS)见[连接配置](../../en_US/installation/configuration.md)。 +- 不要硬编码凭据。示例从 `SQLSERVER_*` 环境变量读取连接信息;CLI 则支持 `--named-connection` 来达到同样目的。 +- 在应用代码中渲染受版本门控的 DDL 之前,先调用 `backend.introspect_and_adapt()`。门控依据的是*检测到的*服务器版本,版本过时会导致门控按错误的版本底线作答。本后端的 CLI 在进入时会执行该调用;脚本必须自行调用。 +- 连接的 `autocommit` 设置保持默认值即可。迁移组的事务边界由 `transaction_mode` 决定(见下一节),而非连接级别的标志。 + + + +## 2. SQL Server 上的事务性 DDL + +**SQL Server 通常支持事务性 DDL。** 普通的模式语句 —— `CREATE TABLE`、`ALTER TABLE`、`DROP TABLE`、`CREATE INDEX` 等 —— 都会参与用户事务,并在事务回滚时一并回滚。因此,迁移组默认的 `TransactionMode.AUTO` 在本后端上提供原子性的组:中途失败不会应用任何内容,也不会写入版本记录。SQL Server 方言没有 `supports_transactional_ddl()` 覆盖实现,因此运行器报告 DDL 为事务性(默认值),这与上述行为一致。 + +编写迁移时需要注意的几点: + +- **并非所有语句都能出现在显式事务中。** 服务器级与数据库级操作,例如 `CREATE DATABASE`、`DROP DATABASE`、`RESTORE DATABASE` 以及若干 `DBCC` 命令,在事务中会被拒绝。请勿将此类语句放入迁移组,或显式地在事务之外执行它们;不要以为"DDL 是事务性的"就能让每条 `CREATE ...` 都安全。 +- **耗时较长的 DDL 会持有锁。** 迁移可能因等待排他架构锁而阻塞。请通过连接配置中的 `query_timeout` 限定运行时长(默认值 `0` 表示无限制),而不要依赖客户端超时。 +- **`SNAPSHOT` 不会自动生效。** 如果为迁移事务选择快照隔离,数据库必须已经启用 `ALLOW_SNAPSHOT_ISOLATION ON`;本后端不会替你修改该设置。隔离级别映射、保存点与死锁重试见[事务](../../en_US/transactions/README.md)。 + +`TransactionMode.AUTO` / `STEP` / `NONE` 的含义、版本记录的写入以及失败元数据(`transactional_ddl`、`executed` 等)均在核心章节中说明;本页只陈述这些模式在本后端上的*实际效果*。 + + + +## 3. 版本门控的特性与类型 + +方言通过 `supports_*` 探测和 `version_at_least(...)` 回答能力问题,版本底线常量位于 `mixins/version_constants.py`。以下是常见的影响 DDL 的版本底线: + +- 序列(sequence)—— 2012(`SQL_SERVER_2012`) +- JSON 函数 / `supports_json_type()` —— 2016(`SQL_SERVER_2016`) +- 时态表(temporal table)/ `supports_system_versioning()` —— 2016 +- SQL Graph(node/edge 表)/ `supports_sql_graph()` —— 2017(`SQL_SERVER_2017`) +- 图最短路径 —— 2019(`SQL_SERVER_2019`) +- 列存储索引上的 `ORDER (...)` —— 2022(`SQL_SERVER_2022`) + +在生成受版本门控的 DDL **之前**先检查门控;门控关闭意味着表达式不会渲染(或抛出 `UnsupportedFeatureError`,由迁移层转换为 `MigrationDialectError`): + +```python +from rhosocial.activerecord.backend.impl.sqlserver.mixins.version_constants import SQL_SERVER_2016 + +backend.introspect_and_adapt() +dialect = backend.dialect + +if dialect.supports_system_versioning() and dialect.version_at_least(SQL_SERVER_2016): + ... # safe to emit version-gated DDL +else: + ... # take a deliberate fallback, or fail deliberately +``` + +请注意,门控回答的是"能否向*服务器*提出该问题",而不是当前登录名是否拥有相应权限。完整的版本底线表以及"门控关闭、版本底线、永久不支持的语句"之间的区别,见[能力门控](../../en_US/capabilities/README.md)。 + + + +## 4. 函数式迁移(run_migration_group) + +新工作应使用函数式 API。本后端只提供连接与方言;装饰器、组运行器、记录存储、排序规则和试运行语义全部是核心特性,详见[核心迁移章节](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md)。 + +SQL Server 上的最小形态如下: + +```python +@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)) + + +backend = SQLServerBackend(connection_config=config) +backend.connect() +backend.introspect_and_adapt() + +# dry run — renders T-SQL through this backend's dialect, writes nothing +preview = run_migration_group(backend, [f"{__name__}:create_users"], dry_run=True) +print(preview.dry_run_sql, preview.dry_run_total) + +# real run — applies the DDL inside a transaction and writes a version record +result = run_migration_group(backend, [f"{__name__}:create_users"], record_store=store) +``` + +由于 DDL 由本后端的方言渲染,你检查的试运行 SQL 就是即将执行的真实 T-SQL —— 包括带 `[方括号]` 的标识符、`IDENTITY(1,1)` 以及该服务器的类型写法。本后端没有专用的试运行标志;`dry_run=True` 与核心章节所述的选项完全一致。 + +完整且通过语法检查的脚本见 [`01_function_migration.py`](../../examples/migration/01_function_migration.py)。 + + + +## 5. 类式迁移与 named-migration CLI + +类式(`NamedMigration`)路径为兼容旧版而保留。本后端通过 [`cli/named_migration.py`](../../../src/rhosocial/activerecord/backend/impl/sqlserver/cli/named_migration.py) 将其接入自身 CLI:该子命令使用共享的连接参数构造 `SQLServerBackend`,并在委托给核心的 `handle_named_migration` 之前调用 `introspect_and_adapt()`。 + +```bash +python -m rhosocial.activerecord.backend.impl.sqlserver named-migration \ + myapp.migrations.v001.CreateUsersTable \ + --host localhost --database myapp --user sa --password '...' \ + --direction up --record-store ./migrations.json --dry-run +``` + +该解析器接受以点分隔的 `module.Class` 限定名(不是函数 API 使用的 `module:function` 形式),以及 `--direction up|down`、`--record-store`、`--dry-run`、`--describe`、`--list`、`--param KEY=VALUE`、`--all`、`--single-transaction` 和 `--async`。连接信息也可以来自 `--named-connection`。`--single-transaction` 会将整批操作包在一个事务中,并只在最终提交后写入记录 —— 鉴于 SQL Server 可以回滚普通 DDL,这个选项在该场景下很有用。 + +这里有两条值得重申的接线规则: + +- 将 `NamedMigration` 类的 FQN 传给*函数式* API(`run_migration_group` 或核心的 `migrate` CLI)会报错,并提示改用本后端的 `named-migration` 命令。请依据[核心对比表](https://github.com/rhosocial/python-activerecord/blob/main/docs/en_US/migration/README.md#1-two-apis-two-entry-points)选择对应的 API。 +- 对于 `MigrationRunner`(类式 API),`dry_run_sql` 仅由命名表达式回调组装;函数式运行器则能捕获两条语句路径。这是核心层面的注意事项,此处再次提示,以免在选择 API 时遗漏。 + +完整的类式演示见 [`02_named_migration.py`](../../examples/migration/02_named_migration.py)。 + + + +## 6. 本地示例 + +| 脚本 | 演示内容 | +|---|---| +| [`01_function_migration.py`](../../examples/migration/01_function_migration.py) | SQL Server 配置 + `@migration` + `run_migration_group`:试运行 → 真正执行 UP → 回滚 DOWN,并使用 `JSONFileMigrationRecordStore` | +| [`02_named_migration.py`](../../examples/migration/02_named_migration.py) | 由 `MigrationRunner` 在 SQL Server 上驱动 `NamedMigration` 子类,以及 `named-migration` CLI 接线方式 | + +这些脚本已通过语法检查,但执行时需要可连接的 SQL Server;连接所需的环境变量见 [docs/examples/README.md](../../examples/README.md)。 diff --git a/pyproject.toml b/pyproject.toml index a9b1843b..8eb11509 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -83,7 +83,7 @@ namespaces = true [tool.pytest.ini_options] minversion = "7.0" -addopts = "-ra -q -p rhosocial.activerecord.testsuite.conftest" +addopts = "-ra -q" asyncio_mode = "auto" testpaths = [ "tests", diff --git a/pytest.ini b/pytest.ini index 1a4a9220..17351ece 100644 --- a/pytest.ini +++ b/pytest.ini @@ -11,10 +11,10 @@ python_functions = test_* ; invocation works without PYTHONPATH=src:tests, which CI sets anyway. pythonpath = tests ; plugins.expression_xdist is this repository's own: it makes the expression -; area (feature/backend/expression) parallel by default, which the org test +; area (feature/backend/construct/expression) parallel by default, which the org test ; rules ask for and a conftest cannot do because xdist reads the worker count ; before any conftest loads. See tests/plugins/expression_xdist.py. -addopts = -v --tb=short -p rhosocial.activerecord.testsuite.conftest -p plugins.expression_xdist +addopts = -v --tb=short -p plugins.expression_xdist filterwarnings = ignore::DeprecationWarning markers = diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/adapters.py b/src/rhosocial/activerecord/backend/impl/sqlserver/adapters.py index 83f8fce9..d88958c0 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/adapters.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/adapters.py @@ -11,7 +11,21 @@ import xml.etree.ElementTree as ET from abc import ABC, abstractmethod from datetime import date, datetime, time, timezone -from typing import Any, Dict, List, Type, Union +from typing import Any, Dict, List, Optional, Type, Union + +from rhosocial.activerecord.backend.adapters import ( + BitString, + BitStringAdapterBase, + Geometry, + GeometryAdapterBase, + MacAddress, + MacAddressAdapterBase, + Multirange, + Range, + RangeAdapterBase, + Vector, + VectorAdapterBase, +) def _parse_sql_datetime(value: str) -> datetime: @@ -48,6 +62,32 @@ def _parse_sql_datetime(value: str) -> datetime: return result +def _parse_sql_time(value: str) -> time: + """Parse a SQL Server ``TIME`` string into a Python ``time``. + + The same wire format as ``datetime2`` applies: no ``T`` separator and + seven fractional digits (100ns precision), e.g. ``'18:36:06.0000000'``. + Python's ``time.fromisoformat`` only accepts three or six fractional + digits on Python < 3.11, so trim and pad the fraction first. + """ + normalized = value.strip().replace('Z', '+00:00') + if 'T' in normalized: + normalized = normalized.partition('T')[2] + dot_pos = normalized.rfind('.') + if dot_pos != -1: + suffix = '' + frac_end = len(normalized) + for marker in ('+', '-'): + idx = normalized.find(marker, dot_pos + 1) + if idx != -1: + frac_end = idx + suffix = normalized[idx:] + break + frac = normalized[dot_pos + 1:frac_end][:6].ljust(6, '0') + normalized = f"{normalized[:dot_pos]}.{frac}{suffix}" + return time.fromisoformat(normalized) + + class TypeAdapter(ABC): """Base class for type adapters.""" @@ -63,7 +103,7 @@ def to_database(self, value: Any, target_type: Type = None, options: Dict = None pass @abstractmethod - def from_database(self, value: Any, target_type: Type = None, options: Dict = None) -> Any: + def from_database(self, value: Any, target_type: Type = None, options: Dict = None, **kwargs) -> Any: """Convert database value to Python value.""" pass @@ -99,7 +139,7 @@ def to_database(self, value: Any, target_type: Type = None, options: Dict = None raise TypeError(f"Expected UUID or str, got {type(value)}") - def from_database(self, value: Any, target_type: Type = None, options: Dict = None) -> uuid.UUID: + def from_database(self, value: Any, target_type: Type = None, options: Dict = None, **kwargs) -> uuid.UUID: if value is None: return None @@ -139,7 +179,7 @@ def to_database(self, value: Any, target_type: Type = None, options: Dict = None raise TypeError(f"Expected datetime, got {type(value)}") - def from_database(self, value: Any, target_type: Type = None, options: Dict = None) -> datetime: + def from_database(self, value: Any, target_type: Type = None, options: Dict = None, **kwargs) -> datetime: if value is None: return None @@ -179,7 +219,7 @@ def to_database(self, value: Any, target_type: Type = None, options: Dict = None raise TypeError(f"Expected datetime, got {type(value)}") - def from_database(self, value: Any, target_type: Type = None, options: Dict = None) -> datetime: + def from_database(self, value: Any, target_type: Type = None, options: Dict = None, **kwargs) -> datetime: if value is None: return None @@ -212,7 +252,7 @@ def to_database(self, value: Any, target_type: Type = None, options: Dict = None return value raise TypeError(f"Expected date, got {type(value)}") - def from_database(self, value: Any, target_type: Type = None, options: Dict = None) -> date: + def from_database(self, value: Any, target_type: Type = None, options: Dict = None, **kwargs) -> date: if value is None: return None if isinstance(value, datetime): @@ -242,7 +282,7 @@ def to_database(self, value: Any, target_type: Type = None, options: Dict = None return value.time() raise TypeError(f"Expected time, got {type(value)}") - def from_database(self, value: Any, target_type: Type = None, options: Dict = None) -> time: + def from_database(self, value: Any, target_type: Type = None, options: Dict = None, **kwargs) -> time: if value is None: return None if isinstance(value, time): @@ -250,7 +290,7 @@ def from_database(self, value: Any, target_type: Type = None, options: Dict = No if isinstance(value, datetime): return value.time() if isinstance(value, str): - return time.fromisoformat(value) + return _parse_sql_time(value) raise TypeError(f"Cannot convert {type(value)} to time") @@ -259,8 +299,17 @@ class SQLServerJSONAdapter(TypeAdapter): SQL Server 2016+ supports JSON functions but doesn't have a native JSON type. JSON data is stored as NVARCHAR(MAX). + + ``default`` / ``object_hook`` are forwarded to ``json.dumps`` / ``json.loads`` + so callers can plug in neutral-type codecs (see + ``rhosocial.activerecord.backend.adapters.json_codec``) without changing the + default behaviour: both default to ``None``, which is plain ``json``. """ + def __init__(self, default=None, object_hook=None): + self._json_default = default + self._json_object_hook = object_hook + @property def supported_types(self) -> Dict[Type, List[str]]: return { @@ -273,15 +322,15 @@ def to_database(self, value: Any, target_type: Type = None, options: Dict = None return None if isinstance(value, (dict, list)): - return json.dumps(value) + return json.dumps(value, default=self._json_default) if isinstance(value, str): - json.loads(value) + json.loads(value, object_hook=self._json_object_hook) return value raise TypeError(f"Expected dict, list, or str, got {type(value)}") - def from_database(self, value: Any, target_type: Type = None, options: Dict = None) -> Union[dict, list]: + def from_database(self, value: Any, target_type: Type = None, options: Dict = None, **kwargs) -> Union[dict, list]: if value is None: return None @@ -289,7 +338,7 @@ def from_database(self, value: Any, target_type: Type = None, options: Dict = No return value if isinstance(value, str): - return json.loads(value) + return json.loads(value, object_hook=self._json_object_hook) raise TypeError(f"Cannot convert {type(value)} to dict/list") @@ -325,7 +374,7 @@ def to_database(self, value: Any, target_type: Type = None, options: Dict = None raise TypeError(f"Expected str, bytes, or dict, got {type(value)}") - def from_database(self, value: Any, target_type: Type = None, options: Dict = None) -> str: + def from_database(self, value: Any, target_type: Type = None, options: Dict = None, **kwargs) -> str: if value is None: return None @@ -359,71 +408,201 @@ def _build_xml(self, parent, data): elem.text = str(value) -class SQLServerSpatialAdapter(TypeAdapter): - """Adapter for GEOGRAPHY and GEOMETRY types. - - SQL Server supports spatial data through: - - geography: For earth-based coordinates (lat/lon) - - geometry: For planar coordinates - - Uses Well-Known Text (WKT) or Well-Known Binary (WKB) format. +class SQLServerGeometryAdapter(GeometryAdapterBase): + """WKT-text adapter for SQL Server ``GEOMETRY`` / ``GEOGRAPHY`` columns. + + The neutral :class:`~rhosocial.activerecord.backend.adapters.Geometry` + value is encoded as plain WKT text and decoded from WKT text (or UTF-8 + bytes containing WKT). ``SRID`` is not part of plain WKT, so a decoded + geometry always has ``srid=None``. + + **Binding limitation**: pyodbc cannot bind a SQL Server CLR spatial value, + and a ``geometry``/``geography`` column rejects a VARCHAR/NVARCHAR parameter + ("Implicit conversion from data type varchar to geometry is not allowed"). + SQL Server requires the parameter to be wrapped, e.g. + ``geometry::STGeomFromText(?, 4326)``. An ORM placeholder alone is therefore + not sufficient; call :meth:`bind_expression` to build the wrapper expression + and bind the WKT text produced by :meth:`to_database` to it. """ - + + def __init__(self, srid: Optional[int] = None, geography: bool = False): + super().__init__() + if srid is not None and (isinstance(srid, bool) or not isinstance(srid, int)): + raise TypeError(f"srid must be int, got {type(srid).__name__}") + if srid is not None and srid < 0: + raise ValueError(f"srid must be non-negative, got {srid}") + if not isinstance(geography, bool): + raise TypeError(f"geography must be bool, got {type(geography).__name__}") + self._srid = srid if srid is not None else (4326 if geography else 0) + self._geography = geography + self.register_type(Geometry, str) + self.register_type(Geometry, bytes) + @property - def supported_types(self) -> Dict[Type, List[str]]: - return { - str: ["geography", "geometry"], - bytes: ["geography", "geometry"], - } - - def to_database(self, value: Any, target_type: Type = None, options: Dict = None) -> Any: - if value is None: - return None - - if isinstance(value, str): - return value - - if isinstance(value, bytes): - return value - - if isinstance(value, dict): - return self._dict_to_wkt(value) - - raise TypeError(f"Expected str, bytes, or dict, got {type(value)}") - - def from_database(self, value: Any, target_type: Type = None, options: Dict = None) -> str: - if value is None: - return None - + def srid(self) -> int: + """SRID used by :meth:`bind_expression`.""" + return self._srid + + @property + def kind(self) -> str: + """SQL Server spatial type name: ``geometry`` or ``geography``.""" + return "geography" if self._geography else "geometry" + + def bind_expression(self, placeholder: str = "?") -> str: + """Return the SQL expression that wraps a WKT parameter. + + Example: ``geometry::STGeomFromText(?, 4326)``. The WKT text from + :meth:`to_database` is bound to ``placeholder``. + """ + return f"{self.kind}::STGeomFromText({placeholder}, {self._srid})" + + def _encode(self, geometry: Geometry, target_type: Type, options: Dict = None) -> Any: + wkt = geometry.to_wkt() + if target_type is bytes: + return wkt.encode("utf-8") + return wkt + + def _decode(self, value: Any, options: Dict = None) -> Geometry: + if isinstance(value, (bytes, bytearray)): + try: + value = bytes(value).decode("utf-8") + except UnicodeDecodeError as exc: + raise ValueError( + "binary spatial values are not supported; use WKT text" + ) from exc + wkt = self._require_text(value) + return Geometry.from_wkt(wkt) + + +class SQLServerVectorAdapter(VectorAdapterBase): + """JSON-text adapter for SQL Server vector columns. + + SQL Server before version 2025 has no native ``VECTOR`` type, so a vector + is carried as JSON text in ``NVARCHAR``/``VARCHAR`` (``NVARCHAR(MAX)`` when + the dimension is not fixed). The adapter encodes the neutral + :class:`~rhosocial.activerecord.backend.adapters.Vector` as a JSON array and + decodes JSON text, UTF-8 bytes, or an already-decoded list/tuple. Non-finite + components use the neutral JSON spellings (``"NaN"``, ``"Infinity"``, + ``"-Infinity"``). If a deployment does provide a native vector type, this + text adapter is still the neutral representation; a native adapter would be + a separate implementation. + """ + + def __init__(self): + super().__init__() + self.register_type(Vector, str) + self.register_type(Vector, bytes) + + def _encode(self, vector: Vector, target_type: Type, options: Dict = None) -> Any: + text = json.dumps(vector.to_json_value(), ensure_ascii=False) + if target_type is bytes: + return text.encode("utf-8") + return text + + def _decode(self, value: Any, options: Dict = None) -> Vector: + if isinstance(value, (list, tuple)): + return Vector.from_json_value(value) + if isinstance(value, (bytes, bytearray)): + value = bytes(value).decode("utf-8") + if not isinstance(value, str): + raise TypeError(f"expected JSON array text or a list, got {type(value).__name__}") + return Vector.from_json_value(json.loads(value)) + + +class SQLServerBitStringAdapter(BitStringAdapterBase): + """Adapter for neutral bit strings carried as ``VARBINARY`` or text. + + SQL Server's own ``BIT`` type is a boolean and is not a bit string; bit + strings are carried in ``BINARY``/``VARBINARY`` columns or in text columns + (``VARCHAR``/``NVARCHAR``). Raw bytes can only represent whole bytes, so a + bit string whose ``bit_length`` is not a multiple of 8 loses its exact + length in the binary representation. The text target keeps the exact + length: :meth:`BitString.to_bits` renders the significant bits (including + leading zeros), and :meth:`_decode` accepts that form unchanged. + """ + + def __init__(self): + super().__init__() + self.register_type(BitString, str) + self.register_type(BitString, bytes) + + def _encode(self, bits: BitString, target_type: Type, options: Dict = None) -> Any: + if target_type is str: + return bits.to_bits() + return bits.data + + def _decode(self, value: Any, options: Dict = None) -> BitString: + if isinstance(value, (bytes, bytearray)): + return BitString.from_bytes(bytes(value)) if isinstance(value, str): - return value - - if isinstance(value, bytes): - return value.decode('utf-8') - - raise TypeError(f"Cannot convert {type(value)} to spatial type") - - def _dict_to_wkt(self, data: dict) -> str: - geom_type = data.get('type', 'Point') - - if geom_type == 'Point': - coords = data.get('coordinates', [0, 0]) - return f"POINT({coords[0]} {coords[1]})" - - elif geom_type == 'LineString': - coords = data.get('coordinates', []) - points = ", ".join(f"{c[0]} {c[1]}" for c in coords) - return f"LINESTRING({points})" - - elif geom_type == 'Polygon': - coords = data.get('coordinates', [[]]) - rings = [] - for ring in coords: - points = ", ".join(f"{c[0]} {c[1]}" for c in ring) - rings.append(f"({points})") - return f"POLYGON({','.join(rings)})" - - raise ValueError(f"Unsupported geometry type: {geom_type}") + return BitString.from_bits(value) + raise TypeError(f"expected bytes or a bit-string text, got {type(value).__name__}") + + +class SQLServerRangeAdapter(RangeAdapterBase): + """JSON-text adapter for neutral ranges stored in text columns. + + SQL Server has no range/multirange type. Ranges are stored as JSON text + (``NVARCHAR``/``VARCHAR``) using the neutral canonical representation from + :meth:`Range.to_json_value` / :meth:`Multirange.to_json_value`. + """ + + def __init__(self): + super().__init__() + self.register_type(Range, str) + self.register_type(Multirange, str) + self.register_type(Range, bytes) + self.register_type(Multirange, bytes) + + def _encode(self, value: Any, target_type: Type, options: Dict = None) -> Any: + text = json.dumps(value.to_json_value(), ensure_ascii=False) + if target_type is bytes: + return text.encode("utf-8") + return text + + def _decode(self, value: Any, target_type: Type, options: Dict = None) -> Any: + if isinstance(value, (bytes, bytearray)): + value = bytes(value).decode("utf-8") + if not isinstance(value, str): + raise TypeError(f"expected JSON text, got {type(value).__name__}") + payload = json.loads(value) + if target_type is Multirange: + return Multirange.from_json_value(payload) + if target_type is Range: + return Range.from_json_value(payload) + if isinstance(payload, list): + return Multirange.from_json_value(payload) + return Range.from_json_value(payload) + + +class SQLServerMacAddressAdapter(MacAddressAdapterBase): + """Canonical-text adapter for MAC addresses. + + SQL Server has no MAC address type; the value is stored in ``VARCHAR``/ + ``CHAR`` as the canonical lowercase colon-separated text + (``01:23:45:67:89:ab``). ``BINARY``/``VARBINARY`` columns are also accepted + when the raw value is exactly 6 or 8 octets. + """ + + def __init__(self): + super().__init__() + self.register_type(MacAddress, str) + self.register_type(MacAddress, bytes) + + def _encode(self, mac: MacAddress, target_type: Type, options: Dict = None) -> Any: + if target_type is bytes: + return mac.octets + return str(mac) + + def _decode(self, value: Any, options: Dict = None) -> MacAddress: + if isinstance(value, bytearray): + value = bytes(value) + if isinstance(value, bytes) and len(value) not in (6, 8): + try: + value = value.decode("utf-8") + except UnicodeDecodeError as exc: + raise ValueError("MAC address bytes must be 6 or 8 octets") from exc + return MacAddress.parse(value) class SQLServerHierarchyIdAdapter(TypeAdapter): @@ -452,7 +631,7 @@ def to_database(self, value: Any, target_type: Type = None, options: Dict = None raise TypeError(f"Expected str or list, got {type(value)}") - def from_database(self, value: Any, target_type: Type = None, options: Dict = None) -> str: + def from_database(self, value: Any, target_type: Type = None, options: Dict = None, **kwargs) -> str: if value is None: return None @@ -484,7 +663,7 @@ def to_database(self, value: Any, target_type: Type = None, options: Dict = None raise TypeError(f"Expected Decimal, int, or float, got {type(value)}") - def from_database(self, value: Any, target_type: Type = None, options: Dict = None): + def from_database(self, value: Any, target_type: Type = None, options: Dict = None, **kwargs): from decimal import Decimal if value is None: diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/async_transaction.py b/src/rhosocial/activerecord/backend/impl/sqlserver/async_transaction.py index c6f38d21..ca6131d1 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/async_transaction.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/async_transaction.py @@ -216,3 +216,7 @@ async def release_savepoint(self, name: str) -> None: def savepoints(self) -> List[str]: """Get list of current savepoints.""" return self._savepoints.copy() + + async def supports_savepoint(self) -> bool: + """Async counterpart of the sync capability probe.""" + return self._backend.dialect.supports_savepoint() diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/backend/async_backend.py b/src/rhosocial/activerecord/backend/impl/sqlserver/backend/async_backend.py index 1c23a75b..7da2aa2e 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/backend/async_backend.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/backend/async_backend.py @@ -172,6 +172,12 @@ def _register_sqlserver_adapters(self) -> None: SQLServerJSONAdapter, SQLServerXMLAdapter, SQLServerDecimalAdapter, + SQLServerGeometryAdapter, + SQLServerVectorAdapter, + SQLServerBitStringAdapter, + SQLServerRangeAdapter, + SQLServerMacAddressAdapter, + SQLServerHierarchyIdAdapter, ) sqlserver_adapters = [ SQLServerUUIDAdapter(), @@ -182,6 +188,14 @@ def _register_sqlserver_adapters(self) -> None: SQLServerJSONAdapter(), SQLServerXMLAdapter(), SQLServerDecimalAdapter(), + SQLServerGeometryAdapter(), + SQLServerVectorAdapter(), + SQLServerBitStringAdapter(), + SQLServerRangeAdapter(), + SQLServerMacAddressAdapter(), + # Registered under the ``hierarchyid`` column type only (see the + # sync backend's note): never under a Python target. + SQLServerHierarchyIdAdapter(), ] for adapter in sqlserver_adapters: for py_type, db_types in adapter.supported_types.items(): diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/backend/backend.py b/src/rhosocial/activerecord/backend/impl/sqlserver/backend/backend.py index f6510612..3f8a82c5 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/backend/backend.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/backend/backend.py @@ -198,6 +198,12 @@ def _register_sqlserver_adapters(self) -> None: SQLServerJSONAdapter, SQLServerXMLAdapter, SQLServerDecimalAdapter, + SQLServerGeometryAdapter, + SQLServerVectorAdapter, + SQLServerBitStringAdapter, + SQLServerRangeAdapter, + SQLServerMacAddressAdapter, + SQLServerHierarchyIdAdapter, ) sqlserver_adapters = [ SQLServerUUIDAdapter(), @@ -208,6 +214,16 @@ def _register_sqlserver_adapters(self) -> None: SQLServerJSONAdapter(), SQLServerXMLAdapter(), SQLServerDecimalAdapter(), + SQLServerGeometryAdapter(), + SQLServerVectorAdapter(), + SQLServerBitStringAdapter(), + SQLServerRangeAdapter(), + SQLServerMacAddressAdapter(), + # Registered under the ``hierarchyid`` column type only, never under + # a Python target: a ``str`` suggestion would put this adapter on + # every text field. A field opts in with + # ``Annotated[str, UseAdapter(SQLServerHierarchyIdAdapter(), str)]``. + SQLServerHierarchyIdAdapter(), ] for adapter in sqlserver_adapters: for py_type, db_types in adapter.supported_types.items(): diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/dialect.py b/src/rhosocial/activerecord/backend/impl/sqlserver/dialect.py index e6f0a978..86a0ae10 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/dialect.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/dialect.py @@ -151,6 +151,7 @@ from .collation import validate_sqlserver_collation_name from .alter_table_modifier import SQLServerAlterColumnModifierMixin from .mixins.identity_column import SQLServerIdentityColumnMixin +from .mixins.integer_auto_increment_column_suggestion import SQLServerIntegerAutoIncrementColumnSuggestionMixin from .mixins.introspection import SQLServerIntrospectionMixin from .mixins.sequence import SQLServerSequenceMixin from .mixins.pivot import SQLServerPivotMixin @@ -171,6 +172,7 @@ from .mixins.window import SQLServerWindowMixin from .mixins.json import SQLServerJSONMixin from .mixins.column_type import SQLServerColumnTypeMixin +from .mixins.data_type_suggestions import SQLServerDataTypeSuggestionsMixin from .mixins.uuid import SQLServerUUIDMixin from .mixins.grouping import SQLServerGroupingMixin from .mixins.locking import SQLServerLockingMixin @@ -255,6 +257,8 @@ class SQLServerDialect( + # Backend suggestion first: no core mixin may shadow its answer. + SQLServerIntegerAutoIncrementColumnSuggestionMixin, # 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 @@ -316,12 +320,14 @@ class SQLServerDialect( SQLDialectBase, # Core infrastructure mixins (provide base implementations # that the dialect overrides as needed) + # SQL Server protocol contract implementations; precedes the core + # ExpressionMixin because it owns STRING_CONCATENATION for this dialect. + SQLServerProtocolSupportMixin, PredicateMixin, ExpressionMixin, # SQL Server-specific mixins (must precede their global counterparts # to ensure SQL Server methods take precedence in MRO) SQLServerAlterColumnModifierMixin, # Before DDLColumnMixin to override format_*_action - SQLServerProtocolSupportMixin, # SQL Server protocol contract implementations SQLServerSequenceMixin, # NEXT VALUE FOR formatter (2012+) SQLServerIdentityColumnMixin, # IDENTITY(seed, increment) formatter + probes SQLServerPivotMixin, # PIVOT / UNPIVOT formatters (2005+) @@ -340,6 +346,10 @@ class SQLServerDialect( # Before DDLColumnMixin: the backend block below comes later, so # supports_fk_match answered for the core. Same value by coincidence. SQLServerConstraintMixin, + # Before DDLTypeMixin, which inherits DataTypeMixin's answer -- a + # NotImplementedError. A table placed after the class it stands in for + # never wins, so the backend's 24-key answer sits ahead of the core mixin. + SQLServerDataTypeSuggestionsMixin, DDLColumnMixin, DDLTypeMixin, UserDefinedTypeMixin, @@ -597,6 +607,24 @@ def format_auto_increment(self) -> Tuple[str, tuple]: """Return IDENTITY(1,1) for auto-increment columns.""" return "IDENTITY(1,1)", () + def format_exists_predicate(self, expr: Any) -> Tuple[str, tuple]: + """Render a scalar ``EXISTS`` as T-SQL ``CASE WHEN ... THEN 1 ELSE 0 END``. + + Core's ``exists()`` uses ``ExistsPredicate`` as an aliased scalar select + expression, which renders as ``SELECT EXISTS (subquery) AS ...`` on + dialects with a boolean type. T-SQL has no boolean scalar and rejects + EXISTS in a SELECT list (error 156), so the aliased (scalar) form maps to + the portable integer 1/0 form; ``_run_scalar`` reads it back and + ``bool()`` coerces it. An unaliased EXISTS stays a plain boolean + predicate, preserving its behaviour in WHERE/HAVING contexts. + """ + subquery_sql, subquery_params = expr.subquery.to_sql() + negation = "NOT " if getattr(expr, "is_not", False) else "" + exists_clause = f"{negation}EXISTS {subquery_sql}" + if getattr(expr, "alias", None): + exists_clause = f"CASE WHEN {exists_clause} THEN 1 ELSE 0 END" + return self._with_predicate_alias(exists_clause, expr), subquery_params + def format_array_expression(self, _expr: "ArrayOperation") -> Tuple[str, tuple]: """Format array expression - not supported.""" raise UnsupportedFeatureError(self.name, "Array operations", _SUGGESTION_ARRAY_TYPES) @@ -870,8 +898,6 @@ def format_column_definition( constraint_parts.append( "PRIMARY KEY NONCLUSTERED" if memory_optimized else "PRIMARY KEY" ) - if branch.is_auto_increment: - constraint_parts.append("IDENTITY(1,1)") elif isinstance(branch, ColumnUniqueConstraint): constraint_parts.append( "UNIQUE NONCLUSTERED" if memory_optimized else "UNIQUE" @@ -1481,10 +1507,10 @@ def format_query_option_clause(self, clause: "bases.BaseExpression") -> Tuple[st return f"OPTION ({', '.join(clause.hints)})", () # ------------------------------------------------------------------ - # DataType protocol — suggestions + # DataType protocol — substitutions # ------------------------------------------------------------------ - def suggested_data_types(self) -> Dict[str, type]: + def substitute_data_types(self) -> Dict[str, type]: """Concepts SQL Server cannot spell, and what it stores instead (D9). Returns a mapping ``{: DataType class}`` for every core @@ -1562,6 +1588,14 @@ def suggested_data_types(self) -> Dict[str, type]: "uuid": SQLServerUniqueIdentifierType, } + def supports_database_assigned_integer_column(self) -> bool: + """T-SQL assigns the value through ``IDENTITY(seed, increment)``. + + Omitting the column on INSERT lets the engine take the next value from + the identity property, and the inserted value can be read back. + """ + return True + # Lazy import to avoid circular dependency (backend → dialect → mixins.types → backend) def _register_type_formatters(): diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/connection/quickstart.py b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/connection/quickstart.py index 03b1f40a..eb6c6f8a 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/connection/quickstart.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/connection/quickstart.py @@ -7,6 +7,7 @@ 3. How to execute expression-based queries 4. How to access query results and handle transactions """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import os @@ -70,14 +71,14 @@ def execute_expression(expression, options=None): columns=[ ColumnDefinition( 'id', - 'INT', + auto_increment_parts(dialect, 'INT')[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), ], - ), + attributes=auto_increment_parts(dialect, 'INT')[1]), ColumnDefinition( 'name', 'NVARCHAR(100)', @@ -95,14 +96,14 @@ def execute_expression(expression, options=None): columns=[ ColumnDefinition( 'id', - 'INT', + auto_increment_parts(dialect, 'INT')[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), ], - ), + attributes=auto_increment_parts(dialect, 'INT')[1]), ColumnDefinition( 'message', 'NVARCHAR(255)', diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/ddl/create_index.py b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/ddl/create_index.py index 93ad9738..374eb42d 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/ddl/create_index.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/ddl/create_index.py @@ -1,6 +1,7 @@ """ Create an index on an existing table. """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import os @@ -43,12 +44,12 @@ dialect=dialect, table=Table(dialect, 'users'), columns=[ - ColumnDefinition('id', 'INT', constraints=[ + ColumnDefinition('id', auto_increment_parts(dialect, 'INT')[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), - ]), + ], attributes=auto_increment_parts(dialect, 'INT')[1]), ColumnDefinition('email', 'NVARCHAR(200)', constraints=[ ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), ]), diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/ddl/create_table.py b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/ddl/create_table.py index 0b7d1d40..8e965dfe 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/ddl/create_table.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/ddl/create_table.py @@ -1,6 +1,7 @@ """ Create a table with primary key, IDENTITY, and constraints. """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import os @@ -45,11 +46,11 @@ columns = [ ColumnDefinition( name='id', - data_type='INT', + data_type=auto_increment_parts(dialect, 'INT')[0], constraints=[ - ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True)), + ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect)), ], - ), + attributes=auto_increment_parts(dialect, 'INT')[1]), ColumnDefinition( name='name', data_type='NVARCHAR(100)', diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/insert/batch.py b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/insert/batch.py index 1e8b3b32..cbe566fd 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/insert/batch.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/insert/batch.py @@ -1,6 +1,7 @@ """ Batch insert multiple rows efficiently. """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import os @@ -43,12 +44,12 @@ dialect=dialect, table=Table(dialect, 'batch_users'), columns=[ - ColumnDefinition('id', 'INT', constraints=[ + ColumnDefinition('id', auto_increment_parts(dialect, 'INT')[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), - ]), + ], attributes=auto_increment_parts(dialect, 'INT')[1]), ColumnDefinition('name', 'NVARCHAR(100)', constraints=[ ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), ]), diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/insert/with_output.py b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/insert/with_output.py index dfec2228..c4a25005 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/insert/with_output.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/insert/with_output.py @@ -3,6 +3,7 @@ SQL Server uses OUTPUT clause instead of RETURNING (PostgreSQL/SQLite). """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import os @@ -45,12 +46,12 @@ dialect=dialect, table=Table(dialect, 'output_users'), columns=[ - ColumnDefinition('id', 'INT', constraints=[ + ColumnDefinition('id', auto_increment_parts(dialect, 'INT')[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), - ]), + ], attributes=auto_increment_parts(dialect, 'INT')[1]), ColumnDefinition('name', 'NVARCHAR(100)', constraints=[ ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), ]), diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/query/basic.py b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/query/basic.py index 50c7a23b..190731d9 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/query/basic.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/query/basic.py @@ -1,6 +1,7 @@ """ Basic SELECT query with WHERE, ORDER BY, and OFFSET FETCH clauses. """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import os @@ -49,12 +50,12 @@ dialect=dialect, table=Table(dialect, 'query_users'), columns=[ - ColumnDefinition('id', 'INT', constraints=[ + ColumnDefinition('id', auto_increment_parts(dialect, 'INT')[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), - ]), + ], attributes=auto_increment_parts(dialect, 'INT')[1]), ColumnDefinition('name', 'NVARCHAR(100)', constraints=[ ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), ]), diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/query/join.py b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/query/join.py index cd585391..567fcd1d 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/query/join.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/query/join.py @@ -1,6 +1,7 @@ """ JOIN multiple tables. """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import os @@ -50,12 +51,12 @@ dialect=dialect, table=Table(dialect, 'join_users'), columns=[ - ColumnDefinition('id', 'INT', constraints=[ + ColumnDefinition('id', auto_increment_parts(dialect, 'INT')[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), - ]), + ], attributes=auto_increment_parts(dialect, 'INT')[1]), ColumnDefinition('name', 'NVARCHAR(100)', constraints=[ ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), ]), @@ -69,12 +70,12 @@ dialect=dialect, table=Table(dialect, 'join_orders'), columns=[ - ColumnDefinition('id', 'INT', constraints=[ + ColumnDefinition('id', auto_increment_parts(dialect, 'INT')[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), - ]), + ], attributes=auto_increment_parts(dialect, 'INT')[1]), ColumnDefinition('user_id', 'INT'), ColumnDefinition('amount', 'DECIMAL(10,2)'), ], diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/schema_diff/add_column.py b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/schema_diff/add_column.py index 4eb2af7f..e5382614 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/schema_diff/add_column.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/schema_diff/add_column.py @@ -6,6 +6,7 @@ Supported versions: SQL Server 2012+ """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import os from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend @@ -42,10 +43,10 @@ # Baseline table: ID, NAME expr = CreateTableStatement( dialect=dialect, table=users, columns=[ - ColumnDefinition(dialect, "id", IntegerType(dialect), + ColumnDefinition(dialect, "id", auto_increment_parts(dialect, IntegerType(dialect))[0], constraints=[ - ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True)), - ]), + ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect)), + ], attributes=auto_increment_parts(dialect, IntegerType(dialect))[1]), ColumnDefinition(dialect, "name", VarCharType(dialect, length=100)), ] ) diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/transaction/basic.py b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/transaction/basic.py index a9eef69c..4f031e35 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/transaction/basic.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/transaction/basic.py @@ -1,6 +1,7 @@ """ Basic transaction with context manager for automatic commit/rollback. """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import os @@ -44,12 +45,12 @@ dialect=dialect, table=Table(dialect, 'txn_users'), columns=[ - ColumnDefinition('id', 'INT', constraints=[ + ColumnDefinition('id', auto_increment_parts(dialect, 'INT')[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), - ]), + ], attributes=auto_increment_parts(dialect, 'INT')[1]), ColumnDefinition('name', 'NVARCHAR(100)', constraints=[ ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), ]), diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/types/json_basic.py b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/types/json_basic.py index a36c07a1..57a45124 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/examples/types/json_basic.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/examples/types/json_basic.py @@ -4,6 +4,7 @@ SQL Server doesn't have a native JSON type but provides functions for working with JSON data stored in NVARCHAR columns. """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import os @@ -46,12 +47,12 @@ dialect=dialect, table=Table(dialect, 'json_data'), columns=[ - ColumnDefinition('id', 'INT', constraints=[ + ColumnDefinition('id', auto_increment_parts(dialect, 'INT')[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), - ]), + ], attributes=auto_increment_parts(dialect, 'INT')[1]), ColumnDefinition('data', 'NVARCHAR(MAX)'), ], if_not_exists=True, diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/expression/types.py b/src/rhosocial/activerecord/backend/impl/sqlserver/expression/types.py index 47276745..ed2f9162 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/expression/types.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/expression/types.py @@ -24,6 +24,7 @@ VarBinaryType, BooleanType, CharType, + LENGTH_PARAMETERS, TinyIntType, UUIDType, VarCharType, @@ -80,6 +81,15 @@ class SQLServerNVarCharMaxType(VarCharType): name = "sqlserver_nvarchar_max" + #: ``MAX`` is not a width, so this class declares no parameters. + #: + #: ``VarCharType`` inherits ``LENGTH_PARAMETERS`` because a declared + #: ``VARCHAR(n)`` is what its width makes it; here the inherited tuple + #: would name an ``__init__`` argument this class does not take, and + #: ``identity()`` reads the tuple. ``NVARCHAR`` and ``NVARCHAR(MAX)`` are + #: different declarations, and the difference is the class, not a length. + PARAMETERS = () + def __init__(self, dialect=None): super().__init__(dialect, length=None) @@ -111,7 +121,10 @@ def __init__(self, dialect=None, length: Optional[int] = None): super().__init__(dialect) self.length = length - PARAMETERS = ("length",) + #: The shared object, not a copy: ``identity()`` compares the tuple, so a + #: literal of the same shape would silently make this declaration unequal + #: to its siblings. + PARAMETERS = LENGTH_PARAMETERS class SQLServerVarBinaryMaxType(BlobType): """SQL Server ``VARBINARY(MAX)`` — byte string up to 2 GB. @@ -187,7 +200,19 @@ class SQLServerTinyIntType(TinyIntType): name = "sqlserver_tinyint" - def __init__(self, dialect=None, *, spelling: str = "tinyint"): + #: Signedness stays in ``PARAMETERS`` so ``identity()`` records it, and the + #: argument is accepted so the tuple names something the constructor really + #: takes. It is nevertheless not a knob: ``False`` is refused rather than + #: quietly turned into a spelling T-SQL does not have. + def __init__( + self, dialect=None, *, unsigned: bool = True, spelling: str = "tinyint" + ): + if unsigned is not True: + raise ValueError( + "SQL Server's TINYINT is unsigned; no T-SQL spelling of it is " + "signed, so unsigned=False is not a declaration this backend " + "can make" + ) super().__init__(dialect, unsigned=True, spelling=spelling) @@ -228,7 +253,7 @@ class SQLServerUniqueIdentifierType(UUIDType): It stays a class of its own because T-SQL spells the type differently, and the ``sqlserver_uniqueidentifier`` name keeps the dispatch keys of this backend's ``format_data_type_*`` family isolated from the others'. - ``suggested_data_types()["uuid"]`` points at it — a substitute that names a + ``substitute_data_types()["uuid"]`` points at it — a substitute that names a type this dialect really renders, which is the only kind of substitute the contract allows. """ diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/__init__.py b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/__init__.py index 9ccdd9c4..b571e92f 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/__init__.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/__init__.py @@ -1,4 +1,5 @@ # src/rhosocial/activerecord/backend/impl/sqlserver/mixins/__init__.py +from .integer_auto_increment_column_suggestion import SQLServerIntegerAutoIncrementColumnSuggestionMixin from .types import SQLServerTypeSupportMixin from .concurrency import SQLServerConcurrencyMixin from .backend_mixin import SQLServerBackendMixin @@ -20,6 +21,7 @@ from .window import SQLServerWindowMixin from .json import SQLServerJSONMixin from .column_type import SQLServerColumnTypeMixin +from .data_type_suggestions import SQLServerDataTypeSuggestionsMixin from .uuid import SQLServerUUIDMixin from .grouping import SQLServerGroupingMixin from .locking import SQLServerLockingMixin @@ -46,6 +48,7 @@ from .literal import SQLServerLiteralValueMixin __all__ = [ + 'SQLServerIntegerAutoIncrementColumnSuggestionMixin', "SQLServerTypeSupportMixin", "SQLServerConcurrencyMixin", "SQLServerBackendMixin", @@ -67,6 +70,7 @@ "SQLServerWindowMixin", "SQLServerJSONMixin", "SQLServerColumnTypeMixin", + "SQLServerDataTypeSuggestionsMixin", "SQLServerUUIDMixin", "SQLServerGroupingMixin", "SQLServerLockingMixin", diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/backend_mixin.py b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/backend_mixin.py index b02f2138..123b673a 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/backend_mixin.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/backend_mixin.py @@ -1,7 +1,7 @@ # src/rhosocial/activerecord/backend/impl/sqlserver/mixins/backend_mixin.py import logging import re -from typing import Any, Dict, Optional, Set, Tuple, Type, TYPE_CHECKING +from typing import Any, Dict, List, Optional, Set, Tuple, Type, TYPE_CHECKING from rhosocial.activerecord.backend.errors import ( ConnectionError, @@ -22,6 +22,7 @@ if TYPE_CHECKING: from ..dialect import SQLServerDialect + from rhosocial.activerecord.backend.type_adapter import SQLTypeAdapter _INSERT_PATTERN = re.compile( @@ -152,17 +153,18 @@ def _insert_table_name(self, sql: str) -> Optional[str]: return match.group(3) or match.group(4) def _identity_insert_info( - self, sql: str, params: Optional[Tuple], identity_columns: Optional[Set[str]] = None + self, sql: str, params: Optional[Tuple] = None, identity_columns: Optional[Set[str]] = None ) -> Optional[str]: """Return the table name that needs ``SET IDENTITY_INSERT ON``, or None. Detects ``INSERT INTO [schema].[table] (col, ...) VALUES (?, ...)`` - statements that explicitly supply a value for the table's identity - column. SQL Server forbids such inserts unless ``IDENTITY_INSERT`` is - enabled for the target table. + statements that explicitly supply the table's identity column. + SQL Server forbids such inserts unless ``IDENTITY_INSERT`` is enabled + for the target table. The column list alone decides: an explicit + value may arrive as a placeholder or as a literal rendered into the + statement, and both are equally forbidden, so ``params`` is not + consulted. """ - if not params: - return None table_name = self._insert_table_name(sql) if not table_name: return None @@ -173,11 +175,8 @@ def _identity_insert_info( match = _INSERT_PATTERN.match(sql) raw_columns = match.group(5) columns = [c.strip().strip("[]\"").lower() for c in raw_columns.split(",") if c.strip()] - if not columns or len(columns) > len(params): - return None - for col, value in zip(columns, params): - if col in identity_columns and value is not None: - return table_name + if any(column in identity_columns for column in columns): + return table_name return None def _execute_control_sql(self, sql: str) -> None: @@ -344,6 +343,21 @@ def is_case_sensitive(self) -> bool: return False def get_default_adapter_suggestions(self) -> Dict[Type, Tuple[Any, Type]]: + """Provide SQL Server's type-adapter suggestions. + + The framework defaults (:meth:`TypeAdaptionMixin.get_default_adapter_suggestions`) + are the base: SQL Server starts from the core table and merges its own + pairs on top, because the backend knows what pyodbc accepts better than + the framework does. A pair is suggested only when this backend + registered an adapter for it, so the merged table never names an + adapter this backend does not provide. + + The neutral families have no SQL Server column type of their own. They + are carried as text -- WKT for geometry, a JSON array for vectors, + bit-string text for ``BitString``, range JSON for ``Range`` / + ``Multirange``, and canonical lowercase colon text for MAC addresses -- + so each one is merged with a plain ``str`` target. + """ if hasattr(self, '_default_suggestions_cache') and self._default_suggestions_cache is not None: return self._default_suggestions_cache @@ -351,22 +365,57 @@ def get_default_adapter_suggestions(self) -> Dict[Type, Tuple[Any, Type]]: from decimal import Decimal from uuid import UUID - suggestions = {} + 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, + ) + + base = super().get_default_adapter_suggestions() + type_mappings = [ (bool, bool), (int, int), (float, float), (str, str), (bytes, bytes), (datetime, datetime), (date, date), (time, time), (Decimal, Decimal), (UUID, str), (dict, str), (list, str), + # Neutral families carried as text on SQL Server. + (Geometry, str), + (Vector, str), + (BitString, str), + (Range, str), + (Multirange, str), + (MacAddress, str), ] + suggestions = merge_adapter_suggestions(base, type_mappings, self.adapter_registry) 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) + if py_type not in suggestions: + self.log( + logging.DEBUG, + f"No adapter found for ({py_type.__name__}, {db_type.__name__}). " + "Suggestion will not be provided for this type.", + ) self._default_suggestions_cache = suggestions return suggestions + 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. + """ + registered = self.adapter_registry.get_all_adapters().values() + unique: Dict[Tuple[str, str], "SQLTypeAdapter"] = {} + for adapter in registered: + adapter_class = type(adapter) + key = (adapter_class.__module__, adapter_class.__qualname__) + unique.setdefault(key, adapter) + return [unique[key] for key in sorted(unique)] + def _build_query_result(self, cursor, data, duration: float): from rhosocial.activerecord.backend.result import QueryResult diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/column_type.py b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/column_type.py index 269bf36d..98a6d472 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/column_type.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/column_type.py @@ -48,7 +48,7 @@ answer :class:`NumericColumn` here, and the measured two-roundings fact is carried by the DataType declaration rather than dropped. -The table answers all eighteen of the framework's common Python types and needs +The table answers all twenty-four of the framework's Python types and needs **no version gate**: the JSON route works on 2019, 2022 and 2025 alike, and the three agree item for item. An entry left out would be indistinguishable from one nobody thought about, so every key is present; the only permitted ``None`` @@ -79,17 +79,32 @@ import uuid from typing import Any, Dict, Type +from rhosocial.activerecord.backend.adapters import ( + BitString, + Geometry, + MacAddress, + Multirange, + Range, + Vector, +) from rhosocial.activerecord.backend.dialect.mixins.column_type import ColumnTypeMixin from rhosocial.activerecord.backend.expression.column_types import ( BinaryColumn, + BitStringColumn, BooleanColumn, ColumnBase, + GeometryColumn, IntegerColumn, + IntervalColumn, JSONColumn, + MacAddressColumn, + MultirangeColumn, NumericColumn, + RangeColumn, StringColumn, TimestampColumn, UUIDColumn, + VectorColumn, ) #: SQL Server's complete answer for every one of the framework's common Python @@ -156,14 +171,14 @@ datetime.date: TimestampColumn, datetime.time: TimestampColumn, datetime.datetime: TimestampColumn, - # A timedelta is a number of seconds here. SQL Server has no interval - # *type* at all -- a span exists only as `DATEDIFF`, which is an - # expression -- so a stored duration has to be a count, and the value - # layer serialises to seconds because the driver refuses a bound - # `timedelta` outright (`suggested-mappings.md` §8.2 item 4). There is - # no `IntervalColumn` class yet, so this is the baseline every backend - # without an interval type gives. - datetime.timedelta: NumericColumn, + # A duration is a span, not a number, so it answers `IntervalColumn`. + # SQL Server has no interval *type* at all -- a span exists only as + # `DATEDIFF`, which is an expression -- so a stored duration has to be a + # count, and the value layer serialises to seconds because the driver + # refuses a bound `timedelta` outright (`suggested-mappings.md` §8.2 + # item 4). The class names the value and promises no arithmetic, which is + # exactly what this server can keep. + datetime.timedelta: IntervalColumn, # Native `UNIQUEIDENTIFIER` (there is also a documented `char(36)` # convention, which is a storage choice and not a column one). Measured: # `=` / `IN` work, prefix `LIKE` works, `NEWID()` is available in a @@ -218,11 +233,24 @@ # Those are storage and value-layer facts; the operation surface -- # equality, `IN`, `ORDER BY` -- is StringColumn's. enum.Enum: StringColumn, + # -- Complex families ------------------------------------------------ + # Their core 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. Richer family operations belong to a SQL Server-named + # subclass in this backend's extra table. Storage is answered in the + # data-type suggestion module. + Geometry: GeometryColumn, + Vector: VectorColumn, + BitString: BitStringColumn, + Range: RangeColumn, + Multirange: MultirangeColumn, + MacAddress: MacAddressColumn, } class SQLServerColumnTypeMixin(ColumnTypeMixin): - """SQL Server's full 18-entry column-type table. + """SQL Server's full 24-entry column-type table. Composed into :class:`~...dialect.SQLServerDialect` **ahead of** core's :class:`ColumnTypeMixin`, so its :meth:`suggested_column_types` is the one @@ -238,7 +266,7 @@ def suggested_column_types(self) -> Dict[Any, Type[ColumnBase]]: """The column class each common Python type means on SQL Server. A fresh copy per call, so a caller mutating the answer cannot corrupt - what the next lookup reads. All eighteen entries are answered with a + what the next lookup reads. All twenty-four entries are answered with a class: SQL Server's storage substitutions (JSON documents in ``NVARCHAR(MAX)``, spans as counts, no native array) still carry the operations, so this table has no last-resort ``None``. diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/data_type_suggestions.py b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/data_type_suggestions.py new file mode 100644 index 00000000..c16b764e --- /dev/null +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/data_type_suggestions.py @@ -0,0 +1,128 @@ +# src/rhosocial/activerecord/backend/impl/sqlserver/mixins/data_type_suggestions.py +"""SQL Server's **suggested data types**: what a bare field is declared as here. + +The DDL half of the type answer; :mod:`.column_type` is the operation half. A +column class says what a value can *do*, this table says what a column *is*. + +Shapes this server forces: + +* **text is Unicode here.** ``str`` is declared ``NVARCHAR(255)`` through this + backend's own class, and unbounded text is ``NVARCHAR(MAX)`` -- ``TEXT`` is + the deprecated non-Unicode type and cannot hold characters outside the + database collation. +* **a byte string is ``VARBINARY(MAX)``.** ``BlobType`` and this backend's + :class:`SQLServerVarBinaryMaxType` render the same declaration; the backend + class is named because it is the one this server's adapter writes. +* **a document and the four sequence entries share ``NVARCHAR(MAX)``**: + SQL Server has no JSON *type* on any version this backend targets. A JSON + value is text in an ordinary column and ``OPENJSON`` / ``JSON_VALUE`` / + ``ISJSON`` are functions over it, which is what :class:`JsonType` renders + here; there is no array type either, so ``list``/``tuple``/``set``/ + ``frozenset`` spend the same word. +* **a UUID is native.** ``UNIQUEIDENTIFIER`` is the server's own 16-byte GUID, + reached through :class:`SQLServerUniqueIdentifierType`; the text form + ``CHAR(36)`` would waste width and lose the fixed-length guarantee. +* **there is no interval type.** ``DATEDIFF`` returns a count of a datepart + rather than a value, so ``datetime.timedelta`` is carried as text, its + neutral adapter's form. + +The complex families are carried as the text their neutral adapters already +write -- WKT for ``Geometry``, a JSON array for ``Vector``, bit-string text for +``BitString``, the literal text for ``Range`` / ``Multirange``, canonical +lowercase colon text for ``MacAddress``. SQL Server does have native +``geometry`` / ``geography`` CLR types, but this backend models no ``DataType`` +class for them yet, so the suggestion names the text carrier a bare field can +round-trip through; a field that wants the CLR type declares it with +``UseSqlType``. No key answers ``None``: a suggestion is what a bare field gets, +and taking the table away from the caller is not an answer. + +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 ( + DateType, + DecimalType, + DoubleType, + IntegerType, + JsonType, + TextType, + TimeType, + TimestampType, + VarCharType, +) +from rhosocial.activerecord.backend.impl.sqlserver.expression.types import ( + SQLServerBitType, + SQLServerNVarCharType, + SQLServerUniqueIdentifierType, + SQLServerVarBinaryMaxType, +) + +#: SQL Server's suggested declaration per framework-modelled Python type. +SQLSERVER_DATA_TYPE_SUGGESTIONS: Dict[Any, Optional[Any]] = { + bool: SQLServerBitType(), + int: IntegerType(), + float: DoubleType(), + # A bare DECIMAL is DECIMAL(18, 0) on SQL Server: no fractional digits, so + # a value like Decimal("10.99") would be rounded to 11 on the way in. Give + # the suggestion a scale so a bare ``Decimal`` field round-trips its cents. + decimal.Decimal: DecimalType(precision=18, scale=4), + str: SQLServerNVarCharType(length=255), + bytes: SQLServerVarBinaryMaxType(), + bytearray: SQLServerVarBinaryMaxType(), + datetime.date: DateType(), + datetime.time: TimeType(), + # DATETIME2's default precision is 7, but anything below 6 loses the + # microsecond part of a datetime (3 keeps only milliseconds). Recommend 6 + # so a bare ``datetime`` field round-trips the microsecond a caller writes. + datetime.datetime: TimestampType(precision=6), + # SQL Server has no interval type; the value's text form is the carrier. + datetime.timedelta: TextType(), + uuid.UUID: SQLServerUniqueIdentifierType(), + dict: JsonType(), + list: JsonType(), + tuple: JsonType(), + set: JsonType(), + frozenset: JsonType(), + enum.Enum: VarCharType(length=255), + # -- Complex families ------------------------------------------------ + # The CLR type exists, but no DataType class of this backend names it; WKT + # text is what the adapter writes, so a bare field round-trips through it. + Geometry: TextType(), + # A dimension is column policy; the adapter's JSON text is the carrier. + Vector: TextType(), + # BIT(n) needs a width the annotation does not carry; digits as text. + BitString: TextType(), + # The element type is column policy; the adapter writes the literal text. + Range: TextType(), + Multirange: TextType(), + MacAddress: VarCharType(length=17), +} + + +class SQLServerDataTypeSuggestionsMixin: + """SQL Server's answer to "what declaration does a bare field get here".""" + + def suggested_data_types(self) -> Dict[Any, Optional[Any]]: + return dict(SQLSERVER_DATA_TYPE_SUGGESTIONS) + + +__all__ = [ + "SQLSERVER_DATA_TYPE_SUGGESTIONS", + "SQLServerDataTypeSuggestionsMixin", +] diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/dql.py b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/dql.py index 4ee797f5..71a96278 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/dql.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/dql.py @@ -1,12 +1,18 @@ # src/rhosocial/activerecord/backend/impl/sqlserver/mixins/dql.py -from typing import Any, Optional, Tuple, TYPE_CHECKING +from typing import Optional, Tuple, TYPE_CHECKING from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError from .version_constants import SQL_SERVER_2012 if TYPE_CHECKING: from rhosocial.activerecord.backend.expression.query_parts import LimitOffsetClause - from rhosocial.activerecord.backend.expression.statements import QueryStatement + +from rhosocial.activerecord.backend.expression import ( + Literal, + OrderByClause, + Subquery, +) +from rhosocial.activerecord.backend.expression.statements import QueryStatement class SQLServerDQLMixin: @@ -80,11 +86,36 @@ def format_limit_offset_clause(self, clause: "LimitOffsetClause") -> Tuple[str, return " ".join(parts), () def format_query_statement(self, expr: "QueryStatement") -> Tuple[str, tuple]: - sql, params = super().format_query_statement(expr) - if expr.limit_offset is not None and expr.order_by is None: - lo_sql = expr.limit_offset.to_sql()[0] - if lo_sql and lo_sql in sql: - sql = sql.replace(lo_sql, f"ORDER BY (SELECT NULL) {lo_sql}") - else: - sql += " ORDER BY (SELECT NULL)" - return sql, tuple(params) + """Format a complete SELECT query. + + SQL Server refuses OFFSET/FETCH on a query without an ORDER BY. The + preamble is synthesized as an ``ORDER BY`` *expression* and rendered by + the generic formatter -- the produced SQL is never patched afterwards, + because a formatter only concatenates what the clause objects return. + """ + if expr.limit_offset is None or expr.order_by is not None: + return super().format_query_statement(expr) + preamble = OrderByClause( + self, + expressions=[ + ( + Subquery( + self, QueryStatement(self, select=[Literal(self, None)]) + ), + "ASC", + ) + ], + ) + ordered = QueryStatement( + self, + select=expr.select, + from_=expr.from_, + where=expr.where, + group_by_having=expr.group_by_having, + order_by=preamble, + qualify=expr.qualify, + limit_offset=expr.limit_offset, + for_update=expr.for_update, + select_modifier=expr.select_modifier, + ) + return super().format_query_statement(ordered) diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/integer_auto_increment_column_suggestion.py b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/integer_auto_increment_column_suggestion.py new file mode 100644 index 00000000..a1ec5d7e --- /dev/null +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/integer_auto_increment_column_suggestion.py @@ -0,0 +1,29 @@ +# src/rhosocial/activerecord/backend/impl/sqlserver/mixins/integer_auto_increment_column_suggestion.py +"""SQLServerIntegerAutoIncrementColumnSuggestionMixin -- sqlserver'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 ( + IdentityClause, + IntegerAutoIncrementColumnSuggestion, +) + +if TYPE_CHECKING: # pragma: no cover + from ....expression.types._base import DataType + + +class SQLServerIntegerAutoIncrementColumnSuggestionMixin: + """Suggest sqlserver's declaration for a generated integer key.""" + + def suggest_integer_auto_increment_column( + self, default_type: "DataType" + ) -> IntegerAutoIncrementColumnSuggestion: + return IntegerAutoIncrementColumnSuggestion( + default_type, IdentityClause(self, start=1, increment=1) + ) diff --git a/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/types.py b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/types.py index b9f738df..d4aa478f 100644 --- a/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/types.py +++ b/src/rhosocial/activerecord/backend/impl/sqlserver/mixins/types.py @@ -1006,8 +1006,8 @@ def format_data_type_json(self, data_type: JsonType) -> Tuple[str, tuple]: JSON arrives in SQL Server 2016 as text in an ordinary column, and ``OPENJSON`` / ``JSON_VALUE`` / ``ISJSON`` are functions over that text, not a storage type. So the concept is rendered as the text - column that actually holds it, which is also why ``suggested_data_types`` - names this class for ``jsonb`` and ``array``. + column that actually holds it, which is also why + ``substitute_data_types`` names this class for ``jsonb`` and ``array``. """ return "NVARCHAR(MAX)", () diff --git a/tests/benchmark/__init__.py b/tests/benchmark/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/benchmark/conftest.py b/tests/benchmark/conftest.py new file mode 100644 index 00000000..7fda0db3 --- /dev/null +++ b/tests/benchmark/conftest.py @@ -0,0 +1,8 @@ +# tests/benchmark/conftest.py +"""Register SQL Server 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..6d57c9b7 --- /dev/null +++ b/tests/benchmark/providers.py @@ -0,0 +1,186 @@ +# tests/benchmark/providers.py +"""SQL Server 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. + +SQL Server is a server backend: each feature run gets a fresh, dedicated +database on the configured instance (created and readied for snapshots by the +backend's ``reset_database`` helper). DDL is derived from the model through +the expression system -- no hand-built SQL. +""" +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.sqlserver import SCENARIOS, scenario + + +# --------------------------------------------------------------------------- # +# 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 BaseMigrationMixin (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): + """Return a scenario plus a config for a fresh, dedicated database. + + The name is unique per setup so concurrent or repeated contracts never + share tables, and it stays well within SQL Server's 128-character limit. + ``reset_database`` creates it on ``master`` and enables READ_COMMITTED_SNAPSHOT. + """ + sc = scenario(scenario_name) + database = f"bench_{tag}_{scenario_name}_{uuid.uuid4().hex}" + sc.reset_database(database) + return sc, sc.make_config(database) + + +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, + "rhosocial.activerecord.backend.impl.sqlserver", "sqlserver") + + 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, + "rhosocial.activerecord.backend.impl.sqlserver", "sqlserver") + + 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..19efdaca 100644 --- a/tests/benchmark/relation/conftest.py +++ b/tests/benchmark/relation/conftest.py @@ -1,16 +1,23 @@ """Benchmark fixtures for relation cache comparison. -Bridges ``user_post_comment_classes`` from the testsuite's relation conftest -so that benchmarks can reuse the same model definitions and backend setup. +Reuses ``user_post_comment_classes`` and the relation topic's table +declarations from the testsuite, so benchmarks run against the same models +and schema as the feature suite. 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 +29,19 @@ # 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 +65,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 database shared by this test group.", +) + +@pytest.fixture(scope="session") # def _redis_client(): # redis = pytest.importorskip("redis") # try: @@ -156,3 +187,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 1f84e39f..65347edc 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,95 +1,26 @@ # tests/conftest.py -"""Root conftest for SQL Server backend tests.""" -import os -import time - -import pytest -import yaml - -os.environ.setdefault( - 'TESTSUITE_PROVIDER_REGISTRY', - 'providers.registry:provider_registry' -) - - -def _load_scenario_map(): - """Load scenario configs from the environment or the default file.""" - config_path = os.getenv("SQLSERVER_SCENARIOS_CONFIG_PATH") - if config_path and not os.path.exists(config_path): - print(f"Warning: scenario file not found: {config_path}") - return {} - if not config_path: - config_path = os.path.join(os.path.dirname(__file__), "config", "sqlserver_scenarios.yaml") - if not os.path.exists(config_path): - return {} - try: - with open(config_path, 'r', encoding='utf-8') as f: - data = yaml.safe_load(f) - except Exception: - return {} - return data.get("scenarios", {}) or {} +"""Root configuration for the SQL Server backend's test tree. +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. -@pytest.fixture(scope="session", autouse=True) -def _prepare_read_committed_snapshot(): - """Verify READ_COMMITTED_SNAPSHOT is enabled on every scenario database. +``READ_COMMITTED_SNAPSHOT`` is no longer checked here either. Each test +directory owns a database and ``support.sqlserver`` turns the option on when it +creates that database, which is both earlier than the first test and free of +the exclusive lock a running database would need. +""" - The actual ALTER DATABASE is performed by the CI workflow step - 'Enable READ_COMMITTED_SNAPSHOT' *before* pytest runs, so there is - no risk of xdist workers deadlocking on the exclusive database lock. +import pytest +import support.sqlserver - This fixture only checks and warns if the option is not yet on - (e.g. when running locally without the workflow). - """ - from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend - from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig +_SCENARIOS = [support.sqlserver.scenario(name) for name in support.sqlserver.SCENARIOS] - scenarios = _load_scenario_map() - if not scenarios: - return - for _scenario_name, config in scenarios.items(): - if not config: - continue - db_name = config.get("database") - if not db_name: - continue - try: - backend = SQLServerBackend(connection_config=SQLServerConnectionConfig(**config)) - backend.connect() - except Exception: - continue - try: - cursor = backend._connection.cursor() - cursor.execute( - "SELECT is_read_committed_snapshot_on FROM sys.databases WHERE name = ?", - (db_name,), - ) - row = cursor.fetchone() - is_on = row[0] if row and isinstance(row, (list, tuple)) else ( - getattr(row, "is_read_committed_snapshot_on", False) if row else False - ) - cursor.close() - if not is_on: - # Not yet enabled — try to enable (single-process / local run). - # With xdist, only the first worker to acquire the lock succeeds; - # others will get a timeout and we silently continue. - for _attempt in range(2): - try: - backend.execute("SET LOCK_TIMEOUT 3000") - backend.execute( - f"ALTER DATABASE [{db_name}] SET READ_COMMITTED_SNAPSHOT ON" - ) - break - except Exception: - time.sleep(0.5) - except Exception: - pass - finally: - try: - backend.disconnect() - except Exception: - pass +@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 def pytest_configure(config): @@ -97,9 +28,7 @@ def pytest_configure(config): config.addinivalue_line( "markers", "requires_sqlserver: mark test as requiring SQL Server connection" ) - config.addinivalue_line( - "markers", "slow: mark test as slow running" - ) + config.addinivalue_line("markers", "slow: mark test as slow running") config.addinivalue_line( "markers", "requires_protocol: Mark tests that require specific database protocol support" ) @@ -108,4 +37,4 @@ def pytest_configure(config): ) config.addinivalue_line( "markers", "requires_inner_join: Mark test as requiring INNER JOIN support" - ) \ No newline at end of file + ) diff --git a/tests/plugins/expression_xdist.py b/tests/plugins/expression_xdist.py index 67a54eeb..fcfce7cf 100644 --- a/tests/plugins/expression_xdist.py +++ b/tests/plugins/expression_xdist.py @@ -18,11 +18,11 @@ installation is not this plugin's business, and the run proceeds serially the way it always has. * **Scope**: only when every non-option argument names a path inside the - expression area (``feature/backend/expression``) is ``-n auto`` appended. A - whole-repository run, a mixed run, or a run of any other directory keeps the - serial default; the live scenario tests have their own parallel runner - (``--scenario-parallel``) and are not dragged into a worker pool they did not - ask for. + expression area (``feature/backend/construct/expression``) is ``-n auto`` + appended. A whole-repository run, a mixed run, or a run of any other + directory keeps the serial default; the live scenario tests have their own + parallel runner (``--scenario-parallel``) and are not dragged into a worker + pool they did not ask for. * **Choice respected**: an explicit ``-n`` / ``--numprocesses`` is never overridden. An explicit ``--dist`` is never overridden either, except that ``loadscope`` and ``loadfile`` are refused outright (§12: they bind whole @@ -45,6 +45,7 @@ "activerecord_sqlserver_test", "feature", "backend", + "construct", "expression", ) diff --git a/tests/providers/basic.py b/tests/providers/basic.py deleted file mode 100644 index c343df90..00000000 --- a/tests/providers/basic.py +++ /dev/null @@ -1,702 +0,0 @@ -# tests/providers/basic.py -""" -This file provides concrete implementations of the `IBasicSyncProvider` and -`IBasicAsyncProvider` interfaces defined in the `rhosocial-activerecord-testsuite` -package for the SQL Server backend. - -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 - -logger = logging.getLogger(__name__) - -from rhosocial.activerecord.backend.type_adapter import BaseSQLTypeAdapter # noqa: E402 -from rhosocial.activerecord.model import ActiveRecord # noqa: E402 - -from rhosocial.activerecord.testsuite.utils import select_fixture # noqa: E402 - -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, - BulkUser as BulkUserBase, -) -from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( # noqa: E402 - AsyncBulkUser as AsyncBulkUserBase, -) - -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, -) - -User310 = TypeCase310 = ValidatedFieldUser310 = TypeTestModel310 = ValidatedUser310 = None -TypeAdapterTest310 = PydanticValidatedModel310 = MappedUser310 = MappedPost310 = MappedComment310 = None -ColumnMappingModel310 = MixedAnnotationModel310 = BulkUser310 = None -AsyncUser310 = AsyncTypeCase310 = AsyncValidatedFieldUser310 = AsyncTypeTestModel310 = None -AsyncValidatedUser310 = AsyncTypeAdapterTest310 = AsyncPydanticValidatedModel310 = AsyncMappedUser310 = ( - AsyncMappedPost310 -) = None -AsyncMappedComment310 = AsyncColumnMappingModel310 = AsyncMixedAnnotationModel310 = AsyncBulkUser310 = 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, - BulkUser as BulkUser310, - ) - 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, - AsyncBulkUser as AsyncBulkUser310, - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.10+ fixtures: {e}") - -User311 = TypeCase311 = ValidatedFieldUser311 = TypeTestModel311 = ValidatedUser311 = None -TypeAdapterTest311 = PydanticValidatedModel311 = MappedUser311 = MappedPost311 = MappedComment311 = None -ColumnMappingModel311 = MixedAnnotationModel311 = BulkUser311 = None -AsyncUser311 = AsyncTypeCase311 = AsyncValidatedFieldUser311 = AsyncTypeTestModel311 = None -AsyncValidatedUser311 = AsyncTypeAdapterTest311 = AsyncPydanticValidatedModel311 = AsyncMappedUser311 = ( - AsyncMappedPost311 -) = None -AsyncMappedComment311 = AsyncColumnMappingModel311 = AsyncMixedAnnotationModel311 = AsyncBulkUser311 = 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, - BulkUser as BulkUser311, - ) - 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, - AsyncBulkUser as AsyncBulkUser311, - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.11+ fixtures: {e}") - -User312 = TypeCase312 = ValidatedFieldUser312 = TypeTestModel312 = ValidatedUser312 = None -TypeAdapterTest312 = PydanticValidatedModel312 = MappedUser312 = MappedPost312 = MappedComment312 = None -ColumnMappingModel312 = MixedAnnotationModel312 = BulkUser312 = None -AsyncUser312 = AsyncTypeCase312 = AsyncValidatedFieldUser312 = AsyncTypeTestModel312 = None -AsyncValidatedUser312 = AsyncTypeAdapterTest312 = AsyncPydanticValidatedModel312 = AsyncMappedUser312 = ( - AsyncMappedPost312 -) = None -AsyncMappedComment312 = AsyncColumnMappingModel312 = AsyncMixedAnnotationModel312 = AsyncBulkUser312 = 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, - BulkUser as BulkUser312, - ) - 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, - AsyncBulkUser as AsyncBulkUser312, - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.12+ fixtures: {e}") - - -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 - - -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" -) -TypeTestModel = _select_model_class( - TypeTestModelBase, TypeTestModel312, TypeTestModel311, TypeTestModel310, "TypeTestModel" -) -ValidatedUser = _select_model_class( - ValidatedUserBase, ValidatedUser312, ValidatedUser311, ValidatedUser310, "ValidatedUser" -) -TypeAdapterTest = _select_model_class( - TypeAdapterTestBase, TypeAdapterTest312, TypeAdapterTest311, TypeAdapterTest310, "TypeAdapterTest" -) -PydanticValidatedModel = _select_model_class( - PydanticValidatedModelBase, - PydanticValidatedModel312, - PydanticValidatedModel311, - PydanticValidatedModel310, - "PydanticValidatedModel", -) -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" -) -ColumnMappingModel = _select_model_class( - ColumnMappingModelBase, ColumnMappingModel312, ColumnMappingModel311, ColumnMappingModel310, "ColumnMappingModel" -) -MixedAnnotationModel = _select_model_class( - MixedAnnotationModelBase, - MixedAnnotationModel312, - MixedAnnotationModel311, - MixedAnnotationModel310, - "MixedAnnotationModel", -) -BulkUser = _select_model_class(BulkUserBase, BulkUser312, BulkUser311, BulkUser310, "BulkUser") - -AsyncUser = _select_model_class(AsyncUserBase, AsyncUser312, AsyncUser311, AsyncUser310, "AsyncUser") -AsyncTypeCase = _select_model_class( - AsyncTypeCaseBase, AsyncTypeCase312, AsyncTypeCase311, AsyncTypeCase310, "AsyncTypeCase" -) -AsyncValidatedFieldUser = _select_model_class( - AsyncValidatedFieldUserBase, - AsyncValidatedFieldUser312, - AsyncValidatedFieldUser311, - AsyncValidatedFieldUser310, - "AsyncValidatedFieldUser", -) -AsyncTypeTestModel = _select_model_class( - AsyncTypeTestModelBase, AsyncTypeTestModel312, AsyncTypeTestModel311, AsyncTypeTestModel310, "AsyncTypeTestModel" -) -AsyncValidatedUser = _select_model_class( - AsyncValidatedUserBase, AsyncValidatedUser312, AsyncValidatedUser311, AsyncValidatedUser310, "AsyncValidatedUser" -) -AsyncTypeAdapterTest = _select_model_class( - AsyncTypeAdapterTestBase, - AsyncTypeAdapterTest312, - AsyncTypeAdapterTest311, - AsyncTypeAdapterTest310, - "AsyncTypeAdapterTest", -) -AsyncPydanticValidatedModel = _select_model_class( - AsyncPydanticValidatedModelBase, - AsyncPydanticValidatedModel312, - AsyncPydanticValidatedModel311, - AsyncPydanticValidatedModel310, - "AsyncPydanticValidatedModel", -) -AsyncMappedUser = _select_model_class( - AsyncMappedUserBase, AsyncMappedUser312, AsyncMappedUser311, AsyncMappedUser310, "AsyncMappedUser" -) -AsyncMappedPost = _select_model_class( - AsyncMappedPostBase, AsyncMappedPost312, AsyncMappedPost311, AsyncMappedPost310, "AsyncMappedPost" -) -AsyncMappedComment = _select_model_class( - AsyncMappedCommentBase, AsyncMappedComment312, AsyncMappedComment311, AsyncMappedComment310, "AsyncMappedComment" -) -AsyncColumnMappingModel = _select_model_class( - AsyncColumnMappingModelBase, - AsyncColumnMappingModel312, - AsyncColumnMappingModel311, - AsyncColumnMappingModel310, - "AsyncColumnMappingModel", -) -AsyncMixedAnnotationModel = _select_model_class( - AsyncMixedAnnotationModelBase, - AsyncMixedAnnotationModel312, - AsyncMixedAnnotationModel311, - AsyncMixedAnnotationModel310, - "AsyncMixedAnnotationModel", -) -AsyncBulkUser = _select_model_class( - AsyncBulkUserBase, AsyncBulkUser312, AsyncBulkUser311, AsyncBulkUser310, "AsyncBulkUser" -) - -from rhosocial.activerecord.testsuite.feature.basic.interfaces import ( # noqa: E402 - IBasicSyncProvider, - IBasicAsyncProvider, -) -from rhosocial.activerecord.testsuite.core.protocols import WorkerTestProtocol # noqa: E402 - -from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( # noqa: E402 - OrderItem as CompositeOrderItem, - AsyncOrderItem as AsyncCompositeOrderItem, - StoreInventory as StoreInventoryModel, - AsyncStoreInventory as AsyncStoreInventoryModel, - Order as OrderModel, - AsyncOrder as AsyncOrderModel, - MappedOrderItem as MappedOrderItemModel, - AsyncMappedOrderItem as AsyncMappedOrderItemModel, - Product as ProductModel, - AsyncProduct as AsyncProductModel, - ProductFormA as ProductFormAModel, - AsyncProductFormA as AsyncProductFormAModel, - ProductWithProxy as ProductWithProxyModel, - AsyncProductWithProxy as AsyncProductWithProxyModel, - ProductWithColumnAndAdapter as ProductWithColumnAndAdapterModel, - AsyncProductWithColumnAndAdapter as AsyncProductWithColumnAndAdapterModel, -) - -from .scenarios import get_enabled_scenarios, get_scenario # noqa: E402 - -from providers.fixtures._common import ( - safe_drop_table, safe_drop_table_async, - disable_fk_checks, enable_fk_checks, - disable_fk_checks_async, enable_fk_checks_async, -) - -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 SQL Server dialect instance. - - Used by the ``feature/basic/ddl`` subtopic (expression/dialect - contract). ``(16, 0, 0)`` advertises support for the ``IF - [NOT] EXISTS`` ``DROP`` modifiers (available since 2016). - """ - from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect - - return SQLServerDialect(version=(16, 0, 0)) - - def _track_backend(self, backend_instance, collection: List) -> None: - if backend_instance not in collection: - collection.append(backend_instance) - - def _load_sqlserver_schema(self, filename: str) -> str: - schema_dir = os.path.join( - os.path.dirname(__file__), "..", "rhosocial", "activerecord_sqlserver_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() - - _load_mysql_schema = _load_sqlserver_schema - - -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: - from rhosocial.activerecord.backend.options import ExecutionOptions - from rhosocial.activerecord.backend.schema import StatementType - from rhosocial.activerecord.backend.expression import DropTableStatement - from rhosocial.activerecord.backend.expression.objects import Table - from providers.fixtures.basic import TABLE_EXPRESSIONS - from providers.fixtures._common import to_sqlserver_ddl_sql - - options = ExecutionOptions(stmt_type=StatementType.DDL) - backend = model_class.__backend__ - safe_drop_table(backend, backend.dialect, table_name) - if fn := TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend.dialect, table_name) - create_sql, params = to_sqlserver_ddl_sql(create_expr) - backend.execute(create_sql, params, options=options) - else: - schema_sql = self._load_sqlserver_schema(f"{table_name}.sql") - backend.execute(schema_sql, options=options) - - 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]: - import pytest - backend_class, config = get_scenario(scenario_name) - temp_backend = backend_class(connection_config=config) - temp_backend.connect() - actual_version = temp_backend.get_server_version() - temp_backend.disconnect() - from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect - temp_dialect = SQLServerDialect(actual_version) - if not temp_dialect.supports_json_type(): - pytest.skip(f"JSON type not supported by SQLServer version {actual_version}") - model = self._setup_model(TypeTestModel, scenario_name, "type_tests") - return model - - 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], ...]: - return self._setup_multiple_models( - [(ColumnMappingModel, "column_mapping_items"), (MixedAnnotationModel, "mixed_annotation_items")], - scenario_name, - ) - - def setup_type_adapter_model_and_schema(self, scenario_name: Optional[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]: - return self._setup_model(CompositeOrderItem, scenario_name, "order_items") - - def setup_order_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(OrderModel, scenario_name, "orders") - - def setup_mapped_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(MappedOrderItemModel, scenario_name, "order_items") - - def setup_product_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(ProductModel, scenario_name, "product") - - def setup_product_form_a_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(ProductFormAModel, scenario_name, "product") - - def setup_product_with_proxy_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(ProductWithProxyModel, scenario_name, "product") - - def setup_product_with_column_and_adapter_model(self, scenario_name: str) -> Type[ActiveRecord]: - return self._setup_model(ProductWithColumnAndAdapterModel, scenario_name, "product") - - 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 = "AsyncSQLServerBackend" if is_async else "SQLServerBackend" - 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 providers.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.sqlserver.backend", - "backend_class_name": backend_class_name, - "config_class_module": "rhosocial.activerecord.backend.impl.sqlserver.config", - "config_class_name": "SQLServerConnectionConfig", - "config_kwargs": config_dict, - "schema_sql": self.get_worker_schema_sql(scenario_name, table_name), - } - - def get_worker_schema_sql(self, scenario_name: str, table_name: str) -> str: - from providers.fixtures.basic import TABLE_EXPRESSIONS - from providers.fixtures._common import to_sqlserver_ddl_sql - from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect - - if fn := TABLE_EXPRESSIONS.get(table_name): - dialect = SQLServerDialect() - sql, _ = to_sqlserver_ddl_sql(fn(dialect, table_name)) - return sql - return self._load_sqlserver_schema(f"{table_name}.sql") - - def cleanup_after_test(self, scenario_name: str): - for backend_instance in self._active_backends: - for table_name in list(self._created_tables): - try: - safe_drop_table(backend_instance, backend_instance.dialect, table_name) - except Exception: - pass - 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.sqlserver.backend.async_backend import AsyncSQLServerBackend - _, config = get_scenario(scenario_name) - await model_class.configure(config, AsyncSQLServerBackend) - 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: - from rhosocial.activerecord.backend.options import ExecutionOptions - from rhosocial.activerecord.backend.schema import StatementType - from rhosocial.activerecord.backend.expression import DropTableStatement - from rhosocial.activerecord.backend.expression.objects import Table - from providers.fixtures.basic import TABLE_EXPRESSIONS - from providers.fixtures._common import to_sqlserver_ddl_sql - - options = ExecutionOptions(stmt_type=StatementType.DDL) - backend = model_class.__backend__ - await safe_drop_table_async(backend, backend.dialect, table_name) - if fn := TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend.dialect, table_name) - create_sql, params = to_sqlserver_ddl_sql(create_expr) - await backend.execute(create_sql, params, options=options) - else: - schema_sql = self._load_sqlserver_schema(f"{table_name}.sql") - await backend.execute(schema_sql, options=options) - - async def _initialize_async_model_schema(self, model_class: Type[ActiveRecord], table_name: str): - await self._reset_table_async(model_class, table_name) - - 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]: - import pytest - from rhosocial.activerecord.backend.impl.sqlserver.backend.async_backend import AsyncSQLServerBackend - _, config = get_scenario(scenario_name) - temp_backend = AsyncSQLServerBackend(connection_config=config) - await temp_backend.connect() - actual_version = await temp_backend.get_server_version() - await temp_backend.disconnect() - from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect - temp_dialect = SQLServerDialect(actual_version) - if not temp_dialect.supports_json_type(): - pytest.skip(f"JSON type not supported by SQLServer version {actual_version}") - model = await self._setup_async_model(AsyncTypeTestModel, scenario_name, "type_tests") - return model - - 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]]: - user = await self._setup_async_model(AsyncMappedUser, scenario_name, "users") - shared_backend = user.__backend__ - post_model_class = AsyncMappedPost - post_model_class.__connection_config__ = user.__connection_config__ - post_model_class.__backend_class__ = user.__backend_class__ - post_model_class.__backend__ = shared_backend - await self._initialize_async_model_schema(post_model_class, "posts") - self._created_tables.add("posts") - comment_model_class = AsyncMappedComment - comment_model_class.__connection_config__ = user.__connection_config__ - comment_model_class.__backend_class__ = user.__backend_class__ - comment_model_class.__backend__ = shared_backend - await self._initialize_async_model_schema(comment_model_class, "comments") - self._created_tables.add("comments") - return user, post_model_class, comment_model_class - - async def setup_mixed_models(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - column_mapping_model = await self._setup_async_model( - AsyncColumnMappingModel, scenario_name, "column_mapping_items" - ) - shared_backend = column_mapping_model.__backend__ - mixed_annotation_model_class = AsyncMixedAnnotationModel - mixed_annotation_model_class.__connection_config__ = column_mapping_model.__connection_config__ - mixed_annotation_model_class.__backend_class__ = column_mapping_model.__backend_class__ - mixed_annotation_model_class.__backend__ = shared_backend - await self._initialize_async_model_schema(mixed_annotation_model_class, "mixed_annotation_items") - self._created_tables.add("mixed_annotation_items") - return column_mapping_model, mixed_annotation_model_class - - 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]: - return await self._setup_async_model(AsyncCompositeOrderItem, scenario_name, "order_items") - - async def setup_order_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncOrderModel, scenario_name, "orders") - - async def setup_mapped_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncMappedOrderItemModel, scenario_name, "order_items") - - async def setup_product_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncProductModel, scenario_name, "product") - - async def setup_product_form_a_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncProductFormAModel, scenario_name, "product") - - async def setup_product_with_proxy_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncProductWithProxyModel, scenario_name, "product") - - async def setup_product_with_column_and_adapter_model(self, scenario_name: str) -> Type[ActiveRecord]: - return await self._setup_async_model(AsyncProductWithColumnAndAdapterModel, scenario_name, "product") - - async def cleanup_after_test(self, scenario_name: str): - for backend_instance in self._active_async_backends: - for table_name in list(self._created_tables): - try: - await safe_drop_table_async(backend_instance, backend_instance.dialect, table_name) - except Exception: - pass - 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 e2c65f7d..00000000 --- a/tests/providers/basic_connection.py +++ /dev/null @@ -1,162 +0,0 @@ -# tests/providers/basic_connection.py -""" -Concrete implementation of IBasicConnectionProvider for SQL Server 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.sqlserver.backend import SQLServerBackend -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): - """ - SQL Server 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 INT IDENTITY(1,1) 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)) - except Exception: - pass - - await backend.execute(""" - CREATE TABLE test_users ( - id INT IDENTITY(1,1) 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) - - pool_config = PoolConfig( - min_size=1, - max_size=5, - backend_factory=lambda: SQLServerBackend(connection_config=config) - ) - pool = BackendPool.create(pool_config) - - with pool.connection() as backend: - self._create_test_table(backend) - self._active_backends.append(backend) - - SyncTestUser.configure(config, SQLServerBackend) - 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.sqlserver.backend.async_backend import AsyncSQLServerBackend - - _, config = get_scenario(scenario_name) - - pool_config = PoolConfig( - min_size=1, - max_size=5, - backend_factory=lambda: AsyncSQLServerBackend(connection_config=config) - ) - - pool = await AsyncBackendPool.create(pool_config) - - async with pool.connection() as backend: - await self._create_test_table_async(backend) - self._active_async_backends.append(backend) - - await AsyncTestUser.configure(config, AsyncSQLServerBackend) - 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 - - for backend in self._active_backends: - 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 - - for backend in self._active_async_backends: - 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) \ No newline at end of file diff --git a/tests/providers/events.py b/tests/providers/events.py deleted file mode 100644 index 26cdaa49..00000000 --- a/tests/providers/events.py +++ /dev/null @@ -1,203 +0,0 @@ -# tests/providers/events.py -""" -Concrete implementations of `IEventsSyncProvider` and `IEventsAsyncProvider` -for the SQL Server backend. -""" - -import os -import sys -import logging -from typing import Type, List - -from rhosocial.activerecord.model import ActiveRecord - -logger = logging.getLogger(__name__) - -from rhosocial.activerecord.testsuite.utils import select_fixture # noqa: E402 - -from rhosocial.activerecord.testsuite.feature.events.fixtures.models import ( # noqa: E402 - EventTestModel as EventTestModelBase, - EventTrackingModel as EventTrackingModelBase, - AsyncEventTestModel as AsyncEventTestModelBase, -) - -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}") - -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}") - -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}") - - -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 - - -EventTestModel = _select_model_class( - EventTestModelBase, EventTestModel312, EventTestModel311, EventTestModel310, "EventTestModel" -) -AsyncEventTestModel = AsyncEventTestModelBase -EventTrackingModel = _select_model_class( - EventTrackingModelBase, EventTrackingModel312, EventTrackingModel311, EventTrackingModel310, "EventTrackingModel" -) - -from rhosocial.activerecord.testsuite.feature.events.interfaces import ( # noqa: E402 - IEventsSyncProvider, - IEventsAsyncProvider, -) - -from .scenarios import get_enabled_scenarios, get_scenario # noqa: E402 - -from providers.fixtures._common import ( - safe_drop_table, safe_drop_table_async, - disable_fk_checks, enable_fk_checks, - disable_fk_checks_async, enable_fk_checks_async, -) - -class EventsProviderBase: - def __init__(self): - self._scenario_db_files = {} - - def get_test_scenarios(self) -> List[str]: - return list(get_enabled_scenarios().keys()) - - def _load_sqlserver_schema(self, filename: str) -> str: - schema_dir = os.path.join( - os.path.dirname(__file__), "..", "rhosocial", "activerecord_sqlserver_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() - - _load_mysql_schema = _load_sqlserver_schema - - -class EventsSyncProvider(EventsProviderBase, IEventsSyncProvider): - def __init__(self): - super().__init__() - self._active_backends = [] - - def _setup_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]: - from rhosocial.activerecord.backend.options import ExecutionOptions - from rhosocial.activerecord.backend.schema import StatementType - from rhosocial.activerecord.backend.expression import DropTableStatement - from rhosocial.activerecord.backend.expression.objects import Table - from providers.fixtures.events import TABLE_EXPRESSIONS - from providers.fixtures._common import to_sqlserver_ddl_sql - - 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) - options = ExecutionOptions(stmt_type=StatementType.DDL) - safe_drop_table(backend_instance, backend_instance.dialect, table_name) - if fn := TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - create_sql, params = to_sqlserver_ddl_sql(create_expr) - backend_instance.execute(create_sql, params, options=options) - else: - schema_sql = self._load_sqlserver_schema(f"{table_name}.sql") - backend_instance.execute(schema_sql, options=options) - 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: - for table_name in ["event_tests", "event_tracking_models"]: - try: - safe_drop_table(backend_instance, backend_instance.dialect, table_name) - except Exception: - pass - 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.sqlserver.backend.async_backend import AsyncSQLServerBackend - from rhosocial.activerecord.backend.options import ExecutionOptions - from rhosocial.activerecord.backend.schema import StatementType - from rhosocial.activerecord.backend.expression import DropTableStatement - from rhosocial.activerecord.backend.expression.objects import Table - from providers.fixtures.events import TABLE_EXPRESSIONS - from providers.fixtures._common import to_sqlserver_ddl_sql - - _, config = get_scenario(scenario_name) - await model_class.configure(config, AsyncSQLServerBackend) - backend_instance = model_class.__backend__ - if backend_instance not in self._active_async_backends: - self._active_async_backends.append(backend_instance) - options = ExecutionOptions(stmt_type=StatementType.DDL) - await safe_drop_table_async(backend_instance, backend_instance.dialect, table_name) - if fn := TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - create_sql, params = to_sqlserver_ddl_sql(create_expr) - await backend_instance.execute(create_sql, params, options=options) - else: - schema_sql = self._load_sqlserver_schema(f"{table_name}.sql") - await backend_instance.execute(schema_sql, options=options) - 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: - for table_name in ["event_tests", "event_tracking_models"]: - try: - await safe_drop_table_async(backend_instance, backend_instance.dialect, table_name) - except Exception: - pass - try: - await backend_instance.disconnect() - except Exception: - pass - self._active_async_backends.clear() diff --git a/tests/providers/fixtures/__init__.py b/tests/providers/fixtures/__init__.py deleted file mode 100644 index 0f70dba1..00000000 --- a/tests/providers/fixtures/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# tests/providers/fixtures/__init__.py -"""SQL Server-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 -SQL Server-compatible DDL (INT IDENTITY / NVARCHAR / DATETIME2 / TINYINT / JSON). -The pre-existing ``.sql`` schema files under -``tests/rhosocial/activerecord_sqlserver_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 1bc1595b..00000000 --- a/tests/providers/fixtures/_common.py +++ /dev/null @@ -1,146 +0,0 @@ -# tests/providers/fixtures/_common.py -"""Shared helpers for the SQL Server DDL expression fixtures.""" - -from __future__ import annotations - -from typing import Tuple - -from rhosocial.activerecord.backend.expression import ( - CreateTableStatement, - DropTableStatement, -) -from rhosocial.activerecord.backend.expression.objects import Table -from rhosocial.activerecord.backend.options import ExecutionOptions -from rhosocial.activerecord.backend.schema import StatementType - - -def to_sqlserver_ddl_sql(expr: CreateTableStatement) -> Tuple[str, tuple]: - """Generate canonical SQL Server DDL for a :class:`CreateTableStatement`. - - 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 across backends. - """ - return expr.to_sql() - - -def create_table_sql(expr: CreateTableStatement) -> Tuple[str, tuple]: - """Public alias for :func:`to_sqlserver_ddl_sql`.""" - return to_sqlserver_ddl_sql(expr) - - -def drop_table(dialect, table_name: str) -> DropTableStatement: - """Build a ``DROP TABLE IF EXISTS table_name`` expression.""" - return DropTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_exists=True, - ) - - -def _drop_fk_constraints_for_table(backend, table_name: str) -> None: - """Drop all foreign key constraints that reference the given table.""" - sql = f""" - DECLARE @sql NVARCHAR(MAX) = N'' - SELECT @sql += 'ALTER TABLE [' + OBJECT_SCHEMA_NAME(fk.parent_object_id) + '].[' + OBJECT_NAME(fk.parent_object_id) + '] DROP CONSTRAINT [' + fk.name + ']; ' - FROM sys.foreign_keys fk - WHERE OBJECT_NAME(fk.referenced_object_id) = '{table_name}' - AND OBJECT_SCHEMA_NAME(fk.parent_object_id) = 'dbo' - EXEC sp_executesql @sql - """ - try: - backend.execute(sql) - except Exception: - pass - - -async def _drop_fk_constraints_for_table_async(backend, table_name: str) -> None: - """Async version: drop all FK constraints that reference the given table.""" - sql = f""" - DECLARE @sql NVARCHAR(MAX) = N'' - SELECT @sql += 'ALTER TABLE [' + OBJECT_SCHEMA_NAME(fk.parent_object_id) + '].[' + OBJECT_NAME(fk.parent_object_id) + '] DROP CONSTRAINT [' + fk.name + ']; ' - FROM sys.foreign_keys fk - WHERE OBJECT_NAME(fk.referenced_object_id) = '{table_name}' - AND OBJECT_SCHEMA_NAME(fk.parent_object_id) = 'dbo' - EXEC sp_executesql @sql - """ - try: - await backend.execute(sql) - except Exception: - pass - - -def _drop_all_fk_constraints(backend) -> None: - """Drop all foreign key constraints in the current database.""" - sql = """ - DECLARE @sql NVARCHAR(MAX) = N'' - SELECT @sql += 'ALTER TABLE [' + OBJECT_SCHEMA_NAME(fk.parent_object_id) + '].[' + OBJECT_NAME(fk.parent_object_id) + '] DROP CONSTRAINT [' + fk.name + ']; ' - FROM sys.foreign_keys fk WHERE OBJECT_SCHEMA_NAME(fk.parent_object_id) = 'dbo' - EXEC sp_executesql @sql - """ - try: - backend.execute(sql) - except Exception: - pass - - -def drop_all_tables(backend) -> None: - """Drop all user tables in the current database, handling FK dependencies.""" - _drop_all_fk_constraints(backend) - sql = """ - DECLARE @sql NVARCHAR(MAX) = N''; - SELECT @sql += 'DROP TABLE IF EXISTS [' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']; ' - FROM INFORMATION_SCHEMA.TABLES - WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'dbo'; - EXEC sp_executesql @sql; - """ - try: - backend.execute(sql) - except Exception: - pass - - -def safe_drop_table(backend, dialect, table_name: str) -> None: - """Drop a single table, first removing FK constraints that reference it.""" - _drop_fk_constraints_for_table(backend, table_name) - options = ExecutionOptions(stmt_type=StatementType.DDL) - try: - drop_expr = DropTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_exists=True, - ) - backend.execute(*drop_expr.to_sql(), options=options) - except Exception: - pass - - -async def safe_drop_table_async(backend, dialect, table_name: str) -> None: - """Async version of safe_drop_table.""" - await _drop_fk_constraints_for_table_async(backend, table_name) - options = ExecutionOptions(stmt_type=StatementType.DDL) - try: - drop_expr = DropTableStatement( - dialect=dialect, - table=Table(dialect, table_name), - if_exists=True, - ) - await backend.execute(*drop_expr.to_sql(), options=options) - except Exception: - pass - - -def disable_fk_checks(backend) -> None: - """No-op: SQL Server does not require FK check disabling for DROP TABLE IF EXISTS.""" - - -async def disable_fk_checks_async(backend) -> None: - """Async no-op.""" - - -def enable_fk_checks(backend) -> None: - """No-op.""" - - -async def enable_fk_checks_async(backend) -> None: - """Async no-op.""" diff --git a/tests/providers/fixtures/basic.py b/tests/providers/fixtures/basic.py deleted file mode 100644 index 3dca45f1..00000000 --- a/tests/providers/fixtures/basic.py +++ /dev/null @@ -1,526 +0,0 @@ -# tests/providers/fixtures/basic.py -"""DDL expressions for the ``feature/basic`` table group (SQL Server). - -Each factory builds a :class:`CreateTableStatement` whose generated T-SQL -DDL is semantically equivalent to the reference ``.sql`` schema files under -``tests/rhosocial/activerecord_sqlserver_test/feature/basic/schema/``. -""" - -from typing import Callable, Dict - -from rhosocial.activerecord.backend.expression import ( - CreateTableStatement, -) -from rhosocial.activerecord.backend.expression.objects import Table -from rhosocial.activerecord.backend.expression.statements import ( - ColumnDefinition, - ColumnConstraint, - ColumnDefaultConstraint, - ColumnNotNullConstraint, - ColumnPrimaryKeyConstraint, - ColumnUniqueConstraint, - ForeignKeyConstraint, - IndexDefinition, - TableConstraint, - TablePrimaryKeyConstraint, - ReferentialAction, -) -from rhosocial.activerecord.backend.expression.types import ( - BigIntType, - BooleanType, - CharType, - DateType, - DateTimeType, - DecimalType, - DoubleType, - FloatType, - IntegerType, - JsonType, - SmallIntType, - TextType, - TimeType, - BlobType, - VarCharType, -) - -from . import _common - -_CASCADE = ReferentialAction.CASCADE - - -def to_sql(expr: CreateTableStatement): - """Route a CreateTableStatement through the canonical SQL Server DDL pass-through.""" - return _common.to_sqlserver_ddl_sql(expr) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "username", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnUniqueConstraint(dialect))]), - ColumnDefinition(dialect, "email", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnUniqueConstraint(dialect))]), - ColumnDefinition(dialect, "age", IntegerType(dialect)), - ColumnDefinition(dialect, "balance", FloatType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.0))]), - ColumnDefinition(dialect, "is_active", BooleanType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "created_at", TextType(dialect)), - ColumnDefinition(dialect, "updated_at", TextType(dialect)), - ], - ) - - -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", CharType(dialect, length=36), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "username", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "email", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "tiny_int", SmallIntType(dialect)), - ColumnDefinition(dialect, "small_int", SmallIntType(dialect)), - ColumnDefinition(dialect, "big_int", BigIntType(dialect)), - ColumnDefinition(dialect, "float_val", FloatType(dialect)), - ColumnDefinition(dialect, "double_val", DoubleType(dialect)), - ColumnDefinition(dialect, "decimal_val", DecimalType(dialect, precision=10, scale=6)), - ColumnDefinition(dialect, "char_val", CharType(dialect, length=10)), - ColumnDefinition(dialect, "varchar_val", VarCharType(dialect, length=50)), - ColumnDefinition(dialect, "text_val", TextType(dialect)), - ColumnDefinition(dialect, "date_val", DateType(dialect)), - ColumnDefinition(dialect, "time_val", TimeType(dialect)), - ColumnDefinition(dialect, "timestamp_val", DateTimeType(dialect)), - ColumnDefinition(dialect, "blob_val", BlobType(dialect)), - ColumnDefinition(dialect, "json_val", JsonType(dialect)), - ColumnDefinition(dialect, "array_val", JsonType(dialect)), - ColumnDefinition(dialect, "is_active", BooleanType(dialect)), - ], - ) - - -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", CharType(dialect, length=36), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))]), - ColumnDefinition(dialect, "string_field", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "test string"))]), - ColumnDefinition(dialect, "int_field", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 42))]), - ColumnDefinition(dialect, "float_field", FloatType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 3.14))]), - ColumnDefinition(dialect, "decimal_field", DoubleType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 10.99))]), - ColumnDefinition(dialect, "bool_field", BooleanType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "datetime_field", TextType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "json_field", JsonType(dialect)), - ColumnDefinition(dialect, "nullable_field", VarCharType(dialect, length=255)), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "username", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "email", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "age", IntegerType(dialect)), - ColumnDefinition(dialect, "balance", DecimalType(dialect, precision=10, scale=2)), - ColumnDefinition(dialect, "credit_score", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "status", VarCharType(dialect, length=50), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "active"))]), - ColumnDefinition(dialect, "is_active", BooleanType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "username", VarCharType(dialect, length=50), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "email", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "age", IntegerType(dialect)), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "code", VarCharType(dialect, length=32)), - ColumnDefinition(dialect, "quantity", IntegerType(dialect)), - ColumnDefinition(dialect, "step_count", IntegerType(dialect)), - ColumnDefinition(dialect, "price", DecimalType(dialect, precision=10, scale=2)), - ColumnDefinition(dialect, "start_at", DateTimeType(dialect)), - ColumnDefinition(dialect, "end_at", DateTimeType(dialect)), - ColumnDefinition(dialect, "status", VarCharType(dialect, length=32)), - ColumnDefinition(dialect, "normalized_name", VarCharType(dialect, length=50)), - ColumnDefinition(dialect, "created_token", VarCharType(dialect, length=255)), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "name", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "age", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0))]), - ColumnDefinition(dialect, "email", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, ""))]), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "author", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "title", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "content", TextType(dialect)), - ColumnDefinition(dialect, "published_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "published", BooleanType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0))]), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - indexes=[IndexDefinition(dialect, name="idx_author", columns=["author"])], - table_constraints=[ - ForeignKeyConstraint( - dialect, - columns=["author"], - foreign_key_table=Table(dialect, "users"), - foreign_key_columns=["id"], - on_delete=_CASCADE, - ), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "post_ref", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "author", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "text", TextType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "approved", BooleanType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0))]), - ], - indexes=[ - IndexDefinition(dialect, name="idx_post_ref", columns=["post_ref"]), - IndexDefinition(dialect, name="idx_author", columns=["author"]), - ], - 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=ReferentialAction.NO_ACTION, - ), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "name", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "item_total", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "remarks", IntegerType(dialect)), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "name", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "tags", TextType(dialect)), - ColumnDefinition(dialect, "meta", TextType(dialect)), - ColumnDefinition(dialect, "description", TextType(dialect)), - ColumnDefinition(dialect, "status", TextType(dialect)), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "name", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "optional_name", VarCharType(dialect, length=255)), - ColumnDefinition(dialect, "optional_age", IntegerType(dialect)), - ColumnDefinition(dialect, "last_login", TextType(dialect)), - ColumnDefinition(dialect, "is_premium", BooleanType(dialect)), - ColumnDefinition(dialect, "unsupported_union", VarCharType(dialect, length=255)), - ColumnDefinition(dialect, "custom_bool", VarCharType(dialect, length=3)), - ColumnDefinition(dialect, "optional_custom_bool", VarCharType(dialect, length=3)), - ], - ) - - -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), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "product_id", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "quantity", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "unit_price", DecimalType(dialect, precision=10, scale=2), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ], - table_constraints=[ - TableConstraint(dialect, branch=TablePrimaryKeyConstraint(dialect, ["order_id", "product_id"])), - ], - ) - - -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), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "product_id", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "batch_id", VarCharType(dialect, length=64), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "stock", IntegerType(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"])), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "total", DecimalType(dialect, precision=10, scale=2), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "created_at", TextType(dialect)), - ColumnDefinition(dialect, "updated_at", TextType(dialect)), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "name", TextType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "price", FloatType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "quantity", IntegerType(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 16ff4d5e..00000000 --- a/tests/providers/fixtures/events.py +++ /dev/null @@ -1,94 +0,0 @@ -# tests/providers/fixtures/events.py -"""DDL expressions for the ``feature/events`` table group (SQL Server). - -Reference: ``tests/rhosocial/activerecord_sqlserver_test/feature/events/schema/``. -""" - -from typing import Callable, Dict - -from rhosocial.activerecord.backend.expression import ( - CreateTableStatement, -) -from rhosocial.activerecord.backend.expression.objects import Table -from rhosocial.activerecord.backend.expression.statements import ( - ColumnDefinition, - ColumnConstraint, - ColumnDefaultConstraint, - ColumnNotNullConstraint, - ColumnNullableConstraint, - ColumnPrimaryKeyConstraint, -) -from rhosocial.activerecord.backend.expression.types import ( - DateTimeType, - IntegerType, - TextType, - VarCharType, -) - -from . import _common - - -def to_sql(expr: CreateTableStatement): - return _common.to_sqlserver_ddl_sql(expr) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "name", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "status", VarCharType(dialect, length=50), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "draft"))]), - ColumnDefinition(dialect, "revision", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "content", TextType(dialect)), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "title", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "content", TextType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "view_count", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0))]), - ColumnDefinition(dialect, "last_viewed_at", DateTimeType(dialect, precision=6), - 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 e6ccd99c..00000000 --- a/tests/providers/fixtures/mixins.py +++ /dev/null @@ -1,145 +0,0 @@ -# tests/providers/fixtures/mixins.py -"""DDL expressions for the ``feature/mixins`` table group (SQL Server). - -Reference: ``tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/``. -""" - -from typing import Callable, Dict - -from rhosocial.activerecord.backend.expression import ( - CreateTableStatement, -) -from rhosocial.activerecord.backend.expression.objects import Table -from rhosocial.activerecord.backend.expression.statements import ( - ColumnDefinition, - ColumnConstraint, - ColumnDefaultConstraint, - ColumnNotNullConstraint, - ColumnNullableConstraint, - ColumnPrimaryKeyConstraint, -) -from rhosocial.activerecord.backend.expression.types import ( - BooleanType, - DateTimeType, - DecimalType, - IntegerType, - TextType, - VarCharType, -) - -from . import _common - - -def to_sql(expr: CreateTableStatement): - return _common.to_sqlserver_ddl_sql(expr) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "title", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "content", TextType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "status", VarCharType(dialect, length=50), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "draft"))]), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "version", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "deleted_at", DateTimeType(dialect, precision=6), - constraints=[ColumnConstraint(dialect, branch=ColumnNullableConstraint(dialect))]), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "title", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "is_completed", BooleanType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0))]), - ColumnDefinition(dialect, "deleted_at", TextType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNullableConstraint(dialect))]), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "title", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "content", TextType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "name", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "price", DecimalType(dialect, precision=10, scale=2), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.0))]), - ColumnDefinition(dialect, "version", IntegerType(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 73f24840..00000000 --- a/tests/providers/fixtures/query.py +++ /dev/null @@ -1,471 +0,0 @@ -# tests/providers/fixtures/query.py -"""DDL expressions for the ``feature/query`` table group (SQL Server). - -Each factory builds a :class:`CreateTableStatement` whose generated T-SQL -DDL is semantically equivalent to the reference ``.sql`` schema files under -``tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/``. -""" - -from typing import Callable, Dict - -from rhosocial.activerecord.backend.expression import ( - CreateTableStatement, -) -from rhosocial.activerecord.backend.expression.objects import Table -from rhosocial.activerecord.backend.expression.statements import ( - ColumnDefinition, - ColumnConstraint, - ColumnDefaultConstraint, - ColumnNotNullConstraint, - ColumnNullableConstraint, - ColumnPrimaryKeyConstraint, - ColumnUniqueConstraint, - ForeignKeyConstraint, - IndexDefinition, - ReferentialAction, -) -from rhosocial.activerecord.backend.expression.types import ( - BooleanType, - DateTimeType, - DecimalType, - DoubleType, - IntegerType, - JsonType, - TextType, - VarCharType, -) - -from . import _common - -_CASCADE = ReferentialAction.CASCADE - - -def to_sql(expr: CreateTableStatement): - return _common.to_sqlserver_ddl_sql(expr) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "username", VarCharType(dialect, length=191), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnUniqueConstraint(dialect))]), - ColumnDefinition(dialect, "email", VarCharType(dialect, length=191), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnUniqueConstraint(dialect))]), - ColumnDefinition(dialect, "age", IntegerType(dialect)), - ColumnDefinition(dialect, "balance", DoubleType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.0))]), - ColumnDefinition(dialect, "is_active", BooleanType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "user_id", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "title", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "content", TextType(dialect)), - ColumnDefinition(dialect, "status", VarCharType(dialect, length=50), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "published"))]), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - indexes=[ - IndexDefinition(dialect, name="idx_user_id", columns=["user_id"]), - IndexDefinition(dialect, name="idx_status", columns=["status"]), - ], - table_constraints=[ - ForeignKeyConstraint( - dialect, - columns=["user_id"], - foreign_key_table=Table(dialect, "users"), - foreign_key_columns=["id"], - on_delete=_CASCADE, - ), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "user_id", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "post_id", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "content", TextType(dialect)), - ColumnDefinition(dialect, "is_hidden", BooleanType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0))]), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - indexes=[ - IndexDefinition(dialect, name="idx_user_id", columns=["user_id"]), - IndexDefinition(dialect, name="idx_post_id", columns=["post_id"]), - ], - 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=ReferentialAction.NO_ACTION, - ), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "user_id", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "order_number", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "total_amount", DecimalType(dialect, precision=10, scale=2), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.0))]), - ColumnDefinition(dialect, "status", VarCharType(dialect, length=50), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "pending"))]), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - indexes=[IndexDefinition(dialect, name="idx_user_id", columns=["user_id"])], - table_constraints=[ - ForeignKeyConstraint( - dialect, - columns=["user_id"], - foreign_key_table=Table(dialect, "users"), - foreign_key_columns=["id"], - ), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "order_id", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "product_name", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "quantity", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "unit_price", DecimalType(dialect, precision=10, scale=2), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "subtotal", DecimalType(dialect, precision=10, scale=2), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.0))]), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - indexes=[IndexDefinition(dialect, name="idx_order_id", columns=["order_id"])], - table_constraints=[ - ForeignKeyConstraint( - dialect, - columns=["order_id"], - foreign_key_table=Table(dialect, "orders"), - foreign_key_columns=["id"], - on_delete=_CASCADE, - ), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "user_id", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "bio", TextType(dialect)), - ColumnDefinition(dialect, "avatar_url", VarCharType(dialect, length=512)), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - table_constraints=[ - ForeignKeyConstraint( - dialect, - columns=["user_id"], - foreign_key_table=Table(dialect, "users"), - foreign_key_columns=["id"], - ), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "username", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "email", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "age", IntegerType(dialect)), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "settings", JsonType(dialect)), - ColumnDefinition(dialect, "tags", JsonType(dialect)), - ColumnDefinition(dialect, "profile", JsonType(dialect)), - ColumnDefinition(dialect, "roles", JsonType(dialect)), - ColumnDefinition(dialect, "scores", JsonType(dialect)), - ColumnDefinition(dialect, "subscription", JsonType(dialect)), - ColumnDefinition(dialect, "preferences", JsonType(dialect)), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "name", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "parent_id", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNullableConstraint(dialect))]), - ColumnDefinition(dialect, "value", DecimalType(dialect, precision=10, scale=2), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.0))]), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - indexes=[IndexDefinition(dialect, name="idx_parent_id", columns=["parent_id"])], - table_constraints=[ - ForeignKeyConstraint( - dialect, - columns=["parent_id"], - foreign_key_table=Table(dialect, "nodes"), - foreign_key_columns=["id"], - on_delete=ReferentialAction.NO_ACTION, - ), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "name", VarCharType(dialect, length=255)), - ColumnDefinition(dialect, "tags", TextType(dialect)), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "user_id", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "order_number", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "total_amount", DecimalType(dialect, precision=10, scale=2), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 0.0))]), - ColumnDefinition(dialect, "status", VarCharType(dialect, length=50), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "pending"))]), - ColumnDefinition(dialect, "priority", VarCharType(dialect, length=50), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "medium"))]), - ColumnDefinition(dialect, "region", VarCharType(dialect, length=50), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, "default"))]), - ColumnDefinition(dialect, "category", VarCharType(dialect, length=255)), - ColumnDefinition(dialect, "product", VarCharType(dialect, length=255)), - ColumnDefinition(dialect, "department", VarCharType(dialect, length=255)), - ColumnDefinition(dialect, "year", VarCharType(dialect, length=10)), - ColumnDefinition(dialect, "quarter", VarCharType(dialect, length=10)), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - indexes=[ - IndexDefinition(dialect, name="idx_user_id", columns=["user_id"]), - IndexDefinition(dialect, name="idx_status", columns=["status"]), - IndexDefinition(dialect, name="idx_priority", columns=["priority"]), - IndexDefinition(dialect, name="idx_region", columns=["region"]), - ], - table_constraints=[ - ForeignKeyConstraint( - dialect, - columns=["user_id"], - foreign_key_table=Table(dialect, "users"), - foreign_key_columns=["id"], - on_delete=_CASCADE, - ), - ], - ) - - -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", IntegerType(dialect), - constraints=[ - ColumnConstraint( - dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), - ) - ]), - ColumnDefinition(dialect, "order_id", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "product_name", VarCharType(dialect, length=255), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "quantity", IntegerType(dialect), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), - ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, 1))]), - ColumnDefinition(dialect, "price", DecimalType(dialect, precision=10, scale=2), - constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), - ColumnDefinition(dialect, "category", VarCharType(dialect, length=255)), - ColumnDefinition(dialect, "region", VarCharType(dialect, length=50)), - ColumnDefinition(dialect, "created_at", DateTimeType(dialect, precision=6)), - ColumnDefinition(dialect, "updated_at", DateTimeType(dialect, precision=6)), - ], - indexes=[IndexDefinition(dialect, name="idx_order_id", columns=["order_id"])], - 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/mixins.py b/tests/providers/mixins.py deleted file mode 100644 index 67cbb499..00000000 --- a/tests/providers/mixins.py +++ /dev/null @@ -1,234 +0,0 @@ -# tests/providers/mixins.py -""" -Concrete implementations of `IMixinsSyncProvider` and `IMixinsAsyncProvider` -for the SQL Server backend. -""" - -import os -import sys -import logging -from typing import Type, List - -from rhosocial.activerecord.model import ActiveRecord - -logger = logging.getLogger(__name__) - -from rhosocial.activerecord.testsuite.utils import select_fixture # noqa: E402 - -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, -) - -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}") - -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}") - -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}") - - -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 - - -TimestampedPost = _select_model_class( - TimestampedPostBase, TimestampedPost312, TimestampedPost311, TimestampedPost310, "TimestampedPost" -) -VersionedProduct = _select_model_class( - VersionedProductBase, VersionedProduct312, VersionedProduct311, VersionedProduct310, "VersionedProduct" -) -Task = _select_model_class(TaskBase, Task312, Task311, Task310, "Task") -CombinedArticle = _select_model_class( - CombinedArticleBase, CombinedArticle312, CombinedArticle311, CombinedArticle310, "CombinedArticle" -) - -AsyncTimestampedPost = AsyncTimestampedPostBase -AsyncVersionedProduct = AsyncVersionedProductBase -AsyncTask = AsyncTaskBase -AsyncCombinedArticle = AsyncCombinedArticleBase - -from rhosocial.activerecord.testsuite.feature.mixins.interfaces import ( # noqa: E402 - IMixinsSyncProvider, - IMixinsAsyncProvider, -) - -from .scenarios import get_enabled_scenarios, get_scenario # noqa: E402 - -from providers.fixtures._common import ( - safe_drop_table, safe_drop_table_async, - disable_fk_checks, enable_fk_checks, - disable_fk_checks_async, enable_fk_checks_async, -) - -class MixinsProviderBase: - def __init__(self): - self._scenario_db_files = {} - - def get_test_scenarios(self) -> List[str]: - return list(get_enabled_scenarios().keys()) - - def _load_sqlserver_schema(self, filename: str) -> str: - schema_dir = os.path.join( - os.path.dirname(__file__), "..", "rhosocial", "activerecord_sqlserver_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() - - _load_mysql_schema = _load_sqlserver_schema - - -class MixinsSyncProvider(MixinsProviderBase, IMixinsSyncProvider): - def __init__(self): - super().__init__() - self._active_backends = [] - - def _setup_model(self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str) -> Type[ActiveRecord]: - from rhosocial.activerecord.backend.options import ExecutionOptions - from rhosocial.activerecord.backend.schema import StatementType - from rhosocial.activerecord.backend.expression import DropTableStatement - from rhosocial.activerecord.backend.expression.objects import Table - from providers.fixtures.mixins import TABLE_EXPRESSIONS - from providers.fixtures._common import to_sqlserver_ddl_sql - - 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) - options = ExecutionOptions(stmt_type=StatementType.DDL) - safe_drop_table(backend_instance, backend_instance.dialect, table_name) - if fn := TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - create_sql, params = to_sqlserver_ddl_sql(create_expr) - backend_instance.execute(create_sql, params, options=options) - else: - schema_sql = self._load_sqlserver_schema(f"{table_name}.sql") - backend_instance.execute(schema_sql, options=options) - 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: - for table_name in ["timestamped_posts", "versioned_products", "tasks", "combined_articles"]: - try: - safe_drop_table(backend_instance, backend_instance.dialect, table_name) - except Exception: - pass - 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.sqlserver.backend.async_backend import AsyncSQLServerBackend - from rhosocial.activerecord.backend.options import ExecutionOptions - from rhosocial.activerecord.backend.schema import StatementType - from rhosocial.activerecord.backend.expression import DropTableStatement - from rhosocial.activerecord.backend.expression.objects import Table - from providers.fixtures.mixins import TABLE_EXPRESSIONS - from providers.fixtures._common import to_sqlserver_ddl_sql - - _, config = get_scenario(scenario_name) - await model_class.configure(config, AsyncSQLServerBackend) - backend_instance = model_class.__backend__ - if backend_instance not in self._active_async_backends: - self._active_async_backends.append(backend_instance) - options = ExecutionOptions(stmt_type=StatementType.DDL) - await safe_drop_table_async(backend_instance, backend_instance.dialect, table_name) - if fn := TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - create_sql, params = to_sqlserver_ddl_sql(create_expr) - await backend_instance.execute(create_sql, params, options=options) - else: - schema_sql = self._load_sqlserver_schema(f"{table_name}.sql") - await backend_instance.execute(schema_sql, options=options) - 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: - for table_name in ["timestamped_posts", "versioned_products", "tasks", "combined_articles"]: - try: - await safe_drop_table_async(backend_instance, backend_instance.dialect, table_name) - except Exception: - pass - try: - await backend_instance.disconnect() - except Exception: - pass - self._active_async_backends.clear() diff --git a/tests/providers/pooling.py b/tests/providers/pooling.py deleted file mode 100644 index dc2014a0..00000000 --- a/tests/providers/pooling.py +++ /dev/null @@ -1,116 +0,0 @@ -# tests/providers/pooling.py -"""Database pooling helpers for the SQL Server 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 SQL -Server instance 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: master`` -produces pooled databases ``master_0``, ``master_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 pyodbc -from dataclasses import replace - -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. ``master_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_literal(name: str) -> str: - """Escape a SQL Server string literal (single quotes doubled).""" - return name.replace("'", "''") - - -def _escape_bracket(name: str) -> str: - """Escape a SQL Server identifier for use inside square brackets.""" - return name.replace("]", "]]") - - -def _connect_admin(config) -> pyodbc.Connection: - """Connect to the ``master`` maintenance database of the scenario's server.""" - admin_config = replace(config, database="master") - return pyodbc.connect( - admin_config.build_connection_string(), - autocommit=True, - timeout=config.timeout or 10, - ) - - -def _reset_sqlserver_database(scenario_name: str, db_name: str) -> None: - """Ensure the pooled database exists and is empty on the scenario's server. - - Connects to ``master`` on the server selected by ``scenario_name``, drops - the pooled ``db_name`` database if it exists (forcing existing connections - closed) and recreates it empty, so the test starts from a clean state. - 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: - conn = _connect_admin(config) - try: - with conn.cursor() as cursor: - db_escaped = _escape_bracket(db_name) - cursor.execute( - f"SELECT COUNT(*) FROM sys.databases " - f"WHERE name = N'{_escape_literal(db_name)}'" - ) - if not cursor.fetchone()[0]: - cursor.execute(f"CREATE DATABASE [{db_escaped}]") - cursor.execute( - f"ALTER DATABASE [{db_escaped}] " - "SET READ_COMMITTED_SNAPSHOT ON" - ) - return - cursor.execute( - f"SELECT COUNT(*) FROM [{db_escaped}].sys.tables " - f"WHERE is_ms_shipped = 0" - ) - if not cursor.fetchone()[0]: - return - cursor.execute( - f"ALTER DATABASE [{db_escaped}] " - "SET SINGLE_USER WITH ROLLBACK IMMEDIATE" - ) - cursor.execute(f"DROP DATABASE [{db_escaped}]") - cursor.execute(f"CREATE DATABASE [{db_escaped}]") - cursor.execute( - f"ALTER DATABASE [{db_escaped}] " - "SET READ_COMMITTED_SNAPSHOT ON" - ) - finally: - conn.close() - except Exception: - pass - - -register_pool_reset_handler(_reset_sqlserver_database) diff --git a/tests/providers/query.py b/tests/providers/query.py deleted file mode 100644 index 3d04393c..00000000 --- a/tests/providers/query.py +++ /dev/null @@ -1,787 +0,0 @@ -# tests/providers/query.py -""" -Concrete implementations of `IQuerySyncProvider` and `IQueryAsyncProvider` -for the SQL Server backend. -""" - -import os -import sys -import logging -from typing import Type, List, Tuple - -from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord - -logger = logging.getLogger(__name__) - -from rhosocial.activerecord.testsuite.utils import select_fixture # noqa: E402 - -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, - 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 ( # noqa: E402 - ExtendedOrder, - ExtendedOrderItem, -) - -User310 = JsonUser310 = Order310 = OrderItem310 = Post310 = Comment310 = 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, - MappedUser as MappedUser310, - MappedPost as MappedPost310, - MappedComment as MappedComment310, - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.10+ fixtures: {e}") - -User311 = JsonUser311 = Order311 = OrderItem311 = Post311 = Comment311 = 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, - MappedUser as MappedUser311, - MappedPost as MappedPost311, - MappedComment as MappedComment311, - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.11+ fixtures: {e}") - -User312 = JsonUser312 = Order312 = OrderItem312 = Post312 = Comment312 = 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, - MappedUser as MappedUser312, - MappedPost as MappedPost312, - MappedComment as MappedComment312, - ) - except ImportError as e: - logger.warning(f"Failed to import Python 3.12+ fixtures: {e}") - - -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 - - -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" -) - -from rhosocial.activerecord.testsuite.feature.query.interfaces import IQuerySyncProvider, IQueryAsyncProvider # noqa: E402 -from rhosocial.activerecord.testsuite.core.protocols import WorkerTestProtocol # noqa: E402 - -from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import ( # noqa: E402 - OrderItem as CompositeOrderItemBase, - AsyncOrderItem as AsyncCompositeOrderItemBase, -) - -from .scenarios import get_enabled_scenarios, get_scenario # noqa: E402 - -from providers.fixtures._common import ( - safe_drop_table, safe_drop_table_async, - disable_fk_checks, enable_fk_checks, - disable_fk_checks_async, enable_fk_checks_async, -) - -class QueryProviderBase: - def __init__(self): - self._scenario_db_files = {} - self._schema_fixtures_provisioned = False - self._mixed_schema_provisioned = False - - @staticmethod - def _ddl_options(): - from rhosocial.activerecord.backend.options import ExecutionOptions - from rhosocial.activerecord.backend.schema import StatementType - return ExecutionOptions(stmt_type=StatementType.DDL) - - def get_test_scenarios(self) -> List[str]: - return list(get_enabled_scenarios().keys()) - - def _cross_schema_statements(self) -> List[str]: - """Provision SCHEMA_A / SCHEMA_B with their tables (T-SQL).""" - return [ - "IF OBJECT_ID('ar_crm.customers', 'U') IS NOT NULL DROP TABLE ar_crm.customers", - "IF SCHEMA_ID('ar_crm') IS NOT NULL DROP SCHEMA ar_crm", - "CREATE SCHEMA ar_crm", - "IF OBJECT_ID('ar_shop.orders', 'U') IS NOT NULL DROP TABLE ar_shop.orders", - "IF OBJECT_ID('ar_crm.orders', 'U') IS NOT NULL DROP TABLE ar_crm.orders", - "IF SCHEMA_ID('ar_shop') IS NOT NULL DROP SCHEMA ar_shop", - "CREATE SCHEMA ar_shop", - "CREATE TABLE ar_crm.customers (" - "id INT IDENTITY(1,1) PRIMARY KEY, name NVARCHAR(100) NOT NULL)", - "CREATE TABLE ar_shop.orders (" - "id INT IDENTITY(1,1) PRIMARY KEY, customer_id INT NOT NULL, amount INT NOT NULL)", - ] - - def _drop_cross_schema_schemas_sync(self, backend_instance) -> None: - for sql in ( - "IF OBJECT_ID('ar_crm.customers', 'U') IS NOT NULL DROP TABLE ar_crm.customers", - "IF OBJECT_ID('ar_shop.orders', 'U') IS NOT NULL DROP TABLE ar_shop.orders", - "IF OBJECT_ID('ar_crm.orders', 'U') IS NOT NULL DROP TABLE ar_crm.orders", - "IF SCHEMA_ID('ar_crm') IS NOT NULL DROP SCHEMA ar_crm", - "IF SCHEMA_ID('ar_shop') IS NOT NULL DROP SCHEMA ar_shop", - ): - try: - backend_instance.execute(sql, options=self._ddl_options()) - except Exception: - pass - self._schema_fixtures_provisioned = False - - async def _drop_cross_schema_schemas_async(self, backend_instance) -> None: - for sql in ( - "IF OBJECT_ID('ar_crm.customers', 'U') IS NOT NULL DROP TABLE ar_crm.customers", - "IF OBJECT_ID('ar_shop.orders', 'U') IS NOT NULL DROP TABLE ar_shop.orders", - "IF OBJECT_ID('ar_crm.orders', 'U') IS NOT NULL DROP TABLE ar_crm.orders", - "IF SCHEMA_ID('ar_crm') IS NOT NULL DROP SCHEMA ar_crm", - "IF SCHEMA_ID('ar_shop') IS NOT NULL DROP SCHEMA ar_shop", - ): - try: - await backend_instance.execute(sql, options=self._ddl_options()) - except Exception: - pass - self._schema_fixtures_provisioned = False - - def _provision_cross_schema_sync(self, backend_instance) -> None: - options = self._ddl_options() - for sql in self._cross_schema_statements(): - backend_instance.execute(sql, options=options) - self._schema_fixtures_provisioned = True - - async def _provision_cross_schema_async(self, backend_instance) -> None: - options = self._ddl_options() - for sql in self._cross_schema_statements(): - await backend_instance.execute(sql, options=options) - self._schema_fixtures_provisioned = True - - def _mixed_schema_statements(self) -> List[str]: - """Provision an identical orders table in SCHEMA_A (T-SQL, no FK).""" - return [ - "IF OBJECT_ID('ar_crm.orders', 'U') IS NOT NULL DROP TABLE ar_crm.orders", - "IF SCHEMA_ID('ar_crm') IS NOT NULL DROP SCHEMA ar_crm", - "CREATE SCHEMA ar_crm", - "CREATE TABLE ar_crm.orders (" - "[id] INT IDENTITY(1,1) PRIMARY KEY, " - "[user_id] INT NOT NULL, " - "[order_number] NVARCHAR(255) NOT NULL, " - "[total_amount] DECIMAL(10,2) NOT NULL DEFAULT 0.00, " - "[status] NVARCHAR(50) NOT NULL DEFAULT 'pending', " - "[created_at] DATETIME2 NULL, [updated_at] DATETIME2 NULL)", - ] - - def _provision_mixed_schema_sync(self, backend_instance) -> None: - options = self._ddl_options() - for sql in self._mixed_schema_statements(): - backend_instance.execute(sql, options=options) - self._mixed_schema_provisioned = True - - async def _provision_mixed_schema_async(self, backend_instance) -> None: - options = self._ddl_options() - for sql in self._mixed_schema_statements(): - await backend_instance.execute(sql, options=options) - self._mixed_schema_provisioned = True - - def _load_sqlserver_schema(self, filename: str) -> str: - schema_dir = os.path.join( - os.path.dirname(__file__), "..", "rhosocial", "activerecord_sqlserver_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() - - _load_mysql_schema = _load_sqlserver_schema - - -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) -> Type[ActiveRecord]: - from rhosocial.activerecord.backend.options import ExecutionOptions - from rhosocial.activerecord.backend.schema import StatementType - from rhosocial.activerecord.backend.expression import DropTableStatement - from rhosocial.activerecord.backend.expression.objects import Table - from providers.fixtures.query import TABLE_EXPRESSIONS - from providers.fixtures._common import to_sqlserver_ddl_sql - - 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) - options = ExecutionOptions(stmt_type=StatementType.DDL) - safe_drop_table(backend_instance, backend_instance.dialect, table_name) - if fn := TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - create_sql, params = to_sqlserver_ddl_sql(create_expr) - backend_instance.execute(create_sql, params, options=options) - else: - schema_sql = self._load_sqlserver_schema(f"{table_name}.sql") - backend_instance.execute(schema_sql, options=options) - return model_class - - def _setup_multiple_models( - self, model_classes: List[Tuple[Type[ActiveRecord], str]], scenario_name: str - ) -> Tuple[Type[ActiveRecord], ...]: - result = [] - shared_backend = None - for i, (model_class, table_name) in enumerate(model_classes): - if i == 0: - configured_model = self._setup_model(model_class, scenario_name, table_name) - shared_backend = configured_model.__backend__ - else: - backend_class, config = get_scenario(scenario_name) - model_class.__connection_config__ = config - model_class.__backend_class__ = backend_class - model_class.__backend__ = shared_backend - self._reset_schema(shared_backend, table_name) - configured_model = model_class - result.append(configured_model) - return tuple(result) - - def _reset_schema(self, backend_instance, table_name: str) -> None: - from rhosocial.activerecord.backend.options import ExecutionOptions - from rhosocial.activerecord.backend.schema import StatementType - from rhosocial.activerecord.backend.expression import DropTableStatement - from rhosocial.activerecord.backend.expression.objects import Table - from providers.fixtures.query import TABLE_EXPRESSIONS - from providers.fixtures._common import to_sqlserver_ddl_sql - - options = ExecutionOptions(stmt_type=StatementType.DDL) - if backend_instance not in self._active_backends: - self._active_backends.append(backend_instance) - safe_drop_table(backend_instance, backend_instance.dialect, table_name) - if fn := TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - create_sql, params = to_sqlserver_ddl_sql(create_expr) - backend_instance.execute(create_sql, params, options=options) - else: - schema_sql = self._load_sqlserver_schema(f"{table_name}.sql") - backend_instance.execute(schema_sql, options=options) - - def setup_order_fixtures( - self, scenario_name: str - ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - return self._setup_multiple_models( - [(User, "users"), (Order, "orders"), (OrderItem, "order_items")], scenario_name - ) - - def setup_blog_fixtures( - self, scenario_name: str - ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - return self._setup_multiple_models([(User, "users"), (Post, "posts"), (Comment, "comments")], scenario_name) - - def setup_json_user_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - import pytest - backend_class, config = get_scenario(scenario_name) - JsonUser.configure(config, backend_class) - backend_instance = JsonUser.__backend__ - if backend_instance not in self._active_backends: - self._active_backends.append(backend_instance) - if not backend_instance.dialect.supports_json_type(): - pytest.skip(f"JSON type not supported by SQLServer version {backend_instance.get_server_version()}") - json_user_model = self._setup_model(JsonUser, scenario_name, "json_users") - return (json_user_model,) - - def setup_tree_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - node_model = self._setup_model(Node, scenario_name, "nodes") - return (node_model,) - - def setup_extended_order_fixtures( - self, scenario_name: str - ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - return self._setup_multiple_models( - [(User, "users"), (ExtendedOrder, "extended_orders"), (ExtendedOrderItem, "extended_order_items")], - scenario_name, - ) - - def setup_combined_fixtures( - self, scenario_name: str - ) -> Tuple[Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord], Type[ActiveRecord]]: - return self._setup_multiple_models( - [(User, "users"), (Order, "orders"), (OrderItem, "order_items"), (Post, "posts"), (Comment, "comments")], - 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]]: - Profile = User.get_relation('profile').get_related_model(User) - return self._setup_multiple_models([(User, "users"), (Profile, "profiles")], scenario_name) - - def setup_order_item_model(self, scenario_name: str) -> Type[ActiveRecord]: - from rhosocial.activerecord.backend.options import ExecutionOptions - from rhosocial.activerecord.backend.schema import StatementType - from rhosocial.activerecord.backend.expression import DropTableStatement - from rhosocial.activerecord.backend.expression.objects import Table - from providers.fixtures.basic import TABLE_EXPRESSIONS as BASIC_EXPRS - from providers.fixtures._common import to_sqlserver_ddl_sql - - backend_class, config = get_scenario(scenario_name) - CompositeOrderItemBase.configure(config, backend_class) - backend_instance = CompositeOrderItemBase.__backend__ - if backend_instance not in self._active_backends: - self._active_backends.append(backend_instance) - options = ExecutionOptions(stmt_type=StatementType.DDL) - safe_drop_table(backend_instance, backend_instance.dialect, "order_items") - if fn := BASIC_EXPRS.get("order_items"): - create_expr = fn(backend_instance.dialect, "order_items") - create_sql, params = to_sqlserver_ddl_sql(create_expr) - backend_instance.execute(create_sql, params, options=options) - 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__ - if shared_backend not in self._active_backends: - self._active_backends.append(shared_backend) - self._provision_cross_schema_sync(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, order_model = self._setup_multiple_models( - [(User, "users"), (Order, "orders")], scenario_name - ) - shared_backend = order_model.__backend__ - backend_class, config = get_scenario(scenario_name) - MixedSchemaOrder.__connection_config__ = config - MixedSchemaOrder.__backend_class__ = backend_class - MixedSchemaOrder.__backend__ = shared_backend - if shared_backend not in self._active_backends: - self._active_backends.append(shared_backend) - self._provision_mixed_schema_sync(shared_backend) - return user_model, order_model, MixedSchemaOrder - - def cleanup_after_test(self, scenario_name: str): - for backend_instance in self._active_backends: - for table_name in [ - "users", - "orders", - "order_items", - "posts", - "comments", - "json_users", - "nodes", - "extended_orders", - "extended_order_items", - "searchable_items", - "profiles", - ]: - try: - safe_drop_table(backend_instance, backend_instance.dialect, table_name) - except Exception: - pass - if self._schema_fixtures_provisioned: - try: - self._drop_cross_schema_schemas_sync(backend_instance) - except Exception: - pass - if self._mixed_schema_provisioned: - try: - self._drop_cross_schema_schemas_sync(backend_instance) - except Exception: - pass - self._mixed_schema_provisioned = False - try: - backend_instance.disconnect() - except Exception: - pass - self._active_backends.clear() - - 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 = "AsyncSQLServerBackend" if is_async else "SQLServerBackend" - 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 providers.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.sqlserver.backend", - "backend_class_name": backend_class_name, - "config_class_module": "rhosocial.activerecord.backend.impl.sqlserver.config", - "config_class_name": "SQLServerConnectionConfig", - "config_kwargs": config_dict, - "schema_sql": schema_sql, - } - - def get_worker_schema_sql(self, scenario_name: str, table_name: str) -> str: - from providers.fixtures.query import TABLE_EXPRESSIONS - from providers.fixtures._common import to_sqlserver_ddl_sql - from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect - - if fn := TABLE_EXPRESSIONS.get(table_name): - dialect = SQLServerDialect() - sql, _ = to_sqlserver_ddl_sql(fn(dialect, table_name)) - return sql - return self._load_sqlserver_schema(f"{table_name}.sql") - - def _get_schema_sql_for_fixture_type(self, fixture_type: str) -> dict: - from providers.fixtures.query import TABLE_EXPRESSIONS - from providers.fixtures._common import to_sqlserver_ddl_sql - from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect - - 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"] - schemas = {} - dialect = SQLServerDialect() - for table in tables: - if fn := TABLE_EXPRESSIONS.get(table): - sql, _ = to_sqlserver_ddl_sql(fn(dialect, table)) - schemas[table] = sql - else: - schemas[table] = self._load_sqlserver_schema(f"{table}.sql") - return schemas - - -class QueryAsyncProvider(QueryProviderBase, IQueryAsyncProvider): - def __init__(self): - super().__init__() - self._active_async_backends = [] - - async def _setup_model_async( - self, model_class: Type[ActiveRecord], scenario_name: str, table_name: str, shared_backend=None - ) -> Type[ActiveRecord]: - from rhosocial.activerecord.backend.impl.sqlserver.backend.async_backend import AsyncSQLServerBackend - from rhosocial.activerecord.backend.options import ExecutionOptions - from rhosocial.activerecord.backend.schema import StatementType - from rhosocial.activerecord.backend.expression import DropTableStatement - from rhosocial.activerecord.backend.expression.objects import Table - from providers.fixtures.query import TABLE_EXPRESSIONS - from providers.fixtures._common import to_sqlserver_ddl_sql - - _, config = get_scenario(scenario_name) - if shared_backend is None: - await model_class.configure(config, AsyncSQLServerBackend) - else: - model_class.__connection_config__ = config - model_class.__backend_class__ = AsyncSQLServerBackend - model_class.__backend__ = shared_backend - backend_instance = model_class.__backend__ - if backend_instance not in self._active_async_backends: - self._active_async_backends.append(backend_instance) - options = ExecutionOptions(stmt_type=StatementType.DDL) - await safe_drop_table_async(backend_instance, backend_instance.dialect, table_name) - if fn := TABLE_EXPRESSIONS.get(table_name): - create_expr = fn(backend_instance.dialect, table_name) - create_sql, params = to_sqlserver_ddl_sql(create_expr) - await backend_instance.execute(create_sql, params, options=options) - else: - schema_sql = self._load_sqlserver_schema(f"{table_name}.sql") - await backend_instance.execute(schema_sql, options=options) - return model_class - - async def _setup_multiple_models_async( - self, model_classes: List[Tuple[Type[ActiveRecord], str]], scenario_name: str - ) -> Tuple[Type[ActiveRecord], ...]: - result = [] - shared_backend = None - for i, (model_class, table_name) in enumerate(model_classes): - if i == 0: - configured_model = await self._setup_model_async(model_class, scenario_name, table_name) - shared_backend = configured_model.__backend__ - else: - model_class.__connection_config__ = configured_model.__connection_config__ - model_class.__backend_class__ = type(shared_backend) - model_class.__backend__ = shared_backend - configured_model = await self._setup_model_async(model_class, scenario_name, table_name, 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_blog_models import AsyncPost, AsyncComment - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_models import AsyncUser - 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], ...]: - import pytest - from rhosocial.activerecord.backend.impl.sqlserver.backend.async_backend import AsyncSQLServerBackend - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_json_models import AsyncJsonUser - _, config = get_scenario(scenario_name) - await AsyncJsonUser.configure(config, AsyncSQLServerBackend) - backend_instance = AsyncJsonUser.__backend__ - if backend_instance not in self._active_async_backends: - self._active_async_backends.append(backend_instance) - if not backend_instance.dialect.supports_json_type(): - pytest.skip(f"JSON type not supported by SQLServer version {backend_instance.get_server_version()}") - json_user_model = await self._setup_model_async(AsyncJsonUser, scenario_name, "json_users") - return (json_user_model,) - - async def setup_tree_fixtures(self, scenario_name: str) -> Tuple[Type[ActiveRecord], ...]: - from rhosocial.activerecord.testsuite.feature.query.fixtures.async_cte_models import AsyncNode - node_model = await self._setup_model_async(AsyncNode, scenario_name, "nodes") - return (node_model,) - - 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.query.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[AsyncActiveRecord], Type[AsyncActiveRecord]]: - 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]: - from rhosocial.activerecord.backend.options import ExecutionOptions - from rhosocial.activerecord.backend.schema import StatementType - from rhosocial.activerecord.backend.expression import DropTableStatement - from rhosocial.activerecord.backend.expression.objects import Table - from rhosocial.activerecord.backend.impl.sqlserver.backend.async_backend import AsyncSQLServerBackend - from providers.fixtures.basic import TABLE_EXPRESSIONS as BASIC_EXPRS - from providers.fixtures._common import to_sqlserver_ddl_sql - - _, config = get_scenario(scenario_name) - await AsyncCompositeOrderItemBase.configure(config, AsyncSQLServerBackend) - backend_instance = AsyncCompositeOrderItemBase.__backend__ - if backend_instance not in self._active_async_backends: - self._active_async_backends.append(backend_instance) - options = ExecutionOptions(stmt_type=StatementType.DDL) - await safe_drop_table_async(backend_instance, backend_instance.dialect, "order_items") - if fn := BASIC_EXPRS.get("order_items"): - create_expr = fn(backend_instance.dialect, "order_items") - create_sql, params = to_sqlserver_ddl_sql(create_expr) - await backend_instance.execute(create_sql, params, options=options) - return AsyncCompositeOrderItemBase - - async def cleanup_after_test(self, scenario_name: str) -> None: - for backend_instance in self._active_async_backends: - for table_name in [ - "users", - "orders", - "order_items", - "posts", - "comments", - "json_users", - "nodes", - "extended_orders", - "extended_order_items", - "searchable_items", - "profiles", - ]: - try: - await safe_drop_table_async(backend_instance, backend_instance.dialect, table_name) - except Exception: - pass - if self._schema_fixtures_provisioned: - try: - await self._drop_cross_schema_schemas_async(backend_instance) - except Exception: - pass - if self._mixed_schema_provisioned: - try: - await self._drop_cross_schema_schemas_async(backend_instance) - except Exception: - pass - self._mixed_schema_provisioned = False - try: - await backend_instance.disconnect() - except Exception: - pass - self._active_async_backends.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.sqlserver.backend.async_backend import AsyncSQLServerBackend - 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__ - if shared_backend not in self._active_async_backends: - self._active_async_backends.append(shared_backend) - order_model = await self._setup_async_model(AsyncOrder, scenario_name, "orders", shared_backend) - - AsyncMixedSchemaOrder.__connection_config__ = config - AsyncMixedSchemaOrder.__backend_class__ = AsyncSQLServerBackend - AsyncMixedSchemaOrder.__backend__ = shared_backend - await self._provision_mixed_schema_async(shared_backend) - return AsyncUser, order_model, AsyncMixedSchemaOrder - - async def setup_schema_fixtures(self, scenario_name: str): - """Two async models in two distinct schemas.""" - from rhosocial.activerecord.backend.impl.sqlserver.backend.async_backend import AsyncSQLServerBackend - from rhosocial.activerecord.testsuite.feature.query.fixtures.schema_models import ( - AsyncSchemaCustomer, - AsyncSchemaOrder, - ) - - _, config = get_scenario(scenario_name) - await AsyncSchemaCustomer.configure(config, AsyncSQLServerBackend) - AsyncSchemaOrder.__connection_config__ = config - AsyncSchemaOrder.__backend_class__ = AsyncSQLServerBackend - AsyncSchemaOrder.__backend__ = AsyncSchemaCustomer.__backend__ - shared_backend = AsyncSchemaCustomer.__backend__ - if shared_backend not in self._active_async_backends: - self._active_async_backends.append(shared_backend) - await self._provision_cross_schema_async(shared_backend) - return AsyncSchemaCustomer, AsyncSchemaOrder diff --git a/tests/providers/query_connection.py b/tests/providers/query_connection.py deleted file mode 100644 index 4959243f..00000000 --- a/tests/providers/query_connection.py +++ /dev/null @@ -1,148 +0,0 @@ -# tests/providers/query_connection.py -""" -Concrete implementation of IQueryConnectionProvider for SQL Server 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.sqlserver.backend import SQLServerBackend -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): - """ - SQL Server 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 INT IDENTITY(1,1) 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)) - except Exception: - pass - - await backend.execute(""" - CREATE TABLE test_users ( - id INT IDENTITY(1,1) 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) - - pool_config = PoolConfig( - min_size=1, - max_size=5, - backend_factory=lambda: SQLServerBackend(connection_config=config) - ) - pool = BackendPool.create(pool_config) - - with pool.connection() as backend: - self._create_test_table(backend) - self._active_backends.append(backend) - - SyncQueryTestUser.configure(config, SQLServerBackend) - 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.sqlserver.backend.async_backend import AsyncSQLServerBackend - - _, config = get_scenario(scenario_name) - - pool_config = PoolConfig( - min_size=1, - max_size=5, - backend_factory=lambda: AsyncSQLServerBackend(connection_config=config) - ) - - pool = await AsyncBackendPool.create(pool_config) - - async with pool.connection() as backend: - await self._create_test_table_async(backend) - self._active_async_backends.append(backend) - - await AsyncQueryTestUser.configure(config, AsyncSQLServerBackend) - 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) - - for backend in self._active_backends: - 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) - - for backend in self._active_async_backends: - try: - await backend.disconnect() - except Exception: - pass - self._active_async_backends.clear() \ No newline at end of file diff --git a/tests/providers/registry.py b/tests/providers/registry.py deleted file mode 100644 index 60314a52..00000000 --- a/tests/providers/registry.py +++ /dev/null @@ -1,59 +0,0 @@ -# tests/providers/registry.py -""" -Test Provider Registry - -This module registers concrete implementations of test suite interfaces. -The registry system allows the test suite to be decoupled from specific -backend implementations, enabling the same tests to run against different -database backends. -""" - -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 - -# Importing the pooling module registers the SQL Server-specific pool reset -# handler (a side effect of the import), mirroring MySQL's tests/providers/pooling.py. -from . import pooling # noqa: F401 - -provider_registry = ProviderRegistry() - -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) - -provider_registry.register( - "feature.basic.connection.IBasicConnectionProvider", BasicConnectionProvider -) -provider_registry.register( - "feature.query.connection.IQueryConnectionProvider", QueryConnectionProvider -) - -# 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 0b03ae24..00000000 --- a/tests/providers/relation.py +++ /dev/null @@ -1,532 +0,0 @@ -# tests/providers/relation.py -from typing import Dict, List, Tuple, Type, Set - -from rhosocial.activerecord.model import ActiveRecord, AsyncActiveRecord -from rhosocial.activerecord.backend.impl.sqlserver.backend.async_backend import AsyncSQLServerBackend -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 - -from providers.fixtures._common import ( - safe_drop_table, safe_drop_table_async, - disable_fk_checks, enable_fk_checks, - disable_fk_checks_async, enable_fk_checks_async, -) - - -def _if_not_exists(table_name: str) -> str: - """Return the ``IF OBJECT_ID(...) IS NULL`` guard prefix for a table. - - SQL Server does not support ``CREATE TABLE IF NOT EXISTS``; the guard - makes the fixture scripts idempotent across runs. - """ - return ( - f"IF OBJECT_ID(N'{table_name}', N'U') IS NULL\n" - f" CREATE TABLE [{table_name}]" - ) - - -EMPLOYEE_DEPARTMENT_SCHEMA = """ - {departments} ( - id INT IDENTITY(1,1) PRIMARY KEY, - name NVARCHAR(255) NOT NULL, - description NVARCHAR(MAX) - ); - {employees} ( - id INT IDENTITY(1,1) PRIMARY KEY, - username NVARCHAR(255) NOT NULL, - department_id INT NOT NULL - ); - DELETE FROM employees; - DELETE FROM departments; -""".format( - departments=_if_not_exists("departments"), - employees=_if_not_exists("employees"), -) - -AUTHOR_BOOK_SCHEMA = """ - {authors} ( - id INT IDENTITY(1,1) PRIMARY KEY, - name NVARCHAR(255) NOT NULL - ); - {books} ( - id INT IDENTITY(1,1) PRIMARY KEY, - title NVARCHAR(255) NOT NULL, - author_id INT NOT NULL - ); - {chapters} ( - id INT IDENTITY(1,1) PRIMARY KEY, - title NVARCHAR(255) NOT NULL, - book_id INT NOT NULL - ); - {profiles} ( - id INT IDENTITY(1,1) PRIMARY KEY, - bio NVARCHAR(MAX) NOT NULL, - author_id INT NOT NULL - ); - DELETE FROM chapters; - DELETE FROM books; - DELETE FROM profiles; - DELETE FROM authors; -""".format( - authors=_if_not_exists("authors"), - books=_if_not_exists("books"), - chapters=_if_not_exists("chapters"), - profiles=_if_not_exists("profiles"), -) - -USER_POST_COMMENT_SCHEMA = """ - {users} ( - id INT IDENTITY(1,1) PRIMARY KEY, - name NVARCHAR(255) NOT NULL, - email NVARCHAR(255), - settings NVARCHAR(MAX) - ); - {posts} ( - id INT IDENTITY(1,1) PRIMARY KEY, - title NVARCHAR(255) NOT NULL, - body NVARCHAR(MAX) NOT NULL, - user_id INT NOT NULL, - view_count INT NOT NULL DEFAULT 0, - metadata NVARCHAR(MAX) - ); - {comments} ( - id INT IDENTITY(1,1) PRIMARY KEY, - body NVARCHAR(MAX) NOT NULL, - post_id INT NOT NULL, - meta NVARCHAR(MAX) - ); - DELETE FROM comments; - DELETE FROM posts; - DELETE FROM users; -""".format( - users=_if_not_exists("users"), - posts=_if_not_exists("posts"), - comments=_if_not_exists("comments"), -) - -RELATION_BOUNDARY_SCHEMA = """ - {owners} ( - id INT IDENTITY(1,1) PRIMARY KEY, - name NVARCHAR(255) NOT NULL - ); - {profiles} ( - id INT IDENTITY(1,1) PRIMARY KEY, - bio NVARCHAR(MAX) NOT NULL, - owner_id INT NULL - ); - {posts} ( - id INT IDENTITY(1,1) PRIMARY KEY, - title NVARCHAR(255) NOT NULL, - owner_id INT NULL - ); - DELETE FROM relation_boundary_posts; - DELETE FROM relation_boundary_profiles; - DELETE FROM relation_boundary_owners; -""".format( - owners=_if_not_exists("relation_boundary_owners"), - profiles=_if_not_exists("relation_boundary_profiles"), - posts=_if_not_exists("relation_boundary_posts"), -) - - -class RelationProviderBase: - def __init__(self): - self._scenario_db_files: Dict[str, List[str]] = {} - self._created_tables: Set[str] = set() - - def get_test_scenarios(self) -> List[str]: - from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect - scenarios = [] - for name in get_enabled_scenarios().keys(): - try: - backend_class, config = get_scenario(name) - backend = backend_class(connection_config=config) - backend.connect() - version = backend.get_server_version() - backend.disconnect() - dialect = SQLServerDialect(version) - if not dialect.supports_json_type(): - continue - except Exception: - pass - scenarios.append(name) - return scenarios - - 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 - - -class RelationSyncProvider(RelationProviderBase, IRelationSyncProvider): - def __init__(self): - super().__init__() - self._active_backends = [] - self._sync_user_post_comment_setup = False - self._sync_relation_boundary_setup = False - - 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) - self._created_tables.update(["employees", "departments"]) - 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) - self._created_tables.update(["authors", "books", "chapters", "profiles"]) - return Author, Book, Chapter, Profile - - def _setup_user_post_comment_sync(self, scenario_name): - if not self._sync_user_post_comment_setup: - 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 - self._created_tables.update(["users", "posts", "comments"]) - - 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 - self._created_tables.update( - ["relation_boundary_owners", "relation_boundary_profiles", "relation_boundary_posts"] - ) - - 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 _reset_sync_setup_state(self): - self._sync_user_post_comment_setup = False - self._sync_relation_boundary_setup = False - - def cleanup_after_test(self, scenario_name: str) -> None: - for backend in self._active_backends: - for table in list(self._created_tables): - try: - safe_drop_table(backend, backend.dialect, table) - except Exception: - pass - try: - backend.disconnect() - except Exception: - pass - self._active_backends.clear() - self._created_tables.clear() - self._reset_sync_setup_state() - - -class RelationAsyncProvider(RelationProviderBase, IRelationAsyncProvider): - def __init__(self): - super().__init__() - self._active_async_backends = [] - self._async_user_post_comment_setup = False - self._async_relation_boundary_setup = False - - async def _execute_script_async(self, backend, sql: str): - for statement in sql.split(";"): - statement = statement.strip() - if statement: - await backend.execute(statement) - - def _configure_async_model_without_connection(self, model_class, config, backend=None): - if backend is None: - backend = AsyncSQLServerBackend(connection_config=config) - model_class.__connection_config__ = config - model_class.__backend_class__ = AsyncSQLServerBackend - model_class.__backend__ = backend - return backend - - async def _setup_employee_department_async(self, scenario_name): - _, config = get_scenario(scenario_name) - backend = self._configure_async_model_without_connection(Employee, config) - self._configure_async_model_without_connection(Department, config, backend) - self._active_async_backends.append(backend) - await backend.connect() - await backend.introspect_and_adapt() - await self._execute_script_async(backend, EMPLOYEE_DEPARTMENT_SCHEMA) - self._created_tables.update(["employees", "departments"]) - return Employee, Department - - async def _setup_author_book_async(self, scenario_name): - _, config = get_scenario(scenario_name) - backend = self._configure_async_model_without_connection(Author, config) - self._configure_async_model_without_connection(Book, config, backend) - self._configure_async_model_without_connection(Chapter, config, backend) - self._configure_async_model_without_connection(Profile, config, backend) - self._active_async_backends.append(backend) - await backend.connect() - await backend.introspect_and_adapt() - await self._execute_script_async(backend, AUTHOR_BOOK_SCHEMA) - self._created_tables.update(["authors", "books", "chapters", "profiles"]) - return Author, Book, Chapter, Profile - - async def _setup_user_post_comment_async(self, scenario_name): - if not self._async_user_post_comment_setup: - _, 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.connect() - await backend.introspect_and_adapt() - await self._execute_script_async(backend, USER_POST_COMMENT_SCHEMA) - self._async_user_post_comment_setup = True - self._created_tables.update(["users", "posts", "comments"]) - - 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.connect() - await backend.introspect_and_adapt() - await self._execute_script_async(backend, RELATION_BOUNDARY_SCHEMA) - self._created_tables.update( - ["relation_boundary_owners", "relation_boundary_profiles", "relation_boundary_posts"] - ) - 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_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_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[AsyncActiveRecord], Type[AsyncActiveRecord], Type[AsyncActiveRecord]]: - 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}") - - def _reset_async_setup_state(self): - self._async_user_post_comment_setup = False - self._async_relation_boundary_setup = False - - async def cleanup_after_test(self, scenario_name: str): - for backend in self._active_async_backends: - for table in list(self._created_tables): - try: - await safe_drop_table_async(backend, backend.dialect, table) - except Exception: - pass - try: - await backend.disconnect() - except Exception: - pass - self._active_async_backends.clear() - self._created_tables.clear() - self._reset_async_setup_state() diff --git a/tests/providers/scenarios.py b/tests/providers/scenarios.py deleted file mode 100644 index f22f617f..00000000 --- a/tests/providers/scenarios.py +++ /dev/null @@ -1,112 +0,0 @@ -# tests/providers/scenarios.py -"""SQL Server backend test scenario configuration mapping table""" - -import os -from dataclasses import replace -from typing import Dict, Any, Tuple, Type -from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend -from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig -from rhosocial.activerecord.testsuite.core.pool import pooled_database_name - -SCENARIO_MAP: Dict[str, Dict[str, Any]] = {} - - -def register_scenario(name: str, config: Dict[str, Any]): - SCENARIO_MAP[name] = config - - -def get_scenario_raw(name: str) -> Tuple[Type[SQLServerBackend], SQLServerConnectionConfig]: - """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 SCENARIO_MAP: - name = next(iter(SCENARIO_MAP)) - else: - raise ValueError("No scenarios registered") - config = SQLServerConnectionConfig(**SCENARIO_MAP[name]) - return SQLServerBackend, config - - -def get_scenario(name: str) -> Tuple[Type[SQLServerBackend], SQLServerConnectionConfig]: - """ - 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]: - return SCENARIO_MAP - - -def _load_scenarios_from_config(): - env_config_path = os.getenv("SQLSERVER_SCENARIOS_CONFIG_PATH") - if env_config_path and os.path.exists(env_config_path): - print(f"Loading SQL Server scenarios from environment-specified path: {env_config_path}") - config_path = env_config_path - else: - config_path = os.path.join(os.path.dirname(__file__), "..", "config", "sqlserver_scenarios.yaml") - if not os.path.exists(config_path): - print("No SQL Server scenarios configuration file found. Skipping scenario registration.") - return - print(f"Loading SQL Server scenarios from default path: {config_path}") - - try: - import yaml - 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 ImportError: - raise ImportError("PyYAML is required to load SQL Server scenario configuration files") - - -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 (SQLSERVER_ACTIVE_SCENARIOS). It contains comma-separated - full scenario names (e.g., "sqlserver_2022,sqlserver_2019"). - """ - filter_str = os.getenv("SQLSERVER_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(): - _load_scenarios_from_config() - - -_register_default_scenarios() diff --git a/tests/providers/worker_tasks.py b/tests/providers/worker_tasks.py deleted file mode 100644 index 10ef2067..00000000 --- a/tests/providers/worker_tasks.py +++ /dev/null @@ -1,382 +0,0 @@ -# tests/providers/worker_tasks.py -""" -Worker task functions for MariaDB backend. - -Features: -1. Module-level functions (pickle-able) -2. Parameters are fully serializable -3. Models configure their own connections inside the function -4. Disconnect after use -5. Both sync and async task functions supported -""" -from typing import Dict, Any, Optional -import importlib - - - - -def _configure_model_from_params(params: dict, model_class) -> None: - """ - Configure model from connection parameters. - - Args: - params: Connection parameters provided by worker_connection_params fixture - model_class: Model class to configure - """ - # Dynamically import backend class - backend_module = importlib.import_module(params['backend_module']) - backend_class = getattr(backend_module, params['backend_class_name']) - - # Dynamically import config class - config_module = importlib.import_module(params['config_module']) - config_class = getattr(config_module, params['config_class_name']) - - # Extract configuration parameters (exclude business parameters) - config_keys = { - 'host', 'port', 'database', 'username', 'password', - 'pool_size', 'pool_timeout', 'charset', 'timezone', - 'ssl_ca', 'ssl_cert', 'ssl_key', 'ssl_mode', - 'autocommit', 'auth_plugin', 'init_command', - 'driver_type', 'options' - } - config_dict = {k: v for k, v in params['config_dict'].items() if k in config_keys} - - config = config_class(**config_dict) - - # Configure model - model_class.configure(config, backend_class) - - -async def _async_configure_model_from_params(params: dict, model_class) -> None: - """ - Async configure model from connection parameters. - - Args: - params: Connection parameters provided by worker_connection_params fixture - model_class: Async model class to configure - """ - # Dynamically import backend class - backend_module = importlib.import_module(params['backend_module']) - backend_class = getattr(backend_module, params['backend_class_name']) - - # Convert sync backend to async backend if needed - # e.g., MariaDBBackend -> AsyncMariaDBBackend - if not backend_class.__name__.startswith('Async'): - backend_class = getattr( - importlib.import_module(f"{params['backend_module']}.async_backend"), - f"Async{backend_class.__name__}", - ) - - # Dynamically import config class - config_module = importlib.import_module(params['config_module']) - config_class = getattr(config_module, params['config_class_name']) - - # Extract configuration parameters (exclude business parameters) - config_keys = { - 'host', 'port', 'database', 'username', 'password', - 'pool_size', 'pool_timeout', 'charset', 'timezone', - 'ssl_ca', 'ssl_cert', 'ssl_key', 'ssl_mode', - 'autocommit', 'auth_plugin', 'init_command', - 'driver_type', 'options' - } - config_dict = {k: v for k, v in params['config_dict'].items() if k in config_keys} - - config = config_class(**config_dict) - - # Configure async model (configure() is already an async method in AsyncBaseActiveRecord) - await model_class.configure(config, backend_class) - - -def create_user_task(params: dict) -> Dict[str, Any]: - """ - Create user task. - - Args: - params: Dictionary containing connection parameters + business parameters - - backend_module, backend_class_name, config_module, config_class_name, config_dict - - username, email, age (optional) - - Returns: - {'id': user_id, 'success': True} or {'error': str, 'success': False} - """ - params = params.copy() - - username = params.pop('username') - email = params.pop('email') - age = params.pop('age', None) - - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import User - - _configure_model_from_params(params, User) - - try: - user = User(username=username, email=email, age=age) - user.save() - return {'id': user.id, 'success': True} - except Exception as e: - return {'error': str(e), 'success': False} - finally: - User.backend().disconnect() - - -def read_user_task(params: dict) -> Dict[str, Any]: - """ - Read user task. - - Args: - params: Dictionary containing connection parameters + business parameters - - backend_module, backend_class_name, config_module, config_class_name, config_dict - - user_id - - Returns: - {'id': ..., 'username': ..., 'email': ..., 'success': True} - or {'error': str, 'success': False} - """ - params = params.copy() - - user_id = params.pop('user_id') - - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import User - - _configure_model_from_params(params, User) - - try: - user = User.find_one({'id': user_id}) - if user: - return { - 'id': user.id, - 'username': user.username, - 'email': user.email, - 'age': user.age, - 'success': True - } - else: - return {'error': 'User not found', 'success': False} - except Exception as e: - return {'error': str(e), 'success': False} - finally: - User.backend().disconnect() - - -def update_user_task(params: dict) -> Dict[str, Any]: - """ - Update user task. - - Args: - params: Dictionary containing connection parameters + business parameters - - backend_module, backend_class_name, config_module, config_class_name, config_dict - - user_id - - age, username, email etc. (optional update fields) - - Returns: - {'id': ..., 'success': True} or {'error': str, 'success': False} - """ - params = params.copy() - - user_id = params.pop('user_id') - - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import User - - _configure_model_from_params(params, User) - - try: - user = User.find_one({'id': user_id}) - if not user: - return {'error': 'User not found', 'success': False} - - if 'age' in params: - user.age = params['age'] - if 'username' in params: - user.username = params['username'] - if 'email' in params: - user.email = params['email'] - - user.save() - return {'id': user.id, 'success': True} - except Exception as e: - return {'error': str(e), 'success': False} - finally: - User.backend().disconnect() - - -def delete_user_task(params: dict) -> Dict[str, Any]: - """ - Delete user task. - - Args: - params: Dictionary containing connection parameters + business parameters - - backend_module, backend_class_name, config_module, config_class_name, config_dict - - user_id - - Returns: - {'success': True} or {'error': str, 'success': False} - """ - params = params.copy() - - user_id = params.pop('user_id') - - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import User - - _configure_model_from_params(params, User) - - try: - user = User.find_one({'id': user_id}) - if not user: - return {'error': 'User not found', 'success': False} - - user.delete() - return {'success': True} - except Exception as e: - return {'error': str(e), 'success': False} - finally: - User.backend().disconnect() - - -# ── Async Task Functions ────────────────────────────────────────────────────── -# These async functions demonstrate AsyncActiveRecord usage in WorkerPool. -# WorkerPool automatically detects async functions and runs them with asyncio.run(). - - -async def async_create_user_task(params: dict) -> Dict[str, Any]: - """ - Async create user task using AsyncActiveRecord. - - Args: - params: Dictionary containing connection parameters + business parameters - - backend_module, backend_class_name, config_module, config_class_name, config_dict - - username, email, age (optional) - - Returns: - {'id': user_id, 'success': True} or {'error': str, 'success': False} - """ - params = params.copy() - - username = params.pop('username') - email = params.pop('email') - age = params.pop('age', None) - - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import AsyncUser - - await _async_configure_model_from_params(params, AsyncUser) - - try: - user = AsyncUser(username=username, email=email, age=age) - await user.save() - return {'id': user.id, 'success': True} - except Exception as e: - return {'error': str(e), 'success': False} - finally: - await AsyncUser.backend().disconnect() - - -async def async_read_user_task(params: dict) -> Dict[str, Any]: - """ - Async read user task using AsyncActiveRecord. - - Args: - params: Dictionary containing connection parameters + business parameters - - backend_module, backend_class_name, config_module, config_class_name, config_dict - - user_id - - Returns: - {'id': ..., 'username': ..., 'email': ..., 'success': True} - or {'error': str, 'success': False} - """ - params = params.copy() - - user_id = params.pop('user_id') - - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import AsyncUser - - await _async_configure_model_from_params(params, AsyncUser) - - try: - user = await AsyncUser.find_one({'id': user_id}) - if user: - return { - 'id': user.id, - 'username': user.username, - 'email': user.email, - 'age': user.age, - 'success': True - } - else: - return {'error': 'User not found', 'success': False} - except Exception as e: - return {'error': str(e), 'success': False} - finally: - await AsyncUser.backend().disconnect() - - -async def async_update_user_task(params: dict) -> Dict[str, Any]: - """ - Async update user task using AsyncActiveRecord. - - Args: - params: Dictionary containing connection parameters + business parameters - - backend_module, backend_class_name, config_module, config_class_name, config_dict - - user_id - - age, username, email etc. (optional update fields) - - Returns: - {'id': ..., 'success': True} or {'error': str, 'success': False} - """ - params = params.copy() - - user_id = params.pop('user_id') - - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import AsyncUser - - await _async_configure_model_from_params(params, AsyncUser) - - try: - user = await AsyncUser.find_one({'id': user_id}) - if not user: - return {'error': 'User not found', 'success': False} - - if 'age' in params: - user.age = params['age'] - if 'username' in params: - user.username = params['username'] - if 'email' in params: - user.email = params['email'] - - await user.save() - return {'id': user.id, 'success': True} - except Exception as e: - return {'error': str(e), 'success': False} - finally: - await AsyncUser.backend().disconnect() - - -async def async_delete_user_task(params: dict) -> Dict[str, Any]: - """ - Async delete user task using AsyncActiveRecord. - - Args: - params: Dictionary containing connection parameters + business parameters - - backend_module, backend_class_name, config_module, config_class_name, config_dict - - user_id - - Returns: - {'success': True} or {'error': str, 'success': False} - """ - params = params.copy() - - user_id = params.pop('user_id') - - from rhosocial.activerecord.testsuite.feature.basic.fixtures.models import AsyncUser - - await _async_configure_model_from_params(params, AsyncUser) - - try: - user = await AsyncUser.find_one({'id': user_id}) - if not user: - return {'error': 'User not found', 'success': False} - - await user.delete() - return {'success': True} - except Exception as e: - return {'error': str(e), 'success': False} - finally: - await AsyncUser.backend().disconnect() diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/adapters/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/adapters/conftest.py new file mode 100644 index 00000000..abdb5b6e --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/adapters/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/adapters/test_json_codec.py b/tests/rhosocial/activerecord_sqlserver_test/feature/adapters/test_json_codec.py new file mode 100644 index 00000000..f78213a5 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/adapters/test_json_codec.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/adapters/test_neutral_types.py b/tests/rhosocial/activerecord_sqlserver_test/feature/adapters/test_neutral_types.py new file mode 100644 index 00000000..9eb5657f --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/adapters/test_neutral_types.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/adapters/test_neutral_types_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/adapters/test_neutral_types_async.py new file mode 100644 index 00000000..d6ed0c37 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/adapters/test_neutral_types_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/backend/SHARDS.md b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/SHARDS.md new file mode 100644 index 00000000..b768a3a6 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/SHARDS.md @@ -0,0 +1,79 @@ +# Directory-bound database shards + +Every leaf directory under `execute/` owns exactly one database. The mapping is +declared in that directory's `conftest.py`: + +```python +from pathlib import Path + +from providers.shards import register + +register(Path(__file__).parent, "test_db_") +``` + +`tests/providers/shards.py` resolves the directory a test lives in, so a test +uses its directory's database both serially and under `pytest-xdist`. The +session fixture `_prepare_directory_shards` in `tests/conftest.py` creates and +clears every registered database once at session start (`tests/providers/ +pooling.py::prepare_directory_shards`); the databases are kept afterwards. + +Directories are the unit of scheduling: `tests/conftest.py` gives every item a +`xdist_group("db:")` marker, so use `--dist=loadgroup` to keep one +directory serial while directories run concurrently. `construct/` holds no +database and no shard. + +## Canonical execute directories + +| test_db | Directory | Covers | +|---|---|---| +| `test_db_1` | `execute/connection` | backend connection, connection resilience, execution options | +| `test_db_2` | `execute/crud` | CRUD and column/type mapping round trips | +| `test_db_3` | `execute/query` | query/EXPLAIN paths | +| `test_db_4` | `execute/join` | joins (no cases in this backend yet) | +| `test_db_5` | `execute/transaction` | transactions, isolation effects, savepoints, deadlock priority | +| `test_db_6` | `execute/ddl_table` | live table DDL (SELECT INTO, temporary tables) | +| `test_db_7` | `execute/ddl_column` | live column DDL (`DEFAULT` literal readback) | +| `test_db_8` | `execute/ddl_constraint` | constraints (no cases in this backend yet) | +| `test_db_9` | `execute/ddl_index` | indexes (no cases in this backend yet) | +| `test_db_10` | `execute/ddl_view` | views (no cases in this backend yet) | +| `test_db_11` | `execute/dml_insert` | batch inserts (`execute_many`) | +| `test_db_12` | `execute/dml_update_delete` | update/delete (no cases in this backend yet) | +| `test_db_13` | `execute/json` | JSON expressions/functions against a server | +| `test_db_14` | `execute/partition` | live partition DDL and maintenance | +| `test_db_15` | `execute/introspection` | live introspector families and probes | +| `test_db_16` | `execute/errors` | error handling against a server | +| `test_db_17` | `execute/concurrency` | concurrency protocol and concurrent async tasks | +| `test_db_18` | `execute/cli` | CLI against a live server | +| `test_db_19` | `execute/functions` | function execution (`seconds_between`, niladic functions) | +| `test_db_20` | `execute/sequence_identity` | identity capability conformance | +| `test_db_21` | `execute/fulltext_spatial` | spatial types against a server | +| `test_db_22` | `execute/show_admin` | SHOW/admin surfaces | +| `test_db_23` | `execute/routine_domain` | routines and domains (no cases in this backend yet) | + +`test_db_24` is unused: backend-unique capabilities are namespaced under +`execute/sqlserver/` (below) instead of a catch-all directory, and their leaves +number from `test_db_25`. + +## Backend-unique capabilities (`execute/sqlserver/`) + +`execute/sqlserver/` is a namespace, not a shard: its parent directory holds no +test files. Each leaf capability is a shard of its own and takes the next free +number after the canonical range. + +| test_db | Directory | Covers | +|---|---|---| +| `test_db_25` | `execute/sqlserver/set_type` | comma-separated `VARCHAR` set emulation (SQL Server has no `SET` type) | +| `test_db_26` | `execute/sqlserver/sql_graph` | SQL Graph: node/edge tables, `MATCH`, `SHORTEST_PATH` | + +Backend-unique construction-only capabilities follow the same namespace on the +construct side and need no database, e.g. +`construct/sqlserver/session_settings/` (T-SQL `SET DEADLOCK_PRIORITY`, +`SET LANGUAGE`, `SET DATEFORMAT`, `IDENTITY` parameterized queries). + +## Adding a leaf + +1. Create `execute//` or `execute/sqlserver//`. +2. Drop a `conftest.py` in the new leaf that registers the next unused + `test_db_` (the canonical range is 1–23; backend-unique leaves start at + 25). +3. Add the row to this table. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/conftest.py new file mode 100644 index 00000000..491e9cc3 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/conftest.py @@ -0,0 +1,157 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/conftest.py +"""Fixtures for the SQL Server native-type tests. + +One table per family (testing plan §4.1), created from ``schema/native_types.sql`` +inside the directory's own database (``test_backend_adapters_native``, which +``feature/backend/conftest.py`` creates). A test asks for exactly the tables it +needs, so a failure names the family instead of a shared row. + +The helpers here deliberately speak literal SQL for the "foreign data" (S3) +step: a native INSERT must not go through any adapter, which is the whole point +of that assertion. +""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration +import re +from pathlib import Path + +import pytest + +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType + +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose="SQL Server native-type round-trips in the directory-owned database.", + passes_means="native values survive literal-SQL writes and adapted reads in their column family", + fails_means="a native type is stored or returned in the wrong form", +) + +DML = ExecutionOptions(stmt_type=StatementType.DML) + + +def _load_native_ddl(): + """Read ``schema/native_types.sql`` into ``{table name: CREATE TABLE ...}``. + + Full-line comments are dropped *before* the statements are split: the + ROWVERSION note contains a semicolon, and splitting first would cut that + note in two and leave its tail as if it were SQL. + """ + text = (Path(__file__).parent / "schema" / "native_types.sql").read_text(encoding="utf-8") + text = "\n".join( + line for line in text.splitlines() if not line.strip().startswith("--") + ) + tables = {} + for chunk in text.split(";"): + statement = chunk.strip() + if not statement: + continue + match = re.search(r"CREATE\s+TABLE\s+([A-Za-z0-9_]+)", statement, re.IGNORECASE) + if match is None: + raise RuntimeError(f"cannot read a table name from: {statement!r}") + tables[match.group(1)] = statement + return tables + + +NATIVE_DDL = _load_native_ddl() + + +class NativeIO: + """Literal-SQL helpers shared by the native-type tests.""" + + def __init__(self, backend): + self.backend = backend + + def insert(self, table, row): + """INSERT one row whose values are already SQL literals. + + No adapter and no parameter binding are involved: this is how a value + that another writer produced reaches the column. + """ + columns = ", ".join(row) + values = ", ".join(row.values()) + self.backend.execute(f"INSERT INTO {table} ({columns}) VALUES ({values})", (), options=DML) + + def raw(self, table, expression, row_id=1): + """Read one column's stored form through a server expression.""" + row = self.backend.fetch_one( + f"SELECT {expression} AS v FROM {table} WHERE id = {int(row_id)}", () + ) + return row["v"] + + def column_type(self, table, column): + """The type name SQL Server records for one column.""" + row = self.backend.fetch_one( + "SELECT typ.name AS v FROM sys.columns col " + "JOIN sys.types typ ON col.user_type_id = typ.user_type_id " + "WHERE col.object_id = OBJECT_ID(?) AND col.name = ?", + (table, column), + ) + return row["v"] + + def adapter(self, py_type, target_type): + """The adapter the backend's registry resolves for one pair.""" + return self.backend.adapter_registry.get_adapter(py_type, target_type) + + +@pytest.fixture +def native_io(sqlserver_backend): + return NativeIO(sqlserver_backend) + + +@pytest.fixture +def native_table(sqlserver_backend): + """Create the named native tables for one test and drop them afterwards. + + The DDL runs on a second connection. SQL Server answers some DDL with + informational messages, pyodbc keeps those as pending results, and the + next command on that connection is then refused with "Connection is busy + with results for another command" -- which is what a model's first + ``save()`` hit. A dedicated DDL connection keeps the test's own + connection free of them. + """ + created = [] + ddl = type(sqlserver_backend)(connection_config=sqlserver_backend.config) + ddl.connect() + + def create(*names): + for name in names: + if name not in NATIVE_DDL: + raise KeyError(f"no DDL declared for {name!r}") + # ``DROP TABLE IF EXISTS`` on a table that is not there also + # answers with a message, so the drop only happens when the table + # really exists. + exists = ddl.fetch_one("SELECT OBJECT_ID(?) AS v", (name,))["v"] + if exists is not None: + ddl.execute(f"DROP TABLE {name}", (), options=DML) + ddl.execute(NATIVE_DDL[name], (), options=DML) + created.append(name) + return names[0] if len(names) == 1 else names + + try: + yield create + finally: + for name in reversed(created): + ddl.execute(f"DROP TABLE IF EXISTS {name}", (), options=DML) + ddl.disconnect() + + +@pytest.fixture +def native_model(sqlserver_backend): + """Configure model classes against the directory's database.""" + configured = [] + + def bind(*model_classes): + for model_class in model_classes: + model_class.configure(sqlserver_backend.config, type(sqlserver_backend)) + configured.append(model_class) + return model_classes[0] if len(model_classes) == 1 else model_classes + + yield bind + + for model_class in configured: + backend = getattr(model_class, "__backend__", None) + if backend is not None: + backend.disconnect() + + diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/schema/native_types.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/schema/native_types.sql new file mode 100644 index 00000000..abeca044 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/schema/native_types.sql @@ -0,0 +1,77 @@ +-- tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/schema/native_types.sql +-- +-- One table per family (testing plan §4.1): a failing family must localise to +-- its own table, never to a row that mixes several families. The tables belong +-- to the directory's own database, which feature/backend/conftest.py creates. +-- Every primary key is a caller-supplied INT, so a test can address the row it +-- wrote without relying on IDENTITY. + +-- MONEY / SMALLMONEY: fixed-point money types with 4 decimal places. +CREATE TABLE native_money ( + id INT NOT NULL PRIMARY KEY, + amount MONEY NULL, + small SMALLMONEY NULL +); + +-- DATETIMEOFFSET: a datetime that carries a UTC offset. +CREATE TABLE native_datetimeoffset ( + id INT NOT NULL PRIMARY KEY, + dto DATETIMEOFFSET(7) NULL +); + +-- UNIQUEIDENTIFIER: SQL Server's native 16-byte GUID type. +CREATE TABLE native_uniqueidentifier ( + id INT NOT NULL PRIMARY KEY, + uid UNIQUEIDENTIFIER NULL +); + +-- XML: a native XML column, stored in SQL Server's own XML form. +CREATE TABLE native_xml ( + id INT NOT NULL PRIMARY KEY, + doc XML NULL +); + +-- HIERARCHYID: a CLR type holding a materialised path. +CREATE TABLE native_hierarchyid ( + id INT NOT NULL PRIMARY KEY, + hid HIERARCHYID NULL +); + +-- BIT: SQL Server's native boolean (never a bit string). +CREATE TABLE native_bit ( + id INT NOT NULL PRIMARY KEY, + flag BIT NULL +); + +-- ROWVERSION: an 8-byte server-maintained concurrency token (not a time). +CREATE TABLE native_rowversion ( + id INT NOT NULL PRIMARY KEY, + rv ROWVERSION, + note NVARCHAR(50) NULL +); + +-- TIMESTAMP: the synonym of ROWVERSION; only one such column per table. +CREATE TABLE native_timestamp ( + id INT NOT NULL PRIMARY KEY, + rv TIMESTAMP, + note NVARCHAR(50) NULL +); + +-- JSON: SQL Server has no JSON type, the payload is text in NVARCHAR(MAX). +CREATE TABLE native_json ( + id INT NOT NULL PRIMARY KEY, + payload NVARCHAR(MAX) NULL +); + +-- GEOMETRY / GEOGRAPHY: the planar and the earth-based spatial types. +CREATE TABLE native_spatial ( + id INT NOT NULL PRIMARY KEY, + geom GEOMETRY NULL, + geog GEOGRAPHY NULL +); + +-- WKT in an ordinary text column: the portable carrier for a neutral geometry. +CREATE TABLE native_wkt_text ( + id INT NOT NULL PRIMARY KEY, + shape NVARCHAR(200) NULL +); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/sqlserver_native_models.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/sqlserver_native_models.py new file mode 100644 index 00000000..10c2fc87 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/sqlserver_native_models.py @@ -0,0 +1,168 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/sqlserver_native_models.py +"""Models for the SQL Server native-type tests. + +Each model maps one Python type onto one SQL Server column family. Where the +backend's default suggestion is not the adapter under test, the field pins it +with ``UseAdapter``; otherwise the model relies on the merged suggestion table, +so the test also proves that wiring. + +The tables are created from ``schema/native_types.sql``; these models never +render DDL. Every table has a caller-supplied ``id`` INT primary key (a plain +``INT``, not ``IDENTITY``), declared as ``__primary_key__`` so the models stay +addressable by identity for ``find_one``/``save``. The ``id`` carries a +``UseFieldGenerator`` that echoes the caller's value: that is core's declaration +that the key is application-supplied, so it is never classed as a server-generated +identity and stripped out of the INSERT. +""" +import uuid +from datetime import datetime +from decimal import Decimal +from typing import Annotated, Optional + +from pydantic import ConfigDict + +from rhosocial.activerecord.backend.adapters.geometry import Geometry +from rhosocial.activerecord.backend.impl.sqlserver.adapters import ( + SQLServerDateTimeOffsetAdapter, + SQLServerGeometryAdapter, + SQLServerHierarchyIdAdapter, + SQLServerXMLAdapter, +) +from rhosocial.activerecord.base.fields import UseAdapter, UseFieldGenerator +from rhosocial.activerecord.model import ActiveRecord + + +class _NativeRow(ActiveRecord): + """Shared configuration for the one-table-per-family models.""" + + __primary_key__ = "id" + + model_config = ConfigDict(arbitrary_types_allowed=True) + + # Caller-supplied INT: the echo generator marks the key as application-assigned + # so core keeps it in the INSERT instead of expecting the server to fill it. + id: Annotated[ + Optional[int], + UseFieldGenerator(before_insert=lambda self: getattr(self, self.primary_key(), None)), + ] = None + + +class MoneyRow(_NativeRow): + """``native_money``: MONEY and SMALLMONEY, both reached through Decimal.""" + + @classmethod + def table_name(cls) -> str: + return "native_money" + + amount: Optional[Decimal] = None + small: Optional[Decimal] = None + + +class DateTimeOffsetRow(_NativeRow): + """``native_datetimeoffset``: the offset-carrying datetime.""" + + @classmethod + def table_name(cls) -> str: + return "native_datetimeoffset" + + dto: Annotated[ + Optional[datetime], UseAdapter(SQLServerDateTimeOffsetAdapter(), datetime) + ] = None + + +class UniqueIdentifierRow(_NativeRow): + """``native_uniqueidentifier``: the native GUID column.""" + + @classmethod + def table_name(cls) -> str: + return "native_uniqueidentifier" + + uid: Optional[uuid.UUID] = None + + +class XmlRow(_NativeRow): + """``native_xml``: the native XML column, carried as text.""" + + @classmethod + def table_name(cls) -> str: + return "native_xml" + + doc: Annotated[Optional[str], UseAdapter(SQLServerXMLAdapter(), str)] = None + + +class HierarchyIdRow(_NativeRow): + """``native_hierarchyid``: the materialised-path column.""" + + @classmethod + def table_name(cls) -> str: + return "native_hierarchyid" + + hid: Annotated[Optional[str], UseAdapter(SQLServerHierarchyIdAdapter(), str)] = None + + +class BitRow(_NativeRow): + """``native_bit``: SQL Server's native boolean, not a bit string.""" + + @classmethod + def table_name(cls) -> str: + return "native_bit" + + flag: Optional[bool] = None + + +class RowVersionRow(_NativeRow): + """``native_rowversion``: an 8-byte token the server maintains. + + ``rv`` is declared generated so the INSERT/UPDATE column lists skip it -- + SQL Server refuses an explicit value for it. The declaration is set here + rather than derived from a model-rendered DDL because the table comes from + ``schema/native_types.sql``. + """ + + __table_generated_columns__ = ("rv",) + + @classmethod + def table_name(cls) -> str: + return "native_rowversion" + + rv: Optional[bytes] = None + note: Optional[str] = None + + +class TimestampRow(RowVersionRow): + """``native_timestamp``: the synonym of ROWVERSION.""" + + @classmethod + def table_name(cls) -> str: + return "native_timestamp" + + +class JsonRow(_NativeRow): + """``native_json``: JSON kept as text, there is no JSON type.""" + + @classmethod + def table_name(cls) -> str: + return "native_json" + + payload: Optional[dict] = None + + +class SpatialRow(_NativeRow): + """``native_spatial``: the planar geometry and the earth-based geography.""" + + @classmethod + def table_name(cls) -> str: + return "native_spatial" + + geom: Optional[Geometry] = None + geog: Annotated[Optional[Geometry], UseAdapter(SQLServerGeometryAdapter(geography=True), str)] = None + + +class WktTextRow(_NativeRow): + """``native_wkt_text``: WKT in an ordinary column, the portable carrier.""" + + @classmethod + def table_name(cls) -> str: + return "native_wkt_text" + + shape: Annotated[Optional[Geometry], UseAdapter(SQLServerGeometryAdapter(), str)] = None diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_bit.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_bit.py new file mode 100644 index 00000000..bd784d96 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_bit.py @@ -0,0 +1,85 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_bit.py +"""BIT: SQL Server's native boolean. + +The column must not be reached through the core ``bool -> int`` default: the +backend merges ``(bool, bool)`` into the suggestion table, so the adapter's +target is the Python ``bool`` itself. The stored form is still ``0``/``1`` +because that is how SQL Server spells a boolean; the assertion is about the +value crossing the driver, not about the column's internal representation. +""" +from sqlserver_native_models import BitRow + + +def _stored(native_io, row_id=1): + return native_io.raw("native_bit", "CAST(flag AS int)", row_id) + + +def test_model_target_is_bool_not_int(native_model): + """The suggestion table resolves BIT to the Python bool, not to int.""" + model = native_model(BitRow) + _, target = model.get_field_type_adapters()["flag"] + assert target is bool, "BIT must not go through the bool -> int default" + + +def test_adapter_does_not_convert_bool_to_int(native_io): + """``to_database`` is the identity for the bool target and int for int.""" + adapter = native_io.adapter(bool, bool) + assert adapter is not None + + wire = adapter.to_database(True, bool, None) + assert wire is True + assert isinstance(wire, bool), "the value crossing the driver is a bool" + + # The conversion this backend deliberately avoids for BIT still exists for + # integer columns, so the two targets are genuinely different. + assert adapter.to_database(True, int, None) == 1 + + +def test_round_trip_s1(native_table, native_model): + native_table("native_bit") + model = native_model(BitRow) + + model(id=1, flag=True).save() + model(id=2, flag=False).save() + + assert model.find_one(1).flag is True + assert model.find_one(2).flag is False + assert isinstance(model.find_one(1).flag, bool) + + +def test_raw_stored_form(native_table, native_io): + native_table("native_bit") + native_io.insert("native_bit", {"id": "1", "flag": "1"}) + native_io.insert("native_bit", {"id": "2", "flag": "0"}) + assert _stored(native_io, 1) == 1 + assert _stored(native_io, 2) == 0 + + +def test_stored_form_is_stable_s2(native_table, native_model, native_io): + native_table("native_bit") + model = native_model(BitRow) + + model(id=1, flag=True).save() + model(id=2, flag=model.find_one(1).flag).save() + assert _stored(native_io, 1) == _stored(native_io, 2) + + +def test_foreign_native_value_s3(native_table, native_model, native_io): + """A native ``1`` decodes to True and re-writes as ``1``.""" + native_table("native_bit") + model = native_model(BitRow) + + native_io.insert("native_bit", {"id": "9001", "flag": "1"}) + foreign = model.find_one(9001) + assert foreign.flag is True + + model(id=9002, flag=foreign.flag).save() + assert _stored(native_io, 9001) == _stored(native_io, 9002) + + +def test_null_bit_round_trip(native_table, native_model): + native_table("native_bit") + model = native_model(BitRow) + + model(id=1, flag=None).save() + assert model.find_one(1).flag is None diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_datetimeoffset.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_datetimeoffset.py new file mode 100644 index 00000000..51048a6a --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_datetimeoffset.py @@ -0,0 +1,162 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_datetimeoffset.py +"""DATETIMEOFFSET: a datetime that carries its UTC offset. + +Two environment limits decide the shape of these tests, and both are asserted +rather than worked around: + +* **write** -- a value carried by a bare ``?`` loses its offset: the ODBC layer + sends a timestamp and SQL Server applies the session offset (``+00:00``). + Preserving ``+08:00`` needs ``CONVERT(datetimeoffset(7), ?)``, and the + execution layer does not render that wrapper (testing plan §4.7, §7.3). +* **read** -- pyodbc 5.5.0 rejects ODBC type ``-155`` + (``SQL_SS_TIMESTAMPOFFSET``), so the column cannot be fetched as a Python + value at all. The stored form is read through + ``CONVERT(varchar(60), dto, 121)`` and decoded by the adapter. +""" +from datetime import datetime, timedelta, timezone + +import pytest + +from rhosocial.activerecord.backend.impl.sqlserver.adapters import ( + SQLServerDateTimeOffsetAdapter, +) +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType +from sqlserver_native_models import DateTimeOffsetRow + +DML = ExecutionOptions(stmt_type=StatementType.DML) + +OFFSET = timezone(timedelta(hours=8)) +VALUE = datetime(2026, 1, 2, 3, 4, 5, 123456, tzinfo=OFFSET) +STORED_TEXT = "2026-01-02 03:04:05.1234567 +08:00" +WRAPPED_INSERT = ( + "INSERT INTO native_datetimeoffset (id, dto) VALUES (?, CONVERT(datetimeoffset(7), ?))" +) + + +def _offset_text(value): + """Render the ``+HH:MM`` suffix Python's ``isoformat`` cannot always give.""" + offset = value.utcoffset() + sign = "+" if offset >= timedelta(0) else "-" + minutes = abs(int(offset.total_seconds())) // 60 + return f"{sign}{minutes // 60:02d}:{minutes % 60:02d}" + + +def _stored(native_io, row_id=1): + return native_io.raw("native_datetimeoffset", "CONVERT(varchar(60), dto, 121)", row_id) + + +def test_model_declares_the_offset_adapter(native_model): + """The field pins the offset adapter, not the plain DATETIME2 one.""" + model = native_model(DateTimeOffsetRow) + adapter, target = model.get_field_type_adapters()["dto"] + assert isinstance(adapter, SQLServerDateTimeOffsetAdapter) + assert target is datetime + + +def test_adapter_semantic_round_trip(native_io): + """S1 without a server: text carrying ``+08:00`` decodes with that offset.""" + adapter = SQLServerDateTimeOffsetAdapter() + + wire = adapter.to_database(VALUE, datetime, None) + assert wire is VALUE, "the driver target is the datetime itself" + + decoded = adapter.from_database(STORED_TEXT, datetime) + assert decoded == VALUE + assert decoded.utcoffset() == timedelta(hours=8) + + +def test_round_trip_preserves_the_offset_s1(native_table, native_io): + """S1 on the server, through the wrapper the execution layer does not render.""" + native_table("native_datetimeoffset") + native_io.backend.execute(WRAPPED_INSERT, (1, STORED_TEXT), options=DML) + + assert _stored(native_io) == STORED_TEXT + assert native_io.raw("native_datetimeoffset", "DATEPART(TZOFFSET, dto)") == 480 + + decoded = SQLServerDateTimeOffsetAdapter().from_database(_stored(native_io), datetime) + assert decoded.utcoffset() == timedelta(hours=8) + + +def test_stored_form_is_stable_s2(native_table, native_io): + """S2: the value read back renders to the identical stored text.""" + native_table("native_datetimeoffset") + adapter = SQLServerDateTimeOffsetAdapter() + + native_io.backend.execute(WRAPPED_INSERT, (1, STORED_TEXT), options=DML) + read_back = adapter.from_database(_stored(native_io), datetime) + # ``isoformat`` on an aware datetime already appends the UTC offset, so the + # naive wall-clock is rendered and the offset is spelled once, after it. + naive_text = read_back.replace(tzinfo=None).isoformat( + sep=" ", timespec="microseconds" + ) + wire_text = naive_text + " " + _offset_text(read_back) + + native_io.backend.execute(WRAPPED_INSERT, (2, wire_text), options=DML) + # The server keeps 100 ns precision and the driver target (datetime) carries + # microseconds, so stability is asserted at the precision the adapter + # claims rather than the storage text's seventh digit. + stored_1 = adapter.from_database(_stored(native_io, 1), datetime) + stored_2 = adapter.from_database(_stored(native_io, 2), datetime) + assert stored_2 == stored_1 + assert stored_2.utcoffset() == stored_1.utcoffset() == timedelta(hours=8) + + +def test_foreign_native_value_s3(native_table, native_io): + """S3: a literal the server wrote itself decodes and re-writes unchanged.""" + native_table("native_datetimeoffset") + + native_io.insert("native_datetimeoffset", {"id": "9001", "dto": f"'{STORED_TEXT}'"}) + assert _stored(native_io, 9001) == STORED_TEXT + + adapter = SQLServerDateTimeOffsetAdapter() + decoded = adapter.from_database(_stored(native_io, 9001), datetime) + # ``isoformat`` on an aware datetime already appends the UTC offset, so the + # naive wall-clock is rendered and the offset is spelled once, after it. + naive_text = decoded.replace(tzinfo=None).isoformat( + sep=" ", timespec="microseconds" + ) + wire_text = naive_text + " " + _offset_text(decoded) + native_io.backend.execute(WRAPPED_INSERT, (9002, wire_text), options=DML) + + decoded_2 = adapter.from_database(_stored(native_io, 9002), datetime) + assert decoded_2 == decoded + assert decoded_2.utcoffset() == decoded.utcoffset() == timedelta(hours=8) + # The server keeps 100 ns precision; the driver target carries + # microseconds, so the seventh digit is not claimed. + + +def test_zero_and_negative_offsets(native_table, native_io): + """Two more offsets, so the claim is about the offset, not one literal.""" + native_table("native_datetimeoffset") + cases = { + 1: "2026-01-02 03:04:05.0000000 +00:00", + 2: "2026-01-02 03:04:05.0000000 -05:00", + } + for row_id, text in cases.items(): + native_io.insert("native_datetimeoffset", {"id": str(row_id), "dto": f"'{text}'"}) + assert _stored(native_io, row_id) == text + + adapter = SQLServerDateTimeOffsetAdapter() + assert adapter.from_database(cases[1], datetime).utcoffset() == timedelta(0) + assert adapter.from_database(cases[2], datetime).utcoffset() == timedelta(hours=-5) + + +@pytest.mark.xfail( + strict=True, + reason=( + "DATETIMEOFFSET cannot round-trip through the ORM yet: a bare '?' carries " + "the value as a timestamp, so SQL Server stores the session offset " + "(+00:00), and pyodbc 5.5.0 rejects ODBC type -155 (SQL_SS_TIMESTAMPOFFSET) " + "on read. Both need work outside this adapter: execution-layer parameter " + "wrapping (testing plan §4.7 and the §8 item 'execution layer supports " + "bind_expression'; §7.3) plus a driver that returns the type." + ), +) +def test_orm_round_trip_preserves_the_offset(native_table, native_model): + native_table("native_datetimeoffset") + model = native_model(DateTimeOffsetRow) + + model(id=1, dto=VALUE).save() + found = model.find_one(1) + assert found.dto.utcoffset() == timedelta(hours=8) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_hierarchyid.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_hierarchyid.py new file mode 100644 index 00000000..17522b9c --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_hierarchyid.py @@ -0,0 +1,102 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_hierarchyid.py +"""HIERARCHYID: the CLR type holding a materialised path. + +The write path works with plain text (``'/1/2/'`` is an accepted parameter for +the column). The read path does not: pyodbc 5.5.0 rejects ODBC type ``-151`` +(``SQL_SS_UDT``), so a native ``SELECT hid`` cannot deliver a value at all. +``hid.ToString()`` is therefore both the stored-form assertion and the text the +adapter decodes. + +This is also the test that pins the adapter's registration: the class existed +but the backend never registered it, so nothing could reach it. +""" +import pytest + +from rhosocial.activerecord.backend.impl.sqlserver.adapters import SQLServerHierarchyIdAdapter +from sqlserver_native_models import HierarchyIdRow + +PATH = "/1/2/" +ROOT = "/" + + +def _stored(native_io, row_id=1): + return native_io.raw("native_hierarchyid", "hid.ToString()", row_id) + + +def test_adapter_is_in_the_backend_inventory(sqlserver_backend): + """The registered inventory carries the hierarchyid adapter.""" + assert SQLServerHierarchyIdAdapter in {type(adapter) for adapter in sqlserver_backend.get_type_adapters()} + + +def test_model_declares_the_hierarchyid_adapter(native_model): + model = native_model(HierarchyIdRow) + adapter, target = model.get_field_type_adapters()["hid"] + assert isinstance(adapter, SQLServerHierarchyIdAdapter) + assert target is str + + +def test_adapter_semantic_round_trip(): + """S1 without a server: text in, text out; a list renders a path.""" + adapter = SQLServerHierarchyIdAdapter() + + assert adapter.to_database(PATH, str, None) == PATH + assert adapter.to_database([1, 2], str, None) == PATH + assert adapter.from_database(PATH, str) == PATH + + +def test_round_trip_s1(native_table, native_model, native_io): + """S1 on the server: the write path works, the stored form is the path.""" + native_table("native_hierarchyid") + model = native_model(HierarchyIdRow) + + model(id=1, hid=PATH).save() + assert _stored(native_io) == PATH + assert native_io.raw("native_hierarchyid", "hid.GetLevel()") == 2 + + +def test_stored_form_is_stable_s2(native_table, native_model, native_io): + native_table("native_hierarchyid") + model = native_model(HierarchyIdRow) + + model(id=1, hid=PATH).save() + read_back = SQLServerHierarchyIdAdapter().from_database(_stored(native_io), str) + model(id=2, hid=read_back).save() + assert _stored(native_io, 1) == _stored(native_io, 2) + + +def test_foreign_native_value_s3(native_table, native_model, native_io): + """A literal the server wrote itself decodes and re-writes unchanged.""" + native_table("native_hierarchyid") + model = native_model(HierarchyIdRow) + + native_io.insert("native_hierarchyid", {"id": "9001", "hid": "hierarchyid::Parse('/1/2/')"}) + foreign = SQLServerHierarchyIdAdapter().from_database(_stored(native_io, 9001), str) + assert foreign == PATH + + model(id=9002, hid=foreign).save() + assert _stored(native_io, 9002) == _stored(native_io, 9001) + + +def test_root_is_a_value(native_table, native_io): + native_table("native_hierarchyid") + native_io.insert("native_hierarchyid", {"id": "1", "hid": "hierarchyid::GetRoot()"}) + assert _stored(native_io) == ROOT + assert SQLServerHierarchyIdAdapter().from_database(ROOT, str) == ROOT + + +@pytest.mark.xfail( + strict=True, + reason=( + "A native HIERARCHYID column cannot be read through the ORM: pyodbc 5.5.0 " + "rejects ODBC type -151 (SQL_SS_UDT), so 'SELECT hid' fails before any " + "adapter runs. Reading needs a server-side projection such as " + "hid.ToString(), which the execution layer does not offer for model " + "columns (testing plan §4.7, §7.3)." + ), +) +def test_orm_read_returns_the_path(native_table, native_model): + native_table("native_hierarchyid") + model = native_model(HierarchyIdRow) + + model(id=1, hid=PATH).save() + assert model.find_one(1).hid == PATH diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_json.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_json.py new file mode 100644 index 00000000..ae4932bc --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_json.py @@ -0,0 +1,90 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_json.py +"""JSON kept as text in ``NVARCHAR(MAX)``. + +SQL Server has no JSON type. The column is text, the server validates it with +``ISJSON()``, and the core ``JSONAdapter`` is the carrier (``dict -> str``). +That is also why ``SELECT`` returns text and the read side has to call +``json.loads`` -- the "driver pre-decodes nothing" hook surface of testing plan +§3.5. +""" +import json + +import pytest +from pydantic import ValidationError + +from sqlserver_native_models import JsonRow + +PAYLOAD = {"a": 1, "b": [1, None, "x"], "unicode": "测试", "big": 2**53 + 1} +STORED_TEXT = json.dumps(PAYLOAD) + + +def _stored(native_io, row_id=1): + return native_io.raw("native_json", "payload", row_id) + + +def test_column_is_text_not_a_json_type(native_table, native_io): + native_table("native_json") + assert native_io.column_type("native_json", "payload") == "nvarchar" + + +def test_round_trip_s1(native_table, native_model): + native_table("native_json") + model = native_model(JsonRow) + + model(id=1, payload=PAYLOAD).save() + found = model.find_one(1) + assert found.payload == PAYLOAD + + +def test_raw_stored_form(native_table, native_io): + """The stored text is valid JSON, which the server confirms itself.""" + native_table("native_json") + native_io.insert("native_json", {"id": "1", "payload": f"'{STORED_TEXT}'"}) + + assert _stored(native_io) == STORED_TEXT + assert native_io.raw("native_json", "ISJSON(payload)") == 1 + assert native_io.raw("native_json", "JSON_VALUE(payload, '$.a')") == "1" + + +def test_stored_form_is_stable_s2(native_table, native_model, native_io): + """No double encoding: the rewrite produces byte-identical text.""" + native_table("native_json") + model = native_model(JsonRow) + + model(id=1, payload=PAYLOAD).save() + read_back = model.find_one(1) + model(id=2, payload=read_back.payload).save() + + assert _stored(native_io, 1) == _stored(native_io, 2) == STORED_TEXT + + +def test_foreign_native_value_s3(native_table, native_model, native_io): + """Text another writer produced reads back as a dict and re-writes as-is.""" + native_table("native_json") + model = native_model(JsonRow) + + native_io.insert("native_json", {"id": "9001", "payload": "'{\"k\": \"v\"}'"}) + foreign = model.find_one(9001) + assert foreign.payload == {"k": "v"} + + model(id=9002, payload=foreign.payload).save() + assert _stored(native_io, 9001) == _stored(native_io, 9002) == '{"k": "v"}' + + +def test_twice_serialized_text_is_detected(native_table, native_model, native_io): + """A payload stored as an already-encoded string is detected, not decoded twice. + + This is the shape a double encoding produces (``"{\\"a\\": 1}"``): the column + holds one JSON document whose value is text. The adapter runs ``json.loads`` + exactly once, so the decoded value is a ``str`` and the model's ``dict`` field + refuses the row instead of silently returning the inner document. + """ + native_table("native_json") + model = native_model(JsonRow) + + double_encoded = json.dumps(json.dumps({"a": 1})) + native_io.insert("native_json", {"id": "1", "payload": f"N'{double_encoded}'"}) + assert _stored(native_io) == double_encoded + + with pytest.raises(ValidationError, match="valid dictionary"): + model.find_one(1) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_money.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_money.py new file mode 100644 index 00000000..15e643fd --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_money.py @@ -0,0 +1,96 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_money.py +"""MONEY / SMALLMONEY on a live SQL Server. + +The column is fixed-point with four decimal places, and the backend reaches it +through the ``Decimal`` suggestion. The assertions follow testing plan §3.1 +(Python value, wire target, stored text) and §3.4 (S1/S2/S3). +""" +from decimal import Decimal + +from rhosocial.activerecord.backend.impl.sqlserver.adapters import SQLServerDecimalAdapter +from sqlserver_native_models import MoneyRow + +AMOUNT = Decimal("1234.5678") +SMALL = Decimal("-12.3456") + + +def _amount(native_io, row_id=1): + return native_io.raw("native_money", "CONVERT(varchar(40), amount, 2)", row_id) + + +def _small(native_io, row_id=1): + return native_io.raw("native_money", "CONVERT(varchar(40), small, 2)", row_id) + + +def test_adapter_semantic_round_trip(native_io): + """S1 without a server: the registered Decimal adapter is the carrier.""" + adapter = native_io.adapter(Decimal, Decimal) + assert isinstance(adapter, SQLServerDecimalAdapter) + + wire = adapter.to_database(AMOUNT, Decimal, None) + assert isinstance(wire, float), "the documented driver target for Decimal is float" + assert adapter.from_database(wire, Decimal) == AMOUNT + + +def test_round_trip_s1(native_table, native_model): + """S1 on the server: a Decimal written to MONEY reads back unchanged.""" + native_table("native_money") + model = native_model(MoneyRow) + + model(id=1, amount=AMOUNT, small=SMALL).save() + found = model.find_one(1) + assert found.amount == AMOUNT + assert found.small == SMALL + + +def test_raw_stored_form(native_table, native_io): + """The column holds a fixed-point value, not a float or a string.""" + native_table("native_money") + native_io.insert("native_money", {"id": "1", "amount": "1234.5678", "small": "-12.3456"}) + + # Style 2 is the locale-independent four-decimal form. + assert _amount(native_io) == "1234.5678" + assert _small(native_io) == "-12.3456" + # The default style keeps MONEY's two-decimal display form. + assert native_io.raw("native_money", "CONVERT(varchar(40), amount)") == "1234.57" + + +def test_stored_form_is_stable_s2(native_table, native_model, native_io): + """S2: writing the value read back produces the same stored text.""" + native_table("native_money") + model = native_model(MoneyRow) + + model(id=1, amount=AMOUNT, small=SMALL).save() + read_back = model.find_one(1) + model(id=2, amount=read_back.amount, small=read_back.small).save() + + assert _amount(native_io, 1) == _amount(native_io, 2) + assert _small(native_io, 1) == _small(native_io, 2) + + +def test_foreign_native_value_s3(native_table, native_model, native_io): + """S3: a value written as native SQL decodes and re-writes canonically.""" + native_table("native_money") + model = native_model(MoneyRow) + + native_io.insert("native_money", {"id": "9001", "amount": "1234.5678", "small": "-12.3456"}) + foreign = model.find_one(9001) + assert foreign.amount == AMOUNT + assert foreign.small == SMALL + + model(id=9002, amount=foreign.amount, small=foreign.small).save() + assert _amount(native_io, 9001) == _amount(native_io, 9002) + + +def test_smallmoney_bounds_round_trip(native_table, native_model, native_io): + """SMALLMONEY's documented range survives the round trip.""" + native_table("native_money") + model = native_model(MoneyRow) + + values = (Decimal("214748.3647"), Decimal("-214748.3648"), Decimal("0.0001")) + for row_id, value in enumerate(values, start=1): + model(id=row_id, small=value).save() + + for row_id, value in enumerate(values, start=1): + assert model.find_one(row_id).small == value + assert _small(native_io, row_id) == str(value) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_rowversion.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_rowversion.py new file mode 100644 index 00000000..b61eb0e6 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_rowversion.py @@ -0,0 +1,93 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_rowversion.py +"""ROWVERSION / TIMESTAMP: an 8-byte concurrency token, explicitly not a time. + +``timestamp`` is SQL Server's synonym of ``rowversion``. Neither is a date/time +type: the value is a server-maintained binary counter that changes whenever the +row changes, which is what the "not a time type" assertion checks. A table may +hold only one such column, so the synonym gets its own table. +""" +from datetime import date, datetime + +from sqlserver_native_models import RowVersionRow, TimestampRow + + +def _rule_out_time_types(value): + assert isinstance(value, bytes), f"rowversion reads as bytes, got {type(value)!r}" + assert not isinstance(value, (date, datetime, str)), "rowversion is not a time type" + assert len(value) == 8, "rowversion is an 8-byte counter" + + +def test_no_adapter_claims_the_column(native_model): + """``bytes`` passes through: nothing converts rowversion into a time value.""" + model = native_model(RowVersionRow) + assert model.get_field_type_adapters()["rv"] is None + + +def test_round_trip_s1(native_table, native_model): + native_table("native_rowversion") + model = native_model(RowVersionRow) + + model(id=1, note="first").save() + found = model.find_one(1) + _rule_out_time_types(found.rv) + assert found.note == "first" + + +def test_raw_stored_form(native_table, native_io): + native_table("native_rowversion") + native_io.insert("native_rowversion", {"id": "1", "note": "'first'"}) + raw = native_io.raw("native_rowversion", "rv") + _rule_out_time_types(raw) + + +def test_value_changes_when_the_row_changes(native_table, native_io): + """This is what proves the column is a concurrency token, not a value.""" + native_table("native_rowversion") + native_io.insert("native_rowversion", {"id": "1", "note": "'before'"}) + before = native_io.raw("native_rowversion", "rv") + + native_io.backend.execute("UPDATE native_rowversion SET note = 'after' WHERE id = 1", ()) + after = native_io.raw("native_rowversion", "rv") + + assert after != before + _rule_out_time_types(after) + + +def test_stored_type_is_stable_s2(native_table, native_model, native_io): + """S2 for a server-generated column: the *type* is stable, the token is new.""" + native_table("native_rowversion") + model = native_model(RowVersionRow) + + model(id=1, note="a").save() + model(id=2, note="a").save() + first = model.find_one(1).rv + second = model.find_one(2).rv + + _rule_out_time_types(first) + _rule_out_time_types(second) + assert first != second, "a second row gets its own token" + + +def test_foreign_native_value_s3(native_table, native_model, native_io): + """A row written without the column still carries a server token.""" + native_table("native_rowversion") + model = native_model(RowVersionRow) + + native_io.insert("native_rowversion", {"id": "9001", "note": "'native'"}) + foreign = model.find_one(9001) + assert foreign.note == "native" + _rule_out_time_types(foreign.rv) + + +def test_timestamp_is_the_synonym(native_table, native_model, native_io): + native_table("native_timestamp") + model = native_model(TimestampRow) + + model(id=1, note="a").save() + first = model.find_one(1).rv + _rule_out_time_types(first) + + native_io.insert("native_timestamp", {"id": "2", "note": "'b'"}) + second = model.find_one(2).rv + _rule_out_time_types(second) + assert second != first diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_uniqueidentifier.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_uniqueidentifier.py new file mode 100644 index 00000000..3223ff3a --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_uniqueidentifier.py @@ -0,0 +1,79 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_uniqueidentifier.py +"""UNIQUEIDENTIFIER: SQL Server's native 16-byte GUID. + +The adapter writes the canonical string form and reads back ``uuid.UUID``. +pyodbc returns the column as text, which is why the stored-form assertion is +``CONVERT(varchar(36), uid)``; the server renders it in upper case. +""" +import uuid + +from sqlserver_native_models import UniqueIdentifierRow + +UID = uuid.UUID("0f8fad5b-d9cb-469f-a165-70867728950e") +STORED_TEXT = "0F8FAD5B-D9CB-469F-A165-70867728950E" + + +def _stored(native_io, row_id=1): + return native_io.raw("native_uniqueidentifier", "CONVERT(varchar(36), uid)", row_id) + + +def test_adapter_semantic_round_trip(native_io): + """S1 without a server: the registered adapter writes and reads a UUID.""" + adapter = native_io.adapter(uuid.UUID, str) + assert adapter is not None, "UUID -> str is the backend's suggestion for UUID" + + wire = adapter.to_database(UID, str, None) + assert isinstance(wire, str) + assert adapter.from_database(wire, uuid.UUID) == UID + + +def test_round_trip_s1(native_table, native_model): + native_table("native_uniqueidentifier") + model = native_model(UniqueIdentifierRow) + + model(id=1, uid=UID).save() + found = model.find_one(1) + assert found.uid == UID + assert isinstance(found.uid, uuid.UUID) + + +def test_raw_stored_form(native_table, native_io): + """The column stores the canonical GUID, upper case on this server.""" + native_table("native_uniqueidentifier") + native_io.insert("native_uniqueidentifier", {"id": "1", "uid": f"'{UID}'"}) + assert _stored(native_io) == STORED_TEXT + + +def test_stored_form_is_stable_s2(native_table, native_model, native_io): + native_table("native_uniqueidentifier") + model = native_model(UniqueIdentifierRow) + + model(id=1, uid=UID).save() + read_back = model.find_one(1) + model(id=2, uid=read_back.uid).save() + assert _stored(native_io, 1) == _stored(native_io, 2) + + +def test_foreign_native_value_s3(native_table, native_model, native_io): + """A lower-case literal reads back as a UUID and re-writes canonically.""" + native_table("native_uniqueidentifier") + model = native_model(UniqueIdentifierRow) + + native_io.insert( + "native_uniqueidentifier", {"id": "9001", "uid": "'0f8fad5b-d9cb-469f-a165-70867728950e'"} + ) + foreign = model.find_one(9001) + assert foreign.uid == UID + + model(id=9002, uid=foreign.uid).save() + assert _stored(native_io, 9001) == _stored(native_io, 9002) == STORED_TEXT + + +def test_nil_uuid_round_trip(native_table, native_model): + """The all-zero GUID is a value, not a NULL.""" + native_table("native_uniqueidentifier") + model = native_model(UniqueIdentifierRow) + + nil = uuid.UUID(int=0) + model(id=1, uid=nil).save() + assert model.find_one(1).uid == nil diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_xml.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_xml.py new file mode 100644 index 00000000..115f6166 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_xml.py @@ -0,0 +1,81 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/native/test_native_xml.py +"""XML: a native XML column carried as text. + +SQL Server parses and validates the document on write, and ``CAST(col AS +NVARCHAR(MAX))`` returns exactly what was stored. The adapter never builds an +element tree: ``str`` in, ``str`` out (``dict`` input only at the encode side). +""" +from rhosocial.activerecord.backend.impl.sqlserver.adapters import SQLServerXMLAdapter +from sqlserver_native_models import XmlRow + +DOC = "1中文" + + +def _stored(native_io, row_id=1): + return native_io.raw("native_xml", "CAST(doc AS NVARCHAR(MAX))", row_id) + + +def test_column_is_the_native_xml_type(native_table, native_io): + native_table("native_xml") + assert native_io.column_type("native_xml", "doc") == "xml" + + +def test_adapter_semantic_round_trip(): + """S1 without a server: text in, text out; no XML parsing on the read side.""" + adapter = SQLServerXMLAdapter() + + assert adapter.to_database(DOC, str, None) == DOC + assert adapter.from_database(DOC, str) == DOC + + encoded = adapter.to_database({"a": "1", "b": ["x", "y"]}, str, None) + assert encoded.startswith("") + assert "1" in encoded + assert "xy" in encoded + + +def test_round_trip_s1(native_table, native_model): + native_table("native_xml") + model = native_model(XmlRow) + + model(id=1, doc=DOC).save() + found = model.find_one(1) + assert found.doc == DOC, "the document must come back verbatim, unicode included" + assert isinstance(found.doc, str), "XML is carried as text, not as an element tree" + + +def test_raw_stored_form(native_table, native_io): + native_table("native_xml") + native_io.insert("native_xml", {"id": "1", "doc": f"N'{DOC}'"}) + assert _stored(native_io) == DOC + + +def test_stored_form_is_stable_s2(native_table, native_model, native_io): + native_table("native_xml") + model = native_model(XmlRow) + + model(id=1, doc=DOC).save() + read_back = model.find_one(1) + model(id=2, doc=read_back.doc).save() + assert _stored(native_io, 1) == _stored(native_io, 2) + + +def test_foreign_native_value_s3(native_table, native_model, native_io): + native_table("native_xml") + model = native_model(XmlRow) + + native_io.insert("native_xml", {"id": "9001", "doc": f"N'{DOC}'"}) + foreign = model.find_one(9001) + assert foreign.doc == DOC + + model(id=9002, doc=foreign.doc).save() + assert _stored(native_io, 9001) == _stored(native_io, 9002) + + +def test_dict_input_is_rendered_as_xml(native_table, native_io): + """The adapter's dict branch produces a document the column accepts.""" + native_table("native_xml") + adapter = SQLServerXMLAdapter() + + document = adapter.to_database({"order": {"id": 7}}, str, None) + native_io.insert("native_xml", {"id": "1", "doc": f"N'{document}'"}) + assert _stored(native_io) == document diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/test_json_adapter_hooks.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/test_json_adapter_hooks.py new file mode 100644 index 00000000..3f551351 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/test_json_adapter_hooks.py @@ -0,0 +1,157 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/test_json_adapter_hooks.py +"""DB-free tests for ``SQLServerJSONAdapter``'s optional ``default`` / ``object_hook``. + +The hooks are forwarded to ``json.dumps`` / ``json.loads``; passing neither +keeps plain ``json`` behaviour, which the no-hook cases pin down. +""" + +import json +from typing import Any + +import pytest +from rhosocial.activerecord.backend.adapters.json_codec import ( + AdapterJSONCodec, + register_type, + unregister_type, +) + +from rhosocial.activerecord.backend.impl.sqlserver.adapters import SQLServerJSONAdapter + + +class _Point: + """Minimal neutral type used to prove the hooks reach ``json``.""" + + json_type_tag = "demo_point_sqlserver" + + def __init__(self, x: int, y: int): + self.x = x + self.y = y + + def to_json_value(self) -> Any: + return {"x": self.x, "y": self.y} + + @classmethod + def from_json_value(cls, value: Any) -> "_Point": + return cls(int(value["x"]), int(value["y"])) + + def __eq__(self, other: object) -> bool: + return isinstance(other, _Point) and (self.x, self.y) == (other.x, other.y) + + +class _Opaque: + """Not JSON serializable by plain ``json.dumps``.""" + + def __str__(self) -> str: + return "opaque" + + +class TestNoHooks: + """``default=None`` / ``object_hook=None`` reproduce the historical behaviour.""" + + @pytest.fixture + def adapter(self): + return SQLServerJSONAdapter() + + def test_dict_and_list_serialize_to_json_text(self, adapter): + assert adapter.to_database({"a": 1}) == '{"a": 1}' + assert adapter.to_database([1, 2]) == "[1, 2]" + + def test_valid_json_string_still_passes_through_after_validation(self, adapter): + raw = '{"a": [1, 2]}' + assert adapter.to_database(raw) is raw + + def test_invalid_json_string_still_rejected(self, adapter): + with pytest.raises(json.JSONDecodeError): + adapter.to_database("{nope}") + + def test_plain_dict_and_list_decode_unchanged(self, adapter): + payload = {"a": [1, {"b": 2}]} + assert adapter.from_database('{"a": [1, {"b": 2}]}') == payload + assert adapter.from_database(payload) is payload + assert adapter.from_database([1, 2]) == [1, 2] + + def test_unsupported_object_still_raises_without_default(self, adapter): + with pytest.raises(TypeError): + adapter.to_database({"o": _Opaque()}) + + def test_null_semantics(self, adapter): + assert adapter.to_database(None) is None + assert adapter.from_database(None) is None + + def test_supported_types_unchanged(self, adapter): + assert adapter.supported_types[dict] == ["nvarchar(max)", "json"] + assert adapter.supported_types[list] == ["nvarchar(max)", "json"] + + def test_unsupported_scalar_still_raises(self, adapter): + with pytest.raises(TypeError): + adapter.from_database(15) + + +class TestCustomDefault: + def test_default_is_used_for_unsupported_objects(self): + adapter = SQLServerJSONAdapter(default=lambda obj: str(obj)) + assert adapter.to_database({"o": _Opaque()}) == '{"o": "opaque"}' + + def test_default_does_not_affect_json_native_values(self): + adapter = SQLServerJSONAdapter(default=lambda obj: "unused") + assert adapter.to_database({"a": [1, None, True]}) == '{"a": [1, null, true]}' + + def test_default_does_not_change_string_validation(self): + adapter = SQLServerJSONAdapter(default=lambda obj: "unused") + raw = '{"a": 1}' + assert adapter.to_database(raw) is raw + + +class TestObjectHook: + def test_object_hook_decodes_matching_dicts(self): + def hook(value): + if set(value) == {"x", "y"}: + return _Point(value["x"], value["y"]) + return value + + adapter = SQLServerJSONAdapter(object_hook=hook) + decoded = adapter.from_database('{"p": {"x": 1, "y": 2}}') + assert decoded == {"p": _Point(1, 2)} + assert isinstance(decoded["p"], _Point) + + def test_object_hook_leaves_other_dicts_untouched(self): + adapter = SQLServerJSONAdapter( + object_hook=lambda value: _Point(0, 0) if "x" in value else value + ) + assert adapter.from_database('{"a": 1, "b": [1, 2]}') == {"a": 1, "b": [1, 2]} + + def test_object_hook_is_not_applied_to_dict_input(self): + adapter = SQLServerJSONAdapter(object_hook=lambda value: _Point(0, 0)) + payload = {"x": 1, "y": 2} + assert adapter.from_database(payload) is payload + + def test_matching_encode_and_decode_round_trip(self): + def default(obj): + if isinstance(obj, _Point): + return obj.to_json_value() + raise TypeError(f"not serializable: {type(obj).__name__}") + + def hook(value): + return _Point(value["x"], value["y"]) if set(value) == {"x", "y"} else value + + adapter = SQLServerJSONAdapter(default=default, object_hook=hook) + stored = adapter.to_database({"p": _Point(1, 2)}) + assert stored == '{"p": {"x": 1, "y": 2}}' + assert adapter.from_database(stored) == {"p": _Point(1, 2)} + + +class TestAdapterJSONCodecInterop: + def test_tagged_codec_round_trips_through_the_adapter(self): + register_type("demo_point_sqlserver", _Point) + try: + codec = AdapterJSONCodec(tagged=True) + adapter = SQLServerJSONAdapter(default=codec.default, object_hook=codec.object_hook) + + stored = adapter.to_database({"p": _Point(1, 2)}) + assert json.loads(stored) == {"p": {"x": 1, "y": 2, "__type__": "demo_point_sqlserver"}} + + decoded = adapter.from_database(stored) + assert isinstance(decoded["p"], _Point) + assert decoded["p"] == _Point(1, 2) + finally: + unregister_type("demo_point_sqlserver") diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/test_neutral_adapters.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/test_neutral_adapters.py new file mode 100644 index 00000000..7ed6da91 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/test_neutral_adapters.py @@ -0,0 +1,318 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/adapters/test_neutral_adapters.py +"""DB-free coverage for SQL Server's neutral-type adapters. + +These adapters bridge the core neutral types (geometry, vector, bit string, +range/multirange, MAC address) to SQL Server column representations. No live +server is involved: encoding/decoding is pure Python, and the backend inventory +is built from the adapter registry. + +SQL Server spatial limitation: a ``geometry``/``geography`` column rejects a +plain VARCHAR parameter, so WKT text must be wrapped as +``geometry::STGeomFromText(?, srid)``. ``SQLServerGeometryAdapter.bind_expression`` +returns that wrapper; the tests pin both the WKT encoding and the wrapper. +""" + +import json +from datetime import datetime + +import pytest +from rhosocial.activerecord.backend.adapters import ( + BitString, + Geometry, + LineString, + MacAddress, + Multirange, + Point, + Range, + Vector, +) +from rhosocial.activerecord.backend.errors import TypeConversionError + +from rhosocial.activerecord.backend.impl.sqlserver.adapters import ( + SQLServerBitStringAdapter, + SQLServerGeometryAdapter, + SQLServerMacAddressAdapter, + SQLServerRangeAdapter, + SQLServerVectorAdapter, +) + + +@pytest.fixture +def geometry_adapter(): + return SQLServerGeometryAdapter() + + +@pytest.fixture +def vector_adapter(): + return SQLServerVectorAdapter() + + +@pytest.fixture +def bitstring_adapter(): + return SQLServerBitStringAdapter() + + +@pytest.fixture +def range_adapter(): + return SQLServerRangeAdapter() + + +@pytest.fixture +def mac_adapter(): + return SQLServerMacAddressAdapter() + + +class TestGeometryAdapter: + def test_encode_is_wkt_text(self, geometry_adapter): + stored = geometry_adapter.to_database(Point(1, 2), str) + assert isinstance(stored, str) + assert stored.startswith("POINT") + + def test_round_trip_point(self, geometry_adapter): + result = geometry_adapter.from_database( + geometry_adapter.to_database(Point(1, 2), str), Geometry + ) + assert result == Point(1, 2) + + def test_round_trip_linestring(self, geometry_adapter): + original = LineString(((0, 0), (1, 1), (2, 0))) + result = geometry_adapter.from_database( + geometry_adapter.to_database(original, str), Geometry + ) + assert result == original + + def test_decode_accepts_utf8_wkt_bytes(self, geometry_adapter): + result = geometry_adapter.from_database(b"POINT (3 4)", Geometry) + assert result == Point(3, 4) + + def test_decode_keeps_srid_from_prefix(self, geometry_adapter): + result = geometry_adapter.from_database("SRID=4326;POINT (1 2)", Geometry) + assert result == Point(1, 2, srid=4326) + + def test_encoded_bytes_target(self, geometry_adapter): + stored = geometry_adapter.to_database(Point(1, 2), bytes) + assert isinstance(stored, bytes) + + def test_bind_expression_defaults_to_geometry_srid_zero(self, geometry_adapter): + assert geometry_adapter.bind_expression() == "geometry::STGeomFromText(?, 0)" + + def test_bind_expression_uses_configured_srid(self): + adapter = SQLServerGeometryAdapter(srid=4326) + assert adapter.bind_expression(":p") == "geometry::STGeomFromText(:p, 4326)" + + def test_bind_expression_geography_defaults_to_4326(self): + adapter = SQLServerGeometryAdapter(geography=True) + assert adapter.kind == "geography" + assert adapter.srid == 4326 + assert adapter.bind_expression() == "geography::STGeomFromText(?, 4326)" + + def test_negative_srid_rejected(self): + with pytest.raises(ValueError): + SQLServerGeometryAdapter(srid=-1) + + def test_invalid_srid_type_rejected(self): + with pytest.raises(TypeError): + SQLServerGeometryAdapter(srid="4326") + + def test_binary_geometry_value_is_rejected(self, geometry_adapter): + with pytest.raises(TypeConversionError): + geometry_adapter.from_database(b"\x00\x01\x02", Geometry) + + def test_invalid_wkt_wrapped(self, geometry_adapter): + with pytest.raises(TypeConversionError): + geometry_adapter.from_database("NOT A GEOMETRY", Geometry) + + def test_unsupported_input_wrapped(self, geometry_adapter): + with pytest.raises(TypeConversionError): + geometry_adapter.to_database(object(), str) + + def test_invalid_decode_type_wrapped(self, geometry_adapter): + with pytest.raises(TypeConversionError): + geometry_adapter.from_database(123, Geometry) + + +class TestVectorAdapter: + def test_encode_is_json_array(self, vector_adapter): + stored = vector_adapter.to_database(Vector((1.5, 2)), str) + assert json.loads(stored) == [1.5, 2] + + def test_round_trip(self, vector_adapter): + original = Vector((1.5, -2.0, 3.25)) + result = vector_adapter.from_database(vector_adapter.to_database(original, str), Vector) + assert result == original + + def test_round_trip_non_finite(self, vector_adapter): + original = Vector((1.0, float("inf")), allow_non_finite=True) + result = vector_adapter.from_database(vector_adapter.to_database(original, str), Vector) + assert result == original + + def test_decode_accepts_bytes_and_list(self, vector_adapter): + assert vector_adapter.from_database(b"[1, 2]", Vector) == Vector((1, 2)) + assert vector_adapter.from_database([3, 4], Vector) == Vector((3, 4)) + + def test_bytes_target(self, vector_adapter): + stored = vector_adapter.to_database(Vector((1, 2)), bytes) + assert isinstance(stored, bytes) + assert json.loads(stored.decode("utf-8")) == [1, 2] + + def test_invalid_json_wrapped(self, vector_adapter): + with pytest.raises(TypeConversionError): + vector_adapter.from_database("{nope}", Vector) + + def test_invalid_decode_type_wrapped(self, vector_adapter): + with pytest.raises(TypeConversionError): + vector_adapter.from_database(42, Vector) + + +class TestBitStringAdapter: + def test_encode_is_varbinary_bytes(self, bitstring_adapter): + stored = bitstring_adapter.to_database(BitString.from_bits("10101010"), bytes) + assert stored == b"\xaa" + + def test_encode_is_bit_text_for_text_target(self, bitstring_adapter): + stored = bitstring_adapter.to_database(BitString.from_bits("10101010"), str) + assert stored == "10101010" + + def test_text_target_preserves_non_byte_aligned_length(self, bitstring_adapter): + """A text carrier keeps the exact bit length binary carriers lose.""" + original = BitString.from_bits("10101") + stored = bitstring_adapter.to_database(original, str) + assert stored == "10101" + assert bitstring_adapter.from_database(stored, BitString) == original + + def test_round_trip_whole_bytes(self, bitstring_adapter): + original = BitString.from_bits("1010101011110000") + result = bitstring_adapter.from_database( + bitstring_adapter.to_database(original, bytes), BitString + ) + assert result == original + + def test_decode_accepts_bit_text(self, bitstring_adapter): + assert bitstring_adapter.from_database("10101", BitString).to_bits() == "10101" + + def test_decode_preserves_leading_zero_bytes(self, bitstring_adapter): + # bit_length covers the whole byte string, so a leading zero byte + # remains part of the 16-bit value. + assert bitstring_adapter.from_database(b"\x00\x0f", BitString) == BitString.from_bytes( + b"\x00\x0f" + ) + + def test_non_byte_aligned_length_is_not_preserved(self, bitstring_adapter): + # Binary columns carry whole bytes; the exact bit length needs metadata. + stored = bitstring_adapter.to_database(BitString.from_bits("10101"), bytes) + decoded = bitstring_adapter.from_database(stored, BitString) + assert decoded.to_bits() == "10101000" + assert decoded.bit_length == 8 + + def test_invalid_decode_type_wrapped(self, bitstring_adapter): + with pytest.raises(TypeConversionError): + bitstring_adapter.from_database(7, BitString) + + +class TestRangeAdapter: + def test_range_round_trip(self, range_adapter): + original = Range(1, 5, "[)") + stored = range_adapter.to_database(original, str) + assert json.loads(stored) == original.to_json_value() + assert range_adapter.from_database(stored, Range) == original + + def test_empty_range_round_trip(self, range_adapter): + original = Range(empty=True) + assert ( + range_adapter.from_database(range_adapter.to_database(original, str), Range) == original + ) + + def test_datetime_range_round_trip(self, range_adapter): + original = Range(datetime(2024, 1, 1, 12, 0), datetime(2024, 6, 1, 12, 0), "[)") + assert ( + range_adapter.from_database(range_adapter.to_database(original, str), Range) == original + ) + + def test_multirange_round_trip_is_canonical(self, range_adapter): + original = Multirange((Range(1, 5), Range(5, 9))) + result = range_adapter.from_database(range_adapter.to_database(original, str), Multirange) + assert result == original + assert len(result.ranges) == 1 + + def test_decode_infers_type_without_explicit_target(self, range_adapter): + assert isinstance( + range_adapter.from_database( + '{"lower": 1, "upper": 2, "bounds": "[)", "empty": false, "element_type": "int"}', + dict, + ), + Range, + ) + assert isinstance(range_adapter.from_database("[]", dict), Multirange) + + def test_bytes_target(self, range_adapter): + stored = range_adapter.to_database(Range(1, 5), bytes) + assert isinstance(stored, bytes) + + def test_mismatched_target_wrapped(self, range_adapter): + text = range_adapter.to_database(Range(1, 5), str) + with pytest.raises(TypeConversionError): + range_adapter.from_database(text, Multirange) + + def test_invalid_json_wrapped(self, range_adapter): + with pytest.raises(TypeConversionError): + range_adapter.from_database("{nope}", Range) + + +class TestMacAddressAdapter: + def test_encode_is_canonical_text(self, mac_adapter): + mac = MacAddress.parse("01:23:45:67:89:AB") + assert mac_adapter.to_database(mac, str) == "01:23:45:67:89:ab" + + def test_round_trip(self, mac_adapter): + original = MacAddress.parse("08002B010203") + result = mac_adapter.from_database(mac_adapter.to_database(original, str), MacAddress) + assert result == original + + def test_decode_accepts_six_raw_octets(self, mac_adapter): + assert mac_adapter.from_database( + b"\x01\x23\x45\x67\x89\xab", MacAddress + ) == MacAddress.parse("01:23:45:67:89:ab") + + def test_bytes_target(self, mac_adapter): + mac = MacAddress.parse("01:23:45:67:89:ab") + assert mac_adapter.to_database(mac, bytes) == mac.octets + + def test_invalid_text_wrapped(self, mac_adapter): + with pytest.raises(TypeConversionError): + mac_adapter.from_database("not-a-mac", MacAddress) + + def test_invalid_binary_length_wrapped(self, mac_adapter): + with pytest.raises(TypeConversionError): + mac_adapter.from_database(b"\x01\x02\x03\x04", MacAddress) + + +@pytest.fixture(scope="module") +def backend(): + from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend + from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig + + config = SQLServerConnectionConfig( + host="127.0.0.1", + port=11433, + database="master", + username="sa", + password="not-used-offline", + ) + return SQLServerBackend(connection_config=config) + + +class TestAdapterInventory: + """The backend's plain adapter inventory includes the neutral adapters.""" + + @pytest.mark.parametrize( + "adapter_class", + [ + SQLServerGeometryAdapter, + SQLServerVectorAdapter, + SQLServerBitStringAdapter, + SQLServerRangeAdapter, + SQLServerMacAddressAdapter, + ], + ) + def test_neutral_adapter_is_registered(self, backend, adapter_class): + assert adapter_class in {type(adapter) for adapter in backend.get_type_adapters()} diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/conftest.py index ed8800e5..2ba4ad78 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/conftest.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/conftest.py @@ -1,89 +1,103 @@ # tests/rhosocial/activerecord_sqlserver_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 + +import support.sqlserver from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.backend.async_backend import ( + AsyncSQLServerBackend, +) from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig -from rhosocial.activerecord.backend.impl.sqlserver.backend.async_backend import AsyncSQLServerBackend -SCENARIO_MAP: Dict[str, Dict[str, Any]] = {} +DECLARATION = Declaration( + uses_database=True, + parallel=False, + purpose="Backend-owned SQL Server tests using shared fixtures or pure rendering " + "(the construct directories).", + passes_means="the rendering or backend contract under test holds for the SQL Server dialect", + fails_means="a rendering assertion breaks, or a backend-specific contract is no longer met", +) +# --- Scenario Loading Logic --- -def register_scenario(name: str, config: Dict[str, Any]): - SCENARIO_MAP[name] = config +SCENARIO_MAP: Dict[str, Dict[str, Any]] = dict(support.sqlserver.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/sqlserver_scenarios.yaml (lowest priority) - If no valid configuration file is found, terminate with an error. +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("SQLSERVER_SCENARIOS_CONFIG_PATH") - - if env_config_path and os.path.exists(env_config_path): - print(f"Loading SQL Server scenarios from environment-specified path: {env_config_path}") - config_path = env_config_path - else: - default_path = os.path.join( - os.path.dirname(__file__), - "../../../../config", - "sqlserver_scenarios.yaml", - ) - if os.path.exists(default_path): - config_path = default_path - elif env_config_path: - print(f"Warning: Scenario file specified in SQLSERVER_SCENARIOS_CONFIG_PATH not found: {env_config_path}") - return - - if not config_path: - raise FileNotFoundError( - "No SQL Server scenarios configuration file found. " - "Either set SQLSERVER_SCENARIOS_CONFIG_PATH to a valid YAML file " - "or place sqlserver_scenarios.yaml in the tests/config directory." - ) + filter_str = os.getenv("SQLSERVER_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() - for scenario_name, config in config_data["scenarios"].items(): - register_scenario(scenario_name, config) - except ImportError: - raise ImportError("PyYAML is required to load SQL Server scenario configuration files") +def get_enabled_scenarios() -> Dict[str, Any]: + return SCENARIO_MAP -_load_scenarios_from_config() +def get_scenario_names(): + return list(get_enabled_scenarios().keys()) -def get_scenario(name: str) -> Tuple[Type[SQLServerBackend], SQLServerConnectionConfig]: +_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) + + +def _prepare_database(scenario_name: str, database: str) -> None: + """Create or clear the directory's database once per scenario.""" + key = (scenario_name, database) + if key in _PREPARED_DATABASES: + return + support.sqlserver.scenario(scenario_name).reset_database(database) + _PREPARED_DATABASES.add(key) + + +def get_scenario( + name: str, database: str +) -> Tuple[Type[SQLServerBackend], SQLServerConnectionConfig]: if name not in SCENARIO_MAP: - if SCENARIO_MAP: - name = next(iter(SCENARIO_MAP)) - else: + if not SCENARIO_MAP: raise ValueError("No scenarios registered") - scenario_config = SCENARIO_MAP[name].copy() - # Apply the pooled database name so parallel workers never share a schema. - from providers.pooling import resolve_database_name + name = next(iter(SCENARIO_MAP)) + _prepare_database(name, database) + return SQLServerBackend, support.sqlserver.scenario(name).make_config(database) - pooled_db = resolve_database_name(name) - if pooled_db: - scenario_config["database"] = pooled_db - config = SQLServerConnectionConfig(**scenario_config) - return SQLServerBackend, config - -def get_enabled_scenarios() -> Dict[str, Any]: - return SCENARIO_MAP +# --- Provider Logic --- class BackendFeatureProvider: @@ -91,20 +105,22 @@ def __init__(self): self._backend = None self._async_backend = None - def setup_backend(self, scenario_name: str): + def setup_backend(self, scenario_name: str, database: str): if self._backend: return self._backend - backend_class, config = get_scenario(scenario_name) + backend_class, config = get_scenario(scenario_name, database) self._backend = backend_class(connection_config=config) self._backend.connect() + self._backend.introspect_and_adapt() return self._backend - async def setup_async_backend(self, scenario_name: str): + async def setup_async_backend(self, scenario_name: str, database: str): if self._async_backend: return self._async_backend - _, config = get_scenario(scenario_name) + _, config = get_scenario(scenario_name, database) self._async_backend = AsyncSQLServerBackend(connection_config=config) await self._async_backend.connect() + await self._async_backend.introspect_and_adapt() return self._async_backend def cleanup(self): @@ -118,28 +134,27 @@ async def async_cleanup(self): self._async_backend = None -def get_scenario_names(): - return list(get_enabled_scenarios().keys()) +# --- Fixtures --- @pytest.fixture(scope="function", params=get_scenario_names()) def sqlserver_backend(request): scenario_name = request.param provider = BackendFeatureProvider() - backend = provider.setup_backend(scenario_name) + backend = provider.setup_backend(scenario_name, database_for(request)) yield backend provider.cleanup() @pytest.fixture(scope="function") -def sqlserver_backend_single(): +def sqlserver_backend_single(request): """Non-parameterized fixture using the first available scenario.""" scenario_names = get_scenario_names() if not scenario_names: pytest.skip("No SQL Server 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() @@ -148,20 +163,20 @@ def sqlserver_backend_single(): async def async_sqlserver_backend(request): scenario_name = request.param 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() @pytest_asyncio.fixture(scope="function") -async def async_sqlserver_backend_single(): +async def async_sqlserver_backend_single(request): """Non-parameterized async fixture using the first available scenario.""" scenario_names = get_scenario_names() if not scenario_names: pytest.skip("No SQL Server 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() @@ -170,6 +185,7 @@ async def async_sqlserver_backend_single(): def sqlserver_dialect(): """Fixture providing SQLServerDialect instance for testing.""" from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect + return SQLServerDialect(version=(16, 0, 0)) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_cli.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli.py similarity index 100% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_cli.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli.py diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_info_query.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_info_query.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_info_query.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_info_query.py index bbfaa923..32dfb78e 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_info_query.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_info_query.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_info_query.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_info_query.py """Offline black-box tests for the ``info`` and ``query`` subcommands. ``info`` runs against its default offline dialect (explicit ``--version``), diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_introspect.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_introspect.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_introspect.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_introspect.py index 7a613764..6f0f5add 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_introspect.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_introspect.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_introspect.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_introspect.py """Offline black-box tests for the ``introspect`` subcommand. The fakes below implement the *real* introspector API -- ``list_tables``, diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_offline.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_offline.py new file mode 100644 index 00000000..b9d7b1a3 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_offline.py @@ -0,0 +1,523 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_offline.py +"""Connectionless CLI unit tests for the ``info``, ``status`` and +``named-expression`` subcommands. + +The focus is the not-yet-covered surface: rich-rendering helpers, the native +async status path, and the named-expression adapter's callback seams. Every +backend, provider and I/O boundary is a ``MagicMock``/``AsyncMock``; no SQL +Server connection is attempted. +""" + +import argparse +import json +import sys +import types +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from rhosocial.activerecord.backend.errors import ConnectionError, QueryError +from rhosocial.activerecord.backend.introspection.status import StatusCategory +from rhosocial.activerecord.backend.impl.sqlserver.backend import async_backend as async_backend_mod +from rhosocial.activerecord.backend.impl.sqlserver.cli import info as info_mod +from rhosocial.activerecord.backend.impl.sqlserver.cli import named_expression as ne_mod +from rhosocial.activerecord.backend.impl.sqlserver.cli import status as status_mod +from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect + +STATUS_INTROSPECTOR = ( + "rhosocial.activerecord.backend.impl.sqlserver.introspection.status_introspector" +) + + +def make_args(create_parser, argv): + parser = argparse.ArgumentParser() + sub = parser.add_subparsers(dest="command") + create_parser(sub) + return parser.parse_args(argv) + + +@pytest.fixture +def fake_rich(monkeypatch): + """Install module-level MagicMock stand-ins for the optional rich package.""" + console_mod = types.ModuleType("rich.console") + console_mod.Console = MagicMock(name="Console") + table_mod = types.ModuleType("rich.table") + table_mod.Table = MagicMock(name="Table") + rich_mod = types.ModuleType("rich") + rich_mod.console = console_mod + rich_mod.table = table_mod + monkeypatch.setitem(sys.modules, "rich", rich_mod) + monkeypatch.setitem(sys.modules, "rich.console", console_mod) + monkeypatch.setitem(sys.modules, "rich.table", table_mod) + return console_mod.Console.return_value + + +def printed(console): + """Flatten all positional strings passed to ``console.print``.""" + return " ".join( + str(arg) + for call in console.print.call_args_list + for arg in call.args + ) + + +class TestInfoRichDisplayHelpers: + def test_format_method_display(self): + assert info_mod._format_method_display("supports_explain_format") == "explain format" + assert info_mod._format_method_display("is_json_available") == "is json available" + + def test_display_method_details_bool_values(self, fake_rich): + info_mod._display_method_details(fake_rich, "supports_cte", True) + info_mod._display_method_details(fake_rich, "supports_graph", False) + out = printed(fake_rich) + assert "[green][OK][/green]" in out + assert "[red][X][/red]" in out + assert "cte" in out + + def test_display_method_details_dict_value(self, fake_rich): + info_mod._display_method_details( + fake_rich, "supports_explain_format", {"args": {"TEXT": True, "XML": False}} + ) + out = printed(fake_rich) + assert "TEXT" in out and "XML" in out + + def test_display_protocol_item_progress_bar(self, fake_rich): + stats = {"percentage": 100, "supported": 2, "total": 2} + info_mod._display_protocol_item(fake_rich, "CTESupport", stats, verbose=0) + out = printed(fake_rich) + assert "CTESupport" in out + assert "####################" in out + assert "(2/2)" in out + + def test_display_protocol_item_verbose_methods(self, fake_rich): + stats = { + "percentage": 50, + "supported": 1, + "total": 2, + "methods": {"supports_cte": True}, + } + info_mod._display_protocol_item(fake_rich, "CTESupport", stats, verbose=2) + assert "cte" in printed(fake_rich) + + @staticmethod + def _stats(): + return {"percentage": 100, "supported": 1, "total": 1} + + def test_display_protocol_group_marks_dialect_specific(self, fake_rich): + info_mod._display_protocol_group( + fake_rich, "SQL Server Native", {"IdentitySupport": self._stats()}, 0 + ) + assert "(dialect-specific)" in printed(fake_rich) + + def test_display_protocol_group_normal(self, fake_rich): + info_mod._display_protocol_group( + fake_rich, "Query Features", {"CTESupport": self._stats()}, 0 + ) + assert "Query Features" in printed(fake_rich) + + @pytest.mark.parametrize("connected", [True, False]) + def test_display_info_rich_header(self, fake_rich, connected): + info = { + "protocols": { + "Query Features": { + "CTESupport": { + "percentage": 100, + "supported": 1, + "total": 1, + } + } + } + } + info_mod._display_info_rich(info, 0, "16.0.0", is_connected=connected) + out = printed(fake_rich) + assert "SQL Server Environment Information" in out + assert "16.0.0" in out + assert ("from actual connection" in out) is connected + + +class TestInfoCheckProtocolEdges: + def _protocol(self): + class ProbeProtocol: + def supports_simple(self): + return True + + def supports_with_arg(self, level): + return True + + def supports_boom(self, level): + raise RuntimeError("bad probe") + + return ProbeProtocol + + def test_method_with_required_param_not_in_all_args_is_false(self): + dialect = SimpleNamespace( + supports_simple=lambda: True, + supports_with_arg=lambda level: True, + ) + results = info_mod.check_protocol_support(dialect, self._protocol()) + assert results["supports_simple"] is True + assert results["supports_with_arg"] is False + + def test_method_raising_on_argument_is_false(self): + dialect = SimpleNamespace( + supports_simple=lambda: True, + supports_boom=lambda level: 1 / 0, + ) + results = info_mod.check_protocol_support(dialect, self._protocol()) + assert results["supports_boom"] is False + + +class TestInfoHandleBranches: + def test_table_format_uses_rich_display_when_available(self, monkeypatch): + monkeypatch.setattr(info_mod, "RICH_AVAILABLE", True) + display = MagicMock() + monkeypatch.setattr(info_mod, "_display_info_rich", display) + info_mod.handle(make_args(info_mod.create_parser, ["info", "-o", "table"])) + display.assert_called_once() + legacy = display.call_args.args[0] + assert "sqlserver" in legacy and "protocols" in legacy + + def test_connection_without_version_tuple_keeps_none(self, monkeypatch, capsys): + class NoVersionBackend: + def __init__(self, connection_config=None): + self._dialect = SQLServerDialect((16, 0, 0)) + + def connect(self): + pass + + def introspect_and_adapt(self): + pass + + def get_server_version(self): + return None + + def disconnect(self): + pass + + @property + def dialect(self): + return self._dialect + + monkeypatch.setattr( + "rhosocial.activerecord.backend.impl.sqlserver.backend.SQLServerBackend", + NoVersionBackend, + ) + info = info_mod.handle( + make_args(info_mod.create_parser, ["info", "--database", "db", "-o", "json"]) + ) + assert info["database"]["connected"] is True + assert info["database"]["version"] is None + json.loads(capsys.readouterr().out) + + +class TestStatusRichDisplay: + def test_full_overview_renders_all_sections(self, fake_rich): + status = SimpleNamespace( + server_version="16.0", + server_vendor="Microsoft", + session=SimpleNamespace(user="sa", database="master"), + connections=SimpleNamespace(active_count=7), + configuration=[ + SimpleNamespace( + name="max memory", value=1024, category=StatusCategory.CONFIGURATION + ) + ], + databases=[SimpleNamespace(name="master", size_bytes=2048)], + ) + status_mod._display_status_rich(status, verbose=1) + out = printed(fake_rich) + assert "SQL Server Status" in out + assert "Session" in out and "sa" in out + assert "Active Connections" in out + assert "Configuration" in out + assert "Databases" in out + + +def _async_status_args(status_type="all", output="json"): + return SimpleNamespace( + type=status_type, + output=output, + verbose=0, + rich_ascii=False, + ) + + +def _async_backend(): + backend = MagicMock() + backend.connect = AsyncMock() + backend.introspect_and_adapt = AsyncMock() + backend.disconnect = AsyncMock() + backend._connection = object() + return backend + + +def _async_introspector(): + introspector = MagicMock() + for name in ( + "get_overview", + "list_configuration", + "list_performance_metrics", + "get_connection_info", + "get_storage_info", + "list_databases", + "list_users", + ): + setattr(introspector, name, AsyncMock(return_value={"ok": name})) + return introspector + + +class TestStatusAsyncDispatch: + @pytest.mark.parametrize( + ("status_type", "method"), + [ + ("config", "list_configuration"), + ("performance", "list_performance_metrics"), + ("connections", "get_connection_info"), + ("storage", "get_storage_info"), + ("databases", "list_databases"), + ("users", "list_users"), + ], + ) + async def test_async_type_dispatch(self, monkeypatch, status_type, method): + introspector = _async_introspector() + monkeypatch.setattr( + f"{STATUS_INTROSPECTOR}.AsyncSQLServerStatusIntrospector", + MagicMock(return_value=introspector), + ) + backend = _async_backend() + provider = MagicMock() + await status_mod._handle_status_async(_async_status_args(status_type), backend, provider) + getattr(introspector, method).assert_awaited_once() + provider.display_results.assert_called_once() + backend.disconnect.assert_awaited_once() + + async def test_async_overview_json(self, monkeypatch, capsys): + introspector = _async_introspector() + introspector.get_overview.return_value = {"server_version": "16.0.0"} + monkeypatch.setattr( + f"{STATUS_INTROSPECTOR}.AsyncSQLServerStatusIntrospector", + MagicMock(return_value=introspector), + ) + await status_mod._handle_status_async( + _async_status_args("all"), _async_backend(), MagicMock() + ) + assert json.loads(capsys.readouterr().out)["server_version"] == "16.0.0" + + async def test_async_csv_tsv_overview_falls_back_to_json(self, monkeypatch, capsys): + introspector = _async_introspector() + introspector.get_overview.return_value = {"server_version": "16.0.0"} + monkeypatch.setattr( + f"{STATUS_INTROSPECTOR}.AsyncSQLServerStatusIntrospector", + MagicMock(return_value=introspector), + ) + for fmt in ("csv", "tsv"): + await status_mod._handle_status_async( + _async_status_args("all", fmt), _async_backend(), MagicMock() + ) + assert json.loads(capsys.readouterr().out)["server_version"] == "16.0.0" + + @pytest.mark.parametrize( + ("error", "provider_method"), + [ + (ConnectionError("refused"), "display_connection_error"), + (QueryError("bad query"), "display_query_error"), + ], + ) + async def test_async_known_errors(self, monkeypatch, error, provider_method): + introspector = _async_introspector() + introspector.get_overview.side_effect = error + monkeypatch.setattr( + f"{STATUS_INTROSPECTOR}.AsyncSQLServerStatusIntrospector", + MagicMock(return_value=introspector), + ) + provider = MagicMock() + with pytest.raises(SystemExit) as exc: + await status_mod._handle_status_async( + _async_status_args("all"), _async_backend(), provider + ) + assert exc.value.code == 1 + getattr(provider, provider_method).assert_called_once() + + async def test_async_unexpected_error(self, monkeypatch, capsys): + introspector = _async_introspector() + introspector.get_overview.side_effect = RuntimeError("boom") + monkeypatch.setattr( + f"{STATUS_INTROSPECTOR}.AsyncSQLServerStatusIntrospector", + MagicMock(return_value=introspector), + ) + with pytest.raises(SystemExit) as exc: + await status_mod._handle_status_async( + _async_status_args("all"), _async_backend(), MagicMock() + ) + assert exc.value.code == 1 + assert "Error during status retrieval" in capsys.readouterr().err + + +class TestNamedExpressionParser: + def test_parser_shape_and_dialect_version(self): + args = make_args( + ne_mod.create_parser, + ["named-expression", "-o", "json", "--dialect-version", "15.0.4000"], + ) + assert args.output == "json" + assert args.dialect_version == "15.0.4000" + assert args.is_async is False + + def test_no_dialect_version_by_default(self): + args = make_args(ne_mod.create_parser, ["named-expression"]) + assert args.dialect_version is None + + +def _ne_args(**overrides): + values = dict( + output="json", + rich_ascii=False, + dialect_version=None, + is_async=False, + database="db", + ) + values.update(overrides) + return SimpleNamespace(**values) + + +@pytest.fixture +def ne_seams(monkeypatch): + """Replace every named-expression adapter seam with a recording mock.""" + args = _ne_args() + provider = MagicMock(name="provider") + config = object() + handle_ne = MagicMock(name="handle_named_expression") + backend = MagicMock(name="backend") + backend._connection = object() + backend_cls = MagicMock(name="SQLServerBackend", return_value=backend) + async_backend = MagicMock(name="async_backend") + async_backend._connection = object() + async_backend.disconnect = AsyncMock() + async_backend_cls = MagicMock(name="AsyncSQLServerBackend", return_value=async_backend) + + monkeypatch.setattr(ne_mod, "create_provider", MagicMock(return_value=provider)) + monkeypatch.setattr( + ne_mod, "resolve_connection_config_from_args", MagicMock(return_value=config) + ) + monkeypatch.setattr( + "rhosocial.activerecord.backend.named_expression.cli.handle_named_expression", + handle_ne, + ) + monkeypatch.setattr(ne_mod, "SQLServerBackend", backend_cls) + monkeypatch.setattr( + async_backend_mod, "AsyncSQLServerBackend", async_backend_cls, raising=False + ) + return SimpleNamespace( + args=args, + provider=provider, + config=config, + handle_ne=handle_ne, + backend=backend, + backend_cls=backend_cls, + async_backend=async_backend, + async_backend_cls=async_backend_cls, + ) + + +class TestNamedExpressionSyncHandle: + def test_sync_callback_set(self, ne_seams): + ne_mod.handle(ne_seams.args) + ne_seams.handle_ne.assert_called_once() + kwargs = ne_seams.handle_ne.call_args.kwargs + assert ne_seams.handle_ne.call_args.args[0] is ne_seams.args + assert ne_seams.handle_ne.call_args.args[1] is ne_seams.provider + assert set(kwargs) == { + "backend_factory", + "get_dialect", + "execute_query", + "disconnect", + "create_dialect", + } + + def test_backend_factory_and_dialect_helpers(self, ne_seams): + ne_mod.handle(ne_seams.args) + kwargs = ne_seams.handle_ne.call_args.kwargs + + backend = kwargs["backend_factory"]() + ne_seams.backend_cls.assert_called_once_with(connection_config=ne_seams.config) + backend.connect.assert_called_once_with() + backend.introspect_and_adapt.assert_called_once_with() + assert backend is ne_seams.backend + assert kwargs["get_dialect"](backend) is backend.dialect + + dialect = kwargs["create_dialect"]() + assert isinstance(dialect, SQLServerDialect) + assert getattr(dialect, "_version", None) is None + + def test_execute_query_wraps_statement_type(self, ne_seams): + ne_mod.handle(ne_seams.args) + kwargs = ne_seams.handle_ne.call_args.kwargs + kwargs["backend_factory"]() + execute = kwargs["execute_query"] + execute("SELECT 1", (), "SELECT") + call = ne_seams.backend.execute.call_args + assert call.args == ("SELECT 1", ()) + assert call.kwargs["options"].stmt_type == "SELECT" + + def test_disconnect_respects_connection_state(self, ne_seams): + ne_mod.handle(ne_seams.args) + kwargs = ne_seams.handle_ne.call_args.kwargs + kwargs["backend_factory"]() + disconnect = kwargs["disconnect"] + ne_seams.backend._connection = None + disconnect() + ne_seams.backend.disconnect.assert_not_called() + ne_seams.backend._connection = object() + disconnect() + ne_seams.backend.disconnect.assert_called_once_with() + + def test_dialect_version_override(self, ne_seams): + ne_seams.args.dialect_version = "15.0.4000" + ne_mod.handle(ne_seams.args) + kwargs = ne_seams.handle_ne.call_args.kwargs + assert kwargs["create_dialect"]().version == (15, 0, 4000) + kwargs["backend_factory"]() + assert ne_seams.backend._dialect.version == (15, 0, 4000) + + +class TestNamedExpressionAsyncHandle: + def test_async_callback_set(self, ne_seams): + ne_seams.args.is_async = True + ne_mod.handle(ne_seams.args) + kwargs = ne_seams.handle_ne.call_args.kwargs + assert set(kwargs) == { + "backend_factory", + "get_dialect", + "execute_query", + "disconnect", + "backend_async_factory", + "get_dialect_async", + "execute_query_async", + "disconnect_async", + "create_dialect", + } + + async def test_async_backend_and_query_helpers(self, ne_seams): + ne_seams.args.is_async = True + ne_mod.handle(ne_seams.args) + kwargs = ne_seams.handle_ne.call_args.kwargs + + backend = kwargs["backend_async_factory"]() + ne_seams.async_backend_cls.assert_called_once_with(connection_config=ne_seams.config) + assert backend is ne_seams.async_backend + assert await kwargs["get_dialect_async"](backend) is backend.dialect + + ne_seams.async_backend.execute = AsyncMock(return_value="ok") + assert await kwargs["execute_query_async"]("EXEC p", (1,), "EXECUTE") == "ok" + ne_seams.async_backend.execute.assert_awaited_once() + + await kwargs["disconnect_async"]() + ne_seams.async_backend.disconnect.assert_awaited_once() + + async def test_async_disconnect_noop_without_connection(self, ne_seams): + ne_seams.args.is_async = True + ne_mod.handle(ne_seams.args) + ne_seams.async_backend._connection = None + await ne_seams.handle_ne.call_args.kwargs["disconnect_async"]() + ne_seams.async_backend.disconnect.assert_not_awaited() diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_status.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_status.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_status.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_status.py index 69dec32c..23fa14c9 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_status.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_status.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_status.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_cli_status.py """Offline black-box tests for the ``status`` subcommand. ``cli/status.py`` exposes ``create_parser(subparsers) + handle(args)``. The diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_introspect_families_cli.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_introspect_families_cli.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_introspect_families_cli.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_introspect_families_cli.py index 2b6894d3..aa0a5134 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_introspect_families_cli.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_introspect_families_cli.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_introspect_families_cli.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_introspect_families_cli.py """The shared families the MySQL and PostgreSQL CLIs ask, as this one asks them. No server is needed here. What is checked is the wiring the CLI owns: that diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_main_parse_args.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_main_parse_args.py similarity index 85% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_main_parse_args.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_main_parse_args.py index 78010b65..0baff9bf 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_main_parse_args.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_main_parse_args.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_main_parse_args.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_main_parse_args.py """Offline tests for ``__main__.parse_args`` with custom argv.""" import pytest diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_status_cli.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_status_cli.py new file mode 100644 index 00000000..6542c260 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/cli/test_status_cli.py @@ -0,0 +1,220 @@ +# tests/activerecord_sqlserver_test/feature/backend/construct/cli/test_status_cli.py +"""Backend-owned tests for ``sqlserver.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.sqlserver.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_sqlserver_test/feature/backend/test_config.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/connection/test_config.py similarity index 97% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_config.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/connection/test_config.py index 89d653b9..143183d8 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_config.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/connection/test_config.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_config.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/connection/test_config.py """Tests for SQL Server connection configuration.""" import os import pytest @@ -6,7 +6,7 @@ from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig -class TestSQLServerConnectionConfig: +class TestConnectionConfig: """Test cases for SQL Server connection configuration.""" def test_basic_config(self): diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_ssl_connection_params.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/connection/test_ssl_connection_params.py similarity index 95% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_ssl_connection_params.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/connection/test_ssl_connection_params.py index faaab9fe..89b573bd 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_ssl_connection_params.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/connection/test_ssl_connection_params.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_ssl_connection_params.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/connection/test_ssl_connection_params.py """Regression tests: SQL Server TLS settings must reach the ODBC connection string. ``build_connection_string()`` is the only place ``pyodbc`` gets its diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/sqlserver/partition_syntax_fixtures.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/partition_syntax_fixtures.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/sqlserver/partition_syntax_fixtures.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/partition_syntax_fixtures.py index 84765ef6..2d4f9a26 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/sqlserver/partition_syntax_fixtures.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/partition_syntax_fixtures.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/sqlserver/partition_syntax_fixtures.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/partition_syntax_fixtures.py """Fixture-driven matrix of SQL Server partition syntax families. Each :class:`PartitionSyntaxCase` names one family of SQL Server's three-tier @@ -8,7 +8,7 @@ builders the offline matrix uses to exercise it. The cases do not repeat the exact assertions of -``test_sqlserver_partition.py`` or ``test_sqlserver_partition_maintenance.py``; +``test_partition_expressions.py`` or ``test_partition_maintenance.py``; they collect the families those files cover into one parameterised table so a new syntax family is added in one place. No server is needed: every builder returns a plan, an expression, or a maintenance report built from canned diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_auto_increment_ddl.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_auto_increment_ddl.py similarity index 77% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_auto_increment_ddl.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_auto_increment_ddl.py index 026fefe7..d08f87e5 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_auto_increment_ddl.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_auto_increment_ddl.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_auto_increment_ddl.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_auto_increment_ddl.py """Regression tests for DDL compilation of auto-increment, standard types, boolean defaults, and timestamps. @@ -8,6 +8,7 @@ - BooleanType with DEFAULT True must be accepted. - TimestampType must map to DATETIME2. """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import pytest @@ -27,15 +28,22 @@ def dialect(): return SQLServerDialect() -def _pk(dialect): - return [ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True))] +def _id_column(dialect, data_type, **kwargs): + """Build an integer auto-increment id column from the backend suggestion.""" + suggested_type, attributes = auto_increment_parts(dialect, data_type) + return ColumnDefinition( + dialect, "id", suggested_type, + constraints=[ColumnConstraint(dialect, branch=ColumnPrimaryKeyConstraint(dialect))], + attributes=attributes, + **kwargs, + ) def _build_table(dialect): return CreateTableStatement( dialect=dialect, table=Table(dialect, "test_tbl"), columns=[ - ColumnDefinition(dialect, "id", IntegerType(dialect), constraints=_pk(dialect)), + _id_column(dialect, IntegerType(dialect)), ColumnDefinition(dialect, "name", TextType(dialect), constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect))]), ColumnDefinition(dialect, "flag", BooleanType(dialect), @@ -51,7 +59,7 @@ class TestAutoIncrementDDL: def test_auto_increment_in_ddl(self, dialect): sql, _ = dialect.format_create_table_statement(_build_table(dialect)) - assert "IDENTITY(1,1)" in sql.upper(), f"auto-increment missing: {sql}" + assert "IDENTITY(1, 1)" in sql.upper(), f"auto-increment missing: {sql}" def test_all_standard_types_compile(self, dialect): sql, params = dialect.format_create_table_statement(_build_table(dialect)) @@ -62,7 +70,7 @@ def test_boolean_default_true(self, dialect): expr = CreateTableStatement( dialect=dialect, table=Table(dialect, "bool_test"), columns=[ - ColumnDefinition(dialect, "id", IntegerType(dialect), constraints=_pk(dialect)), + _id_column(dialect, IntegerType(dialect)), ColumnDefinition(dialect, "flag", BooleanType(dialect), constraints=[ColumnConstraint(dialect, branch=ColumnNotNullConstraint(dialect)), ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, True))]), @@ -75,7 +83,7 @@ def test_timestamp_type(self, dialect): expr = CreateTableStatement( dialect=dialect, table=Table(dialect, "ts_test"), columns=[ - ColumnDefinition(dialect, "id", IntegerType(dialect), constraints=_pk(dialect)), + _id_column(dialect, IntegerType(dialect)), ColumnDefinition(dialect, "created_at", TimestampType(dialect)), ], ) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_column_definition.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_column_definition.py similarity index 94% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_column_definition.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_column_definition.py index bb93bde3..52c144a4 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_column_definition.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_column_definition.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_column_definition.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_column_definition.py """Tests for the SQL Server-specific column definition expressions.""" import pytest diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_constraint_capabilities.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_constraint_capabilities.py similarity index 97% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_constraint_capabilities.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_constraint_capabilities.py index 098afc3c..af1a2c10 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_constraint_capabilities.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_constraint_capabilities.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_constraint_capabilities.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_constraint_capabilities.py """SQL Server constraint capability switches, pinned to live measurements. Every value asserted here was measured against the instance @@ -29,16 +29,17 @@ ``format_column_definition`` spells itself. The trait walk is driven by the same pairs as -``test_clause_pair_guard_sqlserver.py`` but through the two public seams, so a +``test_clause_pair_guard.py`` but through the two public seams, so a seam that stopped consulting the shared helper fails here. The per-spelling walk there also asserts the two refusals stay distinguishable; this file asserts the seam, that one asserts the wording. Not covered here, on purpose: the SQL-standard clauses SQL Server cannot spell at all were already driven through the two-spelling pair walk in -``test_clause_pair_guard_sqlserver.py``; duplicating the assertions would +``test_clause_pair_guard.py``; duplicating the assertions would let the two files disagree. """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import pytest @@ -409,15 +410,15 @@ def test_primary_key_renders_when_no_trait_is_asked_for(self): column = ColumnDefinition( d, "id", - IntegerType(d), + auto_increment_parts(d, IntegerType(d))[0], constraints=[ ColumnConstraint( - d, branch=ColumnPrimaryKeyConstraint(d, is_auto_increment=True) + d, branch=ColumnPrimaryKeyConstraint(d) ) ], - ) + attributes=auto_increment_parts(d, IntegerType(d))[1]) sql, params = column.to_sql() - assert sql == "[id] INT PRIMARY KEY IDENTITY(1,1)" + assert sql == "[id] INT PRIMARY KEY IDENTITY(1, 1)" assert params == () diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_create_table_like.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_create_table_like.py similarity index 97% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_create_table_like.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_create_table_like.py index a466f65d..6c41c36f 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_create_table_like.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_create_table_like.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_create_table_like.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_create_table_like.py """ SQL Server CREATE TABLE behavior tests. @@ -22,7 +22,7 @@ from rhosocial.activerecord.backend.expression.objects import Table -class TestSQLServerCreateTableLike: +class TestCreateTableLike: """Tests for CREATE TABLE behavior on SQL Server.""" def test_like_not_supported_by_dialect(self): diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_database_ddl.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_database_ddl.py similarity index 90% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_database_ddl.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_database_ddl.py index 70971cec..a2d158f0 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_database_ddl.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_database_ddl.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_database_ddl.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_database_ddl.py """Explicit SQLServerDialect database DDL capability + rendering tests.""" from rhosocial.activerecord.backend.expression.objects import Database diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_ddl_improvements.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_ddl_improvements.py similarity index 95% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_ddl_improvements.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_ddl_improvements.py index aa0af20c..483b728e 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_ddl_improvements.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_ddl_improvements.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_ddl_improvements.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_ddl_improvements.py """Tests for SQL Server DDL improvements: capability gating, UnsupportedFeatureError.""" import pytest from unittest.mock import patch @@ -20,7 +20,7 @@ from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect -class TestSQLServerTableCapabilityGating: +class TestTableCapabilityGating: def test_table_declaration_defaults_are_absent(self): dialect = SQLServerDialect(version=(16, 0, 0)) expression = CreateTableStatement( @@ -62,7 +62,7 @@ def test_table_tablespace_declaration_is_propagated_and_fails_fast(self): expression.to_sql() -class TestSQLServerViewCapabilityGating: +class TestViewCapabilityGating: """Tests for SQL Server VIEW DDL capability gating.""" def test_create_view_check_option_gated(self): @@ -97,7 +97,7 @@ def test_materialized_view_not_supported(self): assert dialect.supports_materialized_view() is False -class TestSQLServerSchemaCapabilityGating: +class TestSchemaCapabilityGating: """Tests for SQL Server SCHEMA DDL capability gating.""" def test_create_schema_supported(self): diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_ddl_source_mixin.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_ddl_source_mixin.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_ddl_source_mixin.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_ddl_source_mixin.py index aaf4c303..2fd3e4a1 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_ddl_source_mixin.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_ddl_source_mixin.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_ddl_source_mixin.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_ddl_source_mixin.py try: from typing import Annotated, ClassVar, Optional @@ -276,6 +276,8 @@ class PlainModel(ActiveRecord): def table_name(cls): return "ddl_source_plain" + __primary_key__ = "id" + id: int optional: Optional[str] = None @@ -285,6 +287,8 @@ class AsyncPlainModel(AsyncActiveRecord): def table_name(cls): return "ddl_source_async_plain" + __primary_key__ = "id" + id: int optional: Optional[str] = None @@ -416,7 +420,6 @@ def test_table_declarations_are_returned_unchanged(model): assert model.table_inherits() is INHERITED_TABLES assert model.table_inherits() == ["parent_a", "parent_b"] assert model.table_tablespace() == TABLE_SPACE - assert model.create_table_statement_classes() is None @pytest.mark.parametrize("model", [SyncModel, AsyncModel], ids=("sync", "async")) @@ -485,7 +488,6 @@ def test_default_declarations_and_batch_interfaces(model): assert model.table_tablespace() is None assert model.table_indexes() == [] assert model.table_constraints() == [] - assert model.create_table_statement_classes() is None @pytest.mark.parametrize("model", [SyncModel, AsyncModel], ids=("sync", "async")) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_ddl_type_offline.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_ddl_type_offline.py new file mode 100644 index 00000000..8f0002a9 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_ddl_type_offline.py @@ -0,0 +1,825 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_ddl_type_offline.py +"""Connectionless unit tests for the SQL Server user-defined TYPE DDL renderer. + +Every test drives a real :class:`SQLServerDialect` (which mixes in +``SQLServerTypeDDLMixin``) with no connection and no network. Expression nodes +are real objects from the framework; only the few seams that cannot be reached +with a valid node (a definition that renders bind parameters, a constraint that +renders no SQL) are replaced with ``monkeypatch``/``MagicMock`` stand-ins. +""" + +from unittest.mock import MagicMock + +import pytest + +from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError +from rhosocial.activerecord.backend.expression import RawSQLPredicate +from rhosocial.activerecord.backend.expression.objects import Table, Type +from rhosocial.activerecord.backend.expression.statements.ddl_table import ( + ColumnCheckConstraint, + ColumnConstraint, + ColumnDefaultConstraint, + ColumnDefinition, + ColumnForeignKeyConstraint, + ColumnNotNullConstraint, + ColumnPrimaryKeyConstraint, + TableCheckConstraint, + TableConstraint, + TableForeignKeyConstraint, + TablePrimaryKeyConstraint, +) +from rhosocial.activerecord.backend.expression.statements.ddl_type import ( + AlterTypeStatement, + CreateTypeStatement, + DropTypeStatement, + TypeAlterAction, +) +from rhosocial.activerecord.backend.impl.dummy.expression import _DummyTypeAlterAction +from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect +from rhosocial.activerecord.backend.impl.sqlserver.expression.ddl.type import ( + SQLServerAliasTypeDefinition, + SQLServerClrTypeDefinition, + SQLServerDropTypeExpression, + SQLServerRenameTypeStatement, + SQLServerTableTypeDefinition, +) +from rhosocial.activerecord.backend.impl.sqlserver.expression.index import ( + SQLServerIndexDefinition, +) +import rhosocial.activerecord.backend.expression.types as core_types +import rhosocial.activerecord.backend.impl.sqlserver.expression.types as ss_types + + +V2005 = (9, 0, 0) +V2008 = (10, 0, 0) +V2012 = (11, 0, 0) +V2014 = (12, 0, 0) +V2016 = (13, 0, 0) +V2017 = (14, 0, 0) +V2019 = (15, 0, 0) +V2022 = (16, 0, 0) + + +def dialect(version=V2022, **kwargs): + """Build a connectionless dialect (optionally with a deployment target).""" + return SQLServerDialect(version, **kwargs) + + +def alias(base_type_cls, version=V2022, nullability=None, **type_kwargs): + d = dialect(version) + base = base_type_cls(d, **type_kwargs) + return d, SQLServerAliasTypeDefinition(d, base, nullability=nullability) + + +class TestCapabilityBooleans: + """The supports_* surface is a pure function of version and target.""" + + @pytest.mark.parametrize("version", [V2005, V2008, V2016, V2022]) + def test_type_object_capabilities_at_2005_and_later(self, version): + d = dialect(version) + assert d.supports_type_objects() is True + assert d.supports_create_type() is True + assert d.supports_drop_type() is True + assert d.supports_rename_type() is True + assert d.supports_alter_type() is False + assert d.supports_type_alter_action(_DummyTypeAlterAction) is False + assert d.supports_create_type_if_not_exists() is False + assert d.supports_create_type_or_replace() is False + assert d.supports_alter_type_if_exists() is False + assert d.supports_multiple_type_alter_actions() is False + assert d.supports_drop_type_cascade() is False + assert d.supports_drop_type_restrict() is False + + def test_unadapted_dialect_has_no_version_gated_capabilities(self): + d = SQLServerDialect(version=None) + assert d.supports_type_objects() is False + assert d.supports_create_type() is False + assert d.supports_drop_type() is False + assert d.supports_rename_type() is False + assert d.supports_drop_type_if_exists() is False + + @pytest.mark.parametrize( + ("version", "expected"), + [(V2005, False), (V2012, False), (V2016, True), (V2022, True)], + ) + def test_drop_type_if_exists_is_2016_gate(self, version, expected): + assert dialect(version).supports_drop_type_if_exists() is expected + + @pytest.mark.parametrize( + ("version", "expected"), [(V2012, False), (V2014, True), (V2022, True)] + ) + def test_memory_optimized_table_types_delegate(self, version, expected): + d = dialect(version) + assert d.supports_memory_optimized_table_types() is expected + assert d.supports_memory_optimized_table_types() == bool( + d.supports_memory_optimized_tables() + ) + + +class TestDeploymentTargetNormalization: + def test_none_target_disables_clr(self): + d = SQLServerDialect(V2022, deployment_target=None) + assert d._is_sqlserver_deployment_target() is False + assert d.supports_clr_type_definition() is False + assert d.supports_clr_user_defined_type() is False + + @pytest.mark.parametrize( + "target", + [ + "sqlserver", + "SQL Server", + "sql_server_linux", + "Microsoft SQL Server", + "azure_sql_managed_instance", + "on-premises", + ], + ) + def test_recognized_targets_enable_clr(self, target): + d = SQLServerDialect(V2022, deployment_target=target) + assert d._is_sqlserver_deployment_target() is True + assert d.supports_clr_type_definition() is True + assert d.supports_clr_user_defined_type() is True + + @pytest.mark.parametrize("target", ["azure_sql_database", "fabric", "postgresql", ""]) + def test_unrecognized_targets_disable_clr(self, target): + d = SQLServerDialect(V2022, deployment_target=target) + assert d._is_sqlserver_deployment_target() is False + assert d.supports_clr_type_definition() is False + + def test_enum_like_target_value_is_unwrapped(self): + class Target: + value = "SQL Server Linux" + + d = SQLServerDialect(V2022) + d.deployment_target = Target() + assert d._is_sqlserver_deployment_target() is True + + +class TestSupportedTypeDefinitions: + @pytest.mark.parametrize( + ("version", "target", "definition", "expected"), + [ + (V2005, "sqlserver", SQLServerAliasTypeDefinition, True), + (V2005, "sqlserver", SQLServerTableTypeDefinition, False), + (V2008, "sqlserver", SQLServerTableTypeDefinition, True), + (V2022, "sqlserver", SQLServerClrTypeDefinition, True), + (V2022, "azure_sql_database", SQLServerClrTypeDefinition, False), + ], + ) + def test_definition_support_matrix(self, version, target, definition, expected): + d = dialect(version, deployment_target=target) + assert d.supports_type_definition(definition) is expected + assert (definition in d.supported_type_definitions()) is expected + + def test_non_class_definition_is_not_supported(self): + d = dialect() + assert d._definition_is_supported("not-a-class") is False + assert d.supports_type_definition("not-a-class") is False + assert d.supports_type_definition(object()) is False + + +class TestNameAndStringHelpers: + def test_type_object_name_with_and_without_schema(self): + d = dialect() + assert d._type_object_name("my_type") == "[my_type]" + assert d._type_object_name("my_type", "app") == "[app].[my_type]" + assert d._type_object_name("type.with.dot", "app") == "[app].[type.with.dot]" + + def test_type_object_name_rejects_empty_type_name(self): + d = dialect() + for bad in ("", " ", None, 42): + with pytest.raises(ValueError): + d._type_object_name(bad) + + def test_type_object_name_rejects_bad_schema(self): + d = dialect() + with pytest.raises(TypeError): + d._type_object_name("t", 42) + with pytest.raises(ValueError): + d._type_object_name("t", " ") + + def test_nstring_literal_escapes_quotes(self): + d = dialect() + assert d._format_nstring("plain") == "N'plain'" + assert d._format_nstring("it's") == "N'it''s'" + + def test_nstring_rejects_non_string(self): + with pytest.raises(TypeError): + dialect()._format_nstring(42) + + +class TestTableTypeColumnValidation: + def test_non_column_definition_is_rejected(self): + with pytest.raises(TypeError, match="ColumnDefinition"): + dialect()._format_table_type_column(object(), memory_optimized=False) + + def test_comment_is_rejected(self): + d = dialect() + column = ColumnDefinition(d, "id", core_types.IntegerType(d)) + column.comment = MagicMock() + with pytest.raises(UnsupportedFeatureError, match="comment"): + d._format_table_type_column(column, memory_optimized=False) + + def test_generated_column_is_rejected(self): + d = dialect() + column = ColumnDefinition(d, "id", core_types.IntegerType(d)) + column.generated_expression = MagicMock() + with pytest.raises(UnsupportedFeatureError, match="computed"): + d._format_table_type_column(column, memory_optimized=False) + + @pytest.mark.parametrize("attribute", ["sparse", "rowguidcol"]) + def test_storage_attributes_are_rejected(self, attribute): + d = dialect() + column = ColumnDefinition(d, "id", core_types.IntegerType(d)) + setattr(column, attribute, True) + with pytest.raises(UnsupportedFeatureError, match="storage attribute"): + d._format_table_type_column(column, memory_optimized=False) + + def test_unsupported_column_constraint_is_rejected(self): + d = dialect() + fk = ColumnForeignKeyConstraint(d, (Table(d, "other"), ["id"])) + column = ColumnDefinition( + d, + "id", + core_types.IntegerType(d), + constraints=[ColumnConstraint(d, branch=fk)], + ) + with pytest.raises(UnsupportedFeatureError, match="TYPE table column constraint"): + d._format_table_type_column(column, memory_optimized=False) + + def test_memory_optimized_disallowed_constraint_is_rejected(self): + d = dialect(V2014) + column = ColumnDefinition( + d, + "id", + core_types.IntegerType(d), + constraints=[ + ColumnConstraint( + d, + branch=ColumnCheckConstraint(d, RawSQLPredicate(d, "1 = 1")), + ) + ], + ) + with pytest.raises(UnsupportedFeatureError, match="memory-optimized"): + d._format_table_type_column(column, memory_optimized=True) + + +class TestTableTypeConstraintValidation: + def test_non_constraint_is_rejected(self): + with pytest.raises(TypeError, match="TableConstraint"): + dialect()._format_table_type_constraint(object(), memory_optimized=False) + + def test_empty_key_columns_are_rejected(self): + d = dialect() + constraint = TableConstraint(d, branch=TablePrimaryKeyConstraint(d, [])) + with pytest.raises(ValueError, match="requires columns"): + d._format_table_type_constraint(constraint, memory_optimized=False) + + @pytest.mark.parametrize( + ("kwargs", "spelling"), + [ + ({"deferrable": True}, "DEFERRABLE"), + ({"not_deferrable": True}, "NOT DEFERRABLE"), + ({"initially_deferred": True}, "INITIALLY DEFERRED"), + ({"initially_immediate": True}, "INITIALLY IMMEDIATE"), + ({"enforced": True}, "ENFORCED"), + ({"not_enforced": True}, "NOT ENFORCED"), + ], + ) + def test_constraint_options_are_rejected(self, kwargs, spelling): + d = dialect() + constraint = TableConstraint(d, branch=TablePrimaryKeyConstraint(d, ["id"]), **kwargs) + with pytest.raises(UnsupportedFeatureError, match=spelling.replace(" ", ".")): + d._format_table_type_constraint(constraint, memory_optimized=False) + + def test_validation_option_is_rejected(self): + d = dialect() + branch = TableCheckConstraint(d, RawSQLPredicate(d, "1 = 1")) + constraint = TableConstraint(d, branch=branch, validation=MagicMock()) + with pytest.raises(UnsupportedFeatureError, match="validation"): + d._format_table_type_constraint(constraint, memory_optimized=False) + + def test_empty_rendered_sql_is_rejected(self, monkeypatch): + d = dialect() + constraint = TableConstraint(d, branch=TablePrimaryKeyConstraint(d, ["id"])) + monkeypatch.setattr(d, "format_table_constraint", lambda *a, **k: ("", ())) + with pytest.raises(ValueError, match="did not render SQL"): + d._format_table_type_constraint(constraint, memory_optimized=False) + + def test_memory_optimized_check_requires_2016(self): + d = dialect(V2014) + constraint = TableConstraint( + d, branch=TableCheckConstraint(d, RawSQLPredicate(d, "1 = 1")) + ) + with pytest.raises(UnsupportedFeatureError, match="2016"): + d._format_table_type_constraint(constraint, memory_optimized=True) + + def test_memory_optimized_foreign_key_is_rejected(self): + d = dialect() + constraint = TableConstraint( + d, + branch=TableForeignKeyConstraint( + d, ["id"], (Type(d, "other"), ["id"]) + ), + ) + with pytest.raises(UnsupportedFeatureError, match="memory-optimized"): + d._format_table_type_constraint(constraint, memory_optimized=True) + + +class TestTableTypeIndexValidation: + def make_index(self, **kwargs): + d = dialect() + return d, SQLServerIndexDefinition(d, "ix", ["id"], **kwargs) + + @pytest.mark.parametrize("index", [object(), "index", None]) + def test_non_index_definition_is_rejected(self, index): + with pytest.raises(TypeError, match="IndexDefinition"): + dialect()._format_table_type_index(index, memory_optimized=False) + + @pytest.mark.parametrize("name", ["", " ", None]) + def test_empty_index_name_is_rejected(self, name): + d = dialect() + index = SQLServerIndexDefinition(d, name, ["id"]) + with pytest.raises(ValueError, match="non-empty string"): + d._format_table_type_index(index, memory_optimized=False) + + def test_no_columns_is_rejected(self): + d = dialect() + index = SQLServerIndexDefinition(d, "ix", []) + with pytest.raises(ValueError, match="at least one column"): + d._format_table_type_index(index, memory_optimized=False) + + @pytest.mark.parametrize( + "kwargs", + [ + {"partial_condition": MagicMock()}, + {"if_not_exists": True}, + {"if_exists": True}, + {"tablespace": "ts"}, + ], + ) + def test_unsupported_index_options_are_rejected(self, kwargs): + d = dialect() + index = SQLServerIndexDefinition(d, "ix", ["id"]) + for key, value in kwargs.items(): + setattr(index, key, value) + with pytest.raises(UnsupportedFeatureError, match="TYPE table index option"): + d._format_table_type_index(index, memory_optimized=False) + + @pytest.mark.parametrize("bad", [True, "1024", 1.5]) + def test_bucket_count_must_be_an_integer(self, bad): + d, index = self.make_index(hash_index=True, bucket_count=1024) + index.bucket_count = bad + with pytest.raises(TypeError, match="bucket_count must be an integer"): + d._format_table_type_index(index, memory_optimized=True) + + @pytest.mark.parametrize("bad", [0, -1, 1_073_741_825]) + def test_bucket_count_range_is_enforced(self, bad): + d = dialect(V2014) + index = SQLServerIndexDefinition( + d, "ix", ["id"], hash_index=True, bucket_count=bad + ) + with pytest.raises(ValueError, match="bucket_count must be between"): + d._format_table_type_index(index, memory_optimized=True) + + def test_bucket_count_requires_hash_index(self): + d = dialect() + index = SQLServerIndexDefinition(d, "ix", ["id"], bucket_count=1024) + with pytest.raises(UnsupportedFeatureError, match="bucket_count is valid only"): + d._format_table_type_index(index, memory_optimized=False) + + def test_hash_index_requires_memory_optimized(self): + d = dialect() + index = SQLServerIndexDefinition( + d, "ix", ["id"], hash_index=True, bucket_count=1024 + ) + with pytest.raises(UnsupportedFeatureError, match="memory-optimized"): + d._format_table_type_index(index, memory_optimized=False) + + def test_hash_index_requires_bucket_count(self): + d = dialect(V2014) + index = SQLServerIndexDefinition(d, "ix", ["id"], hash_index=True) + with pytest.raises(ValueError, match="bucket_count is required"): + d._format_table_type_index(index, memory_optimized=True) + + def test_bad_index_type_is_rejected(self): + d, index = self.make_index(type="heap") + with pytest.raises(UnsupportedFeatureError, match="index type HEAP"): + d._format_table_type_index(index, memory_optimized=False) + + def test_non_string_index_type_is_rejected(self): + d, index = self.make_index(type=123) + with pytest.raises(TypeError, match="index type must be a string"): + d._format_table_type_index(index, memory_optimized=False) + + def test_clustered_index_rejected_on_memory_optimized(self): + d, index = self.make_index(type="clustered") + with pytest.raises(UnsupportedFeatureError, match="cannot be clustered"): + d._format_table_type_index(index, memory_optimized=True) + + def test_expression_index_column_is_rendered(self): + d = dialect() + index = SQLServerIndexDefinition(d, "ix", [Type(d, "col")]) + sql, params = d._format_table_type_index(index, memory_optimized=False) + assert "INDEX [ix] ([col])" in sql + assert params == () + + def test_bad_index_column_type_is_rejected(self): + d = dialect() + index = SQLServerIndexDefinition(d, "ix", [42]) + with pytest.raises(TypeError, match="strings or expressions"): + d._format_table_type_index(index, memory_optimized=False) + + def test_unique_index_and_include_columns_render(self): + d = dialect(V2019) + index = SQLServerIndexDefinition( + d, "ix", ["id"], unique=True, include_columns=["payload"] + ) + sql, _ = d._format_table_type_index(index, memory_optimized=True) + assert sql.startswith("UNIQUE INDEX [ix] NONCLUSTERED") + assert "INCLUDE ([payload])" in sql + + def test_non_string_include_column_is_rejected(self): + d = dialect(V2019) + index = SQLServerIndexDefinition(d, "ix", ["id"], include_columns=["ok"]) + index.include_columns = ["ok", 42] + with pytest.raises(TypeError, match="INCLUDE columns must be strings"): + d._format_table_type_index(index, memory_optimized=True) + + def test_hack_index_include_is_rejected(self): + d = dialect(V2019) + index = SQLServerIndexDefinition( + d, + "ix", + ["id"], + hash_index=True, + bucket_count=1024, + include_columns=["payload"], + ) + with pytest.raises(UnsupportedFeatureError, match="HASH indexes cannot use INCLUDE"): + d._format_table_type_index(index, memory_optimized=True) + + def test_hash_index_emits_bucket_count(self): + d = dialect(V2014) + index = SQLServerIndexDefinition( + d, "ix", ["id"], hash_index=True, bucket_count=2048 + ) + sql, _ = d._format_table_type_index(index, memory_optimized=True) + assert "NONCLUSTERED HASH ([id]) WITH (BUCKET_COUNT = 2048)" in sql + + def test_include_requires_2019(self): + d = dialect(V2017) + index = SQLServerIndexDefinition(d, "ix", ["id"], include_columns=["payload"]) + with pytest.raises(UnsupportedFeatureError, match="2019"): + d._format_table_type_index(index, memory_optimized=True) + + +class TestFormatCreateType: + def test_create_alias_type_renders_all_representative_sql_server_types(self): + cases = [ + (core_types.IntegerType, {}, "INT"), + (core_types.BigIntType, {}, "BIGINT"), + (core_types.DecimalType, {"precision": 10, "scale": 2}, "DECIMAL(10, 2)"), + (ss_types.SQLServerNVarCharType, {"length": 64}, "NVARCHAR(64)"), + (core_types.VarCharType, {"length": 32}, "VARCHAR(32)"), + (ss_types.SQLServerUniqueIdentifierType, {}, "UNIQUEIDENTIFIER"), + (core_types.TimestampType, {}, "DATETIME2"), + (core_types.TimestampTzType, {}, "DATETIMEOFFSET"), + (ss_types.SQLServerVarBinaryType, {"length": 100}, "VARBINARY(100)"), + (ss_types.SQLServerXmlType, {}, "XML"), + ] + for type_cls, kwargs, fragment in cases: + d = dialect() + base = type_cls(d, **kwargs) + definition = SQLServerAliasTypeDefinition(d, base) + stmt = CreateTypeStatement(d, Type(d, "t"), definition) + sql, params = d.format_create_type_statement(stmt) + assert sql == f"CREATE TYPE [t] FROM {fragment}" + assert params == () + + def test_create_type_rejects_wrong_statement_type(self): + with pytest.raises(TypeError, match="CreateTypeStatement"): + dialect().format_create_type_statement(object()) + + def test_create_type_rejects_mutually_exclusive_options(self): + d, definition = alias(core_types.IntegerType) + stmt = CreateTypeStatement(d, Type(d, "t"), definition) + stmt.if_not_exists = True + stmt.or_replace = True + with pytest.raises(ValueError, match="mutually exclusive"): + d.format_create_type_statement(stmt) + + def test_create_type_rejects_old_version_and_unsupported_options(self): + d = SQLServerDialect(version=None) + definition = SQLServerAliasTypeDefinition(d, core_types.IntegerType(d)) + stmt = CreateTypeStatement(d, Type(d, "t"), definition) + with pytest.raises(UnsupportedFeatureError): + d.format_create_type_statement(stmt) + + modern = dialect() + definition = SQLServerAliasTypeDefinition(modern, core_types.IntegerType(modern)) + with pytest.raises(UnsupportedFeatureError, match="IF NOT EXISTS"): + modern.format_create_type_statement( + CreateTypeStatement(modern, Type(modern, "t"), definition, if_not_exists=True) + ) + with pytest.raises(UnsupportedFeatureError, match="OR REPLACE"): + modern.format_create_type_statement( + CreateTypeStatement(modern, Type(modern, "t"), definition, or_replace=True) + ) + + def test_create_type_rejects_wrong_type_object(self): + d, definition = alias(core_types.IntegerType) + stmt = CreateTypeStatement(d, MagicMock(), definition) + with pytest.raises(TypeError, match="must be a Type"): + d.format_create_type_statement(stmt) + + def test_create_type_rejects_wrong_definition(self): + d = dialect() + stmt = CreateTypeStatement(d, Type(d, "t"), MagicMock()) + with pytest.raises(TypeError, match="TypeDefinition"): + d.format_create_type_statement(stmt) + + def test_create_type_rejects_definition_with_bind_params(self, monkeypatch): + d, definition = alias(core_types.IntegerType) + monkeypatch.setattr(definition, "to_sql", lambda: ("FROM INT", (1,))) + stmt = CreateTypeStatement(d, Type(d, "t"), definition) + with pytest.raises(ValueError, match="without bind parameters"): + d.format_create_type_statement(stmt) + + +class TestFormatAlterAndDropType: + def test_alter_type_statement_is_always_unsupported(self): + d = dialect() + action = _DummyTypeAlterAction(d, "renamed") + with pytest.raises(TypeError, match="AlterTypeStatement"): + d.format_alter_type_statement(object()) + with pytest.raises(UnsupportedFeatureError, match="ALTER TYPE"): + d.format_alter_type_statement( + AlterTypeStatement(d, Type(d, "t"), [action]) + ) + + def test_format_type_alter_action(self): + d = dialect() + action = _DummyTypeAlterAction(d, "renamed") + assert isinstance(action, TypeAlterAction) + with pytest.raises(TypeError, match="TypeAlterAction"): + d.format_type_alter_action(object()) + with pytest.raises(UnsupportedFeatureError, match="ALTER TYPE action"): + d.format_type_alter_action(action) + + def test_drop_type_renders_if_exists_on_modern_versions(self): + d = dialect(V2016) + sql, params = d.format_drop_type_statement( + DropTypeStatement(d, Type(d, "status", schema_name="app"), if_exists=True) + ) + assert sql == "DROP TYPE IF EXISTS [app].[status]" + assert params == () + + def test_drop_type_rejects_wrong_statement_and_type(self): + d = dialect() + with pytest.raises(TypeError, match="DropTypeStatement"): + d.format_drop_type_statement(object()) + stmt = DropTypeStatement(d, MagicMock()) + with pytest.raises(TypeError, match="must be a Type"): + d.format_drop_type_statement(stmt) + + def test_drop_type_if_exists_requires_2016(self): + d = dialect(V2012) + stmt = DropTypeStatement(d, Type(d, "status"), if_exists=True) + with pytest.raises(UnsupportedFeatureError, match="2016"): + d.format_drop_type_statement(stmt) + + def test_drop_type_cascade_and_restrict_are_rejected(self): + d = dialect() + target = Type(d, "status") + with pytest.raises(ValueError, match="mutually exclusive"): + SQLServerDropTypeExpression(d, target, cascade=True, restrict=True) + with pytest.raises(UnsupportedFeatureError, match="CASCADE"): + d.format_drop_type_statement( + SQLServerDropTypeExpression(d, target, cascade=True) + ) + with pytest.raises(UnsupportedFeatureError, match="RESTRICT"): + d.format_drop_type_statement( + SQLServerDropTypeExpression(d, target, restrict=True) + ) + + +class TestFormatTypeDefinition: + def test_alias_nullability_spellings(self): + d = dialect() + base = core_types.IntegerType(d) + assert d.format_type_definition(SQLServerAliasTypeDefinition(d, base)) == ( + "FROM INT", + (), + ) + assert d.format_type_definition( + SQLServerAliasTypeDefinition(d, base, nullability=True) + ) == ("FROM INT NOT NULL", ()) + assert d.format_type_definition( + SQLServerAliasTypeDefinition(d, base, nullability=False) + ) == ("FROM INT NULL", ()) + + def test_alias_with_bind_params_is_rejected(self, monkeypatch): + d = dialect() + definition = SQLServerAliasTypeDefinition(d, core_types.IntegerType(d)) + monkeypatch.setattr(definition.base_type, "to_sql", lambda: ("INT", (5,))) + with pytest.raises(ValueError, match="without bind parameters"): + d.format_type_definition(definition) + + def test_clr_definition_with_and_without_class(self): + d = dialect() + without_class = SQLServerClrTypeDefinition(d, "My.Assembly") + with_class = SQLServerClrTypeDefinition(d, "My.Assembly", "My.Class") + assert d.format_type_definition(without_class) == ("EXTERNAL NAME [My.Assembly]", ()) + assert d.format_type_definition(with_class) == ( + "EXTERNAL NAME [My.Assembly].[My.Class]", + (), + ) + + def test_table_definition_delegates_to_table_renderer(self): + d = dialect() + definition = SQLServerTableTypeDefinition( + d, columns=[ColumnDefinition(d, "id", core_types.IntegerType(d))] + ) + sql, params = d.format_type_definition(definition) + assert sql == "AS TABLE ([id] INT)" + assert params == () + + def test_wrong_definition_type_is_rejected(self): + with pytest.raises(TypeError, match="TypeDefinition"): + dialect().format_type_definition(object()) + + def test_unsupported_definition_is_rejected(self): + d = dialect() + unsupported = SQLServerClrTypeDefinition(d, "assembly", "Class") + azure = dialect(deployment_target="azure_sql_database") + with pytest.raises(UnsupportedFeatureError, match="TYPE definition"): + azure.format_type_definition(unsupported) + + +class TestFormatRenameType: + def test_rename_uses_sp_rename(self): + d = dialect() + stmt = SQLServerRenameTypeStatement(d, "old", "new", schema_name="app") + sql, params = d.format_rename_type_statement(stmt) + assert sql == "EXECUTE sp_rename N'[app].[old]', N'new', N'USERDATATYPE'" + assert params == () + + def test_rename_rejects_wrong_statement(self): + with pytest.raises(TypeError, match="SQLServerRenameTypeStatement"): + dialect().format_rename_type_statement(object()) + + def test_rename_requires_2005(self): + d = SQLServerDialect(version=None) + stmt = SQLServerRenameTypeStatement(d, "old", "new") + with pytest.raises(UnsupportedFeatureError, match="2005"): + d.format_rename_type_statement(stmt) + + +class TestTableTypeDefinitionGuards: + def test_memory_optimized_requires_2014(self): + d = dialect(V2012) + definition = SQLServerTableTypeDefinition( + d, + columns=[ColumnDefinition(d, "id", core_types.IntegerType(d))], + indexes=[SQLServerIndexDefinition(d, "ix", ["id"])], + memory_optimized=True, + ) + with pytest.raises(UnsupportedFeatureError, match="2014"): + d.format_type_definition(definition) + + def test_memory_optimized_without_key_or_index_is_rejected(self): + d = dialect(V2014) + definition = SQLServerTableTypeDefinition( + d, + columns=[ColumnDefinition(d, "id", core_types.IntegerType(d))], + memory_optimized=True, + ) + with pytest.raises(ValueError, match="at least one index"): + d.format_type_definition(definition) + + def test_too_many_indexes_before_2017(self): + d = dialect(V2016) + columns = [ + ColumnDefinition(d, f"c{i}", core_types.IntegerType(d)) for i in range(9) + ] + indexes = [SQLServerIndexDefinition(d, f"ix{i}", [f"c{i}"]) for i in range(9)] + definition = SQLServerTableTypeDefinition( + d, columns=columns, indexes=indexes, memory_optimized=True + ) + with pytest.raises(UnsupportedFeatureError, match="8 indexes"): + d.format_type_definition(definition) + + @pytest.mark.parametrize( + ("branch_cls", "args"), + [ + (ColumnNotNullConstraint, ()), + (ColumnPrimaryKeyConstraint, ()), + (ColumnDefaultConstraint, (0,)), + ], + ) + def test_supported_column_constraints_render(self, branch_cls, args): + d = dialect() + branch = branch_cls(d, *args) + column = ColumnDefinition( + d, "id", core_types.IntegerType(d), constraints=[ColumnConstraint(d, branch=branch)] + ) + sql, _ = d._format_table_type_column(column, memory_optimized=False) + assert sql.startswith("[id] INT") + + +class TestRemainingBranches: + """Small targeted checks for the last reachable renderer branches.""" + + def test_unmatched_definition_class_is_not_supported(self): + assert dialect()._definition_is_supported(object) is False + + def test_memory_optimized_column_foreign_key_is_rejected(self): + d = dialect() + column = ColumnDefinition( + d, + "id", + core_types.IntegerType(d), + constraints=[ + ColumnConstraint( + d, branch=ColumnForeignKeyConstraint(d, (Table(d, "other"), ["id"])) + ) + ], + ) + with pytest.raises(UnsupportedFeatureError, match="memory-optimized"): + d._format_table_type_column(column, memory_optimized=True) + + def test_table_foreign_key_constraint_is_rejected(self): + d = dialect() + constraint = TableConstraint( + d, + branch=TableForeignKeyConstraint(d, ["id"], (Table(d, "other"), ["id"])), + ) + with pytest.raises(UnsupportedFeatureError, match="TYPE table constraint"): + d._format_table_type_constraint(constraint, memory_optimized=False) + + def test_successful_table_constraint_render(self): + d = dialect() + constraint = TableConstraint(d, branch=TablePrimaryKeyConstraint(d, ["id"])) + sql, params = d._format_table_type_constraint(constraint, memory_optimized=False) + assert "PRIMARY KEY ([id])" in sql + assert params == () + + def test_hash_index_requires_2014(self): + d = dialect(V2012) + index = SQLServerIndexDefinition(d, "ix", ["id"], hash_index=True, bucket_count=1024) + with pytest.raises(UnsupportedFeatureError, match="2014"): + d._format_table_type_index(index, memory_optimized=True) + + def test_explicit_index_type_spelling(self): + d = dialect() + index = SQLServerIndexDefinition(d, "ix", ["id"], type="nonclustered") + sql, _ = d._format_table_type_index(index, memory_optimized=False) + assert sql == "INDEX [ix] NONCLUSTERED ([id])" + + def test_table_definition_renders_constraints_and_indexes(self): + d = dialect() + definition = SQLServerTableTypeDefinition( + d, + columns=[ColumnDefinition(d, "id", core_types.IntegerType(d))], + constraints=[TableConstraint(d, branch=TablePrimaryKeyConstraint(d, ["id"]))], + indexes=[SQLServerIndexDefinition(d, "ix", ["id"])], + ) + sql, params = d.format_type_definition(definition) + assert "PRIMARY KEY ([id])" in sql + assert "INDEX [ix] ([id])" in sql + assert params == () + + def test_memory_optimized_definition_appends_option(self): + d = dialect(V2014) + definition = SQLServerTableTypeDefinition( + d, + columns=[ColumnDefinition(d, "id", core_types.IntegerType(d))], + indexes=[SQLServerIndexDefinition(d, "ix", ["id"])], + memory_optimized=True, + ) + sql, params = d.format_type_definition(definition) + assert sql.endswith("WITH (MEMORY_OPTIMIZED = ON)") + assert params == () + + def test_create_type_rejects_unsupported_definition(self): + d = dialect() + clr = SQLServerClrTypeDefinition(d, "assembly", "Class") + azure = dialect(deployment_target="azure_sql_database") + stmt = CreateTypeStatement(azure, Type(azure, "t"), clr) + with pytest.raises(UnsupportedFeatureError, match="TYPE definition"): + azure.format_create_type_statement(stmt) + + def test_drop_type_rejects_unadapted_dialect(self): + d = SQLServerDialect(version=None) + stmt = DropTypeStatement(d, Type(d, "status")) + with pytest.raises(UnsupportedFeatureError, match="DROP TYPE"): + d.format_drop_type_statement(stmt) + + def test_manually_flagged_cascade_and_restrict_are_rejected(self): + d = dialect() + expr = SQLServerDropTypeExpression(d, Type(d, "status")) + expr.cascade = True + expr.restrict = True + with pytest.raises(ValueError, match="mutually exclusive"): + d.format_drop_type_statement(expr) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_identity_clause_sqlserver.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_identity_clause.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_identity_clause_sqlserver.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_identity_clause.py index dfccd0de..b6bdcb99 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_identity_clause_sqlserver.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_identity_clause.py @@ -1,8 +1,8 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_identity_clause_sqlserver.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_identity_clause.py """SQL Server's identity column: ``IDENTITY(seed, increment)`` and its gate. Measured on live SQL Server 2019 / 2022 / 2025 (the execution confirmation -lives in ``test_identity_execution_confirmation.py``): +lives in ``execute/sequence_identity/test_identity_capability_conformance.py``): * ``IDENTITY(seed, increment)`` executes at every version. It is this dialect's identity expression, so ``supports_identity_column()`` is diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_partition.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_expressions.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_partition.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_expressions.py index 0871bdd9..58299bec 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_partition.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_expressions.py @@ -42,7 +42,7 @@ SQL_SERVER_2005 = (9, 0, 0) -class TestSQLServerPartitionProtocolConformance: +class TestPartitionProtocolConformance: """Tests SQLServerPartitionMixin satisfies PartitionSupport and SQLServerPartitionSupport.""" def test_partition_mixin_satisfies_partition_support_protocol(self): @@ -59,7 +59,7 @@ def test_sqlserver_partition_protocol_methods_are_implemented(self): assert missing == set(), f"Missing methods: {missing}" -class TestSQLServerPartitionCapabilities: +class TestPartitionCapabilities: """Tests partition capability flags for various SQL Server versions.""" def test_partition_supported_on_modern_versions(self): @@ -96,7 +96,7 @@ def test_switch_split_merge_capabilities(self): assert d.supports_merge_partition() is True -class TestSQLServerPartitionClause: +class TestPartitionClause: """Tests format_partition_clause for core PartitionClause.""" def test_format_partition_clause_with_scheme(self): @@ -138,7 +138,7 @@ def test_format_partition_clause_on_old_version(self): d.format_partition_clause(partition) -class TestSQLServerPartitionFunction: +class TestPartitionFunction: """Tests CREATE PARTITION FUNCTION formatting.""" def test_basic_partition_function(self): @@ -185,7 +185,7 @@ def test_partition_function_schema_qualified(self): assert "[dbo].[pf_sales]" in sql -class TestSQLServerPartitionScheme: +class TestPartitionScheme: """Tests CREATE PARTITION SCHEME formatting.""" def test_basic_partition_scheme(self): @@ -219,7 +219,7 @@ def test_partition_scheme_all_to_filegroup(self): assert sql == expected -class TestSQLServerCreateTableWithPartition: +class TestCreateTableWithPartition: """Tests CREATE TABLE with partition clause.""" def test_create_table_with_partition(self): @@ -275,7 +275,7 @@ def test_create_table_with_partition_on_old_version(self): stmt.to_sql() -class TestSQLServerPartitionMaintenanceExpressions: +class TestPartitionMaintenanceExpressions: """SPLIT/MERGE/SWITCH/NEXT USED and the two drops.""" def test_split_range(self): @@ -377,7 +377,7 @@ def test_split_and_merge_are_refused_on_old_versions(self): ).to_sql() -class TestSQLServerPartitionCatalogueQuestions: +class TestPartitionCatalogueQuestions: """The questions maintenance asks of ``sys.partition_*``.""" def test_function_list_projects_boundaries_and_type(self): diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_partition_maintenance.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_maintenance.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_partition_maintenance.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_maintenance.py index 0911ed50..6c37b1e6 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_partition_maintenance.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_maintenance.py @@ -1,10 +1,10 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_partition_maintenance.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_maintenance.py """Unit tests for SQL Server partition planning and maintenance. These run without a server: a fake maintenance object answers the catalogue questions from canned rows and records the statements the real executor would run. The catalogue SQL itself is asserted in -``test_sqlserver_partition.py``; this file is about decisions -- which +``test_partition_expressions.py``; this file is about decisions -- which boundaries are missing, what a dry run would do, and why a drop is refused. """ @@ -179,7 +179,7 @@ def _function_info( ] -class TestSQLServerPartitionPlan: +class TestPartitionPlan: """Plan normalisation and explicit refusals.""" def test_boundaries_are_sorted_and_counted(self): @@ -236,7 +236,7 @@ def test_capability_gate_refuses_an_unsupported_version(self): maintenance.ensure(_plan()) -class TestSQLServerPartitionCatalogueParsing: +class TestPartitionCatalogueParsing: """Rows as the catalogue returns them become the report's value objects.""" def test_functions_are_grouped_by_boundary(self): @@ -322,7 +322,7 @@ def test_tables_and_ranges_are_parsed(self): assert ranges[0].low_boundary == "2026-01-01" -class TestSQLServerPartitionEnsure: +class TestPartitionEnsure: """``ensure`` creates, splits and reports without touching what exists.""" def test_missing_function_is_created_with_its_scheme(self): @@ -475,7 +475,7 @@ async def run(): assert async_report.operations == sync_report.operations -class TestSQLServerPartitionListAndValidate: +class TestPartitionListAndValidate: """``list`` reports, and ``validate`` never repairs.""" def test_list_reports_missing_boundaries_and_issues(self): @@ -541,7 +541,7 @@ def test_validate_flags_a_table_on_the_wrong_scheme_and_holes(self): assert report.operations == () -class TestSQLServerPartitionDropOrMerge: +class TestPartitionDropOrMerge: """SQL Server has no DROP PARTITION; the executor merges boundaries.""" def test_dry_run_is_the_default_and_executes_nothing(self): @@ -700,7 +700,7 @@ def test_one_unused_scheme_can_go_while_another_keeps_the_function(self): assert any("still mapped by scheme" in issue for issue in report.issues) -class TestSQLServerPartitionRetention: +class TestPartitionRetention: """Retention is derived from the catalogue, never guessed.""" @staticmethod @@ -821,7 +821,7 @@ async def run(): assert async_report.dry_run is True -class TestSQLServerPartitionErrors: +class TestPartitionErrors: """A non-transactional engine reports failures instead of pretending.""" def test_a_failed_statement_is_recorded_and_later_ones_stop(self): @@ -864,7 +864,7 @@ async def run(): assert report.operations == () -class TestSQLServerPartitionPostState: +class TestPartitionPostState: """A real run reports the catalogue it left behind, not the one it read.""" def test_ensure_reports_the_boundaries_it_created(self): @@ -911,7 +911,7 @@ def test_dry_run_keeps_the_pre_execution_snapshot(self): assert report.dry_run is True -class TestSQLServerPartitionCoreMapping: +class TestPartitionCoreMapping: """The engine rows are also exposed as core ``PartitionInfo`` rows.""" def test_ranges_become_core_partition_rows(self): diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_maintenance_offline.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_maintenance_offline.py new file mode 100644 index 00000000..b612210f --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_maintenance_offline.py @@ -0,0 +1,1244 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_maintenance_offline.py +"""Offline mock-driven coverage for the SQL Server partition maintenance module. + +The companion ``test_partition_maintenance.py`` drives the executors through +fake subclasses that override every I/O seam, so the module-level conversion +helpers and the real ``_fetch_rows`` / ``_read_*`` / ``_execute`` implementations +are never entered. This file closes that gap with pure mocks: a connectionless +real dialect renders the statements, a ``MagicMock``/``AsyncMock`` backend +answers ``execute``, and no driver, network or server is involved. + +Both the sync and the native-async executors are covered; the async cases are +plain ``async def`` tests under the repository's ``asyncio_mode = auto``. +""" + +from datetime import date, datetime, time, timezone +from decimal import Decimal +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest +from rhosocial.activerecord.backend.dialect.exceptions import UnsupportedFeatureError +from rhosocial.activerecord.backend.errors import DatabaseError + +from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect +from rhosocial.activerecord.backend.impl.sqlserver.partition.maintenance import ( + AsyncSQLServerPartitionMaintenance, + SQLServerPartitionMaintenance, + _as_int, + _boundary_family, + _boundary_parameter, + _coerce_cutoff, + _parse_catalogue_boundary, + _range_bound, + _SQLServerPartitionMaintenanceBase, + _trim_iso_fraction, +) +from rhosocial.activerecord.backend.impl.sqlserver.partition.plan import ( + SQLServerPartitionPlan, + _boundary_token, +) +from rhosocial.activerecord.backend.impl.sqlserver.partition.report import ( + PartitionFunctionInfo, + PartitionOperation, + PartitionRangeInfo, + PartitionSchemeInfo, + PartitionTableInfo, +) + +DIALECT = SQLServerDialect(version=(16, 0, 0)) + + +def _plan(boundaries=(date(2026, 1, 1), date(2026, 2, 1)), **kwargs): + return SQLServerPartitionPlan( + function=kwargs.pop("function", "pf_logs"), + data_type=kwargs.pop("data_type", "DATE"), + boundaries=boundaries, + **kwargs, + ) + + +def _function( + boundaries=("2026-01-01", "2026-02-01"), *, data_type="date", direction="RIGHT", count=None +): + return PartitionFunctionInfo( + name="pf_logs", + data_type=data_type, + range_direction=direction, + boundary_values=tuple(boundaries), + partition_count=len(boundaries) + 1 if count is None else count, + ) + + +def _scheme(name="ps_logs", *, function="pf_logs", filegroups=("PRIMARY",)): + return PartitionSchemeInfo(name, function, tuple(filegroups)) + + +def _table(name="logs", *, schema="dbo", scheme="ps_logs", function="pf_logs", count=3): + return PartitionTableInfo(name, schema, scheme, function, "created_at", count) + + +def _range(number=1, *, table="logs", schema="dbo", low=None, high=None, rows=None, pages=None): + return PartitionRangeInfo( + table, + schema, + number, + low, + high, + rows, + None if pages is None else pages * 8192, + ) + + +def _backend(*, dialect=DIALECT, execute=None): + backend = MagicMock() + backend.dialect = dialect + if execute is not None: + backend.execute = execute + return backend + + +def _base(*, dialect=DIALECT): + return _SQLServerPartitionMaintenanceBase(_backend(dialect=dialect)) + + +def _gate_dialect(**overrides): + dialect = MagicMock() + dialect.supports_table_partitioning.return_value = True + dialect.supports_partition_function.return_value = True + dialect.supports_partition_scheme.return_value = True + dialect.supports_subpartitioning.return_value = False + dialect.supports_split_partition.return_value = True + dialect.supports_merge_partition.return_value = True + for name, value in overrides.items(): + getattr(dialect, name).return_value = value + return dialect + + +class TestAsInt: + """Catalogue integers arrive as ints, strings or None.""" + + @pytest.mark.parametrize( + ("value", "expected"), + [(None, None), (7, 7), (0, 0), ("12", 12), ("-3", -3), ("007", 7)], + ) + def test_reads_int_like_values(self, value, expected): + assert _as_int(value) == expected + + def test_rejects_non_numeric_text(self): + with pytest.raises(ValueError): + _as_int("n/a") + + +class TestBoundaryParameter: + """Bind parameters must be spelled so every ODBC driver accepts them.""" + + @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"), + (time(3, 4, 5), "03:04:05"), + (Decimal("1.50"), "1.50"), + (42, 42), + ("text", "text"), + (None, None), + ], + ) + def test_conversion(self, value, expected): + assert _boundary_parameter(value) == expected + + +class TestBoundaryFamily: + """Type spellings group by the comparison the server supports.""" + + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("date", "date"), + ("DATE", "date"), + ("datetime", "datetime"), + ("datetime2", "datetime"), + ("DATETIME2(3)", "datetime"), + ("smalldatetime", "datetime"), + ("datetimeoffset", "datetime"), + ("DATETIMEOFFSET(7)", "datetime"), + ("time", "time"), + ("TIME(7)", "time"), + ("tinyint", "int"), + ("smallint", "int"), + ("INT", "int"), + ("bigint", "int"), + ("decimal", "number"), + ("DECIMAL(10, 2)", "number"), + ("numeric(18, 0)", "number"), + ("money", "number"), + ("smallmoney", "number"), + ("float", "number"), + ("real", "number"), + ("nvarchar(50)", "text"), + ("varchar(max)", "text"), + ("xml", "text"), + ], + ) + def test_family(self, value, expected): + assert _boundary_family(value) == expected + + +class TestTrimIsoFraction: + """Pre-3.11 parsers only accept six fractional digits.""" + + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("2026-01-01", "2026-01-01"), + ("2026-01-01 00:00:00", "2026-01-01 00:00:00"), + ("00:00:00.1", "00:00:00.1"), + ("00:00:00.123456", "00:00:00.123456"), + ("00:00:00.1234567", "00:00:00.123456"), + ("00:00:00.123456789+00:00", "00:00:00.123456+00:00"), + ("1.", "1."), + ], + ) + def test_trim(self, value, expected): + assert _trim_iso_fraction(value) == expected + + +class TestParseCatalogueBoundary: + """Catalogue text is read back into the declared type's Python value.""" + + @pytest.mark.parametrize( + ("data_type", "text", "expected"), + [ + ("date", "2026-01-02T00:00:00", date(2026, 1, 2)), + ("DATE", "2026-01-02", date(2026, 1, 2)), + ("datetime", "2026-01-02 03:04:05", datetime(2026, 1, 2, 3, 4, 5)), + ("datetime2", "2026-01-02T03:04:05.1234567", datetime(2026, 1, 2, 3, 4, 5, 123456)), + ("datetimeoffset", "2026-01-02T03:04:05+08:00", datetime(2026, 1, 2, 3, 4, 5)), + ("datetime", "2026-01-02T03:04:05Z", datetime(2026, 1, 2, 3, 4, 5)), + ("time", "03:04:05", time(3, 4, 5)), + ("int", "42", 42), + ("bigint", "-7", -7), + ("decimal", "1.50", Decimal("1.50")), + ("money", "12.345", Decimal("12.345")), + ("nvarchar(50)", "abc", "abc"), + ], + ) + def test_valid(self, data_type, text, expected): + assert _parse_catalogue_boundary(data_type, text) == expected + + @pytest.mark.parametrize( + ("data_type", "text"), + [("date", "not-a-date"), ("int", "1.5"), ("decimal", "NaN!"), ("time", "25:00:00")], + ) + def test_invalid_text_raises_value_error(self, data_type, text): + with pytest.raises(ValueError, match="is not a valid"): + _parse_catalogue_boundary(data_type, text) + + +class TestCoerceCutoff: + """A caller's cutoff is coerced to the comparand for the function type.""" + + @pytest.mark.parametrize( + ("data_type", "value", "expected"), + [ + ("date", datetime(2026, 1, 2, 23, 0), date(2026, 1, 2)), + ("date", date(2026, 1, 2), date(2026, 1, 2)), + ("date", "2026-01-02T00:00:00", date(2026, 1, 2)), + ("datetime", date(2026, 1, 2), datetime(2026, 1, 2)), + ( + "datetime", + datetime(2026, 1, 2, 3, 4, 5, 123456), + datetime(2026, 1, 2, 3, 4, 5, 123456), + ), + ("datetime", "2026-01-02T03:04:05.1234567Z", datetime(2026, 1, 2, 3, 4, 5, 123456)), + ( + "datetime", + datetime(2026, 1, 2, 3, 4, tzinfo=timezone.utc), + datetime(2026, 1, 2, 3, 4), + ), + ("time", time(3, 4, 5), time(3, 4, 5)), + ("time", "03:04:05.1234567", time(3, 4, 5, 123456)), + ("int", "42", 42), + ("int", 42, 42), + ("decimal", "1.50", Decimal("1.50")), + ("decimal", 1.5, Decimal("1.5")), + ("nvarchar(50)", datetime(2026, 1, 2, 3, 4), "2026-01-02 03:04:00"), + ("nvarchar(50)", date(2026, 1, 2), "2026-01-02"), + ("nvarchar(50)", time(3, 4), "03:04:00"), + ("nvarchar(50)", Decimal("1.50"), "1.50"), + ("nvarchar(50)", 7, "7"), + ], + ) + def test_valid(self, data_type, value, expected): + assert _coerce_cutoff(data_type, value) == expected + + @pytest.mark.parametrize( + ("data_type", "value"), + [("date", "not-a-date"), ("int", "x"), ("decimal", "oops"), ("time", "99:99")], + ) + def test_invalid_cutoff_raises_value_error(self, data_type, value): + with pytest.raises(ValueError, match="is not a valid"): + _coerce_cutoff(data_type, value) + + +class TestRangeBound: + """Low/high catalogue text joins into one display string.""" + + @pytest.mark.parametrize( + ("low", "high", "expected"), + [ + (None, None, None), + ("a", None, "a.."), + (None, "b", "..b"), + ("a", "b", "a..b"), + ], + ) + def test_join(self, low, high, expected): + assert _range_bound(low, high) == expected + + +class TestCatalogueParsing: + """Row dictionaries become the report's immutable value objects.""" + + def test_functions_group_rows_and_preserve_boundary_order(self): + rows = [ + { + "function_name": "pf", + "data_type": "date", + "boundary_value_on_right": "1", + "partition_count": "3", + "boundary_value": "2026-01-01", + }, + { + "function_name": "pf", + "data_type": "date", + "boundary_value_on_right": 1, + "partition_count": 3, + "boundary_value": "2026-02-01", + }, + { + "function_name": "pf", + "data_type": "date", + "boundary_value_on_right": 0, + "partition_count": 3, + "boundary_value": None, + }, + {"function_name": None, "data_type": "date"}, + ] + result = _SQLServerPartitionMaintenanceBase._parse_functions(rows) + assert len(result) == 1 + assert result[0].range_direction == "RIGHT" + assert result[0].boundary_values == ("2026-01-01", "2026-02-01") + assert result[0].partition_count == 3 + + def test_functions_default_to_left_and_zero(self): + result = _SQLServerPartitionMaintenanceBase._parse_functions( + [{"function_name": "pf", "boundary_value_on_right": 0}] + ) + assert result[0].range_direction == "LEFT" + assert result[0].data_type == "" + assert result[0].partition_count == 0 + + def test_schemes_skip_missing_names_and_empty_filegroups(self): + rows = [ + { + "scheme_name": "ps", + "function_name": "pf", + "partition_count": "3", + "filegroup_name": "", + }, + { + "scheme_name": "ps", + "function_name": "pf", + "partition_count": 3, + "filegroup_name": "fg1", + }, + {"scheme_name": None, "function_name": "pf"}, + ] + result = _SQLServerPartitionMaintenanceBase._parse_schemes(rows) + assert len(result) == 1 + assert result[0].filegroups == ("fg1",) + assert result[0].destination_count == 1 + + def test_tables_deduplicate_by_schema_and_name(self): + rows = [ + { + "table_name": "logs", + "schema_name": "dbo", + "scheme_name": "ps", + "function_name": "pf", + "partition_count": "3", + "partition_column": None, + }, + { + "table_name": "logs", + "schema_name": "dbo", + "scheme_name": "ps", + "function_name": "pf", + "partition_count": 3, + "partition_column": "created_at", + }, + { + "table_name": "other", + "schema_name": None, + "scheme_name": None, + "function_name": None, + "partition_count": None, + }, + {"table_name": None, "schema_name": "dbo"}, + ] + result = _SQLServerPartitionMaintenanceBase._parse_tables(rows) + assert len(result) == 2 + assert result[0].partition_column is None + assert result[0].partition_count == 3 + assert result[1].schema is None + assert result[1].scheme == "" + assert result[1].function == "" + + def test_ranges_calculate_bytes_and_tolerate_nulls(self): + rows = [ + { + "table_name": "logs", + "schema_name": "dbo", + "partition_number": "2", + "row_count": "10", + "used_page_count": "3", + "low_boundary": "a", + "high_boundary": None, + }, + { + "table_name": "logs", + "schema_name": None, + "partition_number": None, + "row_count": None, + "used_page_count": None, + "low_boundary": None, + "high_boundary": None, + }, + ] + result = _SQLServerPartitionMaintenanceBase._parse_ranges(rows) + assert result[0].data_bytes == 3 * 8192 + assert result[0].row_count == 10 + assert result[0].partition_number == 2 + assert result[1].partition_number == 0 + assert result[1].row_count is None + assert result[1].data_bytes is None + assert result[1].schema is None + + @pytest.mark.parametrize( + ("functions", "name", "found"), + [ + ((_function(),), "pf_logs", True), + ((_function(),), "absent", False), + ((), "pf_logs", False), + ], + ) + def test_find_function(self, functions, name, found): + assert ( + _SQLServerPartitionMaintenanceBase._find_function(functions, name) is not None + ) is found + + @pytest.mark.parametrize( + ("name", "found"), + [("ps_logs", True), ("absent", False), (None, False)], + ) + def test_find_scheme(self, name, found): + schemes = (_scheme(),) + assert (_SQLServerPartitionMaintenanceBase._find_scheme(schemes, name) is not None) is found + + def test_core_partitions_map_ranges_to_the_core_contract(self): + tables = (_table(),) + ranges = (_range(1, high="a", rows=4, pages=1), _range(2, low="a")) + result = _SQLServerPartitionMaintenanceBase._core_partitions(ranges, tables) + assert len(result) == 2 + assert result[0].name == "logs_1" + assert result[0].parent == "logs" + assert result[0].level == 1 + assert result[0].method == "RANGE" + assert result[0].bound == "..a" + assert result[0].size_bytes == 8192 + assert result[0].extras["scheme"] == "ps_logs" + assert result[0].extras["function"] == "pf_logs" + assert result[1].bound == "a.." + assert result[1].size_bytes is None + + def test_core_partitions_without_a_table_omit_engine_extras(self): + result = _SQLServerPartitionMaintenanceBase._core_partitions((_range(),), ()) + assert "scheme" not in result[0].extras + assert "function" not in result[0].extras + assert result[0].extras["partition_number"] == 1 + + +class TestPlanning: + """Pure planning helpers make every decision before any statement runs.""" + + def test_ensure_with_missing_function_creates_function_and_scheme(self): + plan = _plan(scheme="ps_logs", all_filegroup="PRIMARY") + missing, planned, issues = _base()._plan_ensure(plan, (), (), ()) + assert missing == () + assert issues == [] + assert [op.action for op, _ in planned] == ["create_function", "create_scheme"] + assert "CREATE PARTITION FUNCTION" in planned[0][0].sql + + def test_ensure_without_scheme_creates_only_the_function(self): + planned = _base()._plan_ensure(_plan(), (), (), ())[1] + assert [op.action for op, _ in planned] == ["create_function"] + + def test_ensure_splits_only_missing_boundaries_without_a_scheme(self): + plan = _plan() + missing, planned, _ = _base()._plan_ensure(plan, (_function(),), (), (True, False)) + assert missing == (date(2026, 2, 1),) + assert [op.action for op, _ in planned] == ["split"] + assert "SPLIT RANGE" in planned[0][0].sql + + def test_ensure_emits_next_used_before_each_split(self): + plan = _plan(scheme="ps_logs", all_filegroup="PRIMARY") + _, planned, _ = _base()._plan_ensure(plan, (_function(),), (_scheme(),), (True, False)) + assert [op.action for op, _ in planned] == ["next_used", "split"] + + def test_ensure_is_idempotent_when_all_boundaries_exist(self): + _, planned, issues = _base()._plan_ensure(_plan(), (_function(),), (), (True, True)) + assert planned == [] + assert issues == [] + + @pytest.mark.parametrize( + ("functions", "kwargs", "match"), + [ + ((_function(direction="LEFT"),), {}, "is RANGE LEFT"), + ((_function(data_type="int"),), {}, "partitions on int"), + ], + ) + def test_ensure_refuses_drift_in_direction_or_type(self, functions, kwargs, match): + with pytest.raises(ValueError, match=match): + _base()._plan_ensure(_plan(**kwargs), functions, (), (False, False)) + + def test_ensure_refuses_explicit_filegroups_on_a_mismatched_function(self): + plan = _plan(scheme="ps_logs", filegroups=("fg0", "fg1", "fg2")) + with pytest.raises(ValueError, match="explicit filegroups"): + _base()._plan_ensure(plan, (_function(count=7),), (), (False, False)) + + def test_ensure_creates_a_missing_scheme_on_an_existing_function(self): + _, planned, _ = _base()._plan_ensure( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), (_function(),), (), (True, True) + ) + assert [op.action for op, _ in planned] == ["create_scheme"] + + def test_ensure_refuses_a_scheme_mapped_to_another_function(self): + with pytest.raises(ValueError, match="maps function"): + _base()._plan_ensure( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (_function(),), + (_scheme(function="pf_other"),), + (False, False), + ) + + def test_ensure_continues_when_the_scheme_has_enough_destinations(self): + _, planned, issues = _base()._plan_ensure( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (_function(),), + (_scheme(filegroups=("fg0", "fg1", "fg2", "fg3")),), + (True, False), + ) + assert [op.action for op, _ in planned] == ["next_used", "split"] + assert not any("destinations" in issue for issue in issues) + + def test_ensure_reports_a_short_scheme_as_an_issue(self): + _, _, issues = _base()._plan_ensure( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (_function(),), + (_scheme(filegroups=("PRIMARY",)),), + (True, True), + ) + assert any("1 destinations for 3 partitions" in issue for issue in issues) + + def test_list_without_a_plan_reports_everything(self): + report = _base()._plan_list(None, (_function(),), (_scheme(),), (_table(),), (_range(),)) + assert report.target == "(all)" + assert report.function is None + assert report.issues == () + assert len(report.functions) == 1 + assert len(report.partitions) == 1 + + def test_list_reports_a_missing_function_and_all_boundaries(self): + report = _base()._plan_list(_plan(), (), (), (), ()) + assert report.missing_boundaries == (date(2026, 1, 1), date(2026, 2, 1)) + assert report.issues == ("partition function 'pf_logs' does not exist",) + + def test_list_reports_direction_type_count_and_scheme_issues(self): + plan = _plan(scheme="ps_logs", all_filegroup="PRIMARY") + report = _base()._plan_list( + plan, + (_function(data_type="int", direction="LEFT", count=9),), + (_scheme(function="pf_other", filegroups=("PRIMARY",)),), + (), + (), + (True, True), + ) + assert report.existing_boundaries == ("2026-01-01", "2026-02-01") + assert any("RANGE LEFT" in issue for issue in report.issues) + assert any("partitions on int" in issue for issue in report.issues) + assert any("9 partitions" in issue for issue in report.issues) + assert any("maps 'pf_other'" in issue for issue in report.issues) + assert any("1 destinations" in issue for issue in report.issues) + + def test_list_has_no_scheme_issue_when_destinations_are_enough(self): + report = _base()._plan_list( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (_function(),), + (_scheme(filegroups=("fg0", "fg1", "fg2", "fg3")),), + (), + (), + (True, True), + ) + assert not any("destinations" in issue for issue in report.issues) + + def test_list_reports_a_missing_scheme(self): + report = _base()._plan_list( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (_function(),), + (), + (), + (), + (True, True), + ) + assert any("scheme 'ps_logs' does not exist" in issue for issue in report.issues) + + def test_drop_merges_only_present_boundaries(self): + planned = _base()._plan_drop( + _plan(), + (_function(),), + (), + (), + (date(2026, 1, 1), date(2026, 2, 1)), + (True, False), + False, + ) + assert [op.action for op, _ in planned] == ["merge"] + assert planned[0][0].name == "2026-01-01" + assert "MERGE RANGE" in planned[0][0].sql + + def test_drop_is_empty_for_an_unknown_function(self): + assert _base()._plan_drop(_plan(), (), (), (), (), (), True) == [] + + def test_drop_without_scaffolding_stops_after_merges(self): + planned = _base()._plan_drop( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (_function(),), + (_scheme(),), + (), + (), + (), + False, + ) + assert all(op.action == "merge" for op, _ in planned) + + def test_drop_removes_unused_scheme_then_function(self): + planned = _base()._plan_drop( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (_function(),), + (_scheme(),), + (), + (), + (), + True, + ) + assert [op.action for op, _ in planned] == ["drop_scheme", "drop_function"] + assert planned[0][0].sql == "DROP PARTITION SCHEME [ps_logs]" + assert planned[1][0].sql == "DROP PARTITION FUNCTION [pf_logs]" + + def test_drop_keeps_the_function_when_a_table_uses_the_scheme(self): + planned = _base()._plan_drop( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (_function(),), + (_scheme(),), + (_table(),), + (), + (), + True, + ) + assert [op.action for op, _ in planned] == [] + + def test_drop_keeps_the_function_when_another_scheme_remains(self): + schemes = (_scheme("ps_one"), _scheme("ps_two")) + planned = _base()._plan_drop( + _plan(), (_function(),), schemes, (_table(scheme="ps_two"),), (), (), True + ) + assert [op.action for op, _ in planned] == ["drop_scheme"] + assert planned[0][0].name == "ps_one" + + def test_report_carries_operations_and_dry_run(self): + op = PartitionOperation(action="split", name="x", sql="SQL") + report = _SQLServerPartitionMaintenanceBase._report( + _plan(), (), (), (), (), (), (), (), [(op, ("p",))], True + ) + assert report.target == "pf_logs" + assert report.operations == (op,) + assert report.dry_run is True + + def test_validate_adds_table_level_findings(self): + report = _base()._plan_list( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (_function(),), + (_scheme(),), + (_table(scheme="ps_other", function="pf_other", count=9),), + (_range(1), _range(3)), + (True, True), + ) + issues = _base()._plan_validate( + report, _plan(scheme="ps_logs", all_filegroup="PRIMARY"), "logs" + ) + assert any("built on 'ps_other'" in issue for issue in issues) + assert any("uses function 'pf_other'" in issue for issue in issues) + assert any("9 partitions" in issue for issue in issues) + assert any("partitions are [1, 3]" in issue for issue in issues) + + def test_validate_a_consistent_table_adds_nothing(self): + plan = _plan(scheme="ps_logs", all_filegroup="PRIMARY") + report = _base()._plan_list( + plan, + (_function(),), + (_scheme(filegroups=("fg0", "fg1", "fg2", "fg3")),), + (_table(),), + (_range(1), _range(2), _range(3)), + (True, True), + ) + assert _base()._plan_validate(report, plan, "logs") == () + + def test_validate_reports_a_missing_table(self): + report = _base()._plan_list(_plan(), (_function(),), (), (), (), (True, True)) + issues = _base()._plan_validate(report, _plan(), "absent") + assert any("is not partitioned or does not exist" in issue for issue in issues) + + def test_validate_without_a_table_adds_nothing(self): + report = _base()._plan_list(_plan(), (_function(),), (), (), (), (True, True)) + assert _base()._plan_validate(report, _plan(), None) == report.issues + + +class TestRunnerAndGates: + """Execution stops at the first error; capability gates are explicit.""" + + def _planned(self): + op1 = PartitionOperation(action="first", name="a", sql="SQL1") + op2 = PartitionOperation(action="second", name="b", sql="SQL2") + return [(op1, ()), (op2, ())] + + def test_dry_run_executes_nothing(self): + maintenance = SQLServerPartitionMaintenance(_backend()) + maintenance._execute = MagicMock() + assert maintenance._run(self._planned(), True) == ((), 0) + maintenance._execute.assert_not_called() + + def test_real_run_executes_every_statement(self): + maintenance = SQLServerPartitionMaintenance(_backend()) + maintenance._execute = MagicMock() + assert maintenance._run(self._planned(), False) == ((), 2) + assert maintenance._execute.call_count == 2 + + def test_first_error_stops_later_statements(self): + maintenance = SQLServerPartitionMaintenance(_backend()) + maintenance._execute = MagicMock(side_effect=[None, DatabaseError("boom")]) + errors, completed = maintenance._run(self._planned(), False) + assert completed == 1 + assert errors == ("second 'b' failed: boom",) + + @pytest.mark.parametrize( + ("flag", "value", "match"), + [ + ("supports_table_partitioning", False, "table partitioning"), + ("supports_partition_function", False, "partition functions"), + ("supports_partition_scheme", False, "partition schemes"), + ("supports_subpartitioning", True, "subpartitioning"), + ("supports_split_partition", False, "SPLIT RANGE"), + ], + ) + def test_require_support_refuses_when_a_gate_fails(self, flag, value, match): + base = _base(dialect=_gate_dialect(**{flag: value})) + with pytest.raises(UnsupportedFeatureError, match=match): + base._require_support(_plan(scheme="ps_logs", all_filegroup="PRIMARY")) + + def test_require_support_accepts_a_capable_dialect(self): + _base(dialect=_gate_dialect())._require_support( + _plan(scheme="ps_logs", all_filegroup="PRIMARY") + ) + + @pytest.mark.parametrize( + ("flag", "value", "match"), + [ + ("supports_table_partitioning", False, "table partitioning"), + ("supports_merge_partition", False, "MERGE RANGE"), + ("supports_subpartitioning", True, "subpartitioning"), + ], + ) + def test_require_merge_refuses_when_a_gate_fails(self, flag, value, match): + base = _base(dialect=_gate_dialect(**{flag: value})) + with pytest.raises(UnsupportedFeatureError, match=match): + base._require_merge() + + def test_require_merge_accepts_a_capable_dialect(self): + _base(dialect=_gate_dialect())._require_merge() + + +class TestSyncSeams: + """The real sync I/O seams issue catalogue questions through backend.execute.""" + + def test_fetch_rows_returns_data_or_empty(self): + backend = _backend(execute=MagicMock(return_value=SimpleNamespace(data=[{"x": 1}]))) + statement = MagicMock() + statement.to_sql.return_value = ("SELECT 1", ()) + assert SQLServerPartitionMaintenance(backend)._fetch_rows(statement) == [{"x": 1}] + backend.execute.assert_called_once_with("SELECT 1", ()) + + def test_fetch_rows_tolerates_null_data(self): + backend = _backend(execute=MagicMock(return_value=SimpleNamespace(data=None))) + statement = MagicMock() + statement.to_sql.return_value = ("SELECT 1", ()) + assert SQLServerPartitionMaintenance(backend)._fetch_rows(statement) == [] + + def test_read_functions_uses_the_catalogue_statement(self): + backend = _backend( + execute=MagicMock( + return_value=SimpleNamespace( + data=[ + {"function_name": "pf", "data_type": "date", "boundary_value_on_right": 1} + ] + ) + ) + ) + result = SQLServerPartitionMaintenance(backend)._read_functions("pf") + assert result[0].name == "pf" + sql, _ = backend.execute.call_args.args + assert "sys.partition_functions" in sql + + def test_read_schemes_uses_the_catalogue_statement(self): + backend = _backend( + execute=MagicMock( + return_value=SimpleNamespace( + data=[{"scheme_name": "ps", "function_name": "pf", "filegroup_name": "PRIMARY"}] + ) + ) + ) + result = SQLServerPartitionMaintenance(backend)._read_schemes("ps", "pf") + assert result[0].filegroups == ("PRIMARY",) + assert "sys.partition_schemes" in backend.execute.call_args.args[0] + + def test_read_tables_uses_the_catalogue_statement(self): + backend = _backend( + execute=MagicMock( + return_value=SimpleNamespace( + data=[{"table_name": "logs", "schema_name": "dbo", "scheme_name": "ps"}] + ) + ) + ) + result = SQLServerPartitionMaintenance(backend)._read_tables("logs", "dbo") + assert result[0].name == "logs" + assert "sys.tables" in backend.execute.call_args.args[0] + + def test_read_ranges_uses_the_catalogue_statement(self): + backend = _backend( + execute=MagicMock( + return_value=SimpleNamespace( + data=[{"table_name": "logs", "partition_number": 1, "used_page_count": 2}] + ) + ) + ) + result = SQLServerPartitionMaintenance(backend)._read_ranges("logs", "dbo") + assert result[0].data_bytes == 2 * 8192 + assert "boundary_text" in backend.execute.call_args.args[0] + + def test_read_boundary_exists_checks_each_boundary(self): + backend = _backend( + execute=MagicMock( + side_effect=[ + SimpleNamespace(data=[{"boundary_exists": 1}]), + SimpleNamespace(data=[{"boundary_exists": 0}]), + SimpleNamespace(data=[]), + ] + ) + ) + plan = _plan(boundaries=(date(2026, 1, 1), date(2026, 2, 1), date(2026, 3, 1))) + assert SQLServerPartitionMaintenance(backend)._read_boundary_exists(plan) == ( + True, + False, + False, + ) + assert backend.execute.call_count == 3 + + def test_read_boundary_exists_for_checks_the_requested_boundaries(self): + backend = _backend( + execute=MagicMock(return_value=SimpleNamespace(data=[{"boundary_exists": 1}])) + ) + result = SQLServerPartitionMaintenance(backend)._read_boundary_exists_for( + _plan(), (date(2026, 1, 1),) + ) + assert result == (True,) + sql, params = backend.execute.call_args.args + assert "CAST" in sql + assert date(2026, 1, 1).isoformat() in params + + def test_execute_delegates_to_the_backend(self): + backend = _backend(execute=MagicMock()) + SQLServerPartitionMaintenance(backend)._execute("DDL", (1,)) + backend.execute.assert_called_once_with("DDL", (1,)) + + +class TestSyncPublicMethods: + """Public methods behave the same with MagicMock seams as with fake ones.""" + + def _maintenance(self, **kwargs): + maintenance = SQLServerPartitionMaintenance(_backend()) + maintenance._read_functions = MagicMock(return_value=kwargs.get("functions", ())) + maintenance._read_schemes = MagicMock(return_value=kwargs.get("schemes", ())) + maintenance._read_tables = MagicMock(return_value=kwargs.get("tables", ())) + maintenance._read_ranges = MagicMock(return_value=kwargs.get("ranges", ())) + maintenance._read_boundary_exists = MagicMock(return_value=kwargs.get("exists", ())) + maintenance._read_boundary_exists_for = MagicMock(return_value=kwargs.get("exists", ())) + maintenance._execute = MagicMock() + return maintenance + + def test_ensure_dry_run_plans_the_function(self): + maintenance = self._maintenance() + report = maintenance.ensure(_plan(), dry_run=True) + assert [op.action for op in report.operations] == ["create_function"] + maintenance._execute.assert_not_called() + + def test_ensure_real_run_reports_the_post_state(self): + maintenance = self._maintenance() + report = maintenance.ensure(_plan(), dry_run=False) + assert report.dry_run is False + assert [op.action for op in report.operations] == ["create_function"] + maintenance._execute.assert_called_once() + + def test_retention_boundaries_from_function(self): + maintenance = self._maintenance(functions=(_function(),)) + assert maintenance.retention_boundaries(_plan(), date(2026, 1, 15)) == (date(2026, 1, 1),) + + def test_retention_boundaries_from_table_ranges(self): + maintenance = self._maintenance( + ranges=(_range(1, high="2026-01-01"), _range(2, high="2026-02-01")) + ) + assert maintenance.retention_boundaries(_plan(), date(2026, 1, 15), table="logs") == ( + date(2026, 1, 1), + ) + + def test_retention_boundaries_with_no_catalogue_is_empty(self): + assert self._maintenance().retention_boundaries(_plan(), date(2026, 1, 15)) == () + + def test_drop_before_defaults_to_a_dry_run(self): + maintenance = self._maintenance(functions=(_function(),), exists=(True, False)) + report = maintenance.drop_before(_plan(), date(2026, 1, 15)) + assert report.dry_run is True + assert [op.action for op in report.operations] == ["merge"] + maintenance._execute.assert_not_called() + + def test_drop_or_merge_real_run_executes(self): + maintenance = self._maintenance(functions=(_function(),), exists=(True, False)) + report = maintenance.drop_or_merge(_plan(), (date(2026, 1, 1),), dry_run=False) + assert report.dry_run is False + assert [op.action for op in report.operations] == ["merge"] + maintenance._execute.assert_called_once() + + def test_validate_uses_the_mocked_seams(self): + maintenance = self._maintenance(functions=(_function(),)) + report = maintenance.validate(_plan(), table="logs") + assert any("does not exist" in issue for issue in report.issues) + + def test_drop_or_merge_reports_a_missing_function(self): + maintenance = self._maintenance() + report = maintenance.drop_or_merge( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (), + dry_run=True, + drop_scaffolding=True, + ) + assert any("does not exist" in issue for issue in report.issues) + assert report.operations == () + + def test_drop_or_merge_reports_a_scheme_used_by_a_table(self): + maintenance = self._maintenance( + functions=(_function(),), schemes=(_scheme(),), tables=(_table(),) + ) + report = maintenance.drop_or_merge( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (), + dry_run=True, + drop_scaffolding=True, + ) + assert any("used by 1 table" in issue for issue in report.issues) + assert any("still mapped by scheme" in issue for issue in report.issues) + + def test_drop_or_merge_ignores_unrelated_schemes(self): + maintenance = self._maintenance( + functions=(_function(),), + schemes=(_scheme("ps_other", function="pf_other"), _scheme("ps_another")), + ) + report = maintenance.drop_or_merge( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (), + dry_run=True, + drop_scaffolding=True, + ) + assert report.operations == () + assert not any("used by" in issue for issue in report.issues) + + +class TestAsyncSeams: + """The native async seams await the backend's AsyncMock execute.""" + + async def test_fetch_rows_returns_data_or_empty(self): + backend = _backend(execute=AsyncMock(return_value=SimpleNamespace(data=[{"x": 1}]))) + statement = MagicMock() + statement.to_sql.return_value = ("SELECT 1", ()) + maintenance = AsyncSQLServerPartitionMaintenance(backend) + assert await maintenance._fetch_rows(statement) == [{"x": 1}] + backend.execute.assert_awaited_once_with("SELECT 1", ()) + + async def test_read_functions(self): + backend = _backend( + execute=AsyncMock( + return_value=SimpleNamespace( + data=[{"function_name": "pf", "data_type": "int", "boundary_value_on_right": 1}] + ) + ) + ) + result = await AsyncSQLServerPartitionMaintenance(backend)._read_functions("pf") + assert result[0].range_direction == "RIGHT" + + async def test_read_schemes(self): + backend = _backend( + execute=AsyncMock( + return_value=SimpleNamespace( + data=[{"scheme_name": "ps", "function_name": "pf", "filegroup_name": "fg1"}] + ) + ) + ) + result = await AsyncSQLServerPartitionMaintenance(backend)._read_schemes() + assert result[0].filegroups == ("fg1",) + + async def test_read_tables(self): + backend = _backend( + execute=AsyncMock( + return_value=SimpleNamespace( + data=[{"table_name": "logs", "schema_name": "dbo", "scheme_name": "ps"}] + ) + ) + ) + result = await AsyncSQLServerPartitionMaintenance(backend)._read_tables("logs") + assert result[0].scheme == "ps" + + async def test_read_ranges(self): + backend = _backend( + execute=AsyncMock( + return_value=SimpleNamespace( + data=[{"table_name": "logs", "partition_number": "1", "used_page_count": "4"}] + ) + ) + ) + result = await AsyncSQLServerPartitionMaintenance(backend)._read_ranges("logs") + assert result[0].data_bytes == 4 * 8192 + + async def test_read_boundary_exists(self): + backend = _backend( + execute=AsyncMock( + side_effect=[ + SimpleNamespace(data=[{"boundary_exists": 1}]), + SimpleNamespace(data=[]), + ] + ) + ) + plan = _plan(boundaries=(date(2026, 1, 1), date(2026, 2, 1))) + assert await AsyncSQLServerPartitionMaintenance(backend)._read_boundary_exists(plan) == ( + True, + False, + ) + + async def test_read_boundary_exists_for(self): + backend = _backend( + execute=AsyncMock(return_value=SimpleNamespace(data=[{"boundary_exists": 1}])) + ) + result = await AsyncSQLServerPartitionMaintenance(backend)._read_boundary_exists_for( + _plan(), (10,) + ) + assert result == (True,) + + async def test_execute_delegates_to_the_backend(self): + backend = _backend(execute=AsyncMock()) + await AsyncSQLServerPartitionMaintenance(backend)._execute("DDL", ()) + backend.execute.assert_awaited_once_with("DDL", ()) + + async def test_async_run_stops_at_the_first_error(self): + maintenance = AsyncSQLServerPartitionMaintenance(_backend()) + first = PartitionOperation(action="first", name="a", sql="SQL1") + second = PartitionOperation(action="second", name="b", sql="SQL2") + maintenance._execute = AsyncMock(side_effect=[None, DatabaseError("boom")]) + errors, completed = await maintenance._run([(first, ()), (second, ())], False) + assert completed == 1 + assert errors == ("second 'b' failed: boom",) + + async def test_async_run_dry_run_is_a_no_op(self): + maintenance = AsyncSQLServerPartitionMaintenance(_backend()) + maintenance._execute = AsyncMock() + op = PartitionOperation(action="first", name="a", sql="SQL1") + assert await maintenance._run([(op, ())], True) == ((), 0) + maintenance._execute.assert_not_awaited() + + +class TestAsyncPublicMethods: + """The async public surface mirrors the sync one with AsyncMock seams.""" + + def _maintenance(self, **kwargs): + maintenance = AsyncSQLServerPartitionMaintenance(_backend()) + maintenance._read_functions = AsyncMock(return_value=kwargs.get("functions", ())) + maintenance._read_schemes = AsyncMock(return_value=kwargs.get("schemes", ())) + maintenance._read_tables = AsyncMock(return_value=kwargs.get("tables", ())) + maintenance._read_ranges = AsyncMock(return_value=kwargs.get("ranges", ())) + maintenance._read_boundary_exists = AsyncMock(return_value=kwargs.get("exists", ())) + maintenance._read_boundary_exists_for = AsyncMock(return_value=kwargs.get("exists", ())) + maintenance._execute = AsyncMock() + return maintenance + + async def test_ensure_dry_run(self): + maintenance = self._maintenance() + report = await maintenance.ensure(_plan(), dry_run=True) + assert [op.action for op in report.operations] == ["create_function"] + maintenance._execute.assert_not_awaited() + + async def test_ensure_real_run(self): + maintenance = self._maintenance() + report = await maintenance.ensure(_plan(), dry_run=False) + assert report.dry_run is False + maintenance._execute.assert_awaited_once() + + async def test_list_without_a_plan(self): + report = await self._maintenance().list() + assert report.target == "(all)" + assert report.issues == () + + async def test_retention_boundaries(self): + maintenance = self._maintenance(functions=(_function(),)) + assert await maintenance.retention_boundaries(_plan(), date(2026, 1, 15)) == ( + date(2026, 1, 1), + ) + + async def test_retention_boundaries_from_table(self): + maintenance = self._maintenance(ranges=(_range(high="2026-01-01"),)) + assert await maintenance.retention_boundaries(_plan(), date(2026, 1, 15), table="logs") == ( + date(2026, 1, 1), + ) + + async def test_retention_boundaries_without_a_catalogue_is_empty(self): + assert await self._maintenance().retention_boundaries(_plan(), date(2026, 1, 15)) == () + + async def test_drop_before(self): + maintenance = self._maintenance(functions=(_function(),), exists=(True, False)) + report = await maintenance.drop_before(_plan(), date(2026, 1, 15)) + assert report.dry_run is True + assert [op.action for op in report.operations] == ["merge"] + + async def test_drop_or_merge_real_run(self): + maintenance = self._maintenance(functions=(_function(),), exists=(True, False)) + report = await maintenance.drop_or_merge(_plan(), (date(2026, 1, 1),), dry_run=False) + assert [op.action for op in report.operations] == ["merge"] + maintenance._execute.assert_awaited_once() + + async def test_validate(self): + maintenance = self._maintenance(functions=(_function(),)) + report = await maintenance.validate(_plan()) + assert report.issues == () + + async def test_drop_or_merge_reports_a_missing_function(self): + maintenance = self._maintenance() + report = await maintenance.drop_or_merge( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (), + dry_run=True, + drop_scaffolding=True, + ) + assert any("does not exist" in issue for issue in report.issues) + assert report.operations == () + + async def test_drop_or_merge_reports_scaffolding_issues(self): + maintenance = self._maintenance( + functions=(_function(),), schemes=(_scheme(),), tables=(_table(),) + ) + report = await maintenance.drop_or_merge( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (), + dry_run=True, + drop_scaffolding=True, + ) + assert any("used by 1 table" in issue for issue in report.issues) + assert any("still mapped by scheme" in issue for issue in report.issues) + + async def test_drop_or_merge_ignores_unrelated_schemes(self): + maintenance = self._maintenance( + functions=(_function(),), + schemes=(_scheme("ps_other", function="pf_other"), _scheme("ps_another")), + ) + report = await maintenance.drop_or_merge( + _plan(scheme="ps_logs", all_filegroup="PRIMARY"), + (), + dry_run=True, + drop_scaffolding=True, + ) + assert report.operations == () + assert not any("used by" in issue for issue in report.issues) + + +class TestPlanBoundaryTokens: + """Plan boundary tokens are only for spotting duplicates inside one plan.""" + + @pytest.mark.parametrize( + ("value", "expected"), + [ + (True, ("bool", "1")), + (False, ("bool", "0")), + (7, ("int", "7")), + (1.5, ("number", "1.500000")), + (Decimal("2.50"), ("number", "2.50")), + (datetime(2026, 1, 2, 3, 4), ("datetime", "2026-01-02 03:04:00")), + (date(2026, 1, 2), ("date", "2026-01-02")), + (time(3, 4), ("time", "03:04:00")), + ("abc", ("str", "abc")), + ], + ) + def test_token(self, value, expected): + assert _boundary_token(value) == expected + + def test_unsupported_value_is_refused(self): + with pytest.raises(ValueError, match="unsupported partition boundary"): + _boundary_token(object()) + + def test_bool_and_int_one_produce_distinct_tokens(self): + assert _boundary_token(True) != _boundary_token(1) + + def test_direction_is_normalised_from_a_lowercase_word(self): + assert _plan(range_direction="left").range_direction.value == "LEFT" + + def test_incomparable_boundaries_are_refused(self): + with pytest.raises(ValueError, match="mutually comparable"): + _plan(boundaries=(1, "two")) + + def test_filegroups_require_a_scheme(self): + with pytest.raises(ValueError, match="require a scheme"): + _plan(filegroups=("fg1",)) + + def test_next_filegroup_must_be_one_of_the_filegroups(self): + with pytest.raises(ValueError, match="not one of the plan's filegroups"): + _plan(scheme="ps", filegroups=("fg0", "fg1", "fg2"), next_filegroup="fgX") + + def test_next_filegroup_must_equal_all_filegroup(self): + with pytest.raises(ValueError, match="must equal all_filegroup"): + _plan(scheme="ps", all_filegroup="PRIMARY", next_filegroup="fgX") + + def test_empty_function_name_is_refused(self): + with pytest.raises(ValueError, match="non-empty string"): + _plan(function=" ") + + def test_blank_scheme_name_is_refused(self): + with pytest.raises(ValueError, match="non-empty string"): + _plan(scheme=" ", all_filegroup="PRIMARY") + + def test_a_scheme_needs_a_destination(self): + with pytest.raises(ValueError, match="needs either explicit filegroups"): + _plan(scheme="ps_logs") diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/sqlserver/test_partition_syntax_matrix.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_syntax_matrix.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/sqlserver/test_partition_syntax_matrix.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_syntax_matrix.py index f00a83a9..7a979231 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/sqlserver/test_partition_syntax_matrix.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_syntax_matrix.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/sqlserver/test_partition_syntax_matrix.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_partition_syntax_matrix.py """Offline matrix over SQL Server's partition syntax families. Every test is parameterised by ``partition_syntax_case`` from diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_table_type_definition_roundtrip.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_table_type_definition_roundtrip.py similarity index 97% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_table_type_definition_roundtrip.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_table_type_definition_roundtrip.py index b2cd7b3b..cfb513cc 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_table_type_definition_roundtrip.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_table_type_definition_roundtrip.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_table_type_definition_roundtrip.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_table_type_definition_roundtrip.py """Round-trip contract for ``SQLServerTableTypeDefinition``. A SQL Server table TYPE has two spellings for the same list of table @@ -54,7 +54,7 @@ class used to override ``get_params()`` to always emit the list under import importlib.util as _importlib_util from pathlib import Path as _Path -_harness_path = _Path(__file__).parent / "expression" / "expression_roundtrip_harness.py" +_harness_path = _Path(__file__).parents[1] / "expression" / "expression_roundtrip_harness.py" _spec = _importlib_util.spec_from_file_location( "sqlserver_roundtrip_harness", _harness_path ) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_type_ddl.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_type_ddl.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_type_ddl.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_type_ddl.py index eec84ee4..9119d353 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_type_ddl.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_type_ddl.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_type_ddl.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/ddl/test_type_ddl.py """SQL Server schema-level TYPE DDL SQL, capability, and protocol tests.""" import pytest diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect.py similarity index 97% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect.py index 3647e641..ca4a64ca 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect.py """ SQL Server backend dialect tests. @@ -8,7 +8,7 @@ from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect -class TestSQLServerDialect: +class TestDialect: """Test cases for SQL Server dialect formatting methods.""" @pytest.fixture @@ -75,7 +75,7 @@ def test_format_limit_offset_none(self, dialect: SQLServerDialect): assert params == () -class TestSQLServerDialectStatements: +class TestDialectStatements: """Test cases for SQL Server statement formatting.""" @pytest.fixture @@ -174,7 +174,7 @@ def test_format_create_unique_index(self, dialect: SQLServerDialect): assert "ON [users]" in sql -class TestSQLServerDialectProtocols: +class TestDialectProtocols: """Test cases for SQL Server dialect protocol support.""" @pytest.fixture diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect_comprehensive.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_comprehensive.py similarity index 96% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect_comprehensive.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_comprehensive.py index aef4ede2..ffe32da3 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect_comprehensive.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_comprehensive.py @@ -1,5 +1,6 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect_comprehensive.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_comprehensive.py """Comprehensive SQL Server dialect formatting tests.""" +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import pytest from rhosocial.activerecord.backend.impl.sqlserver.dialect import ( @@ -8,7 +9,7 @@ ) -class TestSQLServerDialectCore: +class TestDialectCore: """Core dialect behavior tests.""" @pytest.fixture(params=[ @@ -35,7 +36,7 @@ def test_get_server_version(self, dialect): assert dialect.get_server_version() == dialect.version -class TestSQLServerDialectPagination: +class TestDialectPagination: """OFFSET FETCH pagination tests.""" @pytest.fixture @@ -75,7 +76,7 @@ def test_old_version_raises(self, dialect): old.format_limit_offset(limit=10, offset=0) -class TestSQLServerDialectDML: +class TestDialectDML: """DML statement formatting tests.""" @pytest.fixture @@ -175,7 +176,7 @@ def test_insert_top(self, dialect): assert "VALUES" in sql -class TestSQLServerDialectSequence: +class TestDialectSequence: """SEQUENCE DDL tests.""" @pytest.fixture @@ -275,7 +276,7 @@ def test_alter_sequence_increment_renders(self, dialect): assert params == () -class TestSQLServerDialectSchema: +class TestDialectSchema: """SCHEMA DDL tests.""" @pytest.fixture @@ -318,7 +319,7 @@ def test_drop_schema(self, dialect): assert "DROP SCHEMA [sales]" in sql -class TestSQLServerDialectTruncate: +class TestDialectTruncate: """TRUNCATE formatting tests.""" @pytest.fixture @@ -337,7 +338,7 @@ def test_truncate_table(self, dialect): assert sql == "TRUNCATE TABLE [users]" -class TestSQLServerDialectLateral: +class TestDialectLateral: """LATERAL (CROSS/OUTER APPLY) formatting tests.""" @pytest.fixture @@ -388,7 +389,7 @@ def test_renders_through_to_sql(self, dialect): assert "CROSS APPLY" in sql -class TestSQLServerDialectSetOperation: +class TestDialectSetOperation: """Set operation (UNION/INTERSECT/EXCEPT) formatting tests.""" @pytest.fixture @@ -473,7 +474,7 @@ def test_except(self, dialect): assert "EXCEPT" in sql -class TestSQLServerDialectForUpdate: +class TestDialectForUpdate: """FOR UPDATE (table hints) formatting tests.""" @pytest.fixture @@ -495,7 +496,7 @@ def test_for_update_skip_locked(self, dialect): assert "READPAST" in sql -class TestSQLServerDialectMerge: +class TestDialectMerge: """MERGE statement formatting tests.""" @pytest.fixture @@ -551,7 +552,7 @@ def test_merge_basic(self, dialect): assert "WHEN NOT MATCHED BY TARGET THEN INSERT" in sql -class TestSQLServerDialectFullText: +class TestDialectFullText: """Full-text search formatting tests.""" @pytest.fixture @@ -572,7 +573,7 @@ def test_contains_with_language(self, dialect): assert "LANGUAGE" in sql -class TestSQLServerDialectTop: +class TestDialectTop: """TOP n clause formatting tests.""" @pytest.fixture @@ -590,7 +591,7 @@ def test_top_n_percent(self, dialect): assert params == () -class TestSQLServerDialectCTE: +class TestDialectCTE: """CTE formatting tests.""" @pytest.fixture @@ -603,7 +604,7 @@ def test_supports_cte(self, dialect): assert dialect.supports_materialized_cte() is False -class TestSQLServerDialectWindow: +class TestDialectWindow: """Window function support tests.""" @pytest.fixture @@ -622,7 +623,7 @@ def test_window_frame_2008(self, dialect): assert d2008.supports_window_frame_clause() is False -class TestSQLServerDialectJSON: +class TestDialectJSON: """JSON support tests.""" @pytest.fixture @@ -645,7 +646,7 @@ def test_json_support_pre_2016(self, dialect): assert d2012.supports_json_type() is False -class TestSQLServerDialectOutputExpression: +class TestDialectOutputExpression: """SQL Server-specific OUTPUT expression tests.""" @pytest.fixture @@ -669,7 +670,7 @@ def test_output_deleted(self, dialect): assert sql == "DELETED.[old_value]" -class TestSQLServerDialectTableHint: +class TestDialectTableHint: """Table hint expression tests.""" @pytest.fixture @@ -705,7 +706,7 @@ def test_readpast_hint(self, dialect): assert "READPAST" in sql -class TestSQLServerDialectOpenJson: +class TestDialectOpenJson: """OPENJSON expression tests.""" @pytest.fixture @@ -748,7 +749,7 @@ def test_openjson_with_schema(self, dialect): assert "AS [orders]" in sql -class TestSQLServerDialectTemporal: +class TestDialectTemporal: """Temporal table expression tests.""" @pytest.fixture @@ -776,7 +777,7 @@ def test_system_versioning(self, dialect): assert "[dbo].[TestTableHistory]" in sql -class TestSQLServerDialectTryCast: +class TestDialectTryCast: """TRY_CAST / TRY_CONVERT expression tests.""" @pytest.fixture @@ -814,7 +815,7 @@ def test_try_convert_with_style(self, dialect): assert "TRY_CONVERT(DATE, [date_str], 100)" in sql -class TestSQLServerDialectFullTextExpressions: +class TestDialectFullTextExpressions: """Full-text search expression tests.""" @pytest.fixture @@ -838,7 +839,7 @@ def test_freetext_predicate(self, dialect): assert "FREETEXT([content], 'database design')" in sql -class TestSQLServerDialectVersionSpecific: +class TestDialectVersionSpecific: """Version-dependent feature support tests.""" def test_2012_features(self): @@ -867,7 +868,7 @@ def test_2022_features(self): assert d.supports_for_update_skip_locked() is True -class TestSQLServerDialectDDL: +class TestDialectDDL: """DDL statement formatting tests.""" @pytest.fixture @@ -890,16 +891,16 @@ def test_create_table_basic(self, dialect): columns=[ ColumnDefinition(dialect, name="id", - data_type=IntegerType(dialect), + data_type=auto_increment_parts(dialect, IntegerType(dialect))[0], constraints=[ ColumnConstraint( dialect, branch=ColumnPrimaryKeyConstraint( - dialect, is_auto_increment=True + dialect ), ) ], - ), + attributes=auto_increment_parts(dialect, IntegerType(dialect))[1]), ColumnDefinition(dialect, name="name", data_type=VarCharType(dialect, length=255), @@ -944,7 +945,7 @@ def test_create_index_with_includes(self, dialect): assert "INCLUDE ([id], [name])" in sql -class TestSQLServerDialectTransaction: +class TestDialectTransaction: """Transaction formatting tests.""" @pytest.fixture diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_exists_predicate.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_exists_predicate.py new file mode 100644 index 00000000..54aeddf3 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_exists_predicate.py @@ -0,0 +1,76 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_exists_predicate.py +"""Offline rendering checks for T-SQL EXISTS (scalar vs boolean context). + +Core's ``exists()`` turns an ``ExistsPredicate`` into an aliased scalar select +expression. T-SQL has no boolean scalar and rejects ``SELECT EXISTS (...)``, so +the SQL Server dialect renders the aliased form as ``CASE WHEN ... THEN 1 ELSE 0 +END``; an unaliased EXISTS must stay a plain boolean predicate for WHERE. +""" + +import pytest + +from rhosocial.activerecord.backend.expression import ( + Column, + ExistsPredicate, + QueryStatement, +) +from rhosocial.activerecord.backend.expression.objects import Table +from rhosocial.activerecord.backend.expression.query_parts import WhereClause +from rhosocial.activerecord.backend.expression.sources import NamedRelationRef +from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect + + +@pytest.fixture +def dialect() -> SQLServerDialect: + return SQLServerDialect((16, 0, 0)) + + +def _subquery(dialect: SQLServerDialect) -> QueryStatement: + return QueryStatement( + dialect, + select=[Column(dialect, "id")], + from_=NamedRelationRef(dialect, Table(dialect, "users")), + ) + + +def test_scalar_exists_renders_case_when(dialect: SQLServerDialect) -> None: + """An aliased (scalar) EXISTS uses the T-SQL integer-boolean form.""" + exists_expr = ExistsPredicate(dialect, _subquery(dialect)) + exists_expr.alias = "_exists" + query = QueryStatement( + dialect, + select=[exists_expr], + from_=NamedRelationRef(dialect, Table(dialect, "users")), + ) + sql, params = query.to_sql() + assert sql == ( + "SELECT CASE WHEN EXISTS (SELECT [id] FROM [users]) THEN 1 ELSE 0 END " + "AS [_exists] FROM [users]" + ) + assert params == () + + +def test_where_exists_stays_boolean_predicate(dialect: SQLServerDialect) -> None: + """An unaliased EXISTS in WHERE is left as a plain predicate.""" + query = QueryStatement( + dialect, + select=[Column(dialect, "id")], + from_=NamedRelationRef(dialect, Table(dialect, "users")), + where=WhereClause(dialect, condition=ExistsPredicate(dialect, _subquery(dialect))), + ) + sql, params = query.to_sql() + assert sql == "SELECT [id] FROM [users] WHERE EXISTS (SELECT [id] FROM [users])" + assert params == () + + +def test_negated_scalar_exists(dialect: SQLServerDialect) -> None: + """NOT EXISTS keeps its negation in the CASE form.""" + exists_expr = ExistsPredicate(dialect, _subquery(dialect), is_not=True) + exists_expr.alias = "_exists" + query = QueryStatement( + dialect, + select=[exists_expr], + from_=NamedRelationRef(dialect, Table(dialect, "users")), + ) + sql, _ = query.to_sql() + assert sql.startswith("SELECT CASE WHEN NOT EXISTS (") diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect_function_support.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_function_support.py similarity index 97% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect_function_support.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_function_support.py index 3b3b9083..36f80ca9 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect_function_support.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_function_support.py @@ -9,7 +9,7 @@ SQL_SERVER_2022 = (16, 0, 0) -class TestSQLServerFunctionSupportBasic: +class TestFunctionSupportBasic: def test_supports_functions_returns_dict(self): dialect = SQLServerDialect(SQL_SERVER_2022) result = dialect.supports_functions() @@ -31,7 +31,7 @@ def test_core_functions_always_supported(self): assert result[func] is True, f"Core function {func} should be supported" -class TestSQLServerFunctionSupportVersionDependent: +class TestFunctionSupportVersionDependent: def test_json_functions_require_sqlserver_2016(self): json_functions = ["json_value", "json_query", "json_modify", "isjson", "openjson"] @@ -110,7 +110,7 @@ def test_datediff_big_requires_sqlserver_2016(self): assert result_new.get("datediff_big") is True -class TestSQLServerFunctionSupportPrivateMethod: +class TestFunctionSupportPrivateMethod: def test_unknown_function_returns_true(self): dialect = SQLServerDialect(SQL_SERVER_2022) result = dialect._is_sqlserver_function_supported("unknown_function_xyz") @@ -132,7 +132,7 @@ def test_version_restricted_function_above_minimum(self): assert result is True -class TestSQLServerFunctionSupportIntegration: +class TestFunctionSupportIntegration: def test_function_dict_contains_both_core_and_backend_functions(self): dialect = SQLServerDialect(SQL_SERVER_2022) result = dialect.supports_functions() diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_dialect_security.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_security.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_dialect_security.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_security.py index 0c107e0e..2d3837b0 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_dialect_security.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_security.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_dialect_security.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_security.py """ Tests for SQL Server dialect SQL injection security. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect_version_branches.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_version_branches.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect_version_branches.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_version_branches.py index 5d8fa6db..df5b4ce0 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect_version_branches.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_version_branches.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_dialect_version_branches.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dialect_version_branches.py """Version-gated dialect branch coverage, fully offline. The SQL Server dialect is instantiated at explicit versions diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/dialect/test_dql_capabilities.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dql_capabilities.py similarity index 94% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/dialect/test_dql_capabilities.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dql_capabilities.py index 89789df3..fc401673 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/dialect/test_dql_capabilities.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dql_capabilities.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/dialect/test_dql_capabilities.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_dql_capabilities.py """SQL Server DQL capability tests: WITH TIES and lock strength.""" import pytest diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_generated_column_capabilities.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_generated_column_capabilities.py similarity index 82% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_generated_column_capabilities.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_generated_column_capabilities.py index 9570c2d5..758aecf4 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_generated_column_capabilities.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_generated_column_capabilities.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_generated_column_capabilities.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_generated_column_capabilities.py """Explicit SQL Server generated/computed-column capability assertions.""" from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_identifier_quoting.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_identifier_quoting.py similarity index 94% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_identifier_quoting.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_identifier_quoting.py index 19fb6860..b759e966 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_identifier_quoting.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_identifier_quoting.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_identifier_quoting.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_identifier_quoting.py """ Tests for SQL Server identifier quoting feature. @@ -10,7 +10,7 @@ from rhosocial.activerecord.backend.warnings import IdentifierQuotingWarning -class TestSQLServerIdentifierQuoting: +class TestIdentifierQuoting: """Test SQLServerDialect format_identifier and reserved words.""" def test_format_identifier_default_bracket_quotes(self): diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_master_probes_guard_sqlserver.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_master_probe_gates.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_master_probes_guard_sqlserver.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_master_probe_gates.py index fced30b9..60afa335 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_master_probes_guard_sqlserver.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_master_probe_gates.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_master_probes_guard_sqlserver.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_master_probe_gates.py """Guard: the master probes that gate clauses SQL Server cannot spell. The round gated three previously-decorative master probes behind real call diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_protocol_conformance.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_protocol_conformance.py similarity index 95% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_protocol_conformance.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_protocol_conformance.py index 668603a9..f338c401 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_protocol_conformance.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_protocol_conformance.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_protocol_conformance.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_protocol_conformance.py """ Generic protocol conformance tests for SQLServerDialect. @@ -81,6 +81,7 @@ def _classified_keys(protocols) -> set: dialect_protocols.ColumnTypeSupport, dialect_protocols.ConstraintSupport, dialect_protocols.DataTypeSupport, + dialect_protocols.DatabaseAssignedColumnSupport, dialect_protocols.DDLTypeSupport, dialect_protocols.ExplainSupport, dialect_protocols.FilterClauseSupport, @@ -88,6 +89,7 @@ def _classified_keys(protocols) -> set: dialect_protocols.GraphSupport, dialect_protocols.ILIKESupport, dialect_protocols.IdentityColumnSupport, + dialect_protocols.IntegerAutoIncrementColumnSuggestionSupport, dialect_protocols.IntrospectionSupport, dialect_protocols.JSONSupport, dialect_protocols.JoinSupport, @@ -160,6 +162,11 @@ def _classified_keys(protocols) -> set: # ever satisfies one by accident, the negative test fails and forces a conscious # decision (move to SQLSERVER_PROTOCOLS or revert). SQLSERVER_NOT_IMPLEMENTED = [ + # --- Tracked gaps --- + # SQL Server does hold DDL inside a transaction, but SQLServerDialect has + # not exposed supports_transactional_ddl() yet, so the dialect cannot + # answer. Move it to SQLSERVER_PROTOCOLS once the probe lands. + dialect_protocols.TransactionalDDLSupport, # --- Intentional non-support --- # SQL Server has no standalone COMMENT ON statement; comments use # sp_addextendedproperty (not modelled as a COMMENT ON expression). @@ -188,7 +195,7 @@ def _classified_keys(protocols) -> set: ] -class TestSQLServerDialectProtocolConformance: +class TestDialectProtocolConformance: """Assert SQLServerDialect implements all generic protocols it declares.""" @pytest.fixture @@ -204,7 +211,7 @@ def test_implements_protocol(self, dialect, protocol): ) -class TestSQLServerDialectNegativeProtocolConformance: +class TestDialectNegativeProtocolConformance: """Assert SQLServerDialect does not implement intentionally-unsupported protocols.""" @pytest.fixture diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_protocol_support.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_protocol_support.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_protocol_support.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_protocol_support.py index 5676943a..af769191 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_protocol_support.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_protocol_support.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_protocol_support.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_protocol_support.py """ SQL Server protocol support tests. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/dialect/test_returning_output.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_returning_capabilities.py similarity index 95% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/dialect/test_returning_output.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_returning_capabilities.py index 09a2073c..5fe81ef4 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/dialect/test_returning_output.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_returning_capabilities.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/dialect/test_returning_output.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_returning_capabilities.py """SQL Server OUTPUT (RETURNING) capability and formatting tests.""" import pytest @@ -21,7 +21,7 @@ def dialect(): return SQLServerDialect(version=(16, 0, 0)) -class TestSQLServerReturningCapabilities: +class TestReturningCapabilities: def test_dml_returning_supported(self, dialect): assert dialect.supports_returning_insert() is True assert dialect.supports_returning_update() is True @@ -37,7 +37,7 @@ def test_into_supported(self, dialect): assert dialect.supports_returning_into() is True -class TestSQLServerOutputFormatting: +class TestOutputFormatting: def test_insert_default_prefix(self, dialect): clause = ReturningClause(dialect, expressions=[Column(dialect, "id")]) sql, _ = dialect.format_returning_clause(clause, default_table="INSERTED") diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_schema_support.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_schema_support.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_schema_support.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_schema_support.py index cab2cf03..b0af1d45 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_schema_support.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_schema_support.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_schema_support.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_schema_support.py """Tests for the SQL Server schema and namespace capabilities. SQL Server models named schema namespaces natively (e.g. dbo), so the dialect diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sequence_probes_sqlserver.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_sequence_probes.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sequence_probes_sqlserver.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_sequence_probes.py index fa8a899a..8ff4af25 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sequence_probes_sqlserver.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_sequence_probes.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sequence_probes_sqlserver.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_sequence_probes.py """Every SQL Server sequence option probe must be load-bearing. A capability probe is *load-bearing* when the formatter's decision follows its diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlxml_support.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_sqlxml_support.py similarity index 86% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlxml_support.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_sqlxml_support.py index ba33cf1e..8e361392 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlxml_support.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_sqlxml_support.py @@ -1,11 +1,11 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlxml_support.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/dialect/test_sqlxml_support.py """Tests for SQL Server SQL/XML standard support boundaries.""" from rhosocial.activerecord.backend.dialect.protocols import SQLXMLSupport from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect -class TestSQLServerSQLXMLSupport: +class TestSQLXMLSupport: """Test SQL Server does not claim standard SQL/XML support.""" def test_sqlserver_does_not_implement_standard_sqlxml_protocol(self): diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_driver_error_mapping.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/errors/test_driver_error_mapping.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_driver_error_mapping.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/errors/test_driver_error_mapping.py index 171be1d1..96d263fd 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_driver_error_mapping.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/errors/test_driver_error_mapping.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_driver_error_mapping.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/errors/test_driver_error_mapping.py """Unit tests for the SQL Server driver-error taxonomy mapping. No database is required: synthetic pyodbc exceptions carry the native error diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_execute_error_contract.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/errors/test_execute_error_contract.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_execute_error_contract.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/errors/test_execute_error_contract.py index 0e55ebc2..0b7aafe9 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_execute_error_contract.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/errors/test_execute_error_contract.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_execute_error_contract.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/errors/test_execute_error_contract.py """Execute error contract for the SQL Server backend, without a database. The contract under test is core's phase-specific error taxonomy: diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/explain/test_sqlserver_explain_deep.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/explain/test_sqlserver_explain_deep.py new file mode 100644 index 00000000..4341f904 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/explain/test_sqlserver_explain_deep.py @@ -0,0 +1,250 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/explain/test_sqlserver_explain_deep.py +"""Backend-local, deep EXPLAIN tests for SQL Server (construction level). + +The shared testsuite contracts only assert that EXPLAIN *can* execute. Deep +semantic interpretation cannot be generalised across backends, and SQL Server +is a special case: ``SET SHOWPLAN_*`` / ``SET STATISTICS *`` must be the only +statement in an exclusive batch, which the generic ``explain()`` execution +flow cannot guarantee. Real-DB EXPLAIN execution is therefore deliberately +avoided here (see ``feature/backend/execute/query/test_backend_explain.py``, +which tests only the result-parsing hook for the same reason). + +What this file pins down instead is everything that is *observable without a +connection*: + +* the capability gates (``supports_explain_plan`` / ``supports_explain_analyze`` + / ``supports_explain_format``) and the format matrix they advertise; +* the **exact SQL** ``format_explain_statement`` emits for every option + combination -- estimated plan (``SET SHOWPLAN_TEXT`` / ``SHOWPLAN_XML``) + versus actual plan (``SET STATISTICS PROFILE`` / ``STATISTICS XML``), + including the ``ON; ...; OFF`` bracketing of the actual-plan forms; +* that ``ExplainStatement.to_sql()`` delegates to that formatter and passes + the inner statement's parameters through unchanged. + +The statement being explained is always built with the expression system +(``QueryStatement`` / ``Column`` / ``Literal`` / predicates / ``Table``), never +from a hand-written SQL string. SQL text appears only as assertion expectations. +All rendering assertions run against several explicit server versions so the +output is proven version-invariant and no server probe ever happens. +""" + +from typing import Optional, Tuple + +import pytest + +from rhosocial.activerecord.backend.expression import ( + Column, + ComparisonPredicate, + ExplainFormat, + ExplainOptions, + ExplainStatement, + Literal, + LogicalPredicate, + QueryStatement, +) +from rhosocial.activerecord.backend.expression.objects import Table +from rhosocial.activerecord.backend.expression.query_parts import WhereClause +from rhosocial.activerecord.backend.expression.sources import NamedRelationRef +from rhosocial.activerecord.backend.impl.sqlserver.dialect import ( + SQL_SERVER_2012, + SQL_SERVER_2016, + SQL_SERVER_2019, + SQL_SERVER_2022, + SQLServerDialect, +) + +VERSIONS = { + "2008": (10, 0, 0), + "2012": SQL_SERVER_2012, + "2016": SQL_SERVER_2016, + "2019": SQL_SERVER_2019, + "2022": SQL_SERVER_2022, +} + + +@pytest.fixture(params=list(VERSIONS.values()), ids=list(VERSIONS.keys())) +def dialect(request) -> SQLServerDialect: + """An offline dialect at each supported server version (no probe, no DB).""" + return SQLServerDialect(request.param) + + +def _build_query(dialect: SQLServerDialect) -> QueryStatement: + """Build the statement to EXPLAIN entirely from expression objects. + + Two literals give the wrapper two bound parameters, so parameter + pass-through is observable without any hand-written SQL text. + """ + return QueryStatement( + dialect, + select=[Column(dialect, "id")], + from_=NamedRelationRef(dialect, Table(dialect, "users")), + where=WhereClause( + dialect, + condition=LogicalPredicate( + dialect, + "AND", + ComparisonPredicate(dialect, ">", Column(dialect, "price"), Literal(dialect, 100)), + ComparisonPredicate( + dialect, "=", Column(dialect, "name"), Literal(dialect, "alice") + ), + ), + ), + ) + + +def _render( + dialect: SQLServerDialect, options: Optional[ExplainOptions], statement=None +) -> Tuple[str, tuple]: + """Render an ExplainStatement through the dialect's public to_sql() path.""" + expr = ExplainStatement(dialect, statement=statement or _build_query(dialect), options=options) + return expr.to_sql() + + +class TestExplainCapabilityGates: + """The ``supports_explain_*`` switches SQL Server advertises.""" + + def test_supports_explain_plan(self, dialect: SQLServerDialect) -> None: + assert dialect.supports_explain_plan() is True + + def test_supports_explain_analyze(self, dialect: SQLServerDialect) -> None: + # SQL Server implements ANALYZE via STATISTICS PROFILE / STATISTICS XML. + assert dialect.supports_explain_analyze() is True + + @pytest.mark.parametrize( + ("format_name", "expected"), + [ + ("TEXT", True), + ("XML", True), + ("xml", True), # gate is case-insensitive + (ExplainFormat.TEXT, True), # enum members are str subclasses + (ExplainFormat.XML, True), + ("JSON", False), + ("YAML", False), + ("", False), + ], + ) + def test_supports_explain_format_matrix( + self, dialect: SQLServerDialect, format_name, expected + ) -> None: + assert dialect.supports_explain_format(format_name) is expected + + def test_analyze_gate_agrees_with_rendered_actual_plan(self, dialect: SQLServerDialect) -> None: + """The gate's True answer is backed by a real STATISTICS PROFILE rendering.""" + assert dialect.supports_explain_analyze() is True + sql, _ = _render(dialect, ExplainOptions(analyze=True)) + assert sql.startswith("SET STATISTICS PROFILE ON;") + + +class TestExplainStatementRendering: + """Exact SQL emitted by ``format_explain_statement`` for each option.""" + + # -- estimated plan (no ANALYZE) ------------------------------------------------- + + def test_no_options_defaults_to_showplan_text(self, dialect: SQLServerDialect) -> None: + sql, _ = _render(dialect, None) + assert sql == ( + "SET SHOWPLAN_TEXT ON; " "SELECT [id] FROM [users] WHERE [price] > ? AND [name] = ?" + ) + + def test_empty_options_default_to_showplan_text(self, dialect: SQLServerDialect) -> None: + sql, _ = _render(dialect, ExplainOptions()) + assert sql == ( + "SET SHOWPLAN_TEXT ON; " "SELECT [id] FROM [users] WHERE [price] > ? AND [name] = ?" + ) + + def test_format_text_renders_showplan_text(self, dialect: SQLServerDialect) -> None: + sql, _ = _render(dialect, ExplainOptions(format=ExplainFormat.TEXT)) + assert sql == ( + "SET SHOWPLAN_TEXT ON; " "SELECT [id] FROM [users] WHERE [price] > ? AND [name] = ?" + ) + + def test_format_xml_renders_showplan_xml_without_off(self, dialect: SQLServerDialect) -> None: + """Estimated XML plan is a single batch; no OFF toggle is emitted.""" + sql, _ = _render(dialect, ExplainOptions(format=ExplainFormat.XML)) + assert sql == ( + "SET SHOWPLAN_XML ON; " "SELECT [id] FROM [users] WHERE [price] > ? AND [name] = ?" + ) + assert "OFF" not in sql + + # -- actual plan (ANALYZE=True), with ON/OFF bracketing ------------------------- + + def test_analyze_without_format_renders_statistics_profile( + self, dialect: SQLServerDialect + ) -> None: + sql, _ = _render(dialect, ExplainOptions(analyze=True)) + assert sql == ( + "SET STATISTICS PROFILE ON; " + "SELECT [id] FROM [users] WHERE [price] > ? AND [name] = ?; " + "SET STATISTICS PROFILE OFF" + ) + + def test_analyze_text_renders_statistics_profile(self, dialect: SQLServerDialect) -> None: + """TEXT is not the XML branch, so ANALYZE falls back to PROFILE.""" + sql, _ = _render(dialect, ExplainOptions(analyze=True, format=ExplainFormat.TEXT)) + assert sql == ( + "SET STATISTICS PROFILE ON; " + "SELECT [id] FROM [users] WHERE [price] > ? AND [name] = ?; " + "SET STATISTICS PROFILE OFF" + ) + + def test_analyze_xml_renders_statistics_xml(self, dialect: SQLServerDialect) -> None: + sql, _ = _render(dialect, ExplainOptions(analyze=True, format=ExplainFormat.XML)) + assert sql == ( + "SET STATISTICS XML ON; " + "SELECT [id] FROM [users] WHERE [price] > ? AND [name] = ?; " + "SET STATISTICS XML OFF" + ) + + def test_unsupported_format_is_ignored_by_renderer(self, dialect: SQLServerDialect) -> None: + """Rendering does not validate format names; callers must use the gate.""" + assert dialect.supports_explain_format("JSON") is False + estimated, _ = _render(dialect, ExplainOptions(format=ExplainFormat.JSON)) + assert estimated == ( + "SET SHOWPLAN_TEXT ON; " "SELECT [id] FROM [users] WHERE [price] > ? AND [name] = ?" + ) + actual, _ = _render(dialect, ExplainOptions(analyze=True, format=ExplainFormat.JSON)) + assert actual == ( + "SET STATISTICS PROFILE ON; " + "SELECT [id] FROM [users] WHERE [price] > ? AND [name] = ?; " + "SET STATISTICS PROFILE OFF" + ) + + # -- delegation / parameter handling -------------------------------------------- + + @pytest.mark.parametrize( + "options", + [ + None, + ExplainOptions(), + ExplainOptions(format=ExplainFormat.XML), + ExplainOptions(analyze=True), + ExplainOptions(analyze=True, format=ExplainFormat.XML), + ], + ) + def test_inner_statement_params_pass_through(self, dialect: SQLServerDialect, options) -> None: + _, params = _render(dialect, options) + assert params == (100, "alice") + + def test_expression_built_statement_sql_is_embedded_verbatim( + self, dialect: SQLServerDialect + ) -> None: + query = _build_query(dialect) + assert query.to_sql()[0] == ("SELECT [id] FROM [users] WHERE [price] > ? AND [name] = ?") + sql, params = _render(dialect, ExplainOptions(format=ExplainFormat.XML), statement=query) + assert sql == ( + "SET SHOWPLAN_XML ON; " "SELECT [id] FROM [users] WHERE [price] > ? AND [name] = ?" + ) + assert params == (100, "alice") + + def test_to_sql_delegates_to_format_explain_statement(self, dialect: SQLServerDialect) -> None: + options = ExplainOptions(analyze=True, format=ExplainFormat.XML) + expr = ExplainStatement(dialect, statement=_build_query(dialect), options=options) + assert expr.format_method == "format_explain_statement" + direct = dialect.format_explain_statement(expr) + assert expr.to_sql() == direct + assert direct == ( + "SET STATISTICS XML ON; " + "SELECT [id] FROM [users] WHERE [price] > ? AND [name] = ?; " + "SET STATISTICS XML OFF", + (100, "alice"), + ) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/expression_parse_contract.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/expression_parse_contract.py similarity index 97% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/expression_parse_contract.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/expression_parse_contract.py index aef70419..dd43a1f1 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/expression_parse_contract.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/expression_parse_contract.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/expression_parse_contract.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/expression_parse_contract.py """The parse-vs-format round-trip sweep for typed-column contracts. Vendored from the shared testsuite's ``utils/parse_contract.py`` when that @@ -45,7 +45,7 @@ from rhosocial.activerecord.backend.expression.types import CustomType, DataType # The harness is this module's sibling, and this module is itself loaded by path -# (from ``test_sqlserver_type_protocol.py``) as well as by name (from the matrix +# (from ``test_type_protocol.py``) as well as by name (from the matrix # beside it) -- a by-name import would only work in the second case, so the # sibling is loaded by path and both callers get the same module. import importlib.util as _importlib_util diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/expression_roundtrip_harness.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/expression_roundtrip_harness.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/expression_roundtrip_harness.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/expression_roundtrip_harness.py index 11aef696..8468be39 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/expression_roundtrip_harness.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/expression_roundtrip_harness.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/expression_roundtrip_harness.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/expression_roundtrip_harness.py """ Expression serialization round-trip / contract test helpers (SQL Server-local copy). diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_expression_roundtrip_all.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/test_expression_roundtrip_all.py similarity index 97% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_expression_roundtrip_all.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/test_expression_roundtrip_all.py index 916d59a2..cc86341e 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_expression_roundtrip_all.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/test_expression_roundtrip_all.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_expression_roundtrip_all.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/test_expression_roundtrip_all.py """ Serialization and SQL coverage for every expression class SQL Server renders. @@ -109,7 +109,11 @@ import pytest -from rhosocial.activerecord.backend.dialect.exceptions import (ProtocolNotImplementedError, UnsupportedFeatureError) +from rhosocial.activerecord.backend.dialect.exceptions import ( + ProtocolNotImplementedError, + UnsupportedDataTypeError, + UnsupportedFeatureError, +) from rhosocial.activerecord.backend.expression.core import Column, Literal from rhosocial.activerecord.backend.expression.objects import ( Database, @@ -159,7 +163,7 @@ from rhosocial.activerecord.backend.expression.types.custom import CustomType from rhosocial.activerecord.backend.expression.uuid import UUIDConstantExpression # The harness is this module's sibling, and this module is itself loaded by path -# (from ``test_sqlserver_type_protocol.py``'s sweep) as well as by name (when +# (from ``test_type_protocol.py``'s sweep) as well as by name (when # pytest collects it here) -- a by-name import would only work in the second # case, so the sibling is loaded by path and both callers get one module object. import importlib.util as _importlib_util @@ -1323,7 +1327,7 @@ def shortest_path(d): # DataType carries no name to dispatch, so the refusal speaks of the # generic type it could not resolve. "rhosocial.activerecord.backend.expression.types._base.DataType": ( - TypeError, + UnsupportedDataTypeError, "does not support the generic type", ), # Core types with no SQL Server spelling (eight). SQL Server has no ARRAY, @@ -1331,25 +1335,25 @@ def shortest_path(d): # declare a generic name the dialect does not implement. This is a # capability gap in this backend's type table, not a defect in the class. "rhosocial.activerecord.backend.expression.types.array.ArrayType": ( - TypeError, _NO_SUCH_TYPE + UnsupportedDataTypeError, _NO_SUCH_TYPE ), "rhosocial.activerecord.backend.expression.types.binary.BinaryType": ( - TypeError, _NO_SUCH_TYPE + UnsupportedDataTypeError, _NO_SUCH_TYPE ), "rhosocial.activerecord.backend.expression.types.binary.VarBinaryType": ( - TypeError, _NO_SUCH_TYPE + UnsupportedDataTypeError, _NO_SUCH_TYPE ), "rhosocial.activerecord.backend.expression.types.datetime_.IntervalType": ( - TypeError, _NO_SUCH_TYPE + UnsupportedDataTypeError, _NO_SUCH_TYPE ), "rhosocial.activerecord.backend.expression.types.datetime_.TimeTzType": ( - TypeError, _NO_SUCH_TYPE + UnsupportedDataTypeError, _NO_SUCH_TYPE ), "rhosocial.activerecord.backend.expression.types.json_.JsonBType": ( - TypeError, _NO_SUCH_TYPE + UnsupportedDataTypeError, _NO_SUCH_TYPE ), "rhosocial.activerecord.backend.expression.types.uuid_.UUIDType": ( - TypeError, _NO_SUCH_TYPE + UnsupportedDataTypeError, _NO_SUCH_TYPE ), # ENUM (nine, and the ninth is this one's reason to exist): the class # constructs now that its keyword-only ``values`` gets a list from the @@ -1357,61 +1361,18 @@ def shortest_path(d): # SQL Server has no ENUM generic, and the dialect says so while # suggesting the VARCHAR it actually uses. "rhosocial.activerecord.backend.expression.types.enum_.EnumType": ( - TypeError, _NO_SUCH_TYPE - ), - # The declared-result annotations: the base and every concrete member of - # it. Each carries only the node it annotates; the alias the core's - # ``format_declared_result`` reads belongs to the concrete named - # annotations, so the guessed instance -- a bare ``Literal`` -- has none, - # and the formatter fails naming it. The core formatter reading it is the - # moving edge of the value-literal rework (a narrowed ``Literal`` no longer - # carries ``alias`` at all); these rows record what the tree actually does - # today, one per class, because the concrete annotations are collected in - # their own right and an unnamed failure is a defect by this matrix's rule. + UnsupportedDataTypeError, _NO_SUCH_TYPE + ), + # --- The abstract declared-result base still cannot render. ----------- + # The ten concrete annotations used to be pinned here because core's + # ``format_declared_result`` read ``expr.source.alias`` off a Literal that + # did not declare it. Core has since fixed that, so those classes render + # and their rows were retired; only the abstract base, whose instance shape + # the formatter still cannot read, remains. "rhosocial.activerecord.backend.expression.declared._Annotation": ( AttributeError, "has no attribute 'alias'", ), - "rhosocial.activerecord.backend.expression.declared.ArrayAnnotation": ( - AttributeError, - "has no attribute 'alias'", - ), - "rhosocial.activerecord.backend.expression.declared.BinaryAnnotation": ( - AttributeError, - "has no attribute 'alias'", - ), - "rhosocial.activerecord.backend.expression.declared.BooleanAnnotation": ( - AttributeError, - "has no attribute 'alias'", - ), - "rhosocial.activerecord.backend.expression.declared.IntegerAnnotation": ( - AttributeError, - "has no attribute 'alias'", - ), - "rhosocial.activerecord.backend.expression.declared.JSONAnnotation": ( - AttributeError, - "has no attribute 'alias'", - ), - "rhosocial.activerecord.backend.expression.declared.NumberAnnotation": ( - AttributeError, - "has no attribute 'alias'", - ), - "rhosocial.activerecord.backend.expression.declared.TemporalAnnotation": ( - AttributeError, - "has no attribute 'alias'", - ), - "rhosocial.activerecord.backend.expression.declared.TextAnnotation": ( - AttributeError, - "has no attribute 'alias'", - ), - "rhosocial.activerecord.backend.expression.declared.UUIDAnnotation": ( - AttributeError, - "has no attribute 'alias'", - ), - "rhosocial.activerecord.backend.expression.declared.XMLAnnotation": ( - AttributeError, - "has no attribute 'alias'", - ), # ---- core expressions SQL Server has no T-SQL spelling for ---- # @@ -1966,7 +1927,7 @@ def test_an_inline_position_writes_text_not_a_parameter(self, sqlserver_dialect) """The DDL position: the value reaches SQL as text and takes no bind. Each kind's *rendered* spelling is the dialect's business and is pinned - in ``test_sqlserver_typed_values.py``; what this row pins is the + in ``test_literal_values.py``; what this row pins is the position -- ``inline=True`` must give text and no parameters for every kind that has an inline form on this dialect. The ones with none are refusals rather than guesses: the non-finite floats, which no SQL text @@ -2019,7 +1980,7 @@ def test_the_position_travels_with_the_literal(self, sqlserver_dialect): assert restored.to_sql() == ("1", ()) -class TestSQLServerExpressionRoundtrip: +class TestExpressionRoundtrip: """All constructible expression classes round-trip through all encodings.""" def test_get_params_roundtrip(self, sqlserver_expr_case, sqlserver_dialect): diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_expressions.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/test_sqlserver_expressions.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_expressions.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/test_sqlserver_expressions.py index c0d4c166..ea8077b7 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_expressions.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/test_sqlserver_expressions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_expressions.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/expression/test_sqlserver_expressions.py """ Tests for SQL Server expression formatting. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_classed_function_entries.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_classed_function_entries.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_classed_function_entries.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_classed_function_entries.py index ae61deea..5bcf6708 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_classed_function_entries.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_classed_function_entries.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_classed_function_entries.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_classed_function_entries.py """The classed function entries and the bare VALUES cells (guide wave M1). Two follow-ups the core has already landed and this backend owed: diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_functions.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_function_factory_imports.py similarity index 96% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_functions.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_function_factory_imports.py index 4eaaceb8..9cfbad25 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_functions.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_function_factory_imports.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_functions.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_function_factory_imports.py """ Tests for SQL Server function factories. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_functions.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_functions.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_functions.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_functions.py index a43369da..391a2053 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_functions.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_functions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_functions.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_functions.py """ Tests for SQLServer-specific SQL function factories. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_json_functions.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_json_functions.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_json_functions.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_json_functions.py index 5ee0f048..258704fb 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_json_functions.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_json_functions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_json_functions.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/functions/test_json_functions.py """ SQL Server JSON function protocol tests. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_coverage_families.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/introspection/test_introspection_coverage_families.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_coverage_families.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/introspection/test_introspection_coverage_families.py index c246e000..6fa78712 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_coverage_families.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/introspection/test_introspection_coverage_families.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_coverage_families.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/introspection/test_introspection_coverage_families.py """Offline tests for the partitions, types and constraints families. SQL Server answers these three families from catalog views this backend did diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_sql_builders.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/introspection/test_introspection_sql_builders.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_sql_builders.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/introspection/test_introspection_sql_builders.py index 5b267e41..51d312fd 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_sql_builders.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/introspection/test_introspection_sql_builders.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_sql_builders.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/introspection/test_introspection_sql_builders.py """Offline tests for the introspection questions, and the SQL they render. Covers the injection hardening: every question is parameterized (``?`` @@ -596,7 +596,7 @@ def test_explicit_schema_is_a_parameter(self): assert params == ("sales",) -class TestParseBackendSpecificTypes: +class TestParseExtraTypes: """The parsers read the aliases the builders above project.""" @staticmethod diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/mixins/README.md b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/mixins/README.md new file mode 100644 index 00000000..88eae6b8 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/mixins/README.md @@ -0,0 +1,13 @@ +# construct/mixins + +Mixin-level formatting tests for this backend. + +Empty by design: the SQL Server backend's mixin-level formatting lives with the +feature it belongs to (`construct/dialect/` for capability probes and +`construct/statements/` for rendered SQL), and its one mixin-specific area — +T-SQL session settings (`SET DEADLOCK_PRIORITY`, `SET LANGUAGE`, +`SET DATEFORMAT`, `IDENTITY` queries) — is a backend-unique capability, so it +lives in `construct/sqlserver/session_settings/`. + +The directory stays so the construct tree has the same eleven directories in +every backend. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_backend_mixin_validation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/sqlserver/session_settings/test_session_settings.py similarity index 96% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_backend_mixin_validation.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/sqlserver/session_settings/test_session_settings.py index df5ae538..982a54c7 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_backend_mixin_validation.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/sqlserver/session_settings/test_session_settings.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_backend_mixin_validation.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/sqlserver/session_settings/test_session_settings.py """Offline tests for SQLServerBackendMixin validation and parameterization. Covers the whitelist/range validation branches of ``set_deadlock_priority``, diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_alter_table_if_exists_backend.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_alter_table_if_exists_ddl.py similarity index 91% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_alter_table_if_exists_backend.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_alter_table_if_exists_ddl.py index f36965f8..79b3ec94 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_alter_table_if_exists_backend.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_alter_table_if_exists_ddl.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_alter_table_if_exists_backend.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_alter_table_if_exists_ddl.py """Tests for SQL Server ALTER TABLE IF [NOT] EXISTS handling. SQL Server supports ``DROP COLUMN IF EXISTS`` and ``DROP CONSTRAINT @@ -24,14 +24,14 @@ def dialect(): return SQLServerDialect(version=(15, 0, 0)) -class TestSQLServerAlterTableModifierCapabilities: +class TestAlterTableModifierCapabilities: def test_supports_switches(self, dialect): assert dialect.supports_add_column_if_not_exists() is False assert dialect.supports_drop_column_if_exists() is True assert dialect.supports_drop_constraint_if_exists() is True -class TestSQLServerAddColumn: +class TestAddColumn: def test_add_column_omits_column_literal(self, dialect): action = AddColumnAction(dialect, ColumnDefinition(dialect, "content", TextType(dialect))) sql, params = action.to_sql() @@ -49,7 +49,7 @@ def test_add_column_if_not_exists_raises(self, dialect): action.to_sql() -class TestSQLServerDropColumnIfExists: +class TestDropColumnIfExists: def test_if_exists_renders_qualifier(self, dialect): action = DropColumnAction(dialect, column_name="x", if_exists=True) sql, params = action.to_sql() @@ -64,7 +64,7 @@ def test_none_renders_plain_form(self, dialect): assert params == () -class TestSQLServerDropConstraintIfExists: +class TestDropConstraintIfExists: def test_if_exists_renders_qualifier(self, dialect): action = DropTableConstraintAction( dialect, constraint_name="fk", if_exists=True diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_clause_pair_guard_sqlserver.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_clause_pair_guard.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_clause_pair_guard_sqlserver.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_clause_pair_guard.py index 1815490f..97503dba 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_clause_pair_guard_sqlserver.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_clause_pair_guard.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_clause_pair_guard_sqlserver.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_clause_pair_guard.py """Guard: every two-spelling clause pair the SQL Server dialect consumes. The rule this file enforces (the round's rules 1/2/3/4): diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_p1_coverage_features.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_p1_coverage_features.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_p1_coverage_features.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_p1_coverage_features.py index b1206bec..f48860fe 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_p1_coverage_features.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_p1_coverage_features.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_p1_coverage_features.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_p1_coverage_features.py """ SQL Server P1 coverage feature tests. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_p2_coverage_features.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_p2_coverage_features.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_p2_coverage_features.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_p2_coverage_features.py index eb03240f..ce3b82e5 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_p2_coverage_features.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_p2_coverage_features.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_p2_coverage_features.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_p2_coverage_features.py """ SQL Server P2 coverage feature tests. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_schema_diff.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_schema_diff.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_schema_diff.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_schema_diff.py index 17fe9d11..10a9fd3d 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_schema_diff.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/statements/test_schema_diff.py @@ -16,7 +16,7 @@ from rhosocial.activerecord.backend.impl.sqlserver.schema import SQLServerSchemaDiffer -class TestSQLServerSchemaDiffer: +class TestSchemaDiffer: def _make_snapshot(self, dialect_class: str, columns: Dict[str, List[IntrospectionColumnInfo]]) -> SchemaSnapshot: tables = {} diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_adapter_suggestions.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_adapter_suggestions.py new file mode 100644 index 00000000..5cf11568 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_adapter_suggestions.py @@ -0,0 +1,86 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_adapter_suggestions.py +"""Offline coverage for SQLServerBackend type-adapter suggestions. + +``get_default_adapter_suggestions`` is pure logic over the adapter registry; +exercising it needs no live server and closes a noted coverage gap in +backend_mixin (see .claude/plan/2026-08-26/coverage-restoration.md). + +The suggestion table has two levels: the framework's core defaults are the +base, and this backend merges its own pairs on top. The assertions below +therefore describe the merged result, not the backend's override list alone. +""" +import uuid +from datetime import date, datetime, time +from decimal import Decimal + +import pytest + +from rhosocial.activerecord.backend.adapters import ( + BitString, + Geometry, + MacAddress, + Multirange, + Range, + Vector, +) +from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig + +NEUTRAL_FAMILIES = (Geometry, Vector, BitString, Range, Multirange, MacAddress) + + +@pytest.fixture(scope="module") +def backend(): + config = SQLServerConnectionConfig( + host="127.0.0.1", + port=11433, + database="master", + username="sa", + password="not-used-offline", + ) + return SQLServerBackend(connection_config=config) + + +class TestDefaultAdapterSuggestions: + def test_returns_mapping_for_registered_types(self, backend): + suggestions = backend.get_default_adapter_suggestions() + for py_type in (datetime, date, time, Decimal): + assert py_type in suggestions, f"missing suggestion for {py_type}" + + def test_merged_table_keeps_core_defaults(self, backend): + """The core table is the base; the backend completes it.""" + suggestions = backend.get_default_adapter_suggestions() + for py_type in (bool, dict, list): + assert py_type in suggestions, f"core default for {py_type} was dropped" + + def test_driver_native_types_stay_unregistered(self, backend): + """int/float/str/bytes are intentionally not pre-registered.""" + suggestions = backend.get_default_adapter_suggestions() + for py_type in (int, float, str, bytes): + assert py_type not in suggestions + + def test_backend_overrides_win_over_core_defaults(self, backend): + """SQL Server's own targets replace the core defaults per type.""" + suggestions = backend.get_default_adapter_suggestions() + assert suggestions[bool][1] is bool + assert suggestions[datetime][1] is datetime + assert suggestions[Decimal][1] is Decimal + + def test_complex_types_map_to_string_storage(self, backend): + suggestions = backend.get_default_adapter_suggestions() + for py_type in (uuid.UUID, dict, list): + _, db_type = suggestions[py_type] + assert db_type is str + + def test_neutral_families_map_to_text_carriers(self, backend): + """Neutral families have no native SQL Server column; they use text.""" + suggestions = backend.get_default_adapter_suggestions() + for py_type in NEUTRAL_FAMILIES: + assert py_type in suggestions, f"missing neutral suggestion for {py_type}" + _, db_type = suggestions[py_type] + assert db_type is str + + def test_result_is_cached(self, backend): + first = backend.get_default_adapter_suggestions() + second = backend.get_default_adapter_suggestions() + assert first is second diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_adapters_offline.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_adapters.py similarity index 87% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_adapters_offline.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_adapters.py index 8368c95f..b0eb491a 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_adapters_offline.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_adapters.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_adapters_offline.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_adapters.py """Offline bidirectional conversion tests for ``impl/sqlserver/adapters.py``. Every adapter is exercised for to_database / from_database round trips, @@ -20,7 +20,6 @@ SQLServerDecimalAdapter, SQLServerHierarchyIdAdapter, SQLServerJSONAdapter, - SQLServerSpatialAdapter, SQLServerTimeAdapter, SQLServerUUIDAdapter, SQLServerXMLAdapter, @@ -47,7 +46,7 @@ def test_explicit_offset_preserved(self): assert result.tzinfo is not None and result.utcoffset().total_seconds() == 5 * 3600 + 1800 -class TestSQLServerUUIDAdapter: +class TestUUIDAdapter: @pytest.fixture def adapter(self): return SQLServerUUIDAdapter() @@ -82,7 +81,7 @@ def test_null_semantics(self, adapter): assert adapter.from_database(None) is None -class TestSQLServerDateTimeAdapter: +class TestDateTimeAdapter: @pytest.fixture def adapter(self): return SQLServerDateTimeAdapter() @@ -122,7 +121,7 @@ def test_roundtrip(self, adapter): assert (roundtripped.year, roundtripped.month, roundtripped.day) == (2026, 1, 2) -class TestSQLServerDateTimeOffsetAdapter: +class TestDateTimeOffsetAdapter: @pytest.fixture def adapter(self): return SQLServerDateTimeOffsetAdapter() @@ -154,7 +153,7 @@ def test_null_semantics(self, adapter): assert adapter.from_database(None) is None -class TestSQLServerDateAdapter: +class TestDateAdapter: @pytest.fixture def adapter(self): return SQLServerDateAdapter() @@ -186,7 +185,7 @@ def test_error_paths(self, adapter): adapter.from_database(12345) -class TestSQLServerTimeAdapter: +class TestTimeAdapter: @pytest.fixture def adapter(self): return SQLServerTimeAdapter() @@ -211,7 +210,7 @@ def test_null_and_error_paths(self, adapter): adapter.from_database(object()) -class TestSQLServerJSONAdapter: +class TestJSONAdapter: @pytest.fixture def adapter(self): return SQLServerJSONAdapter() @@ -245,7 +244,7 @@ def test_null_semantics(self, adapter): assert adapter.from_database(None) is None -class TestSQLServerXMLAdapter: +class TestXMLAdapter: @pytest.fixture def adapter(self): return SQLServerXMLAdapter() @@ -283,45 +282,7 @@ def test_dict_roundtrip_covers_nested_list_and_text_nodes(self, adapter): assert [elem.text for elem in root.findall("tag")] == ["a", "b"] -class TestSQLServerSpatialAdapter: - @pytest.fixture - def adapter(self): - return SQLServerSpatialAdapter() - - def test_point_wkt(self, adapter): - assert adapter._dict_to_wkt({"type": "Point", "coordinates": [1, 2]}) == "POINT(1 2)" - - def test_linestring_separates_pairs_with_commas(self, adapter): - assert ( - adapter._dict_to_wkt({"type": "LineString", "coordinates": [[1, 2], [3, 4]]}) - == "LINESTRING(1 2, 3 4)" - ) - - def test_polygon_wkt_single_ring(self, adapter): - ring = [[[0, 0], [0, 1], [1, 1], [0, 0]]] - assert ( - adapter._dict_to_wkt({"type": "Polygon", "coordinates": ring}) - == "POLYGON((0 0, 0 1, 1 1, 0 0))" - ) - - def test_unknown_geometry_type_raises(self, adapter): - with pytest.raises(ValueError, match="Unsupported geometry type"): - adapter._dict_to_wkt({"type": "MultiSurface"}) - - def test_str_bytes_passthrough_on_the_way_in(self, adapter): - wkt = "POINT(1 2)" - assert adapter.to_database(wkt) is wkt - assert adapter.to_database(b"WKB-BLOB") == b"WKB-BLOB" # bytes kept binary - - def test_from_database_decodes_bytes(self, adapter): - assert adapter.from_database(b"POINT(1 2)") == "POINT(1 2)" - - def test_null_semantics(self, adapter): - assert adapter.to_database(None) is None - assert adapter.from_database(None) is None - - -class TestSQLServerHierarchyIdAdapter: +class TestHierarchyIdAdapter: @pytest.fixture def adapter(self): return SQLServerHierarchyIdAdapter() @@ -342,7 +303,7 @@ def test_null_semantics(self, adapter): assert adapter.from_database(None) is None -class TestSQLServerDecimalAdapter: +class TestDecimalAdapter: @pytest.fixture def adapter(self): return SQLServerDecimalAdapter() diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_column_type.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_column_type.py similarity index 90% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_column_type.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_column_type.py index b65cb87a..4ca8bc59 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_column_type.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_column_type.py @@ -1,5 +1,5 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_column_type.py -"""SQL Server's eighteen-entry column-type table. +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_column_type.py +"""SQL Server's twenty-four-entry column-type table. Pure dialect tests -- no server, no connection. What is asserted here is the *declaration*: that the dialect composes core's @@ -29,14 +29,29 @@ from rhosocial.activerecord.backend.expression.column_types import ( ArrayColumn, BinaryColumn, + BitStringColumn, BooleanColumn, ColumnBase, + GeometryColumn, IntegerColumn, + IntervalColumn, JSONColumn, + MacAddressColumn, + MultirangeColumn, NumericColumn, + RangeColumn, StringColumn, TimestampColumn, UUIDColumn, + VectorColumn, +) +from rhosocial.activerecord.backend.adapters import ( + BitString, + Geometry, + MacAddress, + Multirange, + Range, + Vector, ) from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect from rhosocial.activerecord.backend.impl.sqlserver.mixins import ( @@ -99,7 +114,7 @@ def test_the_mixin_overrides_core(self): ) def test_every_entry_is_answered(self, dialect): - """All eighteen, by name -- an omission fails here, not at lookup.""" + """All twenty-four, by name -- an omission fails here, not at lookup.""" missing = [e for e in COMMON_TYPES if e not in dialect.suggested_column_types()] assert missing == [] @@ -161,7 +176,7 @@ class TestBaselineCells: (datetime.date, TimestampColumn), (datetime.time, TimestampColumn), (datetime.datetime, TimestampColumn), - (datetime.timedelta, NumericColumn), + (datetime.timedelta, IntervalColumn), (uuid.UUID, UUIDColumn), (enum.Enum, StringColumn), ], @@ -247,9 +262,25 @@ def test_no_entry_answers_array_column(self, dialect): table = dialect.suggested_column_types() assert [e for e, cls in table.items() if cls is ArrayColumn] == [] - def test_timedelta_is_numeric(self, dialect): - """There is no interval *type*; a span exists only as ``DATEDIFF``.""" - assert dialect.suggested_column_types()[datetime.timedelta] is NumericColumn + def test_timedelta_is_an_interval(self, dialect): + """There is no interval *type*; a span exists only as ``DATEDIFF``. + + The class names the value, so the stored count of seconds does not + make it a number, and no numeric arithmetic is promised. + """ + assert dialect.suggested_column_types()[datetime.timedelta] is IntervalColumn + + def test_the_complex_families_answer_the_core_classes(self, dialect): + table = dialect.suggested_column_types() + for entry, klass in ( + (Geometry, GeometryColumn), + (Vector, VectorColumn), + (BitString, BitStringColumn), + (Range, RangeColumn), + (Multirange, MultirangeColumn), + (MacAddress, MacAddressColumn), + ): + assert table[entry] is klass class TestColumnClassResolution: @@ -261,8 +292,8 @@ def test_dict_resolves_to_json_column_on_2019(self): def test_list_resolves_to_json_column_on_2025(self): assert resolve_column_class(SQLServerDialect(version=SQL_SERVER_2025), list) is JSONColumn - def test_timedelta_resolves_to_numeric_column(self, dialect): - assert resolve_column_class(dialect, datetime.timedelta) is NumericColumn + def test_timedelta_resolves_to_interval_column(self, dialect): + assert resolve_column_class(dialect, datetime.timedelta) is IntervalColumn def test_the_refusal_is_a_type_error(self): """``ColumnTypeResolutionError`` subclasses ``TypeError`` by design.""" @@ -369,7 +400,7 @@ def test_the_summary_table_reads_the_way_the_spec_writes_it(): "date": "TimestampColumn", "time": "TimestampColumn", "datetime": "TimestampColumn", - "timedelta": "NumericColumn", + "timedelta": "IntervalColumn", "UUID": "UUIDColumn", "dict": "JSONColumn", "list": "JSONColumn", @@ -377,6 +408,12 @@ def test_the_summary_table_reads_the_way_the_spec_writes_it(): "set": "JSONColumn", "frozenset": "JSONColumn", "Enum": "StringColumn", + "Geometry": "GeometryColumn", + "Vector": "VectorColumn", + "BitString": "BitStringColumn", + "Range": "RangeColumn", + "Multirange": "MultirangeColumn", + "MacAddress": "MacAddressColumn", } diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_data_type_parsing.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_data_type_parsing.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_data_type_parsing.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_data_type_parsing.py index adff97d4..ab879d5a 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_data_type_parsing.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_data_type_parsing.py @@ -36,7 +36,7 @@ SQL_SERVER_2022 = (16, 0, 0) -class TestSQLServerParseType: +class TestParseType: """Tests for SQL Server parse_type implementation.""" @pytest.fixture diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_get_type_adapters.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_get_type_adapters.py new file mode 100644 index 00000000..17a634e4 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_get_type_adapters.py @@ -0,0 +1,59 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_get_type_adapters.py +"""Offline coverage for ``SQLServerBackend.get_type_adapters()``. + +``get_type_adapters`` is a plain inventory over the backend's adapter registry; +exercising it needs no live server. +""" + +import pytest +from rhosocial.activerecord.backend.type_adapter import TypeAdapterCatalogProtocol + +from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig + + +def _adapter_key(adapter): + adapter_class = type(adapter) + return (adapter_class.__module__, adapter_class.__qualname__) + + +@pytest.fixture(scope="module") +def backend(): + config = SQLServerConnectionConfig( + host="127.0.0.1", + port=11433, + database="master", + username="sa", + password="not-used-offline", + ) + return SQLServerBackend(connection_config=config) + + +class TestGetTypeAdapters: + def test_backend_implements_catalog_protocol(self, backend): + assert isinstance(backend, TypeAdapterCatalogProtocol) + + def test_returns_non_empty_list(self, backend): + adapters = backend.get_type_adapters() + assert isinstance(adapters, list) + assert adapters + + def test_adapters_unique_by_class(self, backend): + keys = [_adapter_key(adapter) for adapter in backend.get_type_adapters()] + assert len(keys) == len(set(keys)) + + def test_order_is_deterministic(self, backend): + first = backend.get_type_adapters() + second = backend.get_type_adapters() + assert [_adapter_key(adapter) for adapter in first] == [ + _adapter_key(adapter) for adapter in second + ] + + def test_returns_new_list_each_call(self, backend): + first = backend.get_type_adapters() + second = backend.get_type_adapters() + assert first is not second + + def test_default_adapter_suggestions_still_available(self, backend): + assert callable(backend.get_default_adapter_suggestions) + assert backend.get_default_adapter_suggestions() diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_sqlserver_typed_values.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_literal_values.py similarity index 96% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_sqlserver_typed_values.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_literal_values.py index 84c3c68f..00b1b322 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_sqlserver_typed_values.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_literal_values.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_sqlserver_typed_values.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_literal_values.py """The value literals on SQL Server: bindings and spellings. One ``Literal`` class carries every value now, and the only question it owns @@ -23,7 +23,7 @@ The live half of the spelling question -- do the servers accept this text and hand the same value back -- lives with the scenario-driven integration tests, -in ``feature/backend/test_literal_default_execution.py``: an expression test +in ``feature/backend/execute/ddl_column/test_literal_default_execution.py``: an expression test takes no real connection. That file records what was written and that no reachable server has confirmed it yet. """ diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_set_type.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_set_type.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_set_type.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_set_type.py index 0cb4dd81..73bcb53b 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_set_type.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_set_type.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_set_type.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_set_type.py """ SQL Server SET type approximation tests. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_spatial_types.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_spatial_types.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_spatial_types.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_spatial_types.py index eaa886bc..206f5eb0 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_spatial_types.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_spatial_types.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_spatial_types.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_spatial_types.py """ SQL Server spatial data type support tests. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_sqlserver_data_type_protocol_contract.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_sqlserver_data_type_protocol_contract.py new file mode 100644 index 00000000..0f0d1e62 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_sqlserver_data_type_protocol_contract.py @@ -0,0 +1,112 @@ +# tests/.../test_sqlserver_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.sqlserver.dialect import SQLServerDialect + +#: Versions spanning the gates this backend declares. +VERSIONS = [(14, 0, 1000), (16, 0, 1000)] + + +def _dialect(version): + return SQLServerDialect(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_sqlserver_test/feature/backend/test_sqlserver_type_protocol.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_type_protocol.py similarity index 97% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_type_protocol.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_type_protocol.py index 5b578e59..8fcf18b5 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_type_protocol.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_type_protocol.py @@ -1,10 +1,10 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_type_protocol.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_type_protocol.py """Tests for the SQL Server backend data-type protocol compliance. Covers: - format/supports 1:1 correspondence - supports_data_types() includes sqlserver_* + core entries, on a cold import -- suggested_data_types() returns classes, keys disjoint from supported, and +- substitute_data_types() returns classes, keys disjoint from supported, and every suggested class is a type this dialect really renders (D9) - spelling gates: the default spelling always renders, an unknown one is refused and named @@ -208,26 +208,26 @@ class itself first, which is how the defect survived. So this runs in class TestSuggestedDataTypes: - """suggested_data_types() returns classes, keys disjoint from supported.""" + """substitute_data_types() returns classes, keys disjoint from supported.""" @pytest.fixture def dialect(self): return SQLServerDialect(SQL_SERVER_2022) def test_returns_dict(self, dialect): - result = dialect.suggested_data_types() + result = dialect.substitute_data_types() assert isinstance(result, dict) def test_values_are_type_classes(self, dialect): - suggested = dialect.suggested_data_types() + suggested = dialect.substitute_data_types() for name, cls in suggested.items(): assert isinstance(cls, type) and issubclass(cls, DataType), ( - f"suggested_data_types()[{name!r}] = {cls!r} is not a DataType class" + f"substitute_data_types()[{name!r}] = {cls!r} is not a DataType class" ) def test_keys_disjoint_from_supported(self, 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"Keys appear in both supports and suggested: {overlap}" @@ -243,20 +243,20 @@ def test_every_substitute_is_a_type_this_dialect_renders(self, dialect): and that has to be a thing this backend stores. """ supported = dialect.supports_data_types() - suggested = dialect.suggested_data_types() + suggested = dialect.substitute_data_types() for key, substitute in sorted(suggested.items()): assert substitute.name in supported, ( - f"suggested_data_types()[{key!r}] is {substitute.__name__}, " + f"substitute_data_types()[{key!r}] is {substitute.__name__}, " f"whose name {substitute.name!r} this dialect does not render" ) def test_suggests_unsupported_core_types(self, dialect): - suggested = dialect.suggested_data_types() + suggested = dialect.substitute_data_types() # Concepts SQL Server has no T-SQL word for. for name in ["uuid", "interval", "array", "enum", "jsonb", "timetz", "binary", "varbinary"]: assert name in suggested, ( - f"Expected suggestion for {name!r} in suggested_data_types()" + f"Expected suggestion for {name!r} in substitute_data_types()" ) def test_does_not_suggest_what_it_renders(self, dialect): @@ -265,7 +265,7 @@ def test_does_not_suggest_what_it_renders(self, dialect): Substituting text for ``xml`` or a zoneless ``DATETIME2`` for ``timestamptz`` would describe a backend that is not this one. """ - suggested = dialect.suggested_data_types() + suggested = dialect.substitute_data_types() for name in ("xml", "timestamptz"): assert name not in suggested, ( f"{name!r} is rendered natively on SQL Server " @@ -282,12 +282,12 @@ def test_uuid_substitute_is_the_backend_class_not_the_core_one(self, dialect): followed. Pointing at ``SQLServerUniqueIdentifierType`` is the answer D9 asks for: a class whose own ``name`` *is* in ``supports_data_types()``. """ - assert dialect.suggested_data_types()["uuid"] is SQLServerUniqueIdentifierType + assert dialect.substitute_data_types()["uuid"] is SQLServerUniqueIdentifierType def test_jsonb_substitute_is_json_because_sql_server_has_one_json(self, dialect): """``jsonb`` is PostgreSQL's binary JSON; SQL Server has no such split.""" - assert dialect.suggested_data_types()["jsonb"] is JsonType - assert dialect.suggested_data_types()["array"] is JsonType + assert dialect.substitute_data_types()["jsonb"] is JsonType + assert dialect.substitute_data_types()["array"] is JsonType class TestSpellingGates: @@ -368,7 +368,7 @@ def test_timestamptz_is_version_gated(self): assert SQLServerDialect(SQL_SERVER_2022).supports_data_type_timestamptz() is True -class TestSQLServerTypeSupportProtocol: +class TestTypeSupportProtocol: """The stated shape of the backend's own type family.""" def test_dialect_implements_the_family(self): @@ -859,12 +859,14 @@ def test_no_integer_formatter_drops_the_flag_silently(self, dialect, name): def test_the_backend_class_pins_the_flag_so_it_cannot_be_flipped(self, dialect): """``SQLServerTinyIntType`` owns the unsigned 8-bit column. - It pins ``unsigned=True`` in its own ``__init__``, so its formatter - cannot be reached with ``unsigned=False`` and has nothing to refuse — - which is why the gate sits on the generic concept instead. + It keeps ``unsigned`` in ``PARAMETERS`` -- so ``identity()`` records it + and a comparison against a signed concept differs -- and accepts the + keyword, because a declared tuple must name an argument the constructor + really takes. The value stays pinned: ``False`` is refused by name + rather than quietly rendered as a type T-SQL does not have. """ assert SQLServerTinyIntType.PARAMETERS == ("unsigned",) - with pytest.raises(TypeError): + with pytest.raises(ValueError, match="is unsigned"): SQLServerTinyIntType(dialect, unsigned=False) assert dialect.format_data_type(SQLServerTinyIntType(dialect)) == ( "TINYINT", () @@ -1607,7 +1609,9 @@ def registry(self): import importlib.util from pathlib import Path - path = Path(__file__).parent / "expression" / "test_expression_roundtrip_all.py" + path = ( + Path(__file__).parents[1] / "expression" / "test_expression_roundtrip_all.py" + ) spec = importlib.util.spec_from_file_location("sqlserver_rt_registry", path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) @@ -1627,7 +1631,7 @@ def test_every_rendered_type_parses_back_coherently(self, registry): from pathlib import Path contract_path = ( - Path(__file__).parent / "expression" / "expression_parse_contract.py" + Path(__file__).parents[1] / "expression" / "expression_parse_contract.py" ) spec = importlib.util.spec_from_file_location( "sqlserver_parse_contract", contract_path diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/sqlserver/test_uuid_and_json_truth.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_uuid_and_json_truth.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/sqlserver/test_uuid_and_json_truth.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_uuid_and_json_truth.py index 1e5616cc..b921391e 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/sqlserver/test_uuid_and_json_truth.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_uuid_and_json_truth.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/sqlserver/test_uuid_and_json_truth.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/construct/types/test_uuid_and_json_truth.py """UUID values and JSON honesty on SQL Server. Three things this backend got wrong, all of the same shape: a probe or a @@ -100,7 +100,7 @@ def test_type_name_is_namespaced_to_this_backend(): def test_suggestion_does_not_point_at_a_type_this_dialect_renders(): """A suggestion exists precisely for types the dialect cannot render.""" dialect = _dialect() - suggestions = dialect.suggested_data_types() + suggestions = dialect.substitute_data_types() assert suggestions["uuid"] is SQLServerUniqueIdentifierType assert suggestions["uuid"].name != "uuid" diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/errors/test_error_taxonomy_contract.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/errors/test_error_taxonomy_contract.py deleted file mode 100644 index e6505864..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/errors/test_error_taxonomy_contract.py +++ /dev/null @@ -1,2 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/errors/test_error_taxonomy_contract.py -from rhosocial.activerecord.testsuite.feature.backend.errors.test_error_taxonomy import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/conftest.py new file mode 100644 index 00000000..7f998041 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_blackbox.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/test_cli_blackbox.py similarity index 95% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_blackbox.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/test_cli_blackbox.py index f1f6e99d..0d2bdd91 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_blackbox.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/test_cli_blackbox.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_test/feature/backend/cli/test_cli_blackbox.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/test_cli_blackbox.py """Black-box CLI tests for the SQL Server backend. Live server scenarios (127.0.0.1:11433-11435) may be unavailable in the @@ -14,7 +14,7 @@ import pytest from rhosocial.activerecord.backend.impl.sqlserver.__main__ import main -from providers.scenarios import get_scenario_raw +from support.sqlserver import get_scenario_raw COMMANDS = [ "info", "query", "introspect", "status", diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_introspect_live.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/test_cli_introspect_live.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_introspect_live.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/test_cli_introspect_live.py index 2b6b8ab2..5080f403 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_introspect_live.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/test_cli_introspect_live.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/cli/test_cli_introspect_live.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/test_cli_introspect_live.py """The ``introspect`` subcommand against a live SQL Server. The offline suite in ``test_cli_introspect.py`` proves the dispatch -- which @@ -20,7 +20,7 @@ from rhosocial.activerecord.backend.impl.sqlserver.__main__ import main -from tests.rhosocial.activerecord_sqlserver_test.feature.backend.introspection_probe import ( +from tests.rhosocial.activerecord_sqlserver_test.feature.backend.execute.introspection.introspection_probe import ( PROBE_DESCRIPTION, PROBE_FUNCTION, PROBE_PROCEDURE, diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/test_cli_live.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/test_cli_live.py new file mode 100644 index 00000000..7566b08a --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/test_cli_live.py @@ -0,0 +1,87 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/cli/test_cli_live.py +"""Real-database CLI integration tests for the SQL Server backend. + +The offline suite under ``feature/backend/construct/cli`` proves command +dispatch with fakes; this module drives ``main()`` against the very server the +backend fixtures connect to. ``introspect`` is already covered end to end by +``test_cli_introspect_live.py``; here we cover the remaining database-backed +commands: ``info``, ``query`` and ``status``. + +Every assertion below reads the CLI's own JSON output after ``main()`` opened +a real connection -- there are no mocks. The ``sqlserver_backend_single`` +fixture skips when no scenario/server is available, so these cases only truly +run where a live SQL Server is present (CI). +""" + +import json + +from rhosocial.activerecord.backend.impl.sqlserver.__main__ import main + + +def _connection_argv(config): + """Connection flags for the scenario the fixture connected with.""" + return [ + "--host", + config.host, + "--port", + str(config.port), + "--database", + config.database, + "--user", + config.username, + "--password", + config.password or "", + "--driver", + config.driver, + ] + + +class TestInfoLiveCli: + """``info -o json`` -- with ``--database``, it introspects the live server.""" + + def test_info_reports_the_connected_server(self, sqlserver_backend_single, capsys): + main(["info", "-o", "json", *_connection_argv(sqlserver_backend_single.config)]) + payload = json.loads(capsys.readouterr().out) + assert isinstance(payload, dict) + assert payload["database"]["type"] == "sqlserver" + assert payload["database"]["version"] + assert isinstance(payload["protocols"], dict) and payload["protocols"] + # ``--database`` sends info down its connect-and-introspect path; a + # mocked/faked run would leave this False, so it marks the live path. + assert payload["database"]["connected"] is True + + +class TestQueryLiveCli: + """``query -o json`` executes SQL on the live server.""" + + def test_query_select_one(self, sqlserver_backend_single, capsys): + main( + [ + "query", + "SELECT 1 AS n", + "-o", + "json", + *_connection_argv(sqlserver_backend_single.config), + ] + ) + payload = json.loads(capsys.readouterr().out) + assert isinstance(payload, list) and len(payload) == 1 + assert payload[0]["n"] == 1 + + +class TestStatusLiveCli: + """``status`` answers both the overview and a single category from the server.""" + + def test_status_all(self, sqlserver_backend_single, capsys): + main(["status", "all", "-o", "json", *_connection_argv(sqlserver_backend_single.config)]) + payload = json.loads(capsys.readouterr().out) + assert isinstance(payload, dict) and payload + assert payload["server_version"] + assert payload["server_vendor"] + assert "configuration" in payload + + def test_status_config(self, sqlserver_backend_single, capsys): + main(["status", "config", "-o", "json", *_connection_argv(sqlserver_backend_single.config)]) + payload = json.loads(capsys.readouterr().out) + assert isinstance(payload, list) and payload + assert all(row["name"] for row in payload) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/concurrency/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/concurrency/conftest.py new file mode 100644 index 00000000..8d95b25c --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/concurrency/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/concurrency/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_concurrency.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/concurrency/test_async_concurrency.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_concurrency.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/concurrency/test_async_concurrency.py index ffac6d48..5e3d9744 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_concurrency.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/concurrency/test_async_concurrency.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_concurrency.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/concurrency/test_async_concurrency.py """ Async Concurrency Tests for asyncio.create_task Scenarios @@ -45,6 +45,8 @@ class ConcurrentUser(AsyncActiveRecord): def table_name(cls): return "concurrent_users" + __primary_key__ = "id" + c: ClassVar[FieldProxy] = FieldProxy() id: Optional[int] = None @@ -60,6 +62,8 @@ class ConcurrentTask(AsyncActiveRecord): def table_name(cls): return "concurrent_tasks" + __primary_key__ = "id" + c: ClassVar[FieldProxy] = FieldProxy() id: Optional[int] = None @@ -279,6 +283,8 @@ class WorkerUser(AsyncActiveRecord): def table_name(cls): return "concurrent_users" + __primary_key__ = "id" + c: ClassVar[FieldProxy] = FieldProxy() id: Optional[int] = None username: str @@ -373,6 +379,8 @@ class TxUser(AsyncActiveRecord): def table_name(cls): return "concurrent_users" + __primary_key__ = "id" + c: ClassVar[FieldProxy] = FieldProxy() id: Optional[int] = None username: str @@ -483,6 +491,8 @@ class SharedUser(AsyncActiveRecord): def table_name(cls): return "concurrent_users" + __primary_key__ = "id" + c: ClassVar[FieldProxy] = FieldProxy() id: Optional[int] = None username: str @@ -515,6 +525,8 @@ class ConcurrentUser(AsyncActiveRecord): def table_name(cls): return "concurrent_users" + __primary_key__ = "id" + c: ClassVar[FieldProxy] = FieldProxy() id: Optional[int] = None username: str @@ -601,6 +613,8 @@ class SafeUser(AsyncActiveRecord): def table_name(cls): return "concurrent_users" + __primary_key__ = "id" + c: ClassVar[FieldProxy] = FieldProxy() id: Optional[int] = None username: str diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_concurrency_protocol.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/concurrency/test_concurrency_protocol.py similarity index 96% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_concurrency_protocol.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/concurrency/test_concurrency_protocol.py index ff8641a7..f96266fe 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_concurrency_protocol.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/concurrency/test_concurrency_protocol.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_concurrency_protocol.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/concurrency/test_concurrency_protocol.py """ Test for ConcurrencyAware protocol implementation in SQL Server backend. @@ -15,7 +15,7 @@ from rhosocial.activerecord.backend.protocols import ConcurrencyAware, ConcurrencyHint -class TestSQLServerConcurrencyAware: +class TestConcurrencyAware: """Test ConcurrencyAware protocol implementation for SQL Server backend.""" def test_sqlserver_backend_implements_protocol(self, sqlserver_backend_single): @@ -48,7 +48,7 @@ def test_sqlserver_concurrency_hint_available_after_connect(self, sqlserver_back assert hint is None or isinstance(hint, ConcurrencyHint) -class TestAsyncSQLServerConcurrencyAware: +class TestAsyncConcurrencyAware: """Test ConcurrencyAware protocol implementation for async SQL Server backend.""" @pytest.fixture(autouse=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/connection/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/connection/conftest.py new file mode 100644 index 00000000..cdc81e47 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/connection/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/connection/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_backend.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/connection/test_backend.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_backend.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/connection/test_backend.py index e00e4fbd..0c058509 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_backend.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/connection/test_backend.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_backend.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/connection/test_backend.py """ SQL Server backend tests using real database connection. @@ -9,7 +9,7 @@ import pytest_asyncio -class TestSQLServerBackend: +class TestBackend: """Synchronous tests for SQL Server backend.""" def test_connection(self, sqlserver_backend_single): @@ -163,7 +163,7 @@ def test_dialect_property(self, sqlserver_backend_single): assert isinstance(sqlserver_backend_single.dialect, SQLServerDialect) -class TestAsyncSQLServerBackend: +class TestAsyncBackend: """Asynchronous tests for SQL Server backend.""" @pytest.mark.asyncio diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_connection_resilience.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/connection/test_connection_resilience.py similarity index 100% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_connection_resilience.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/connection/test_connection_resilience.py diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_execution_options.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/connection/test_execution_options.py similarity index 100% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_execution_options.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/connection/test_execution_options.py diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/conftest.py new file mode 100644 index 00000000..8cca2cfe --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_column_mapping_backend.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_async_column_mapping_backend.py similarity index 97% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_column_mapping_backend.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_async_column_mapping_backend.py index 0543af6d..d78a2ecc 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_column_mapping_backend.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_async_column_mapping_backend.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_column_mapping_backend.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_async_column_mapping_backend.py import pytest import pytest_asyncio from datetime import datetime diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_crud_backend.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_async_crud_backend.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_crud_backend.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_async_crud_backend.py index b7d57539..dd46995d 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_crud_backend.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_async_crud_backend.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_crud_backend.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_async_crud_backend.py """ SQL Server async CRUD backend tests. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_column_mapping_backend.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_column_mapping_backend.py similarity index 97% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_column_mapping_backend.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_column_mapping_backend.py index 8095abfa..0a848974 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_column_mapping_backend.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_column_mapping_backend.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_column_mapping_backend.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_column_mapping_backend.py import pytest from datetime import datetime import uuid diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_crud_backend.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_crud_backend.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_crud_backend.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_crud_backend.py index 3b859861..3df952b2 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_crud_backend.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_crud_backend.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_crud_backend.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/crud/test_crud_backend.py """ SQL Server backend CRUD tests using real database connection. @@ -10,7 +10,7 @@ from decimal import Decimal -class TestMySQLCRUDBackend: +class TestCRUD: """Synchronous CRUD tests for SQL Server backend.""" @pytest.fixture @@ -124,7 +124,7 @@ def test_fetch_none(self, sqlserver_backend, test_table): assert row is None -class TestAsyncMySQLCRUDBackend: +class TestAsyncCRUD: """Asynchronous CRUD tests for SQL Server backend.""" @pytest_asyncio.fixture diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_column/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_column/conftest.py new file mode 100644 index 00000000..7bdb7c24 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_column/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_column/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_literal_default_execution.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_column/test_literal_default_execution.py similarity index 96% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_literal_default_execution.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_column/test_literal_default_execution.py index adf54c71..70b07be9 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_literal_default_execution.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_column/test_literal_default_execution.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_literal_default_execution.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_column/test_literal_default_execution.py """Live confirmation that the dialect's DDL literals really execute. The expression area asserts *what text the dialect writes*; this file asserts diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_constraint/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_constraint/conftest.py new file mode 100644 index 00000000..55865ebd --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_constraint/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_constraint/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_index/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_index/conftest.py new file mode 100644 index 00000000..31c686ef --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_index/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_index/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_table/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_table/conftest.py new file mode 100644 index 00000000..d3a77899 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_table/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_table/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_ddl_features.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_table/test_ddl_features.py similarity index 97% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_ddl_features.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_table/test_ddl_features.py index fd45b680..f38a4cee 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_ddl_features.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_table/test_ddl_features.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_ddl_features.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_table/test_ddl_features.py """ SQL Server DDL features tests. @@ -12,7 +12,7 @@ from decimal import Decimal -class TestSQLServerDDLFeatures: +class TestDDLFeatures: """Tests for SQL Server DDL features.""" @pytest.fixture diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_view/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_view/conftest.py new file mode 100644 index 00000000..429f6bed --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_view/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/ddl_view/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/dml_insert/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/dml_insert/conftest.py new file mode 100644 index 00000000..bb30d3f4 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/dml_insert/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/dml_insert/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_execute_many.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/dml_insert/test_execute_many.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_execute_many.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/dml_insert/test_execute_many.py index c41b86dc..904c0ec7 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_execute_many.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/dml_insert/test_execute_many.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_execute_many.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/dml_insert/test_execute_many.py """ SQL Server execute_many tests for batch operations. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/dml_update_delete/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/dml_update_delete/conftest.py new file mode 100644 index 00000000..fd97faf2 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/dml_update_delete/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/dml_update_delete/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/errors/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/errors/conftest.py new file mode 100644 index 00000000..466e8de4 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/errors/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/errors/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_error_handling.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/errors/test_async_error_handling.py similarity index 100% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_error_handling.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/errors/test_async_error_handling.py diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/fulltext_spatial/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/fulltext_spatial/conftest.py new file mode 100644 index 00000000..fbea4400 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/fulltext_spatial/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/fulltext_spatial/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_spatial_types_backend.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/fulltext_spatial/test_spatial_types_backend.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_spatial_types_backend.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/fulltext_spatial/test_spatial_types_backend.py index cefe25ef..8150bf8a 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_spatial_types_backend.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/fulltext_spatial/test_spatial_types_backend.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_spatial_types_backend.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/fulltext_spatial/test_spatial_types_backend.py """ SQL Server spatial data type integration tests using real database connection. @@ -19,7 +19,7 @@ ) -class TestSQLServerSpatialTypeBackend: +class TestSpatialTypeBackend: """Synchronous tests for SQL Server spatial types with real database.""" def test_supports_spatial_type_detection(self, sqlserver_backend): @@ -265,7 +265,7 @@ def test_format_create_spatial_index(self, sqlserver_backend): sqlserver_backend.execute("DROP TABLE IF EXISTS #test_spatial_idx") -class TestAsyncSQLServerSpatialTypeBackend: +class TestAsyncSpatialTypeBackend: """Asynchronous tests for SQL Server spatial types with real database.""" @pytest.mark.asyncio diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/functions/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/functions/conftest.py new file mode 100644 index 00000000..1eb94925 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/functions/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/functions/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_niladic_functions.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/functions/test_niladic_functions.py similarity index 90% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_niladic_functions.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/functions/test_niladic_functions.py index 09788b58..b3c16eea 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_niladic_functions.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/functions/test_niladic_functions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_niladic_functions.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/functions/test_niladic_functions.py """ SQL Server niladic function integration tests. @@ -13,6 +13,7 @@ These tests verify the rendered SQL and execute it against a real database in both DDL DEFAULT and SELECT contexts. """ +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 import pytest from rhosocial.activerecord.backend.expression import ( @@ -42,7 +43,7 @@ DQL_OPTIONS = ExecutionOptions(stmt_type=StatementType.DQL) -class TestSQLServerNiladicSelectContext: +class TestNiladicSelectContext: """Test niladic functions in SELECT context against real SQL Server.""" def test_select_current_timestamp_niladic(self, sqlserver_backend): @@ -107,7 +108,7 @@ def test_select_now(self, sqlserver_backend): assert len(result.data) == 1 -class TestSQLServerNiladicDDLContext: +class TestNiladicDDLContext: """Test niladic functions in DDL DEFAULT context against real SQL Server.""" def test_ddl_default_current_timestamp_niladic(self, sqlserver_backend): @@ -124,12 +125,12 @@ def test_ddl_default_current_timestamp_niladic(self, sqlserver_backend): dialect=dialect, table=Table(dialect, table_name), columns=[ - ColumnDefinition(dialect, 'id', IntegerType(dialect), constraints=[ + ColumnDefinition(dialect, 'id', auto_increment_parts(dialect, IntegerType(dialect))[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), - ]), + ], attributes=auto_increment_parts(dialect, IntegerType(dialect))[1]), ColumnDefinition(dialect, 'ts', TimestampType(dialect), constraints=[ ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, current_timestamp(dialect))), ]), @@ -165,12 +166,12 @@ def test_ddl_default_sysdatetime(self, sqlserver_backend): dialect=dialect, table=Table(dialect, table_name), columns=[ - ColumnDefinition(dialect, 'id', IntegerType(dialect), constraints=[ + ColumnDefinition(dialect, 'id', auto_increment_parts(dialect, IntegerType(dialect))[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), - ]), + ], attributes=auto_increment_parts(dialect, IntegerType(dialect))[1]), ColumnDefinition(dialect, 'ts', TimestampType(dialect, precision=6), constraints=[ ColumnConstraint( dialect, @@ -197,7 +198,7 @@ def test_ddl_default_sysdatetime(self, sqlserver_backend): ).to_sql()) -class TestAsyncSQLServerNiladicSelectContext: +class TestAsyncNiladicSelectContext: """Async niladic function tests in SELECT context against real SQL Server.""" @pytest.mark.asyncio @@ -214,7 +215,7 @@ async def test_async_select_current_timestamp_niladic(self, async_sqlserver_back assert len(result.data) == 1 -class TestAsyncSQLServerNiladicDDLContext: +class TestAsyncNiladicDDLContext: """Async niladic function tests in DDL DEFAULT context against real SQL Server.""" @pytest.mark.asyncio @@ -232,12 +233,12 @@ async def test_async_ddl_default_current_timestamp_niladic(self, async_sqlserver dialect=dialect, table=Table(dialect, table_name), columns=[ - ColumnDefinition(dialect, 'id', IntegerType(dialect), constraints=[ + ColumnDefinition(dialect, 'id', auto_increment_parts(dialect, IntegerType(dialect))[0], constraints=[ ColumnConstraint( dialect, - branch=ColumnPrimaryKeyConstraint(dialect, is_auto_increment=True), + branch=ColumnPrimaryKeyConstraint(dialect), ), - ]), + ], attributes=auto_increment_parts(dialect, IntegerType(dialect))[1]), ColumnDefinition(dialect, 'ts', TimestampType(dialect), constraints=[ ColumnConstraint(dialect, branch=ColumnDefaultConstraint(dialect, current_timestamp(dialect))), ]), diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_seconds_between.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/functions/test_seconds_between.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_seconds_between.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/functions/test_seconds_between.py index 175c6e81..32bd5475 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_seconds_between.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/functions/test_seconds_between.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/expression/test_seconds_between.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/functions/test_seconds_between.py """``seconds_between`` on SQL Server: ``DATEDIFF_BIG`` milliseconds over 1000. The node answers a question -- the signed, fractional distance from one instant diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/conftest.py new file mode 100644 index 00000000..94005e62 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/introspection_probe.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/introspection_probe.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/introspection_probe.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/introspection_probe.py index 00ec8f3a..f00a4cb7 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/introspection_probe.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/introspection_probe.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/introspection_probe.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/introspection_probe.py """Schema objects the live introspection tests share. Both the CLI test and the introspector test need a table, a view, a diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_data_profile.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_introspection_data_profile.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_data_profile.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_introspection_data_profile.py index 3ea0bfac..8e5a7bb7 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_data_profile.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_introspection_data_profile.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_data_profile.py +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/backend/test_introspection_backend_specific.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_introspection_extended_families.py similarity index 96% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_backend_specific.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_introspection_extended_families.py index a6bc6df5..30c8fc69 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_backend_specific.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_introspection_extended_families.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_introspection_backend_specific.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_introspection_extended_families.py """Live tests for the questions core has no shape for. Core's introspector models what every backend has (databases, tables, @@ -19,7 +19,7 @@ import pytest from decimal import Decimal -from tests.rhosocial.activerecord_sqlserver_test.feature.backend.introspection_probe import ( +from tests.rhosocial.activerecord_sqlserver_test.feature.backend.execute.introspection.introspection_probe import ( PROBE_DESCRIPTION, PROBE_FUNCTION, PROBE_PROCEDURE, @@ -109,7 +109,7 @@ def assert_extended_properties(properties): assert prop.minor_id == 0 -class TestSyncBackendSpecific: +class TestExtendedFamilies: def test_list_schemas(self, probed_backend): assert_schemas(probed_backend.introspector.list_schemas()) @@ -144,7 +144,7 @@ def test_extended_properties_schema_only_narrows_objects(self, probed_backend): ) -class TestAsyncBackendSpecific: +class TestAsyncExtendedFamilies: async def test_list_schemas(self, probed_async_backend): assert_schemas(await probed_async_backend.introspector.list_schemas()) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_status_introspector_async_offline.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_status_introspector_async_offline.py new file mode 100644 index 00000000..b2e5a9de --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_status_introspector_async_offline.py @@ -0,0 +1,373 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_status_introspector_async_offline.py +"""Offline unit tests for the asynchronous SQL Server status introspector. + +SQL Server has a native async driver, so its async paths must be covered just +like the synchronous ones. Every test here mocks the async I/O boundary with +``AsyncMock`` and uses a real dialect offline: no server connection is made. +""" +from contextlib import ExitStack +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect +from rhosocial.activerecord.backend.impl.sqlserver.introspection.status_introspector import ( + AsyncSQLServerStatusIntrospector, +) +from rhosocial.activerecord.backend.introspection.status import ( + ConnectionInfo, + DatabaseBriefInfo, + ServerOverview, + SessionInfo, + StatusCategory, + StatusItem, + StorageInfo, + UserInfo, +) + + +def make_async_introspector(version=(16, 0, 0)): + """Build an async introspector over a mock backend with a real (offline) dialect.""" + backend = MagicMock() + backend.dialect = SQLServerDialect(version=version) + return AsyncSQLServerStatusIntrospector(backend=backend) + + +class TestAsyncStatusIntrospectorHelpers: + """The shared, non-I/O helpers are inherited by the async introspector too.""" + + def test_inherited_helpers_vendor_and_parse_value(self): + introspector = make_async_introspector() + assert introspector._get_vendor_name() == "SQL Server" + assert introspector._parse_value("4096") == 4096 + assert introspector._parse_value("n/a") == "n/a" + + def test_inherited_create_status_item(self): + item = make_async_introspector()._create_status_item( + name="Batch Requests/sec", value="4096", category=StatusCategory.PERFORMANCE, + ) + assert isinstance(item, StatusItem) + assert item.value == 4096 + assert item.category == StatusCategory.PERFORMANCE + assert item.is_readonly is True + assert item.is_dynamic is False + + +class TestAsyncStatusIntrospectorExecution: + """The async cursor-reading primitives, with a mocked cursor.""" + + async def test_execute_query_returns_rows_and_closes_cursor(self): + introspector = make_async_introspector() + cursor = MagicMock() + cursor.fetchall.return_value = [("16.0.1000.6",)] + introspector._backend._get_cursor.return_value = cursor + + rows = await introspector._execute_query("SELECT 1") + + assert rows == [("16.0.1000.6",)] + cursor.execute.assert_called_once_with("SELECT 1") + cursor.fetchall.assert_called_once_with() + cursor.close.assert_called_once_with() + + async def test_execute_query_closes_cursor_on_error(self): + introspector = make_async_introspector() + cursor = MagicMock() + cursor.execute.side_effect = RuntimeError("boom") + introspector._backend._get_cursor.return_value = cursor + + with pytest.raises(RuntimeError, match="boom"): + await introspector._execute_query("SELECT bad") + cursor.close.assert_called_once_with() + + async def test_execute_query_dict_lowercases_column_names(self): + introspector = make_async_introspector() + cursor = MagicMock() + cursor.description = [("Name",), ("Value_In_Use",)] + cursor.fetchall.return_value = [("max connections", "100")] + introspector._backend._get_cursor.return_value = cursor + + rows = await introspector._execute_query_dict("SELECT name, value_in_use FROM sys.configurations") + + assert rows == [{"name": "max connections", "value_in_use": "100"}] + cursor.close.assert_called_once_with() + + async def test_execute_query_dict_closes_cursor_on_error(self): + introspector = make_async_introspector() + cursor = MagicMock() + cursor.description = [("Name",)] + cursor.fetchall.side_effect = RuntimeError("boom") + introspector._backend._get_cursor.return_value = cursor + + with pytest.raises(RuntimeError, match="boom"): + await introspector._execute_query_dict("SELECT name") + cursor.close.assert_called_once_with() + + +class TestAsyncStatusIntrospectorPublicMethods: + """Row parsing and failure handling of the asynchronous public API.""" + + async def test_get_version_string_from_row(self): + introspector = make_async_introspector() + with patch.object( + introspector, "_execute_query", new_callable=AsyncMock, + return_value=[("16.0.1000.6",)], + ): + assert await introspector._get_version_string() == "16.0.1000.6" + + @pytest.mark.parametrize("rows", [[], None]) + async def test_get_version_string_without_rows(self, rows): + introspector = make_async_introspector() + with patch.object(introspector, "_execute_query", new_callable=AsyncMock, return_value=rows): + assert await introspector._get_version_string() == "Unknown" + + async def test_get_version_string_on_error(self): + introspector = make_async_introspector() + with patch.object( + introspector, "_execute_query", new_callable=AsyncMock, side_effect=RuntimeError("down") + ): + assert await introspector._get_version_string() == "Unknown" + + async def test_list_configuration_parses_rows(self): + introspector = make_async_introspector() + rows = [ + {"name": "max connections", "value_in_use": "100", "is_dynamic": 0, "is_advanced": 0}, + {"name": "cursor threshold", "value_in_use": "-1", "is_dynamic": 1, "is_advanced": 1}, + ] + with patch.object(introspector, "_execute_query_dict", new_callable=AsyncMock, return_value=rows): + items = await introspector.list_configuration() + + assert [item.name for item in items] == ["max connections", "cursor threshold"] + assert all(isinstance(item, StatusItem) for item in items) + assert items[0].value == 100 + assert items[0].is_dynamic is False + assert items[1].value == "-1" + assert items[1].is_dynamic is True + assert all(item.category == StatusCategory.CONFIGURATION for item in items) + + async def test_list_configuration_category_filter(self): + introspector = make_async_introspector() + rows = [{"name": "x", "value_in_use": "1", "is_dynamic": 1}] + with patch.object(introspector, "_execute_query_dict", new_callable=AsyncMock, return_value=rows): + assert len(await introspector.list_configuration(StatusCategory.CONFIGURATION)) == 1 + assert await introspector.list_configuration(StatusCategory.PERFORMANCE) == [] + + async def test_list_configuration_on_error(self): + introspector = make_async_introspector() + with patch.object( + introspector, "_execute_query_dict", new_callable=AsyncMock, + side_effect=RuntimeError("down"), + ): + assert await introspector.list_configuration() == [] + + async def test_list_performance_metrics_parses_rows(self): + introspector = make_async_introspector() + rows = [ + {"counter_name": "Batch Requests/sec", "cntr_value": 4096, + "object_name": "SQL Server:SQL Statistics"}, + {"counter_name": "User Connections", "cntr_value": 12}, + ] + with patch.object(introspector, "_execute_query_dict", new_callable=AsyncMock, return_value=rows): + items = await introspector.list_performance_metrics() + + assert [item.name for item in items] == ["Batch Requests/sec", "User Connections"] + assert items[0].value == 4096 + assert items[0].description == "SQL Server:SQL Statistics" + assert items[1].description is None + assert all(item.category == StatusCategory.PERFORMANCE for item in items) + + async def test_list_performance_metrics_on_error(self): + introspector = make_async_introspector() + with patch.object( + introspector, "_execute_query_dict", new_callable=AsyncMock, + side_effect=RuntimeError("down"), + ): + assert await introspector.list_performance_metrics() == [] + + async def test_get_connection_info_populated(self): + introspector = make_async_introspector() + with patch.object( + introspector, "_execute_query_dict", new_callable=AsyncMock, + return_value=[{"active": 5, "max_conn": 100}], + ): + info = await introspector.get_connection_info() + assert isinstance(info, ConnectionInfo) + assert info.active_count == 5 + assert info.max_connections == 100 + + async def test_get_connection_info_zero_max_becomes_none(self): + introspector = make_async_introspector() + with patch.object( + introspector, "_execute_query_dict", new_callable=AsyncMock, + return_value=[{"active": 5, "max_conn": 0}], + ): + info = await introspector.get_connection_info() + assert info.active_count == 5 + assert info.max_connections is None + + @pytest.mark.parametrize("rows", [[], None]) + async def test_get_connection_info_without_rows(self, rows): + introspector = make_async_introspector() + with patch.object(introspector, "_execute_query_dict", new_callable=AsyncMock, return_value=rows): + info = await introspector.get_connection_info() + assert info.active_count is None + assert info.max_connections is None + + async def test_get_connection_info_on_error(self): + introspector = make_async_introspector() + with patch.object( + introspector, "_execute_query_dict", new_callable=AsyncMock, + side_effect=RuntimeError("down"), + ): + info = await introspector.get_connection_info() + assert info.active_count is None + + async def test_get_storage_info_converts_bytes(self): + introspector = make_async_introspector() + with patch.object( + introspector, "_execute_query_dict", new_callable=AsyncMock, + return_value=[{"total_bytes": "8192"}], + ): + info = await introspector.get_storage_info() + assert isinstance(info, StorageInfo) + assert info.total_size_bytes == 8192 + + @pytest.mark.parametrize( + ("rows", "expected"), + [([{"total_bytes": None}], 0), ([], None), (None, None)], + ) + async def test_get_storage_info_optional_shapes(self, rows, expected): + introspector = make_async_introspector() + with patch.object(introspector, "_execute_query_dict", new_callable=AsyncMock, return_value=rows): + assert (await introspector.get_storage_info()).total_size_bytes == expected + + async def test_get_storage_info_on_error(self): + introspector = make_async_introspector() + with patch.object( + introspector, "_execute_query_dict", new_callable=AsyncMock, + side_effect=RuntimeError("down"), + ): + assert (await introspector.get_storage_info()).total_size_bytes is None + + async def test_list_databases_parses_rows(self): + introspector = make_async_introspector() + rows = [ + {"db_name": "master", "size_bytes": "8388608"}, + {"db_name": "tempdb", "size_bytes": None}, + {"db_name": "model"}, + ] + with patch.object(introspector, "_execute_query_dict", new_callable=AsyncMock, return_value=rows): + databases = await introspector.list_databases() + + assert [db.name for db in databases] == ["master", "tempdb", "model"] + assert all(isinstance(db, DatabaseBriefInfo) for db in databases) + assert databases[0].size_bytes == 8388608 + assert databases[1].size_bytes is None + assert databases[2].size_bytes is None + + async def test_list_databases_on_error(self): + introspector = make_async_introspector() + with patch.object( + introspector, "_execute_query_dict", new_callable=AsyncMock, + side_effect=RuntimeError("down"), + ): + assert await introspector.list_databases() == [] + + async def test_list_users_parses_rows(self): + introspector = make_async_introspector() + rows = [ + {"name": "sa", "type_desc": "SQL_LOGIN", "is_sysadmin": 1}, + {"name": "app_user", "type_desc": "SQL_LOGIN", "is_sysadmin": 0}, + {"name": "DOMAIN\\Group"}, + ] + with patch.object(introspector, "_execute_query_dict", new_callable=AsyncMock, return_value=rows): + users = await introspector.list_users() + + assert [user.name for user in users] == ["sa", "app_user", "DOMAIN\\Group"] + assert all(isinstance(user, UserInfo) for user in users) + assert users[0].is_superuser is True + assert users[0].extra == {"type": "SQL_LOGIN"} + assert users[1].is_superuser is False + assert users[2].extra == {"type": None} + + async def test_list_users_on_error(self): + introspector = make_async_introspector() + with patch.object( + introspector, "_execute_query_dict", new_callable=AsyncMock, + side_effect=RuntimeError("down"), + ): + assert await introspector.list_users() == [] + + @pytest.mark.parametrize( + ("encrypt", "expected"), + [("TRUE", True), ("FALSE", False), (None, None), ("", None)], + ) + async def test_get_session_info_ssl_flag(self, encrypt, expected): + introspector = make_async_introspector() + rows = [{ + "session_user": "svc", "cur_db": "master", "host": "WIN-1", + "transport": "TCP/IP", "encrypt": encrypt, + }] + with patch.object(introspector, "_execute_query_dict", new_callable=AsyncMock, return_value=rows): + info = await introspector.get_session_info() + assert isinstance(info, SessionInfo) + assert info.user == "svc" + assert info.database == "master" + assert info.host == "WIN-1" + assert info.ssl_enabled is expected + + @pytest.mark.parametrize("rows", [[], None]) + async def test_get_session_info_without_rows(self, rows): + introspector = make_async_introspector() + with patch.object(introspector, "_execute_query_dict", new_callable=AsyncMock, return_value=rows): + info = await introspector.get_session_info() + assert info.user is None + + async def test_get_session_info_on_error(self): + introspector = make_async_introspector() + with patch.object( + introspector, "_execute_query_dict", new_callable=AsyncMock, + side_effect=RuntimeError("down"), + ): + info = await introspector.get_session_info() + assert info.user is None + + async def test_get_overview_delegates_and_builds_result(self): + introspector = make_async_introspector() + session = SessionInfo(user="svc") + config = [StatusItem(name="max connections", value=100)] + perf = [StatusItem(name="Batch Requests/sec", value=4096, + category=StatusCategory.PERFORMANCE)] + conn = ConnectionInfo(active_count=5) + storage = StorageInfo(total_size_bytes=8192) + databases = [DatabaseBriefInfo(name="master")] + users = [UserInfo(name="sa", is_superuser=True)] + delegates = { + "_get_version_string": "16.0.1000.6", + "get_session_info": session, + "list_configuration": config, + "list_performance_metrics": perf, + "get_connection_info": conn, + "get_storage_info": storage, + "list_databases": databases, + "list_users": users, + } + with ExitStack() as stack: + mocks = { + name: stack.enter_context( + patch.object(introspector, name, new_callable=AsyncMock, return_value=value) + ) + for name, value in delegates.items() + } + overview = await introspector.get_overview() + + assert isinstance(overview, ServerOverview) + assert overview.server_version == "16.0.1000.6" + assert overview.server_vendor == "SQL Server" + assert overview.session is session + assert overview.configuration == config + perf + assert overview.connections is conn + assert overview.storage is storage + assert overview.databases == databases + assert overview.users == users + for mocked in mocks.values(): + mocked.assert_awaited_once_with() diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_status_introspector_offline.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_status_introspector_offline.py new file mode 100644 index 00000000..5430df5b --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_status_introspector_offline.py @@ -0,0 +1,489 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/introspection/test_status_introspector_offline.py +"""Self-owned offline unit tests for the synchronous SQL Server status introspector. + +These tests exercise the backend's own parsing and query-building logic with +``MagicMock``/controlled rows only; no SQL Server (or any other DB) is needed. +The testsuite's compatibility contracts cover only the shared API, so the +backend-specific row-shape parsing lives here. +""" +from contextlib import ExitStack +from unittest.mock import MagicMock, patch + +import pytest + +from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect +from rhosocial.activerecord.backend.impl.sqlserver.introspection.status_introspector import ( + SQLServerStatusIntrospector, +) +from rhosocial.activerecord.backend.introspection.status import ( + ConnectionInfo, + DatabaseBriefInfo, + ServerOverview, + SessionInfo, + StatusCategory, + StatusItem, + StorageInfo, + UserInfo, +) + + +def make_introspector(version=(16, 0, 0)): + """Build a sync introspector over a mock backend with a real (offline) dialect.""" + backend = MagicMock() + backend.dialect = SQLServerDialect(version=version) + return SQLServerStatusIntrospector(backend=backend) + + +class TestStatusIntrospectorHelpers: + """Pure helpers on ``SQLServerStatusIntrospectorMixin``.""" + + def test_dialect_property_returns_backend_dialect(self): + introspector = make_introspector() + assert introspector.dialect is introspector._backend.dialect + + def test_get_vendor_name(self): + assert make_introspector()._get_vendor_name() == "SQL Server" + + @pytest.mark.parametrize( + ("raw", "expected"), + [ + ("123", 123), + ("0", 0), + ("007", 7), + ("abc", "abc"), + ("-5", "-5"), + ("12.5", "12.5"), + ("", ""), + (42, 42), + (None, None), + ], + ) + def test_parse_value(self, raw, expected): + assert make_introspector()._parse_value(raw) == expected + + def test_create_status_item_defaults(self): + item = make_introspector()._create_status_item( + name="max connections", value="100", category=StatusCategory.CONFIGURATION, + ) + assert isinstance(item, StatusItem) + assert item.name == "max connections" + assert item.value == 100 + assert item.category == StatusCategory.CONFIGURATION + assert item.description is None + assert item.unit is None + assert item.is_readonly is True + assert item.is_dynamic is False + + def test_create_status_item_explicit_flags(self): + item = make_introspector()._create_status_item( + name="Batch Requests/sec", value="4096", category=StatusCategory.PERFORMANCE, + description="SQL Server:SQL Statistics", unit="requests/s", + is_readonly=False, is_dynamic=True, + ) + assert item.value == 4096 + assert item.description == "SQL Server:SQL Statistics" + assert item.unit == "requests/s" + assert item.is_readonly is False + assert item.is_dynamic is True + assert item.category == StatusCategory.PERFORMANCE + + def test_build_server_overview_combines_configuration_and_performance(self): + introspector = make_introspector() + config = [StatusItem(name="a", value=1)] + perf = [StatusItem(name="b", value=2, category=StatusCategory.PERFORMANCE)] + session = SessionInfo(user="svc", ssl_enabled=True) + conn = ConnectionInfo(active_count=3) + storage = StorageInfo(total_size_bytes=8192) + databases = [DatabaseBriefInfo(name="master")] + users = [UserInfo(name="sa", is_superuser=True)] + + overview = introspector._build_server_overview( + "16.0.1000.6", session, config, perf, conn, storage, databases, users, + ) + + assert isinstance(overview, ServerOverview) + assert overview.server_version == "16.0.1000.6" + assert overview.server_vendor == "SQL Server" + assert overview.session is session + assert overview.configuration == config + perf + assert overview.performance == [] + assert overview.connections is conn + assert overview.storage is storage + assert overview.databases == databases + assert overview.users == users + + +class TestStatusIntrospectorQueryBuilders: + """The private ``*_sql`` helpers render through the dialect, not hand-written SQL.""" + + def test_version_sql(self): + sql, params = make_introspector()._version_sql() + assert "SERVERPROPERTY('ProductVersion')" in sql + assert "CAST" in sql + assert params == () + + def test_configuration_sql(self): + sql, params = make_introspector()._configuration_sql() + assert "[sys].[configurations]" in sql + assert "[value_in_use]" in sql + assert "ORDER BY [name]" in sql + assert params == () + + def test_performance_metrics_sql_with_limit(self): + sql, params = make_introspector()._performance_metrics_sql(50) + assert "[sys].[dm_os_performance_counters]" in sql + assert "RTRIM([counter_name])" in sql + assert "OFFSET 0 ROWS FETCH NEXT 50 ROWS ONLY" in sql + assert params == () + + def test_performance_metrics_sql_without_limit(self): + sql, _ = make_introspector()._performance_metrics_sql(None) + assert "FETCH NEXT" not in sql + assert "ORDER BY [cntr_value] DESC" in sql + + @pytest.mark.parametrize( + ("version", "expected"), + # SQL Server 2012 is version 11.0 -- that is the OFFSET/FETCH boundary. + [((16, 0, 0), 50), ((11, 0, 0), 50), ((10, 50, 0), None)], + ) + def test_performance_metrics_limit_by_version(self, version, expected): + assert make_introspector(version)._performance_metrics_limit() == expected + + def test_performance_metrics_limit_defaults_to_50_when_version_unavailable(self): + backend = MagicMock() + type(backend.dialect).version = property( + lambda self: (_ for _ in ()).throw(RuntimeError("no version yet")) + ) + introspector = SQLServerStatusIntrospector(backend=backend) + assert introspector._performance_metrics_limit() == 50 + + def test_connection_info_sql(self): + sql, params = make_introspector()._connection_info_sql() + assert "COUNT(*)" in sql + assert "[sys].[dm_exec_connections]" in sql + assert "'user connections'" in sql + assert "AS [active]" in sql + assert "AS [max_conn]" in sql + assert params == () + + def test_storage_info_sql(self): + sql, params = make_introspector()._storage_info_sql() + assert "[sys].[master_files]" in sql + assert "SUM([size] * 8 * 1024)" in sql + assert "AS [total_bytes]" in sql + assert params == () + + def test_database_list_sql(self): + sql, params = make_introspector()._database_list_sql() + assert "LEFT JOIN" in sql + assert "[sys].[databases]" in sql + assert "[mf].[type] = 0" in sql + assert "GROUP BY [d].[name]" in sql + assert "AS [size_bytes]" in sql + assert "AS [db_name]" in sql + assert params == () + + def test_user_list_sql(self): + sql, params = make_introspector()._user_list_sql() + assert "[sys].[server_principals]" in sql + assert "IS_SRVROLEMEMBER('sysadmin', [name])" in sql + assert "IN ('S', 'U', 'G')" in sql + assert params == () + + def test_session_info_sql(self): + sql, params = make_introspector()._session_info_sql() + assert "SYSTEM_USER AS [session_user]" in sql # niladic: no parentheses + assert "DB_NAME() AS [cur_db]" in sql + assert "HOST_NAME() AS [host]" in sql + assert sql.count("CONNECTIONPROPERTY(") == 2 + assert "'encrypt_option'" in sql + assert params == () + + +class TestStatusIntrospectorExecution: + """The two cursor-reading primitives, with a mocked cursor.""" + + def test_execute_query_returns_rows_and_closes_cursor(self): + introspector = make_introspector() + cursor = MagicMock() + cursor.fetchall.return_value = [("16.0.1000.6",)] + introspector._backend._get_cursor.return_value = cursor + + rows = introspector._execute_query("SELECT 1") + + assert rows == [("16.0.1000.6",)] + cursor.execute.assert_called_once_with("SELECT 1") + cursor.fetchall.assert_called_once_with() + cursor.close.assert_called_once_with() + + def test_execute_query_closes_cursor_on_error(self): + introspector = make_introspector() + cursor = MagicMock() + cursor.execute.side_effect = RuntimeError("boom") + introspector._backend._get_cursor.return_value = cursor + + with pytest.raises(RuntimeError, match="boom"): + introspector._execute_query("SELECT bad") + cursor.close.assert_called_once_with() + + def test_execute_query_dict_lowercases_column_names(self): + introspector = make_introspector() + cursor = MagicMock() + cursor.description = [("Name",), ("Value_In_Use",)] + cursor.fetchall.return_value = [("max connections", "100")] + introspector._backend._get_cursor.return_value = cursor + + rows = introspector._execute_query_dict("SELECT name, value_in_use FROM sys.configurations") + + assert rows == [{"name": "max connections", "value_in_use": "100"}] + cursor.close.assert_called_once_with() + + def test_execute_query_dict_closes_cursor_on_error(self): + introspector = make_introspector() + cursor = MagicMock() + cursor.description = [("Name",)] + cursor.fetchall.side_effect = RuntimeError("boom") + introspector._backend._get_cursor.return_value = cursor + + with pytest.raises(RuntimeError, match="boom"): + introspector._execute_query_dict("SELECT name") + cursor.close.assert_called_once_with() + + +class TestStatusIntrospectorPublicMethods: + """Row parsing and failure handling of the synchronous public API.""" + + def test_get_version_string_from_row(self): + introspector = make_introspector() + with patch.object(introspector, "_execute_query", return_value=[("16.0.1000.6",)]): + assert introspector._get_version_string() == "16.0.1000.6" + + @pytest.mark.parametrize("rows", [[], None]) + def test_get_version_string_without_rows(self, rows): + introspector = make_introspector() + with patch.object(introspector, "_execute_query", return_value=rows): + assert introspector._get_version_string() == "Unknown" + + def test_get_version_string_on_error(self): + introspector = make_introspector() + with patch.object(introspector, "_execute_query", side_effect=RuntimeError("down")): + assert introspector._get_version_string() == "Unknown" + + def test_list_configuration_parses_rows(self): + introspector = make_introspector() + rows = [ + {"name": "max connections", "value_in_use": "100", "is_dynamic": 0, "is_advanced": 0}, + {"name": "cursor threshold", "value_in_use": "-1", "is_dynamic": 1, "is_advanced": 1}, + ] + with patch.object(introspector, "_execute_query_dict", return_value=rows): + items = introspector.list_configuration() + + assert [item.name for item in items] == ["max connections", "cursor threshold"] + assert all(isinstance(item, StatusItem) for item in items) + assert items[0].value == 100 + assert items[0].is_dynamic is False + assert items[1].value == "-1" # negative numeric text is kept verbatim + assert items[1].is_dynamic is True + assert all(item.category == StatusCategory.CONFIGURATION for item in items) + + def test_list_configuration_category_filter(self): + introspector = make_introspector() + rows = [{"name": "x", "value_in_use": "1", "is_dynamic": 1}] + with patch.object(introspector, "_execute_query_dict", return_value=rows): + assert len(introspector.list_configuration(StatusCategory.CONFIGURATION)) == 1 + assert introspector.list_configuration(StatusCategory.PERFORMANCE) == [] + + def test_list_configuration_on_error(self): + introspector = make_introspector() + with patch.object(introspector, "_execute_query_dict", side_effect=RuntimeError("down")): + assert introspector.list_configuration() == [] + + def test_list_performance_metrics_parses_rows(self): + introspector = make_introspector() + rows = [ + {"counter_name": "Batch Requests/sec", "cntr_value": 4096, + "object_name": "SQL Server:SQL Statistics"}, + {"counter_name": "User Connections", "cntr_value": 12}, + ] + with patch.object(introspector, "_execute_query_dict", return_value=rows): + items = introspector.list_performance_metrics() + + assert [item.name for item in items] == ["Batch Requests/sec", "User Connections"] + assert items[0].value == 4096 + assert items[0].description == "SQL Server:SQL Statistics" + assert items[1].description is None + assert all(item.category == StatusCategory.PERFORMANCE for item in items) + + def test_list_performance_metrics_on_error(self): + introspector = make_introspector() + with patch.object(introspector, "_execute_query_dict", side_effect=RuntimeError("down")): + assert introspector.list_performance_metrics() == [] + + def test_get_connection_info_populated(self): + introspector = make_introspector() + with patch.object( + introspector, "_execute_query_dict", return_value=[{"active": 5, "max_conn": 100}] + ): + info = introspector.get_connection_info() + assert isinstance(info, ConnectionInfo) + assert info.active_count == 5 + assert info.max_connections == 100 + + def test_get_connection_info_zero_max_becomes_none(self): + introspector = make_introspector() + with patch.object( + introspector, "_execute_query_dict", return_value=[{"active": 5, "max_conn": 0}] + ): + info = introspector.get_connection_info() + assert info.active_count == 5 + assert info.max_connections is None + + @pytest.mark.parametrize("rows", [[], None]) + def test_get_connection_info_without_rows(self, rows): + introspector = make_introspector() + with patch.object(introspector, "_execute_query_dict", return_value=rows): + info = introspector.get_connection_info() + assert info.active_count is None + assert info.max_connections is None + + def test_get_connection_info_on_error(self): + introspector = make_introspector() + with patch.object(introspector, "_execute_query_dict", side_effect=RuntimeError("down")): + info = introspector.get_connection_info() + assert info.active_count is None + + def test_get_storage_info_converts_bytes(self): + introspector = make_introspector() + with patch.object(introspector, "_execute_query_dict", return_value=[{"total_bytes": "8192"}]): + info = introspector.get_storage_info() + assert isinstance(info, StorageInfo) + assert info.total_size_bytes == 8192 + + @pytest.mark.parametrize( + ("rows", "expected"), + [([{"total_bytes": None}], 0), ([], None), (None, None)], + ) + def test_get_storage_info_optional_shapes(self, rows, expected): + introspector = make_introspector() + with patch.object(introspector, "_execute_query_dict", return_value=rows): + assert introspector.get_storage_info().total_size_bytes == expected + + def test_get_storage_info_on_error(self): + introspector = make_introspector() + with patch.object(introspector, "_execute_query_dict", side_effect=RuntimeError("down")): + assert introspector.get_storage_info().total_size_bytes is None + + def test_list_databases_parses_rows(self): + introspector = make_introspector() + rows = [ + {"db_name": "master", "size_bytes": "8388608"}, + {"db_name": "tempdb", "size_bytes": None}, + {"db_name": "model"}, + ] + with patch.object(introspector, "_execute_query_dict", return_value=rows): + databases = introspector.list_databases() + + assert [db.name for db in databases] == ["master", "tempdb", "model"] + assert all(isinstance(db, DatabaseBriefInfo) for db in databases) + assert databases[0].size_bytes == 8388608 + assert databases[1].size_bytes is None + assert databases[2].size_bytes is None + + def test_list_databases_on_error(self): + introspector = make_introspector() + with patch.object(introspector, "_execute_query_dict", side_effect=RuntimeError("down")): + assert introspector.list_databases() == [] + + def test_list_users_parses_rows(self): + introspector = make_introspector() + rows = [ + {"name": "sa", "type_desc": "SQL_LOGIN", "is_sysadmin": 1}, + {"name": "app_user", "type_desc": "SQL_LOGIN", "is_sysadmin": 0}, + {"name": "DOMAIN\\Group"}, + ] + with patch.object(introspector, "_execute_query_dict", return_value=rows): + users = introspector.list_users() + + assert [user.name for user in users] == ["sa", "app_user", "DOMAIN\\Group"] + assert all(isinstance(user, UserInfo) for user in users) + assert users[0].is_superuser is True + assert users[0].extra == {"type": "SQL_LOGIN"} + assert users[1].is_superuser is False + assert users[2].extra == {"type": None} + + def test_list_users_on_error(self): + introspector = make_introspector() + with patch.object(introspector, "_execute_query_dict", side_effect=RuntimeError("down")): + assert introspector.list_users() == [] + + @pytest.mark.parametrize( + ("encrypt", "expected"), + [("TRUE", True), ("FALSE", False), (None, None), ("", None)], + ) + def test_get_session_info_ssl_flag(self, encrypt, expected): + introspector = make_introspector() + rows = [{ + "session_user": "svc", "cur_db": "master", "host": "WIN-1", + "transport": "TCP/IP", "encrypt": encrypt, + }] + with patch.object(introspector, "_execute_query_dict", return_value=rows): + info = introspector.get_session_info() + assert isinstance(info, SessionInfo) + assert info.user == "svc" + assert info.database == "master" + assert info.host == "WIN-1" + assert info.ssl_enabled is expected + + @pytest.mark.parametrize("rows", [[], None]) + def test_get_session_info_without_rows(self, rows): + introspector = make_introspector() + with patch.object(introspector, "_execute_query_dict", return_value=rows): + info = introspector.get_session_info() + assert info.user is None + + def test_get_session_info_on_error(self): + introspector = make_introspector() + with patch.object(introspector, "_execute_query_dict", side_effect=RuntimeError("down")): + info = introspector.get_session_info() + assert info.user is None + + def test_get_overview_delegates_and_builds_result(self): + introspector = make_introspector() + session = SessionInfo(user="svc") + config = [StatusItem(name="max connections", value=100)] + perf = [StatusItem(name="Batch Requests/sec", value=4096, + category=StatusCategory.PERFORMANCE)] + conn = ConnectionInfo(active_count=5) + storage = StorageInfo(total_size_bytes=8192) + databases = [DatabaseBriefInfo(name="master")] + users = [UserInfo(name="sa", is_superuser=True)] + delegates = { + "_get_version_string": "16.0.1000.6", + "get_session_info": session, + "list_configuration": config, + "list_performance_metrics": perf, + "get_connection_info": conn, + "get_storage_info": storage, + "list_databases": databases, + "list_users": users, + } + with ExitStack() as stack: + mocks = { + name: stack.enter_context( + patch.object(introspector, name, return_value=value) + ) + for name, value in delegates.items() + } + overview = introspector.get_overview() + + assert isinstance(overview, ServerOverview) + assert overview.server_version == "16.0.1000.6" + assert overview.server_vendor == "SQL Server" + assert overview.session is session + assert overview.configuration == config + perf + assert overview.connections is conn + assert overview.storage is storage + assert overview.databases == databases + assert overview.users == users + for mocked in mocks.values(): + mocked.assert_called_once_with() diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/join/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/join/conftest.py new file mode 100644 index 00000000..28682b0d --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/join/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/join/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/json/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/json/conftest.py new file mode 100644 index 00000000..9d474d80 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/json/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/json/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_json_expressions.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/json/test_json_expressions.py similarity index 96% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_json_expressions.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/json/test_json_expressions.py index 1450a8bd..db9c26ba 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_json_expressions.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/json/test_json_expressions.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_json_expressions.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/json/test_json_expressions.py """ Tests for SQL Server JSON expression formatting. @@ -15,7 +15,7 @@ from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect -class TestSQLServerJSONSupport: +class TestJSONSupport: """Test SQL Server JSON dialect support.""" @pytest.fixture @@ -49,7 +49,7 @@ def test_supports_json_table(self, dialect): assert dialect.supports_json_table() is False -class TestSQLServerJSONAdapter: +class TestJSONAdapter: """Test SQL Server JSON type adapter.""" def test_json_to_db(self): @@ -77,7 +77,7 @@ def test_json_from_db(self): assert result == [1, 2, 3] -class TestSQLServerJSONQueries: +class TestJSONQueries: """Test SQL Server JSON queries with real database.""" @pytest.fixture diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_json_functions_backend.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/json/test_json_functions_backend.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_json_functions_backend.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/json/test_json_functions_backend.py index 931a0695..1840bc5f 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_json_functions_backend.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/json/test_json_functions_backend.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_json_functions_backend.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/json/test_json_functions_backend.py """ SQL Server JSON function integration tests using real database connection. @@ -14,7 +14,7 @@ ) -class TestSQLServerJSONFunctionBackend: +class TestJSONFunctionBackend: """Synchronous tests for SQL Server JSON functions with real database.""" def test_supports_json_function(self, sqlserver_backend): @@ -152,7 +152,7 @@ def test_format_json_extract_integration(self, sqlserver_backend): sqlserver_backend.execute("DROP TABLE IF EXISTS #test_format_json_extract") -class TestAsyncSQLServerJSONFunctionBackend: +class TestAsyncJSONFunctionBackend: """Asynchronous tests for SQL Server JSON functions with real database.""" @pytest.mark.asyncio diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/partition/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/partition/conftest.py new file mode 100644 index 00000000..8fe0ba5c --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/partition/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/partition/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_partition_live.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/partition/test_partition_live.py similarity index 89% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_partition_live.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/partition/test_partition_live.py index a1574df2..b00aea95 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_partition_live.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/partition/test_partition_live.py @@ -1,11 +1,11 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_sqlserver_partition_live.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/partition/test_partition_live.py """Live tests for SQL Server partition DDL and maintenance. These are skipped -- not passed -- when no scenario is configured or the configured server cannot be reached, so a machine without the 2022 image does not report a false success. The offline suites in -``test_sqlserver_partition.py`` and -``test_sqlserver_partition_maintenance.py`` cover the rendering and the +``test_partition_expressions.py`` and +``test_partition_maintenance.py`` cover the rendering and the decisions; this file covers what only a server can answer: whether ``CREATE PARTITION FUNCTION`` / ``SCHEME`` / ``SPLIT`` / ``MERGE`` / ``SWITCH`` really work, and where rows land. @@ -14,11 +14,12 @@ """ import os +import socket from datetime import date import pytest -from providers.scenarios import get_enabled_scenarios, get_scenario +from support.sqlserver import get_enabled_scenarios, get_scenario_raw from rhosocial.activerecord.backend.impl.sqlserver.expression.partition import ( SQLServerSwitchPartitionExpression, @@ -68,28 +69,36 @@ def _cleanup(backend): pass +def _server_reachable(config) -> bool: + """Whether the scenario's server accepts a TCP connection.""" + probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + probe.settimeout(2) + try: + probe.connect((config.host, int(config.port))) + except OSError: + return False + finally: + probe.close() + return True + + @pytest.fixture(scope="function") -def partition_backend(): - """A backend against the first scenario for one test, or a skip when unavailable.""" - scenarios = get_enabled_scenarios() - if not scenarios: +def partition_backend(request): + """The directory's backend for one test, or a skip when unavailable.""" + scenario_names = list(get_enabled_scenarios()) + if not scenario_names: pytest.skip("No SQL Server scenarios configured") - scenario_name = next(iter(scenarios)) - backend_class, config = get_scenario(scenario_name) - backend = backend_class(connection_config=config) + _, config = get_scenario_raw(scenario_names[0]) + if not _server_reachable(config): + pytest.skip(f"Scenario server unreachable: {config.host}:{config.port}") + backend = request.getfixturevalue("sqlserver_backend_single") try: - backend.connect() backend.execute("SELECT 1") except Exception as exc: # pragma: no cover - environment dependent - try: - backend.disconnect() - except Exception: - pass pytest.skip(f"SQL Server is unavailable: {exc}") _cleanup(backend) yield backend _cleanup(backend) - backend.disconnect() @pytest.fixture(scope="function") @@ -139,7 +148,7 @@ def _partition_of(backend, created_at: date) -> int: return int(row[0]["partition_number"]) -class TestSQLServerPartitionLive: +class TestPartitionLive: """What the server confirms about SQL Server's function/scheme model.""" def test_ensure_created_a_function_and_scheme(self, partition_backend, partition_fixture): diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/query/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/query/conftest.py new file mode 100644 index 00000000..44072dd8 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/query/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/query/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_backend_explain.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/query/test_backend_explain.py similarity index 100% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_backend_explain.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/query/test_backend_explain.py diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/routine_domain/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/routine_domain/conftest.py new file mode 100644 index 00000000..60220b2d --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/routine_domain/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/routine_domain/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sequence_identity/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sequence_identity/conftest.py new file mode 100644 index 00000000..fa94cae0 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sequence_identity/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sequence_identity/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_identity_execution_confirmation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sequence_identity/test_identity_capability_conformance.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_identity_execution_confirmation.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sequence_identity/test_identity_capability_conformance.py index 9f301d81..cb0751e2 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_identity_execution_confirmation.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sequence_identity/test_identity_capability_conformance.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_identity_execution_confirmation.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sequence_identity/test_identity_capability_conformance.py """Execution confirmation for SQL Server's identity column. Rendering is not execution: a formatter can produce SQL that looks perfect and diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/show_admin/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/show_admin/conftest.py new file mode 100644 index 00000000..6a56e02c --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/show_admin/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/show_admin/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_show_functionality.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/show_admin/test_show_functionality.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_show_functionality.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/show_admin/test_show_functionality.py index 9fd345aa..9f29b603 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_show_functionality.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/show_admin/test_show_functionality.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_show_functionality.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/show_admin/test_show_functionality.py """ Tests for MySQL SHOW functionality. @@ -9,7 +9,7 @@ from unittest.mock import MagicMock, patch -class TestSQLServerShowFunctionalityInit: +class TestShowFunctionalityInit: """Tests for SQLServerShowFunctionality initialization.""" def test_init_with_version(self, sqlserver_backend_single): diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/set_type/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/set_type/conftest.py new file mode 100644 index 00000000..cc91b04d --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/set_type/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/set_type/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_set_type_backend.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/set_type/test_set_type_backend.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_set_type_backend.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/set_type/test_set_type_backend.py index 247be7a7..3a639438 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_set_type_backend.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/set_type/test_set_type_backend.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_set_type_backend.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/set_type/test_set_type_backend.py """ SQL Server comma-separated value integration tests using real database connection. @@ -14,7 +14,7 @@ ) -class TestSQLServerSetTypeBackend: +class TestSetTypeBackend: """Synchronous tests for comma-separated values with real database.""" def test_supports_set_type(self, sqlserver_backend): @@ -236,7 +236,7 @@ def test_set_count_function(self, sqlserver_backend): sqlserver_backend.execute("DROP TABLE IF EXISTS #test_set_count") -class TestAsyncSQLServerSetTypeBackend: +class TestAsyncSetTypeBackend: """Asynchronous tests for comma-separated values with real database.""" @pytest.mark.asyncio diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/sql_graph/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/sql_graph/conftest.py new file mode 100644 index 00000000..7578ab02 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/sql_graph/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/sql_graph/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/dialect/test_sqlserver_sql_graph.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/sql_graph/test_sqlserver_sql_graph.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/dialect/test_sqlserver_sql_graph.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/sql_graph/test_sqlserver_sql_graph.py index 35d5d13e..60c77a95 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/dialect/test_sqlserver_sql_graph.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/sql_graph/test_sqlserver_sql_graph.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/dialect/test_sqlserver_sql_graph.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/sqlserver/sql_graph/test_sqlserver_sql_graph.py """SQL Server SQL Graph tests (node/edge tables, MATCH predicate, SHORTEST_PATH). SQL Server SQL Graph is independent from SQL/PGQ; see the plan diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/conftest.py new file mode 100644 index 00000000..d8cbe20c --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/conftest.py @@ -0,0 +1,17 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/conftest.py +"""No directory-specific fixtures: these tests use the backend-owned fixtures.""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + + +# This directory's tests use the directory-owned database (see the backend root +# conftest's ``database_for``), so they run serially on one worker per scenario. +DECLARATION = Declaration( + uses_database=True, + parallel=True, + purpose=( + "Execute tests for this directory: they create and drop objects in the " + "directory-owned database." + ), + passes_means="This directory's database-backed execute tests pass in isolation.", + fails_means="A database-backed execute test failed against this directory's database.", +) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_transaction_backend.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_async_transaction_backend.py similarity index 95% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_transaction_backend.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_async_transaction_backend.py index 56282bc3..49fbf55a 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_transaction_backend.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_async_transaction_backend.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_transaction.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_async_transaction_backend.py import pytest import pytest_asyncio diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_transaction_isolation_effect.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_async_transaction_isolation_effect.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_transaction_isolation_effect.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_async_transaction_isolation_effect.py index d25446f4..f0f81790 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_transaction_isolation_effect.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_async_transaction_isolation_effect.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_async_transaction_isolation_effect.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_async_transaction_isolation_effect.py """ Async tests for SQL Server transaction isolation level and mode effects. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_transaction_backend.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_backend.py similarity index 100% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_transaction_backend.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_backend.py diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_transaction_deadlock_priority.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_deadlock_priority.py similarity index 91% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_transaction_deadlock_priority.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_deadlock_priority.py index 301c26a4..a8f98132 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_transaction_deadlock_priority.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_deadlock_priority.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_transaction_deadlock_priority.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_deadlock_priority.py """Offline tests for SQLServerTransactionManager.set_deadlock_priority delegation.""" from unittest.mock import MagicMock diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_transaction_isolation_effect.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_isolation_effect.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_transaction_isolation_effect.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_isolation_effect.py index 89a5231f..8a2f003f 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_transaction_isolation_effect.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_isolation_effect.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_transaction_isolation_effect.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_isolation_effect.py """ Tests for SQL Server transaction isolation level actual effects. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/transaction/test_sqlserver_transaction_isolation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_isolation_levels.py similarity index 98% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/transaction/test_sqlserver_transaction_isolation.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_isolation_levels.py index c5e0964e..1c3e365a 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/transaction/test_sqlserver_transaction_isolation.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_isolation_levels.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/transaction/test_transaction_isolation.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_isolation_levels.py """ SQL Server transaction isolation level tests. @@ -12,7 +12,7 @@ from rhosocial.activerecord.backend.transaction import IsolationLevel -class TestSyncTransactionIsolation: +class TestTransactionIsolation: """Synchronous transaction isolation level tests.""" @pytest.fixture diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/transaction/test_transaction_savepoint.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_savepoint.py similarity index 99% rename from tests/rhosocial/activerecord_sqlserver_test/feature/backend/transaction/test_transaction_savepoint.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_savepoint.py index aa8cc313..f1ed6da6 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/transaction/test_transaction_savepoint.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_savepoint.py @@ -1,4 +1,4 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/transaction/test_transaction_savepoint.py +# tests/rhosocial/activerecord_sqlserver_test/feature/backend/execute/transaction/test_transaction_savepoint.py """ SQL Server transaction savepoint tests. diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_adapter_suggestions.py b/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_adapter_suggestions.py deleted file mode 100644 index 650622c1..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_adapter_suggestions.py +++ /dev/null @@ -1,51 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/backend/test_adapter_suggestions.py -"""Offline coverage for SQLServerBackend type-adapter suggestions. - -``get_default_adapter_suggestions`` is pure logic over the adapter registry; -exercising it needs no live server and closes a noted coverage gap in -backend_mixin (see .claude/plan/2026-08-26/coverage-restoration.md). -""" -import uuid -from datetime import date, datetime, time -from decimal import Decimal - -import pytest - -from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend -from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig - - -@pytest.fixture(scope="module") -def backend(): - config = SQLServerConnectionConfig( - host="127.0.0.1", - port=11433, - database="master", - username="sa", - password="not-used-offline", - ) - return SQLServerBackend(connection_config=config) - - -class TestDefaultAdapterSuggestions: - def test_returns_mapping_for_registered_types(self, backend): - suggestions = backend.get_default_adapter_suggestions() - for py_type in (datetime, date, time, Decimal): - assert py_type in suggestions, f"missing suggestion for {py_type}" - - def test_primitives_rely_on_default_binding(self, backend): - """bool/int/float/str/bytes are intentionally not pre-registered.""" - suggestions = backend.get_default_adapter_suggestions() - for py_type in (bool, int, float, str, bytes): - assert py_type not in suggestions - - def test_complex_types_map_to_string_storage(self, backend): - suggestions = backend.get_default_adapter_suggestions() - for py_type in (uuid.UUID, dict, list): - _, db_type = suggestions[py_type] - assert db_type is str - - def test_result_is_cached(self, backend): - first = backend.get_default_adapter_suggestions() - second = backend.get_default_adapter_suggestions() - assert first is second diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/bulk_crud/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/bulk_crud/conftest.py new file mode 100644 index 00000000..cb3721d1 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/bulk_crud/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/bulk_crud/test_bulk_operations.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/bulk_crud/test_bulk_operations.py index 773c36ba..f28b8899 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/bulk_crud/test_bulk_operations.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/bulk_crud/test_bulk_operations.py @@ -5,5 +5,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_sqlserver_test/feature/basic/bulk_crud/test_bulk_operations_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/bulk_crud/test_bulk_operations_async.py index 456413fc..1019cec3 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/bulk_crud/test_bulk_operations_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/bulk_crud/test_bulk_operations_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/conftest.py index f55d2a17..149495a1 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/conftest.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/conftest.py @@ -1 +1,9 @@ -from rhosocial.activerecord.testsuite.feature.basic.conftest import * +# tests/rhosocial/activerecord_sqlserver_test/feature/basic/conftest.py +"""Fixtures shared by the ``basic`` subtopics. + +The testsuite defines one fixture per model here, and every ``basic`` +subdirectory imports its own minimal test set from below. This file only re +exports the model fixtures, so the subdirectories can request them by name. +""" + +from rhosocial.activerecord.testsuite.feature.basic.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/conftest.py index d554bf35..e096c58b 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/conftest.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/conftest.py @@ -1 +1,4 @@ -from rhosocial.activerecord.testsuite.feature.basic.connection.conftest import * +# tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/conftest.py +"""Use the shared ``basic/connection`` minimal test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.connection.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_context.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_context.py index bff0f732..5ea0a5c0 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_context.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_context.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_context import * -from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_context_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_context_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_context_async.py index 2fb7ba2f..57e87411 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_context_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_context_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/connection/test_active_record_crud.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_crud.py index a35a15b1..a7cd8ec1 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_crud.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_crud.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_crud import * -from rhosocial.activerecord.testsuite.feature.basic.connection.test_active_record_crud_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_crud_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_crud_async.py index 66b76a7a..35c98ae2 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_crud_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_active_record_crud_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/connection/test_pool_transaction_paths.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_pool_transaction_paths.py index ab1d84a8..fe437106 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_pool_transaction_paths.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_pool_transaction_paths.py @@ -4,4 +4,3 @@ """ from rhosocial.activerecord.testsuite.feature.basic.connection.test_pool_transaction_paths import * # noqa: F403 -from rhosocial.activerecord.testsuite.feature.basic.connection.test_pool_transaction_paths_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_pool_transaction_paths_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_pool_transaction_paths_async.py new file mode 100644 index 00000000..c1bf2a12 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/connection/test_pool_transaction_paths_async.py @@ -0,0 +1 @@ +from rhosocial.activerecord.testsuite.feature.basic.connection.test_pool_transaction_paths_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/conftest.py new file mode 100644 index 00000000..9ef0698f --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/crud/test_composite_pk_crud.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/test_composite_pk_crud.py deleted file mode 100644 index 191b5f51..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/test_composite_pk_crud.py +++ /dev/null @@ -1,6 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/crud/test_composite_pk_crud_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/test_composite_pk_crud_async.py deleted file mode 100644 index 44edbff9..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/test_composite_pk_crud_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/crud/test_crud.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/test_crud.py index 8002915a..9547eb0b 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/test_crud.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/test_crud.py @@ -24,5 +24,3 @@ # from the generic testsuite file into this module's scope. `pytest` then # discovers and runs them as if they were defined directly in this file. 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_sqlserver_test/feature/basic/crud/test_crud_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/test_crud_async.py index 61bf4ff3..c18abe5a 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/test_crud_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud/test_crud_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/crud_composite_pk/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud_composite_pk/conftest.py new file mode 100644 index 00000000..de447d24 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud_composite_pk/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/crud_composite_pk/test_composite_pk_crud.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud_composite_pk/test_composite_pk_crud.py new file mode 100644 index 00000000..0cae3710 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud_composite_pk/test_composite_pk_crud.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/crud_composite_pk/test_composite_pk_crud_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud_composite_pk/test_composite_pk_crud_async.py new file mode 100644 index 00000000..be23c09e --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/crud_composite_pk/test_composite_pk_crud_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/ddl/test_data_type_suggestion_contract.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/ddl/test_data_type_suggestion_contract.py new file mode 100644 index 00000000..7e673f8c --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/ddl/test_data_type_suggestion_contract.py @@ -0,0 +1,4 @@ +# tests/activerecord_sqlserver_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_sqlserver_test/feature/basic/events/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/conftest.py new file mode 100644 index 00000000..718f7425 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/conftest.py +"""Use the shared ``basic/events`` L2 environment.""" +from rhosocial.activerecord.testsuite.feature.basic.events.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/conftest.py new file mode 100644 index 00000000..19857564 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/conftest.py +"""Use the shared ``basic/events/core`` L2 environment.""" +from rhosocial.activerecord.testsuite.feature.basic.events.core.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/test_handlers.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/test_handlers.py new file mode 100644 index 00000000..30ebd57d --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/test_handlers.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/events/core/test_handlers_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/test_handlers_async.py new file mode 100644 index 00000000..121aa451 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/test_handlers_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/events/core/test_lifecycle.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/test_lifecycle.py new file mode 100644 index 00000000..cc13c55b --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/test_lifecycle.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/events/core/test_lifecycle_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/test_lifecycle_async.py new file mode 100644 index 00000000..53a8e20f --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/events/core/test_lifecycle_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/expressions/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/expressions/conftest.py new file mode 100644 index 00000000..673790ff --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/expressions/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/expressions/test_expressions.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/expressions/test_expressions.py new file mode 100644 index 00000000..d0eea05d --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/expressions/test_expressions.py @@ -0,0 +1,8 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/expressions/test_expressions_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/expressions/test_expressions_async.py new file mode 100644 index 00000000..e6bee517 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/expressions/test_expressions_async.py @@ -0,0 +1,8 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/field_generation/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/field_generation/conftest.py new file mode 100644 index 00000000..a3e5c8d8 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/field_generation/test_field_generation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/field_generation/test_field_generation.py new file mode 100644 index 00000000..8e1ef97c --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/field_generation/test_field_generation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/field_generation/test_field_generation_async.py new file mode 100644 index 00000000..ae6648ba --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/fields/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/conftest.py new file mode 100644 index 00000000..2327bcec --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/fields/test_basic_mapped_models.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_basic_mapped_models.py index c44121e8..2c253a9d 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_basic_mapped_models.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_basic_mapped_models.py @@ -3,4 +3,3 @@ import pytest from rhosocial.activerecord.testsuite.feature.basic.conftest import mapped_models_fixtures from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures import * -from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_basic_mapped_models_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_basic_mapped_models_async.py new file mode 100644 index 00000000..9fb037a7 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_basic_mapped_models_async.py @@ -0,0 +1 @@ +from rhosocial.activerecord.testsuite.feature.basic.fields.test_example_basic_fixtures_async import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_example_basic_fixtures.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_example_basic_fixtures.py index 94d06152..be5ae782 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_example_basic_fixtures.py +++ b/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/fields/test_example_basic_fixtures_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_example_basic_fixtures_async.py index 14b6d43b..0a9b3d5a 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_example_basic_fixtures_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_example_basic_fixtures_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/fields/test_field_column_mapping.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_field_column_mapping.py index 88943a5d..4992dd03 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_field_column_mapping.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_field_column_mapping.py @@ -17,5 +17,3 @@ # 2. Import all test classes and functions from the generic test file. # This pulls in the actual test logic that will be executed. 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_sqlserver_test/feature/basic/fields/test_field_column_mapping_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_field_column_mapping_async.py index 8f7301b1..703271b0 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_field_column_mapping_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_field_column_mapping_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/fields/test_fields.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_fields.py deleted file mode 100644 index 418a48e3..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_fields.py +++ /dev/null @@ -1,21 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/basic/test_fields.py -""" -This is a "bridge" file that connects the generic tests defined in the -`python-activerecord-testsuite` package with the concrete backend -implementation of this project. - -IMPORTANT: -- DO NOT add any test logic to this file. -- Its only purpose is to import the generic tests and the fixtures required - to run them against this specific backend. -""" - -# 1. Import the fixtures from the testsuite's conftest. -# This makes the fixtures defined in the testsuite available to the tests -# when they are run in the context of this backend project. - -# 2. Import all test classes and functions from the generic test file. -# This pulls in the actual test logic that will be executed. -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_sqlserver_test/feature/basic/fields/test_fields_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_fields_async.py deleted file mode 100644 index ef3b6976..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/fields/test_fields_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/nopk/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/nopk/conftest.py new file mode 100644 index 00000000..682f7f6c --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/nopk/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/nopk/test_keyless_models.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/nopk/test_keyless_models.py index a0dd8778..88a7a927 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/nopk/test_keyless_models.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/nopk/test_keyless_models.py @@ -1,3 +1,2 @@ # tests/rhosocial/activerecord_sqlserver_test/feature/basic/nopk/test_keyless_models.py 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_sqlserver_test/feature/basic/nopk/test_keyless_models_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/nopk/test_keyless_models_async.py new file mode 100644 index 00000000..002d1a36 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/readonly/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/readonly/conftest.py new file mode 100644 index 00000000..44c89dab --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/readonly/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/readonly/test_readonly_models.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/readonly/test_readonly_models.py index 61b36ea8..6d32ab96 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/readonly/test_readonly_models.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/readonly/test_readonly_models.py @@ -1,3 +1,2 @@ # tests/rhosocial/activerecord_sqlserver_test/feature/basic/readonly/test_readonly_models.py 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_sqlserver_test/feature/basic/readonly/test_readonly_models_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/readonly/test_readonly_models_async.py new file mode 100644 index 00000000..bc6ebf7a --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/type_adapter/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/type_adapter/conftest.py new file mode 100644 index 00000000..081d1856 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/type_adapter/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/type_adapter/test_type_adapter.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/type_adapter/test_type_adapter.py index 558892e6..0b9e1105 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/type_adapter/test_type_adapter.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/type_adapter/test_type_adapter.py @@ -11,5 +11,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_sqlserver_test/feature/basic/type_adapter/test_type_adapter_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/type_adapter/test_type_adapter_async.py index cbb400e4..25e9dd9f 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/type_adapter/test_type_adapter_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/type_adapter/test_type_adapter_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/types/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types/conftest.py new file mode 100644 index 00000000..37ce965b --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/types/test_type_variants.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types/test_type_variants.py new file mode 100644 index 00000000..c288aba8 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types/test_type_variants.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/types/test_type_variants_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types/test_type_variants_async.py new file mode 100644 index 00000000..2456a730 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types/test_type_variants_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/types_complex/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_complex/conftest.py new file mode 100644 index 00000000..5833dd9a --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_complex/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_complex/conftest.py +"""Use the shared ``basic/types_complex`` test set.""" + +from rhosocial.activerecord.testsuite.feature.basic.types_complex.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_complex/test_complex_variants.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_complex/test_complex_variants.py new file mode 100644 index 00000000..7d6dac1e --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_complex/test_complex_variants.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/types_complex/test_complex_variants_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_complex/test_complex_variants_async.py new file mode 100644 index 00000000..4e1b2f1d --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_complex/test_complex_variants_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/types_long_content/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_long_content/conftest.py new file mode 100644 index 00000000..f81ce6a0 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_long_content/conftest.py @@ -0,0 +1,28 @@ +# tests/rhosocial/activerecord_sqlserver_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. SQL Server renders all four content concepts (text/blob/json/xml), so +this group actually runs its round-trip tests here. + +The declaration belongs in the shared fixture, but until it is added there the +SQL Server 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. The ``is None`` guard means a future shared +fix is never overwritten. +""" + +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_sqlserver_test/feature/basic/types_long_content/test_long_content.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_long_content/test_long_content.py new file mode 100644 index 00000000..982377af --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_long_content/test_long_content.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/types_long_content/test_long_content_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_long_content/test_long_content_async.py new file mode 100644 index 00000000..13898f1d --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/types_long_content/test_long_content_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/validation/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/conftest.py new file mode 100644 index 00000000..677bddb3 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/conftest.py @@ -0,0 +1,4 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/validation/test_pydantic_native_validation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/test_pydantic_native_validation.py index bbd5e5cd..d6174f0c 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/test_pydantic_native_validation.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/test_pydantic_native_validation.py @@ -10,5 +10,3 @@ # fixtures and shared test classes. Do not remove them as unused imports. 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_sqlserver_test/feature/basic/validation/test_pydantic_native_validation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/test_pydantic_native_validation_async.py index 0dea7b19..c55d7f8a 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/test_pydantic_native_validation_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/test_pydantic_native_validation_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/validation/test_validation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/test_validation.py index fa64563f..77b0df22 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/test_validation.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/test_validation.py @@ -21,5 +21,3 @@ # parameterized to run against the scenarios defined in `providers/scenarios.py`. 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_sqlserver_test/feature/basic/validation/test_validation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/test_validation_async.py index 751664a3..ff57ebb9 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/test_validation_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/validation/test_validation_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/worker/test_connection_management.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_connection_management.py index 851edc32..7977025e 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_connection_management.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_connection_management.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.basic.worker.test_connection_management import * -from rhosocial.activerecord.testsuite.feature.basic.worker.test_connection_management_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_connection_management_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_connection_management_async.py index 93dc3024..b0739a1d 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_connection_management_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_connection_management_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/worker/test_parallel_crud.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_parallel_crud.py index 84911433..d38eb25d 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_parallel_crud.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_parallel_crud.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.basic.worker.test_parallel_crud import * -from rhosocial.activerecord.testsuite.feature.basic.worker.test_parallel_crud_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_parallel_crud_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_parallel_crud_async.py index 9981a670..4b741faf 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_parallel_crud_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_parallel_crud_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/basic/worker/test_worker_pool_lifecycle.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_worker_pool_lifecycle.py index 474e3660..2e0485b7 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_worker_pool_lifecycle.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_worker_pool_lifecycle.py @@ -1,3 +1 @@ from rhosocial.activerecord.testsuite.feature.basic.worker.test_worker_pool_lifecycle import * -from rhosocial.activerecord.testsuite.feature.basic.worker.test_worker_pool_lifecycle_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_worker_pool_lifecycle_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_worker_pool_lifecycle_async.py index d1a0a6ac..794c2e9a 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_worker_pool_lifecycle_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/basic/worker/test_worker_pool_lifecycle_async.py @@ -1,3 +1,5 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/conftest.py deleted file mode 100644 index 0cc3dba5..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_bulk.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_bulk.py deleted file mode 100644 index 508723af..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_bulk_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_bulk_async.py deleted file mode 100644 index 93522c88..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_dml.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_dml.py deleted file mode 100644 index daf79d05..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_dml_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_dml_async.py deleted file mode 100644 index 43214f10..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_dql.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_dql.py deleted file mode 100644 index df9f8d98..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_dql_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_dql_async.py deleted file mode 100644 index 1a0e1d77..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_read_only.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_read_only.py deleted file mode 100644 index 7b9befb3..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_read_only_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_read_only_async.py deleted file mode 100644 index d8668b1c..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_set_cte.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_set_cte.py deleted file mode 100644 index 253caa54..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_set_cte_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_set_cte_async.py deleted file mode 100644 index b60ecaff..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_soft_delete.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_soft_delete.py deleted file mode 100644 index 5fe311b2..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_soft_delete_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_soft_delete_async.py deleted file mode 100644 index 21ef6585..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_validation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_validation.py deleted file mode 100644 index aa055ff4..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli/test_cli_validation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli/test_cli_validation_async.py deleted file mode 100644 index 28c97f34..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/conftest.py new file mode 100644 index 00000000..5c38a618 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/conftest.py @@ -0,0 +1,16 @@ +# tests/rhosocial/activerecord_sqlserver_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``; +this backend's own ``feature/cli`` 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_sqlserver_test/feature/cli_contracts/test_cli_bulk.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_bulk.py new file mode 100644 index 00000000..30b69a2f --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_bulk.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_bulk_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_bulk_async.py new file mode 100644 index 00000000..f91725f2 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_bulk_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_dml.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_dml.py new file mode 100644 index 00000000..2741c3f1 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_dml.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_dml_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_dml_async.py new file mode 100644 index 00000000..7de6516e --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_dml_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_dql.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_dql.py new file mode 100644 index 00000000..73594cc8 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_dql.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_dql_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_dql_async.py new file mode 100644 index 00000000..64affb90 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_dql_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_migrate.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_migrate.py new file mode 100644 index 00000000..deed76c5 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_migrate.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_migrate_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_migrate_async.py new file mode 100644 index 00000000..25e1484f --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_migrate_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_read_only.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_read_only.py new file mode 100644 index 00000000..0f48b880 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_read_only.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_read_only_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_read_only_async.py new file mode 100644 index 00000000..ff42857c --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_read_only_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_set_cte.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_set_cte.py new file mode 100644 index 00000000..e5d84c0b --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_set_cte.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_set_cte_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_set_cte_async.py new file mode 100644 index 00000000..bbe4c935 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_set_cte_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_soft_delete.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_soft_delete.py new file mode 100644 index 00000000..db69ddbe --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_soft_delete.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_soft_delete_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_soft_delete_async.py new file mode 100644 index 00000000..937e6937 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_soft_delete_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_validation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_validation.py new file mode 100644 index 00000000..2151e5a0 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_validation.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cli_contracts/test_cli_validation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_validation_async.py new file mode 100644 index 00000000..ec2f1699 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cli_contracts/test_cli_validation_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/conftest.py index f262347e..4e259f17 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/conftest.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/conftest.py @@ -20,4 +20,38 @@ def fixtures(): @pytest.fixture async def async_fixtures(): """Async stub fixture for the protocol/function decorator smoke tests.""" - return None \ No newline at end of file + return None + + +def pytest_collection_modifyitems(items): + """Skip the testsuite's real-DB ``test_explain`` contracts for SQL Server. + + Those contracts execute ``.explain().aggregate()`` against a live server. + SQL Server cannot honour that generic flow: ``SET SHOWPLAN_*`` / + ``SET STATISTICS *`` must be the only statement in an exclusive batch, and + with the plan flag on the driver's ``fetchall()`` reports ``No results`` + (pyodbc). Executing EXPLAIN against a connection is deliberately avoided + for this backend -- see the local construction-level deep tests in + ``feature/backend/construct/explain/test_sqlserver_explain_deep.py`` which + pin the capability gates and the exact SHOWPLAN/STATISTICS SQL instead. + """ + reason = ( + "SQL Server SHOWPLAN/STATISTICS requires an exclusive batch; real-DB " + "EXPLAIN execution is deliberately avoided here. EXPLAIN is covered " + "construction-level in test_sqlserver_explain_deep.py." + ) + for item in items: + if item.originalname == "test_explain": + item.add_marker(pytest.mark.skip(reason=reason)) + # SQL Server trims trailing spaces from CHAR/nchar comparisons, so the + # shared error-handling contracts' exact round-trips of padded values + # cannot hold. This is SQL Server's defined comparison semantics. + if item.originalname in ( + "test_special_character_full_matrix", + "test_comment_style_variation_immunity", + ): + item.add_marker( + pytest.mark.skip( + reason="SQL Server trims trailing spaces; exact round-trip cannot hold" + ) + ) \ No newline at end of file diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/connection/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/connection/conftest.py index 2935c59d..ec25dad1 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/connection/conftest.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/connection/conftest.py @@ -1,24 +1,35 @@ # tests/rhosocial/activerecord_sqlserver_test/feature/connection/conftest.py +"""Pytest configuration for connection pool tests. + +The pool fixtures exercise the pool itself, so their connections open on the +directory's own database: ``database_config`` creates it once per scenario and +hands every pool fixture the scenario and its connection configuration. +Depending on ``database_config`` is also what pins this directory's tests to one +worker per scenario -- without it two workers could plant the shared +``concurrent_test_*`` tables in the same database at the same time, which is +what turned MySQL's concurrency tests red. + +The tables the ``*_with_tables`` fixtures create and drop through the pool are +declared in ``pool_definitions.py``: a definition class takes a ``dialect`` +only, so this conftest holds no SQL of its own. """ -Pytest configuration for connection pool tests. +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration -This module provides fixtures for testing connection pools with SQL Server backends. -""" - -import os -from typing import Dict, Any, Generator +from typing import Generator import pytest import pytest_asyncio -import yaml - -from rhosocial.activerecord.backend.impl.sqlserver.backend import SQLServerBackend -from rhosocial.activerecord.backend.impl.sqlserver.backend.async_backend import AsyncSQLServerBackend -from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig from rhosocial.activerecord.connection.pool import ( - PoolConfig, - BackendPool, AsyncBackendPool, + BackendPool, + PoolConfig, +) + +from pool_definitions import ( + AsyncConcurrentTestPostsDefinition, + AsyncConcurrentTestUsersDefinition, + ConcurrentTestPostsDefinition, + ConcurrentTestUsersDefinition, ) @@ -34,122 +45,49 @@ # postgres suite's pytest_asyncio_loop_factories hook instead, which scopes # the choice to the tests rather than the process. -# --- 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("SQLSERVER_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", "sqlserver_scenarios.yaml") - if os.path.exists(default_path): - config_path = default_path - elif env_config_path: - print(f"Warning: Scenario file specified in SQLSERVER_SCENARIOS_CONFIG_PATH not found: {env_config_path}") - return - - if not config_path: - raise FileNotFoundError( - "No SQLServer scenarios configuration file found. " - "Set SQLSERVER_SCENARIOS_CONFIG_PATH or place sqlserver_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 +# --- directory contract: the directory's identity for xdist grouping --- -_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") - scenario_config = 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: - scenario_config["database"] = pooled_db - return scenario_config +# 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 database shared by this test group.", +) +@pytest.fixture(scope="session") +def database_config(backend_scenario): + """The scenario, its connection configuration, and the database name. -def get_scenario_names(): - return list(SCENARIO_MAP.keys()) + The pool fixtures above own their connections, so this directory creates + no shared ``database`` backend; the database is still the directory's own + (``test_connection``), emptied once per scenario here -- the job the old + ``ensure_database`` hook did -- so every pool opens on a clean database + with ``READ_COMMITTED_SNAPSHOT`` on. + """ + name = "test_connection" + backend_scenario.reset_database(name) + return backend_scenario, backend_scenario.make_config(name), name # --- Pool Fixtures --- -def create_sqlserver_backend_factory(config_dict: Dict[str, Any]): - """Create a factory function that produces SQLServerBackend instances.""" - - def factory(): - config_copy = config_dict.copy() - ssl_disabled = config_copy.pop("ssl_disabled", None) - config = SQLServerConnectionConfig(**config_copy) - if ssl_disabled is not None: - config.ssl_disabled = ssl_disabled - backend = SQLServerBackend(connection_config=config) - backend.connect() - return backend - - return factory - - -def create_async_sqlserver_backend_factory(config_dict: Dict[str, Any]): - """Create a factory function that produces AsyncSQLServerBackend instances.""" - - def factory(): - config_copy = config_dict.copy() - ssl_disabled = config_copy.pop("ssl_disabled", None) - config = SQLServerConnectionConfig(**config_copy) - if ssl_disabled is not None: - config.ssl_disabled = ssl_disabled - backend = AsyncSQLServerBackend(connection_config=config) - # Note: connect() will be called by the pool when needed - return backend - - return factory - - -@pytest.fixture(scope="function", params=get_scenario_names()) -def sqlserver_pool(request) -> Generator[BackendPool, None, None]: +@pytest.fixture(scope="function") +def sqlserver_pool(database_config) -> Generator[BackendPool, None, None]: """Create a BackendPool with SQL Server backends for testing.""" - scenario_name = request.param - config_dict = get_scenario_config(scenario_name).copy() - + scenario, config, _name = database_config pool_config = PoolConfig( min_size=1, max_size=5, timeout=30.0, validate_on_borrow=True, validation_query="SELECT 1", - backend_factory=create_sqlserver_backend_factory(config_dict), + backend_factory=lambda: scenario.backend_class(connection_config=config), ) pool = BackendPool.create(pool_config) @@ -157,19 +95,17 @@ def sqlserver_pool(request) -> Generator[BackendPool, None, None]: pool.close(timeout=5.0, force=True) -@pytest_asyncio.fixture(scope="function", params=get_scenario_names()) -async def async_sqlserver_pool(request) -> AsyncBackendPool: +@pytest_asyncio.fixture(scope="function") +async def async_sqlserver_pool(database_config) -> AsyncBackendPool: """Create an AsyncBackendPool with SQL Server backends for testing.""" - scenario_name = request.param - config_dict = get_scenario_config(scenario_name).copy() - + scenario, config, _name = database_config pool_config = PoolConfig( min_size=1, max_size=5, timeout=30.0, validate_on_borrow=True, validation_query="SELECT 1", - backend_factory=create_async_sqlserver_backend_factory(config_dict), + backend_factory=lambda: scenario.async_backend_class(connection_config=config), ) pool = await AsyncBackendPool.create(pool_config) @@ -177,18 +113,16 @@ async def async_sqlserver_pool(request) -> AsyncBackendPool: await pool.close(timeout=5.0, force=True) -@pytest.fixture(scope="function", params=get_scenario_names()) -def sqlserver_pool_large(request) -> Generator[BackendPool, None, None]: +@pytest.fixture(scope="function") +def sqlserver_pool_large(database_config) -> Generator[BackendPool, None, None]: """Create a larger BackendPool for stress testing.""" - scenario_name = request.param - config_dict = get_scenario_config(scenario_name).copy() - + scenario, config, _name = database_config pool_config = PoolConfig( min_size=1, max_size=5, timeout=60.0, validate_on_borrow=False, # Faster for stress tests - backend_factory=create_sqlserver_backend_factory(config_dict), + backend_factory=lambda: scenario.backend_class(connection_config=config), ) pool = BackendPool.create(pool_config) @@ -196,18 +130,16 @@ def sqlserver_pool_large(request) -> Generator[BackendPool, None, None]: pool.close(timeout=5.0, force=True) -@pytest_asyncio.fixture(scope="function", params=get_scenario_names()) -async def async_sqlserver_pool_large(request) -> AsyncBackendPool: +@pytest_asyncio.fixture(scope="function") +async def async_sqlserver_pool_large(database_config) -> AsyncBackendPool: """Create a larger AsyncBackendPool for stress testing.""" - scenario_name = request.param - config_dict = get_scenario_config(scenario_name).copy() - + scenario, config, _name = database_config pool_config = PoolConfig( min_size=1, max_size=5, timeout=60.0, validate_on_borrow=False, - backend_factory=create_async_sqlserver_backend_factory(config_dict), + backend_factory=lambda: scenario.async_backend_class(connection_config=config), ) pool = await AsyncBackendPool.create(pool_config) @@ -221,60 +153,40 @@ async def async_sqlserver_pool_large(request) -> AsyncBackendPool: @pytest.fixture(scope="function") def sqlserver_pool_with_tables(sqlserver_pool: BackendPool) -> Generator[BackendPool, None, None]: """Create a pool with test tables initialized.""" + definitions = ( + ConcurrentTestPostsDefinition, + ConcurrentTestUsersDefinition, + ) with sqlserver_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 INT IDENTITY(1,1) PRIMARY KEY, - thread_id INTEGER, - name VARCHAR(255), - created_at DATETIME DEFAULT CURRENT_TIMESTAMP - ) - """) - backend.execute(""" - CREATE TABLE concurrent_test_posts ( - id INT IDENTITY(1,1) PRIMARY KEY, - thread_id INTEGER, - user_id INTEGER, - title VARCHAR(255), - content NVARCHAR(MAX) - ) - """) + fixtures = [definition(backend.dialect) for definition in definitions] + for fixture in fixtures: + backend.execute(*fixture.drop_table.to_sql()) + backend.execute(*fixture.create_table.to_sql()) yield sqlserver_pool with sqlserver_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()) @pytest_asyncio.fixture(scope="function") -async def async_sqlserver_pool_with_tables(async_sqlserver_pool: AsyncBackendPool) -> AsyncBackendPool: +async def async_sqlserver_pool_with_tables( + async_sqlserver_pool: AsyncBackendPool, +) -> AsyncBackendPool: """Create an async pool with test tables initialized.""" + definitions = ( + AsyncConcurrentTestPostsDefinition, + AsyncConcurrentTestUsersDefinition, + ) async with async_sqlserver_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 INT IDENTITY(1,1) PRIMARY KEY, - task_id INTEGER, - name VARCHAR(255), - created_at DATETIME DEFAULT CURRENT_TIMESTAMP - ) - """) - await backend.execute(""" - CREATE TABLE concurrent_test_posts ( - id INT IDENTITY(1,1) PRIMARY KEY, - task_id INTEGER, - user_id INTEGER, - title VARCHAR(255), - content NVARCHAR(MAX) - ) - """) + fixtures = [definition(backend.dialect) for definition in definitions] + for fixture in fixtures: + await backend.execute(*fixture.drop_table.to_sql()) + await backend.execute(*fixture.create_table.to_sql()) yield async_sqlserver_pool async with async_sqlserver_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()) \ No newline at end of file diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/connection/pool_definitions.py b/tests/rhosocial/activerecord_sqlserver_test/feature/connection/pool_definitions.py new file mode 100644 index 00000000..980b2f24 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/connection/pool_definitions.py @@ -0,0 +1,141 @@ +# tests/rhosocial/activerecord_sqlserver_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). + +Every type here is a core expression type: SQL Server renders ``VarChar`` as +``VARCHAR(n)``, ``Text`` as ``NVARCHAR(MAX)`` and ``TimestampType`` as +``DATETIME2``, and the primary key branch carries the ``IDENTITY(1,1)`` +spelling the old hand-written DDL used -- the table set is unchanged, only +its ownership moved. +""" +from rhosocial.activerecord.backend.expression.statements import auto_increment_parts # noqa: E402 + +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.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"): + data_type, attributes = auto_increment_parts(self.dialect, Int(self.dialect)) + return self.column(name, data_type, [ + Constraint(self.dialect, branch=PrimaryKey(self.dialect)), + ], attributes=attributes) + + + 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)), + ] \ No newline at end of file diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/core/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/core/conftest.py new file mode 100644 index 00000000..bd0477df --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/core/conftest.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/core/conftest.py +"""Use the stubs declared for the feature area. + +The protocol/function decorator smoke tests moved out of ``feature/`` because +that directory also holds every feature subdirectory: a directory carries +either test files or subdirectories, never both. +""" + +from rhosocial.activerecord_sqlserver_test.feature.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/test_features.py b/tests/rhosocial/activerecord_sqlserver_test/feature/core/test_features.py similarity index 100% rename from tests/rhosocial/activerecord_sqlserver_test/feature/test_features.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/core/test_features.py diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/test_features_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/core/test_features_async.py similarity index 100% rename from tests/rhosocial/activerecord_sqlserver_test/feature/test_features_async.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/core/test_features_async.py diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/cte/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cte/conftest.py new file mode 100644 index 00000000..e43c1c49 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cte/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cte/test_composite_pk_cte.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cte/test_composite_pk_cte.py new file mode 100644 index 00000000..f0c6aada --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cte/test_composite_pk_cte.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/cte/test_composite_pk_cte_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/cte/test_composite_pk_cte_async.py new file mode 100644 index 00000000..27ecc9de --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/cte/test_composite_pk_cte_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/ddl/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/conftest.py new file mode 100644 index 00000000..87b14277 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/ddl/core/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/core/conftest.py new file mode 100644 index 00000000..5a4caf9a --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/core/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/ddl/core/test_ddl_source_contract.py b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/core/test_ddl_source_contract.py new file mode 100644 index 00000000..51b999ff --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/core/test_ddl_source_contract.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/ddl/core/test_derivation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/core/test_derivation.py new file mode 100644 index 00000000..1ccd02d2 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/core/test_derivation.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/ddl/core/test_derivation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/core/test_derivation_async.py new file mode 100644 index 00000000..f6ef342e --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/core/test_derivation_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/ddl/core/test_migration_function_contract.py b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/core/test_migration_function_contract.py new file mode 100644 index 00000000..99ebc475 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/core/test_migration_function_contract.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/ddl/core/test_statement_derivation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/core/test_statement_derivation.py new file mode 100644 index 00000000..af630e63 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/ddl/core/test_statement_derivation.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/events/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/events/conftest.py deleted file mode 100644 index 1d4bdf9f..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/events/conftest.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.events.conftest import * diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/events/schema/event_tests.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/events/schema/event_tests.sql deleted file mode 100644 index 1f44712d..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/events/schema/event_tests.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE TABLE [event_tests] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [name] NVARCHAR(255) NOT NULL, - [status] NVARCHAR(50) NOT NULL DEFAULT 'draft', - [revision] INT NOT NULL DEFAULT 1, - [content] NVARCHAR(MAX) NULL, - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/events/schema/event_tracking_models.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/events/schema/event_tracking_models.sql deleted file mode 100644 index 50504b6c..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/events/schema/event_tracking_models.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE TABLE [event_tracking_models] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [title] NVARCHAR(255) NOT NULL, - [content] NVARCHAR(MAX) NOT NULL, - [view_count] INT NOT NULL DEFAULT 0, - [last_viewed_at] DATETIME2 NULL -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/events/test_handlers.py b/tests/rhosocial/activerecord_sqlserver_test/feature/events/test_handlers.py deleted file mode 100644 index 7664e5a1..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/events/test_handlers.py +++ /dev/null @@ -1,6 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.events.conftest import ( - event_model, -) -from rhosocial.activerecord.testsuite.feature.events.test_handlers import * -from rhosocial.activerecord.testsuite.feature.events.test_handlers_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/events/test_handlers_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/events/test_handlers_async.py deleted file mode 100644 index 1eaf19ed..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/events/test_handlers_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/events/test_lifecycle.py b/tests/rhosocial/activerecord_sqlserver_test/feature/events/test_lifecycle.py deleted file mode 100644 index 4ff54858..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/events/test_lifecycle.py +++ /dev/null @@ -1,6 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.events.conftest import ( - event_model, -) -from rhosocial.activerecord.testsuite.feature.events.test_lifecycle import * -from rhosocial.activerecord.testsuite.feature.events.test_lifecycle_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/events/test_lifecycle_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/events/test_lifecycle_async.py deleted file mode 100644 index 7045e375..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/events/test_lifecycle_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/interface/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/interface/conftest.py deleted file mode 100644 index 1d0c1eb7..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/interface/conftest.py +++ /dev/null @@ -1,8 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/interface/test_threadsafe_dict.py b/tests/rhosocial/activerecord_sqlserver_test/feature/interface/test_threadsafe_dict.py deleted file mode 100644 index cc3f96d4..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/interface/test_threadsafe_dict.py +++ /dev/null @@ -1,7 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/interface/test_threadsafe_dict_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/interface/test_threadsafe_dict_async.py deleted file mode 100644 index 8d273aeb..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/interface/test_threadsafe_dict_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/logging/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/logging/conftest.py new file mode 100644 index 00000000..6e7cd202 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/logging/conftest.py @@ -0,0 +1,7 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/logging/conftest.py +"""No database is used here. + +The execution-logging cases drive the backend through fake connections and +cursors, so this directory declares no ``prepare`` / ``teardown`` contract: it +needs neither a database nor the per-directory pinning that comes with one. +""" diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/conftest.py deleted file mode 100644 index 09487095..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/conftest.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.mixins.conftest import * diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/combined_articles.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/combined_articles.sql deleted file mode 100644 index 7033344d..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/combined_articles.sql +++ /dev/null @@ -1,10 +0,0 @@ -CREATE TABLE [combined_articles] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [title] NVARCHAR(255) NOT NULL, - [content] NVARCHAR(MAX) NOT NULL, - [status] NVARCHAR(50) NOT NULL DEFAULT 'draft', - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL, - [version] INT NOT NULL DEFAULT 1, - [deleted_at] DATETIME2 NULL -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/tasks.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/tasks.sql deleted file mode 100644 index a7793c0a..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/tasks.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE TABLE [tasks] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [title] NVARCHAR(255) NOT NULL, - [is_completed] TINYINT NOT NULL DEFAULT 0, - [deleted_at] NVARCHAR(MAX) NULL -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/timestamped_posts.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/timestamped_posts.sql deleted file mode 100644 index 77f6a6bc..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/timestamped_posts.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE TABLE [timestamped_posts] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [title] NVARCHAR(255) NOT NULL, - [content] NVARCHAR(MAX) NOT NULL, - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/versioned_products.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/versioned_products.sql deleted file mode 100644 index 5a5b0f44..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/schema/versioned_products.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE TABLE [versioned_products] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [name] NVARCHAR(255) NOT NULL, - [price] DECIMAL(10,2) NOT NULL DEFAULT 0.00, - [version] INT NOT NULL DEFAULT 1 -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_combined_articles.py b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_combined_articles.py deleted file mode 100644 index e54bf2d9..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_combined_articles.py +++ /dev/null @@ -1,3 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.mixins.test_combined_articles import * -from rhosocial.activerecord.testsuite.feature.mixins.test_combined_articles_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_combined_articles_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_combined_articles_async.py deleted file mode 100644 index ced86960..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_combined_articles_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/mixins/test_optimistic_lock.py b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_optimistic_lock.py deleted file mode 100644 index 204720b5..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_optimistic_lock.py +++ /dev/null @@ -1,3 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.mixins.test_optimistic_lock import * -from rhosocial.activerecord.testsuite.feature.mixins.test_optimistic_lock_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_optimistic_lock_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_optimistic_lock_async.py deleted file mode 100644 index dac69867..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_optimistic_lock_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/mixins/test_soft_delete.py b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_soft_delete.py deleted file mode 100644 index d9ca8f22..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_soft_delete.py +++ /dev/null @@ -1,3 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.mixins.test_soft_delete import * -from rhosocial.activerecord.testsuite.feature.mixins.test_soft_delete_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_soft_delete_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_soft_delete_async.py deleted file mode 100644 index e0fcb9c6..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_soft_delete_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/mixins/test_timestamps.py b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_timestamps.py deleted file mode 100644 index d9c0c7d8..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_timestamps.py +++ /dev/null @@ -1,3 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.mixins.test_timestamps import * -from rhosocial.activerecord.testsuite.feature.mixins.test_timestamps_async import * # noqa: F403 - diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_timestamps_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_timestamps_async.py deleted file mode 100644 index ba92c79b..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/mixins/test_timestamps_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/aggregate/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/conftest.py new file mode 100644 index 00000000..5d2de426 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/aggregate/test_active_query_aggregate.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/test_active_query_aggregate.py index c2647c16..ce1694e1 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/test_active_query_aggregate.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/test_active_query_aggregate.py @@ -1,11 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_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_sqlserver_test/feature/query/aggregate/test_active_query_aggregate_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/test_active_query_aggregate_async.py index a495a854..56fe78ce 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/test_active_query_aggregate_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/test_active_query_aggregate_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/aggregate/test_aggregate_queries.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/test_aggregate_queries.py index 81fae10f..bd904132 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/test_aggregate_queries.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/test_aggregate_queries.py @@ -1,11 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_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_sqlserver_test/feature/query/aggregate/test_aggregate_queries_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/test_aggregate_queries_async.py index 1f6ad283..819e320a 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/test_aggregate_queries_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/aggregate/test_aggregate_queries_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/basic/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/conftest.py new file mode 100644 index 00000000..97ca8b5d --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/basic/test_active_query_basic.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_active_query_basic.py deleted file mode 100644 index 3f7d2595..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_active_query_basic.py +++ /dev/null @@ -1,11 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/basic/test_active_query_basic_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_active_query_basic_async.py deleted file mode 100644 index 07be936c..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_active_query_basic_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/basic/test_basic.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_basic.py deleted file mode 100644 index 80ad85c1..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_basic.py +++ /dev/null @@ -1,11 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/basic/test_basic_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_basic_async.py deleted file mode 100644 index 95ce1b22..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_basic_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/basic/test_composite_pk_query.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_composite_pk_query.py deleted file mode 100644 index 9c81fbe7..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_composite_pk_query.py +++ /dev/null @@ -1,6 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/basic/test_composite_pk_query_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_composite_pk_query_async.py index 8ffa2c0b..bbf9e424 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_composite_pk_query_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_composite_pk_query_async.py @@ -1,3 +1,9 @@ # tests/rhosocial/activerecord_sqlserver_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) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_find_one_or_create.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_find_one_or_create.py deleted file mode 100644 index c87b5482..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_find_one_or_create.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_find_one_or_create.py -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_sqlserver_test/feature/query/basic/test_queries.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_queries.py deleted file mode 100644 index 913cf471..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_queries.py +++ /dev/null @@ -1,9 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/query/test_queries.py -""" -Bridge file for sync 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 import * # noqa: F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_queries_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_queries_async.py deleted file mode 100644 index a66ce4a2..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/basic/test_queries_async.py +++ /dev/null @@ -1,10 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/conftest.py index c1a1d4ab..12e43eaf 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/conftest.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/conftest.py @@ -1 +1,8 @@ -from rhosocial.activerecord.testsuite.feature.query.conftest import * +# tests/rhosocial/activerecord_sqlserver_test/feature/query/conftest.py +"""Fixtures for the query topic. + +The fixture definitions live in the shared suite; each subdirectory declares +its own minimal test set, so this file only makes the fixtures visible. +""" + +from rhosocial.activerecord.testsuite.feature.query.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/conftest.py index ac9ebd66..f0ca8ff1 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/conftest.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/conftest.py @@ -1 +1,3 @@ -from rhosocial.activerecord.testsuite.feature.query.connection.conftest import * +# tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/conftest.py +"""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_sqlserver_test/feature/query/connection/test_active_query_context.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_active_query_context.py index 1fc51bc1..c188521d 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_active_query_context.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_active_query_context.py @@ -1,7 +1,3 @@ -from rhosocial.activerecord.testsuite.feature.query.connection.conftest import ( - sync_pool_and_model, - async_pool_and_model, -) -from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context import * -from rhosocial.activerecord.testsuite.feature.query.connection.test_active_query_context_async import * # noqa: F403 - +# tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_active_query_context.py +"""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_sqlserver_test/feature/query/connection/test_active_query_context_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_active_query_context_async.py index 59330af4..392719fd 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_active_query_context_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_active_query_context_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/connection/test_cte_query_context.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_cte_query_context.py index b15a35d9..7aa0a886 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_cte_query_context.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_cte_query_context.py @@ -1,7 +1,3 @@ -from rhosocial.activerecord.testsuite.feature.query.connection.conftest import ( - sync_pool_and_model, - async_pool_and_model, -) -from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context import * -from rhosocial.activerecord.testsuite.feature.query.connection.test_cte_query_context_async import * # noqa: F403 - +# tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_cte_query_context.py +"""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_sqlserver_test/feature/query/connection/test_cte_query_context_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_cte_query_context_async.py index 5f457339..38061252 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_cte_query_context_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_cte_query_context_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/connection/test_set_operation_context.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_set_operation_context.py index c49fadc1..7d2ad7ab 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_set_operation_context.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_set_operation_context.py @@ -1,7 +1,3 @@ -from rhosocial.activerecord.testsuite.feature.query.connection.conftest import ( - sync_pool_and_model, - async_pool_and_model, -) -from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context import * -from rhosocial.activerecord.testsuite.feature.query.connection.test_set_operation_context_async import * # noqa: F403 - +# tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_set_operation_context.py +"""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_sqlserver_test/feature/query/connection/test_set_operation_context_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_set_operation_context_async.py index ff2c9cc0..41eb9d4d 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_set_operation_context_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/connection/test_set_operation_context_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/core/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/core/conftest.py new file mode 100644 index 00000000..c6ab01ce --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/core/conftest.py @@ -0,0 +1,62 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/core/conftest.py +"""L2 backend fixtures for the SQL Server-only query "core" tests. + +- ``database``: one database per directory (session scope, emptied at start); +- ``schema``: the tables this directory's files use, dropped and recreated + for every test (function scope). + +The files here assert on expression SQL (COLLATE construction) and own their +throwaway raw tables inside the test module, so no topic definition is +prepared; the database still exists because it is the directory's identity. +""" +from rhosocial.activerecord.testsuite.pytest_plugin import Declaration + +import pytest + +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType +from rhosocial.activerecord_sqlserver_test.feature.query.conftest import * # noqa: F401,F403 + +DDL = ExecutionOptions(stmt_type=StatementType.DDL) + +DEFINITIONS = () + + + +# 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 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 = "test_query_core" + 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 tables 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) \ No newline at end of file diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/test_collation_expression.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/core/test_collation_expression.py similarity index 92% rename from tests/rhosocial/activerecord_sqlserver_test/feature/query/test_collation_expression.py rename to tests/rhosocial/activerecord_sqlserver_test/feature/query/core/test_collation_expression.py index 4d9eaa52..0f03a1eb 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/test_collation_expression.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/core/test_collation_expression.py @@ -1,12 +1,12 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/query/test_collation_expression.py +# tests/rhosocial/activerecord_sqlserver_test/feature/query/core/test_collation_expression.py """ Tests for expression-level COLLATE support on SQL Server. """ import pytest - from rhosocial.activerecord.backend.expression import Column, Literal from rhosocial.activerecord.backend.expression.collation import collate + from rhosocial.activerecord.backend.impl.sqlserver.collation import SQLServerCollation from rhosocial.activerecord.backend.impl.sqlserver.dialect import SQLServerDialect @@ -18,7 +18,9 @@ def dialect(): @pytest.fixture def collation_table(sqlserver_backend): - sqlserver_backend.execute("IF OBJECT_ID('test_collation_expression', 'U') IS NOT NULL DROP TABLE test_collation_expression") + sqlserver_backend.execute( + "IF OBJECT_ID('test_collation_expression', 'U') IS NOT NULL DROP TABLE test_collation_expression" + ) sqlserver_backend.execute(""" CREATE TABLE test_collation_expression ( id INT IDENTITY(1,1) PRIMARY KEY, @@ -30,7 +32,9 @@ def collation_table(sqlserver_backend): VALUES (N'Alice'), (N'alice'), (N'Bob') """) yield "test_collation_expression" - sqlserver_backend.execute("IF OBJECT_ID('test_collation_expression', 'U') IS NOT NULL DROP TABLE test_collation_expression") + sqlserver_backend.execute( + "IF OBJECT_ID('test_collation_expression', 'U') IS NOT NULL DROP TABLE test_collation_expression" + ) class TestSQLServerCollationExpression: diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_database/test_cross_database_compatibility.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_database/test_cross_database_compatibility.py deleted file mode 100644 index f070c1ca..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_database/test_cross_database_compatibility.py +++ /dev/null @@ -1,11 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cross_database/test_cross_database_compatibility_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_database/test_cross_database_compatibility_async.py deleted file mode 100644 index 82ce1c83..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_database/test_cross_database_compatibility_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cross_schema/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_schema/conftest.py new file mode 100644 index 00000000..ed34fc65 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_schema/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cross_schema/test_cross_schema_join.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_schema/test_cross_schema_join.py new file mode 100644 index 00000000..3196b98b --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_schema/test_cross_schema_join.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cross_schema/test_cross_schema_join_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_schema/test_cross_schema_join_async.py new file mode 100644 index 00000000..f9e5826a --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_schema/test_cross_schema_join_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cross_schema/test_mixed_schema.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_schema/test_mixed_schema.py new file mode 100644 index 00000000..e25caff4 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_schema/test_mixed_schema.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cross_schema/test_mixed_schema_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_schema/test_mixed_schema_async.py new file mode 100644 index 00000000..aed0c8ac --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_schema/test_mixed_schema_async.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cross_schema/test_mixed_schema_qualifiers.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_schema/test_mixed_schema_qualifiers.py new file mode 100644 index 00000000..126b6cbc --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cross_schema/test_mixed_schema_qualifiers.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cte/test_composite_pk_cte.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cte/test_composite_pk_cte.py deleted file mode 100644 index 350a5dc2..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/cte/test_composite_pk_cte.py +++ /dev/null @@ -1,6 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cte/test_composite_pk_cte_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cte/test_composite_pk_cte_async.py deleted file mode 100644 index 2ea3a4e6..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/cte/test_composite_pk_cte_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cte/test_cte_query_active_query.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cte/test_cte_query_active_query.py deleted file mode 100644 index 7c8f715e..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/cte/test_cte_query_active_query.py +++ /dev/null @@ -1,11 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cte/test_cte_query_active_query_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cte/test_cte_query_active_query_async.py deleted file mode 100644 index 74337381..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/cte/test_cte_query_active_query_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cte/test_cte_query_set_operation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cte/test_cte_query_set_operation.py deleted file mode 100644 index b272c9d9..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/cte/test_cte_query_set_operation.py +++ /dev/null @@ -1,11 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/cte/test_cte_query_set_operation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/cte/test_cte_query_set_operation_async.py deleted file mode 100644 index 9d2dbdf4..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/cte/test_cte_query_set_operation_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/eager_loading/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/conftest.py new file mode 100644 index 00000000..c0d9a644 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/eager_loading/test_eager_loading_caching.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_caching.py index a12faed9..943ae524 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_caching.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_caching.py @@ -1,7 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/query/test_eager_loading_caching.py -""" -Bridge file for eager loading caching tests from the testsuite. -""" -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_sqlserver_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_sqlserver_test/feature/query/eager_loading/test_eager_loading_caching_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_caching_async.py index d3df88dd..7e050170 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_caching_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_caching_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/eager_loading/test_eager_loading_nested.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_nested.py index f29d67e4..8454f111 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_nested.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_nested.py @@ -1,7 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/query/test_eager_loading_nested.py -""" -Bridge file for nested eager loading tests from the testsuite. -""" -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_sqlserver_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_sqlserver_test/feature/query/eager_loading/test_eager_loading_nested_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_nested_async.py index 2cc4be8d..a0ba2f50 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_nested_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_nested_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/eager_loading/test_eager_loading_scenarios.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_scenarios.py index 7cb2f8dc..6347def7 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_scenarios.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_scenarios.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_scenarios.py -"""Bridge file for sync eager loading scenario tests.""" -from rhosocial.activerecord.testsuite.feature.query.eager_loading.test_eager_loading_scenarios import * # noqa: F401, F403 +"""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_sqlserver_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py index 22a0cd31..285734da 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_scenarios_async.py @@ -1,5 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_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_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_all.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_all.py index cb448805..d9b46cc1 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_all.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_all.py @@ -1,7 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/query/test_eager_loading_with_all.py -""" -Bridge file for eager loading with_all tests from the testsuite. -""" -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_sqlserver_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_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_all_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_all_async.py index 60166910..cb74ca0f 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_all_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_all_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_modifier.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_modifier.py index 4ed99594..76aab626 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_modifier.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_modifier.py @@ -1,12 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/query/test_eager_loading_with_modifier.py -""" -Bridge file for eager loading with_modifier tests from the testsuite. - -Includes: -- Basic modifier tests (filter, order, noop) -- Backward-compatibility tests (eager == lazy) -- for_update + with_ tests (SQLServer supports LockingSupport) -""" -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_sqlserver_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_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py index 2a7489f8..a05eb1b3 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_modifier_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_one.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_one.py index 83a47e03..8543ed6f 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_one.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_one.py @@ -1,7 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/query/test_eager_loading_with_one.py -""" -Bridge file for eager loading with_one tests from the testsuite. -""" -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_sqlserver_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_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_one_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_one_async.py index fdd95a5c..3b8996aa 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_one_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/eager_loading/test_eager_loading_with_one_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/error_handling/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/error_handling/conftest.py new file mode 100644 index 00000000..6c440b88 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/error_handling/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/error_handling/test_error_handling.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/error_handling/test_error_handling.py index f16008e1..e5e5dcaf 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/error_handling/test_error_handling.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/error_handling/test_error_handling.py @@ -1,32 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_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. - -SQL Server trims trailing spaces from VARCHAR/NVARCHAR columns on retrieval -(fundamental server behavior), so the two tests that assert exact round-trip -preservation of trailing spaces cannot pass and are skipped here. -""" -import pytest - -import rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling as _src -import rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async as _src_async - -_TRAILING_SPACE_REASON = ( - "SQL Server trims trailing spaces from VARCHAR/NVARCHAR on retrieval " - "(fundamental server behavior); these tests assert MySQL-style " - "trailing-space preservation." -) -_TRAILING_SPACE_TESTS = [ - "test_special_character_full_matrix", - "test_comment_style_variation_immunity", -] - -for _module in (_src, _src_async): - for _name in _TRAILING_SPACE_TESTS: - setattr(_module, _name, pytest.mark.skip(reason=_TRAILING_SPACE_REASON)(getattr(_module, _name))) - -from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling import * # noqa: F403, E402 -from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async import * # noqa: F403, E402 +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/error_handling/test_error_handling_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/error_handling/test_error_handling_async.py index 10aee273..240e91a6 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/error_handling/test_error_handling_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/error_handling/test_error_handling_async.py @@ -1,25 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_test/feature/query/error_handling/test_error_handling_async.py -"""Bridge file for async feature.query.error_handling.test_error_handling_async tests. - -SQL Server trims trailing spaces from VARCHAR/NVARCHAR columns on retrieval -(fundamental server behavior), so the two tests that assert exact round-trip -preservation of trailing spaces cannot pass and are skipped here. -""" -import pytest - -import rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async as _src - -_TRAILING_SPACE_REASON = ( - "SQL Server trims trailing spaces from VARCHAR/NVARCHAR on retrieval " - "(fundamental server behavior); these tests assert MySQL-style " - "trailing-space preservation." -) -_TRAILING_SPACE_TESTS = [ - "test_special_character_full_matrix", - "test_comment_style_variation_immunity", -] - -for _name in _TRAILING_SPACE_TESTS: - setattr(_src, _name, pytest.mark.skip(reason=_TRAILING_SPACE_REASON)(getattr(_src, _name))) - -from rhosocial.activerecord.testsuite.feature.query.error_handling.test_error_handling_async import * # noqa: F401, F403, E402 +"""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_sqlserver_test/feature/query/joins/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/joins/conftest.py new file mode 100644 index 00000000..f234d979 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/joins/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/joins/test_active_query_join.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/joins/test_active_query_join.py deleted file mode 100644 index 2db79fc2..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/joins/test_active_query_join.py +++ /dev/null @@ -1,11 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/joins/test_active_query_join_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/joins/test_active_query_join_async.py deleted file mode 100644 index 990be03d..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/joins/test_active_query_join_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/joins/test_joins.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/joins/test_joins.py deleted file mode 100644 index 5c283b82..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/joins/test_joins.py +++ /dev/null @@ -1,11 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/joins/test_joins_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/joins/test_joins_async.py deleted file mode 100644 index 1b721a01..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/joins/test_joins_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/json/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/json/conftest.py new file mode 100644 index 00000000..2468910b --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/json/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/json/test_json_probe_honesty.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/json/test_json_probe_honesty.py new file mode 100644 index 00000000..2791d7dd --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/json/test_json_probe_honesty.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/logging/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/logging/conftest.py new file mode 100644 index 00000000..6dfb2641 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/logging/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/logging/test_logging_data_summarization.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/logging/test_logging_data_summarization.py index 085ae69f..f4693f11 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/logging/test_logging_data_summarization.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/logging/test_logging_data_summarization.py @@ -1,11 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_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_sqlserver_test/feature/query/logging/test_logging_data_summarization_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/logging/test_logging_data_summarization_async.py index ec86cc26..b300e24b 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/logging/test_logging_data_summarization_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/logging/test_logging_data_summarization_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/optimization/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/optimization/conftest.py new file mode 100644 index 00000000..2a541c55 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/optimization/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/optimization/test_query_optimization.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/optimization/test_query_optimization.py index df7b1ac2..f7a58501 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/optimization/test_query_optimization.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/optimization/test_query_optimization.py @@ -1,11 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_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_sqlserver_test/feature/query/optimization/test_query_optimization_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/optimization/test_query_optimization_async.py index 2d5f526b..21d9bedd 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/optimization/test_query_optimization_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/optimization/test_query_optimization_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/range_queries/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/conftest.py new file mode 100644 index 00000000..d225fa56 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/range_queries/test_active_query_range.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_active_query_range.py index eb6a8e2b..6ef402c2 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_active_query_range.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_active_query_range.py @@ -1,11 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_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_sqlserver_test/feature/query/range_queries/test_active_query_range_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_active_query_range_async.py index 3df23b6c..22e29aaf 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_active_query_range_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_active_query_range_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/range_queries/test_range_queries.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_range_queries.py index bdc72a4a..a79de95c 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_range_queries.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_range_queries.py @@ -1,11 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_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_sqlserver_test/feature/query/range_queries/test_range_queries_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_range_queries_async.py index e3700ab1..b97def27 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_range_queries_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_range_queries_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/range_queries/test_range_query_detailed.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_range_query_detailed.py index d7cab3de..4f1c88b1 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_range_query_detailed.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_range_query_detailed.py @@ -1,11 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_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_sqlserver_test/feature/query/range_queries/test_range_query_detailed_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_range_query_detailed_async.py index 329ede84..9c1a6e80 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_range_query_detailed_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/range_queries/test_range_query_detailed_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/relation/README.md b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/README.md new file mode 100644 index 00000000..c661c470 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/README.md @@ -0,0 +1,11 @@ +# query/relation tests (SQL Server bridge) + +SQL Server bridge for the shared `feature/query/relation` testsuite topic. This +directory mirrors the testsuite source tree after its feature restructure: the +old `feature/relation/` bridge group and the old `feature/query/relations/` +bridge group were merged here. + +- `conftest.py` — star-imports `testsuite.feature.query.relation.conftest`. +- `ordering/conftest.py` — star-imports `testsuite.feature.query.relation.ordering.conftest`. + +See [feature tests](../README.md) and [tests/README.md](../../../../README.md). diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/conftest.py new file mode 100644 index 00000000..d8e6508d --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/conftest.py @@ -0,0 +1,2 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/conftest.py +"""No subdir conftest in the testsuite; fixtures come from the topic conftest.""" diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_base.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_base.py new file mode 100644 index 00000000..7493a688 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_base.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_base.py +""" +Bridge file for relation base tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.base.test_base import * # noqa: F403 +except ImportError: + pytest.skip("relation base tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_base_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_base_async.py new file mode 100644 index 00000000..9cb77b95 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_base_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_base_async.py +""" +Bridge file for async relation base tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.base.test_base_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation base tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_interfaces.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_interfaces.py new file mode 100644 index 00000000..545728ec --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_interfaces.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_interfaces.py +""" +Bridge file for relation interface tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.base.test_interfaces import * # noqa: F403 +except ImportError: + pytest.skip("relation interface tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_interfaces_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_interfaces_async.py new file mode 100644 index 00000000..bd1cf902 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_interfaces_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/base/test_interfaces_async.py +""" +Bridge file for async relation interface tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.base.test_interfaces_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation interface tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/boundary/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/boundary/conftest.py new file mode 100644 index 00000000..feab2091 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/boundary/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/boundary/conftest.py +"""Use the shared ``relation/boundary`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.query.relation.boundary.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/boundary/test_boundary.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/boundary/test_boundary.py new file mode 100644 index 00000000..b7089e09 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/boundary/test_boundary.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/boundary/test_boundary.py +""" +Bridge file for relation boundary tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.boundary.test_boundary import * # noqa: F403 +except ImportError: + pytest.skip("relation boundary tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/boundary/test_boundary_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/boundary/test_boundary_async.py new file mode 100644 index 00000000..58ff760c --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/boundary/test_boundary_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/boundary/test_boundary_async.py +""" +Bridge file for async relation boundary tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.boundary.test_boundary_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation boundary tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/conftest.py new file mode 100644 index 00000000..66e76291 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/conftest.py @@ -0,0 +1,2 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/conftest.py +"""No subdir conftest in the testsuite; fixtures come from the topic conftest.""" diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache.py new file mode 100644 index 00000000..a5a2123a --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache.py +""" +Bridge file for relation cache tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.cache.test_cache import * # noqa: F403 +except ImportError: + pytest.skip("relation cache tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache_async.py new file mode 100644 index 00000000..f5dbd0ad --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache_async.py +""" +Bridge file for async relation cache tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.cache.test_cache_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation cache tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache_clearing.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache_clearing.py new file mode 100644 index 00000000..bfeb442c --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache_clearing.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache_clearing.py +""" +Bridge file for relation cache clearing tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.cache.test_cache_clearing import * # noqa: F403 +except ImportError: + pytest.skip("relation cache clearing tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache_clearing_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache_clearing_async.py new file mode 100644 index 00000000..d137ab38 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache_clearing_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/cache/test_cache_clearing_async.py +""" +Bridge file for async relation cache clearing tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.cache.test_cache_clearing_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation cache clearing tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/conftest.py new file mode 100644 index 00000000..18165957 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/conftest.py @@ -0,0 +1,7 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/relation/derived/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/conftest.py new file mode 100644 index 00000000..9a72bb36 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/conftest.py +"""Use the shared ``relation/derived`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.query.relation.derived.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field.py new file mode 100644 index 00000000..aa66c8da --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field.py +""" +Bridge file for relation derived-field tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.derived.test_relation_derived_field import * # noqa: F403 +except ImportError: + pytest.skip("relation derived-field tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field_async.py new file mode 100644 index 00000000..d7724e9d --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field_async.py +""" +Bridge file for async relation derived-field tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.derived.test_relation_derived_field_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation derived-field tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field_json.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field_json.py new file mode 100644 index 00000000..c6317438 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field_json.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field_json.py +""" +Bridge file for relation derived-field JSON tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.derived.test_relation_derived_field_json import * # noqa: F403 +except ImportError: + pytest.skip("relation derived-field JSON tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field_json_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field_json_async.py new file mode 100644 index 00000000..704ccabd --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field_json_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/derived/test_relation_derived_field_json_async.py +""" +Bridge file for async relation derived-field JSON tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.derived.test_relation_derived_field_json_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation derived-field JSON tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/conftest.py new file mode 100644 index 00000000..bd95d3d5 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/conftest.py @@ -0,0 +1,2 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/conftest.py +"""No subdir conftest in the testsuite; fixtures come from the topic conftest.""" diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptor_compat.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptor_compat.py new file mode 100644 index 00000000..2bead2d7 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptor_compat.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptor_compat.py +""" +Bridge file for relation descriptor compatibility tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.descriptors.test_descriptor_compat import * # noqa: F403 +except ImportError: + pytest.skip("relation descriptor compatibility tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptor_compat_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptor_compat_async.py new file mode 100644 index 00000000..1b31a436 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptor_compat_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptor_compat_async.py +""" +Bridge file for async relation descriptor compatibility tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.descriptors.test_descriptor_compat_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation descriptor compatibility tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptors.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptors.py new file mode 100644 index 00000000..4dca78fa --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptors.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptors.py +""" +Bridge file for relation descriptor tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.descriptors.test_descriptors import * # noqa: F403 +except ImportError: + pytest.skip("relation descriptor tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptors_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptors_async.py new file mode 100644 index 00000000..680aa539 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptors_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/descriptors/test_descriptors_async.py +""" +Bridge file for async relation descriptor tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.descriptors.test_descriptors_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation descriptor tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/conftest.py new file mode 100644 index 00000000..b0e14bd3 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/conftest.py +"""Use the shared ``relation/eager_loading`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_nested_relationship_access.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_nested_relationship_access.py new file mode 100644 index 00000000..a7c0c28e --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_nested_relationship_access.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_nested_relationship_access.py +""" +Bridge file for nested relationship access tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.test_nested_relationship_access import * # noqa: F403 +except ImportError: + pytest.skip("nested relationship access tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py new file mode 100644 index 00000000..461c1382 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_nested_relationship_access_async.py # noqa: E501 +""" +Bridge file for async nested relationship access tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.test_nested_relationship_access_async import * # noqa: F403,E501 +except ImportError: + pytest.skip("async nested relationship access tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_with_method.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_with_method.py new file mode 100644 index 00000000..b741e877 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_with_method.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_with_method.py +""" +Bridge file for with_() method tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.test_with_method import * # noqa: F403 +except ImportError: + pytest.skip("with_() method tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_with_method_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_with_method_async.py new file mode 100644 index 00000000..612d2ebd --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_with_method_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/eager_loading/test_with_method_async.py +""" +Bridge file for async with_() method tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.eager_loading.test_with_method_async import * # noqa: F403 +except ImportError: + pytest.skip("async with_() method tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/integration/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/integration/conftest.py new file mode 100644 index 00000000..9147ae29 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/integration/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/integration/conftest.py +"""Use the shared ``relation/integration`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.query.relation.integration.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/integration/test_integration.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/integration/test_integration.py new file mode 100644 index 00000000..e96d2dc5 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/integration/test_integration.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/integration/test_integration.py +""" +Bridge file for relation integration tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.integration.test_integration import * # noqa: F403 +except ImportError: + pytest.skip("relation integration tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/integration/test_integration_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/integration/test_integration_async.py new file mode 100644 index 00000000..970e34f9 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/integration/test_integration_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/integration/test_integration_async.py +""" +Bridge file for async relation integration tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.integration.test_integration_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation integration tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/legacy/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/legacy/conftest.py new file mode 100644 index 00000000..f5b20e94 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/legacy/conftest.py @@ -0,0 +1,2 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/legacy/conftest.py +"""No subdir conftest in the testsuite; fixtures come from the topic conftest.""" diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/legacy/test_relational_validation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/legacy/test_relational_validation.py new file mode 100644 index 00000000..2525a0b6 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/legacy/test_relational_validation.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/legacy/test_relational_validation.py +""" +Bridge file for legacy relational validation tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.legacy.test_relational_validation import * # noqa: F403 +except ImportError: + pytest.skip("legacy relational validation tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/legacy/test_relational_validation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/legacy/test_relational_validation_async.py new file mode 100644 index 00000000..64b15d12 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/legacy/test_relational_validation_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/legacy/test_relational_validation_async.py +""" +Bridge file for async legacy relational validation tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.legacy.test_relational_validation_async import * # noqa: F403 +except ImportError: + pytest.skip("async legacy relational validation tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/conftest.py new file mode 100644 index 00000000..117d4422 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/conftest.py +"""Use the shared ``relation/modifiers`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_behavior.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_behavior.py new file mode 100644 index 00000000..cddcb313 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_behavior.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_behavior.py +""" +Bridge file for relation modifier behavior tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.test_modifier_behavior import * # noqa: F403 +except ImportError: + pytest.skip("relation modifier behavior tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_behavior_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_behavior_async.py new file mode 100644 index 00000000..3ce0b3ff --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_behavior_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_behavior_async.py +""" +Bridge file for async relation modifier behavior tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.test_modifier_behavior_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation modifier behavior tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_warning.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_warning.py new file mode 100644 index 00000000..d3c8e0c4 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_warning.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_warning.py +""" +Bridge file for relation modifier warning tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.test_modifier_warning import * # noqa: F403 +except ImportError: + pytest.skip("relation modifier warning tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_warning_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_warning_async.py new file mode 100644 index 00000000..cd24fdbb --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_warning_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/modifiers/test_modifier_warning_async.py +""" +Bridge file for async relation modifier warning tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.modifiers.test_modifier_warning_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation modifier warning tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/ordering/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/ordering/conftest.py new file mode 100644 index 00000000..60bcf821 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/ordering/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/relation/ordering/test_has_many_order_by.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/ordering/test_has_many_order_by.py new file mode 100644 index 00000000..6c340a97 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/ordering/test_has_many_order_by.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/ordering/test_has_many_order_by.py +""" +Bridge file for HasMany order_by tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.ordering.test_has_many_order_by import * # noqa: F403 +except ImportError: + pytest.skip("HasMany order_by tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/ordering/test_has_many_order_by_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/ordering/test_has_many_order_by_async.py new file mode 100644 index 00000000..dbcf4ea3 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/ordering/test_has_many_order_by_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/ordering/test_has_many_order_by_async.py +""" +Bridge file for async HasMany order_by tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.ordering.test_has_many_order_by_async import * # noqa: F403 +except ImportError: + pytest.skip("async HasMany order_by tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/conftest.py new file mode 100644 index 00000000..4b2d78a5 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/conftest.py +"""Use the shared ``relation/validation`` minimal test set.""" +from rhosocial.activerecord.testsuite.feature.query.relation.validation.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_path_validation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_path_validation.py new file mode 100644 index 00000000..fa34be0d --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_path_validation.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_path_validation.py +""" +Bridge file for relation path validation tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.validation.test_path_validation import * # noqa: F403 +except ImportError: + pytest.skip("relation path validation tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_path_validation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_path_validation_async.py new file mode 100644 index 00000000..3cca429e --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_path_validation_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_path_validation_async.py +""" +Bridge file for async relation path validation tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.validation.test_path_validation_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation path validation tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_validator.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_validator.py new file mode 100644 index 00000000..69d25891 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_validator.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_validator.py +""" +Bridge file for relation validator tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.validation.test_validator import * # noqa: F403 +except ImportError: + pytest.skip("relation validator tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_validator_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_validator_async.py new file mode 100644 index 00000000..49cc9da2 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_validator_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_test/feature/query/relation/validation/test_validator_async.py +""" +Bridge file for async relation validator tests from the testsuite. +""" +import pytest +try: + from rhosocial.activerecord.testsuite.feature.query.relation.validation.test_validator_async import * # noqa: F403 +except ImportError: + pytest.skip("async relation validator tests testsuite not available", allow_module_level=True) diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relational_validation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relational_validation.py deleted file mode 100644 index 7259fd69..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relational_validation.py +++ /dev/null @@ -1,11 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/relations/test_relational_validation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relational_validation_async.py deleted file mode 100644 index aef8e93d..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relational_validation_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/relations/test_relations_basic.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relations_basic.py deleted file mode 100644 index 623695cd..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relations_basic.py +++ /dev/null @@ -1,11 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/relations/test_relations_basic_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relations_basic_async.py deleted file mode 100644 index 852cd4dc..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relations_basic_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/relations/test_relations_with.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relations_with.py deleted file mode 100644 index ea1e2717..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relations_with.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/relations/test_relations_with_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relations_with_async.py deleted file mode 100644 index 5e55c2c3..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/relations/test_relations_with_async.py +++ /dev/null @@ -1,5 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/schema/comments.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/comments.sql deleted file mode 100644 index fff3a511..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/comments.sql +++ /dev/null @@ -1,13 +0,0 @@ -CREATE TABLE [comments] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [user_id] INT NOT NULL, - [post_id] INT NOT NULL, - [content] NVARCHAR(MAX) NULL, - [is_hidden] BIT DEFAULT 0, - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL, - INDEX [idx_user_id] ([user_id]), - INDEX [idx_post_id] ([post_id]), - FOREIGN KEY ([user_id]) REFERENCES [users]([id]) ON DELETE NO ACTION, - FOREIGN KEY ([post_id]) REFERENCES [posts]([id]) ON DELETE NO ACTION -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/extended_order_items.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/extended_order_items.sql deleted file mode 100644 index 07920b4b..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/extended_order_items.sql +++ /dev/null @@ -1,13 +0,0 @@ -CREATE TABLE [extended_order_items] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [order_id] INT NOT NULL, - [product_name] NVARCHAR(255) NOT NULL, - [quantity] INT NOT NULL DEFAULT 1, - [price] DECIMAL(10,2) NOT NULL, - [category] NVARCHAR(255) NULL, - [region] NVARCHAR(50) NULL, - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL, - INDEX [idx_order_id] ([order_id]), - FOREIGN KEY ([order_id]) REFERENCES [extended_orders]([id]) ON DELETE CASCADE -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/extended_orders.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/extended_orders.sql deleted file mode 100644 index f5b8d03c..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/extended_orders.sql +++ /dev/null @@ -1,21 +0,0 @@ -CREATE TABLE [extended_orders] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [user_id] INT NOT NULL, - [order_number] NVARCHAR(255) NOT NULL, - [total_amount] DECIMAL(10,2) NOT NULL DEFAULT 0.00, - [status] NVARCHAR(50) NOT NULL DEFAULT 'pending', - [priority] NVARCHAR(50) NOT NULL DEFAULT 'medium', - [region] NVARCHAR(50) NOT NULL DEFAULT 'default', - [category] NVARCHAR(255) NULL, - [product] NVARCHAR(255) NULL, - [department] NVARCHAR(255) NULL, - [year] NVARCHAR(10) NULL, - [quarter] NVARCHAR(10) NULL, - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL, - INDEX [idx_user_id] ([user_id]), - INDEX [idx_status] ([status]), - INDEX [idx_priority] ([priority]), - INDEX [idx_region] ([region]), - FOREIGN KEY ([user_id]) REFERENCES [users]([id]) ON DELETE CASCADE -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/json_users.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/json_users.sql deleted file mode 100644 index 83c874b1..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/json_users.sql +++ /dev/null @@ -1,15 +0,0 @@ -CREATE TABLE [json_users] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [username] NVARCHAR(255) NOT NULL, - [email] NVARCHAR(255) NOT NULL, - [age] INT NULL, - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL, - [settings] NVARCHAR(MAX) NULL, - [tags] NVARCHAR(MAX) NULL, - [profile] NVARCHAR(MAX) NULL, - [roles] NVARCHAR(MAX) NULL, - [scores] NVARCHAR(MAX) NULL, - [subscription] NVARCHAR(MAX) NULL, - [preferences] NVARCHAR(MAX) NULL -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/nodes.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/nodes.sql deleted file mode 100644 index 3ae9f6e4..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/nodes.sql +++ /dev/null @@ -1,10 +0,0 @@ -CREATE TABLE [nodes] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [name] NVARCHAR(255) NOT NULL, - [parent_id] INT NULL, - [value] DECIMAL(10,2) NOT NULL DEFAULT 0.00, - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL, - INDEX [idx_parent_id] ([parent_id]), - FOREIGN KEY ([parent_id]) REFERENCES [nodes]([id]) ON DELETE CASCADE -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/order_items.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/order_items.sql deleted file mode 100644 index e5c4dd1a..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/order_items.sql +++ /dev/null @@ -1,12 +0,0 @@ -CREATE TABLE [order_items] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [order_id] INT NOT NULL, - [product_name] NVARCHAR(255) NOT NULL, - [quantity] INT NOT NULL DEFAULT 1, - [unit_price] DECIMAL(10,2) NOT NULL, - [subtotal] DECIMAL(10,2) NOT NULL DEFAULT 0.00, - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL, - INDEX [idx_order_id] ([order_id]), - FOREIGN KEY ([order_id]) REFERENCES [orders]([id]) ON DELETE CASCADE -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/orders.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/orders.sql deleted file mode 100644 index fb6a0594..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/orders.sql +++ /dev/null @@ -1,11 +0,0 @@ -CREATE TABLE [orders] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [user_id] INT NOT NULL, - [order_number] NVARCHAR(255) NOT NULL, - [total_amount] DECIMAL(10,2) NOT NULL DEFAULT 0.00, - [status] NVARCHAR(50) NOT NULL DEFAULT 'pending', - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL, - INDEX [idx_user_id] ([user_id]), - FOREIGN KEY ([user_id]) REFERENCES [users]([id]) ON DELETE CASCADE -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/posts.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/posts.sql deleted file mode 100644 index 1130a768..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/posts.sql +++ /dev/null @@ -1,12 +0,0 @@ -CREATE TABLE [posts] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [user_id] INT NOT NULL, - [title] NVARCHAR(255) NOT NULL, - [content] NVARCHAR(MAX) NULL, - [status] NVARCHAR(50) NOT NULL DEFAULT 'published', - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL, - INDEX [idx_user_id] ([user_id]), - INDEX [idx_status] ([status]), - FOREIGN KEY ([user_id]) REFERENCES [users]([id]) ON DELETE CASCADE -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/profiles.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/profiles.sql deleted file mode 100644 index 79650587..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/profiles.sql +++ /dev/null @@ -1,10 +0,0 @@ --- tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/profiles.sql -CREATE TABLE `profiles` ( - `id` INT IDENTITY(1,1) PRIMARY KEY, - `user_id` INT NOT NULL, - `bio` TEXT, - `avatar_url` VARCHAR(512), - `created_at` DATETIME(6), - `updated_at` DATETIME(6), - FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/searchable_items.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/searchable_items.sql deleted file mode 100644 index 4c45d0e0..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/searchable_items.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE TABLE [searchable_items] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [name] NVARCHAR(255) NULL, - [tags] NVARCHAR(MAX) NULL, - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/users.sql b/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/users.sql deleted file mode 100644 index 7263c057..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/schema/users.sql +++ /dev/null @@ -1,10 +0,0 @@ -CREATE TABLE [users] ( - [id] INT IDENTITY(1,1) PRIMARY KEY, - [username] NVARCHAR(191) NOT NULL, - [email] NVARCHAR(191) NOT NULL, - [age] INT NULL, - [balance] FLOAT NOT NULL DEFAULT 0.0, - [is_active] TINYINT NOT NULL DEFAULT 1, - [created_at] DATETIME2 NULL, - [updated_at] DATETIME2 NULL -); diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_active_query_set_operation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_active_query_set_operation.py deleted file mode 100644 index 564e08e4..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_active_query_set_operation.py +++ /dev/null @@ -1,11 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/set_operations/test_active_query_set_operation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_active_query_set_operation_async.py deleted file mode 100644 index fa3dc5cf..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_active_query_set_operation_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/set_operations/test_composite_pk_set_operation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_composite_pk_set_operation.py deleted file mode 100644 index 2d219f7f..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_composite_pk_set_operation.py +++ /dev/null @@ -1,6 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/set_operations/test_composite_pk_set_operation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_composite_pk_set_operation_async.py deleted file mode 100644 index a138970e..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_composite_pk_set_operation_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/set_operations/test_set_operation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_set_operation.py deleted file mode 100644 index 1479a2f2..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_set_operation.py +++ /dev/null @@ -1,11 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/set_operations/test_set_operation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_set_operation_async.py deleted file mode 100644 index 6253ff27..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/set_operations/test_set_operation_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/special/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/conftest.py new file mode 100644 index 00000000..f4065a9f --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/special/test_example_query_fixtures.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/test_example_query_fixtures.py index 6d7441de..dff54fc4 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/test_example_query_fixtures.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/test_example_query_fixtures.py @@ -1,11 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_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_sqlserver_test/feature/query/special/test_example_query_fixtures_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/test_example_query_fixtures_async.py index 352e1157..f0e8feb2 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/test_example_query_fixtures_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/test_example_query_fixtures_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/special/test_special_queries.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/test_special_queries.py index dddc8966..8ef2e270 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/test_special_queries.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/test_special_queries.py @@ -1,11 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_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_sqlserver_test/feature/query/special/test_special_queries_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/test_special_queries_async.py index a7f1f7a1..c0a0956e 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/test_special_queries_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/special/test_special_queries_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/typed_column/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/conftest.py new file mode 100644 index 00000000..042f0113 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/typed_column/test_column_operations_core.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_column_operations_core.py new file mode 100644 index 00000000..58478fbe --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_column_operations_core.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/typed_column/test_enum_capability_contracts.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_enum_capability_contracts.py new file mode 100644 index 00000000..53237642 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_enum_capability_contracts.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/typed_column/test_protocol_guarantees.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_protocol_guarantees.py new file mode 100644 index 00000000..952607af --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_protocol_guarantees.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/typed_column/test_seconds_between_contract.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_seconds_between_contract.py index 0974d21a..127e33be 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_seconds_between_contract.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_seconds_between_contract.py @@ -1,2 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/typed_column/test_typed_column_contracts.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_typed_column_contracts.py new file mode 100644 index 00000000..fa8756ef --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_typed_column_contracts.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/typed_column/test_uuid_capability_contracts.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_uuid_capability_contracts.py new file mode 100644 index 00000000..3aadd166 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/typed_column/test_uuid_capability_contracts.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/window_functions/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/window_functions/conftest.py new file mode 100644 index 00000000..47b84ce8 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/window_functions/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/window_functions/test_window_functions.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/window_functions/test_window_functions.py index 6174b045..beada91e 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/window_functions/test_window_functions.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/window_functions/test_window_functions.py @@ -1,11 +1,3 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_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_sqlserver_test/feature/query/window_functions/test_window_functions_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/window_functions/test_window_functions_async.py index 0d82d7c6..831b481b 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/window_functions/test_window_functions_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/window_functions/test_window_functions_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/worker/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/conftest.py index a0a99fe3..e1e1535c 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/conftest.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/conftest.py @@ -1 +1,3 @@ -from rhosocial.activerecord.testsuite.feature.query.worker.conftest import * +# tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/conftest.py +"""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_sqlserver_test/feature/query/worker/test_parallel_queries.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_parallel_queries.py index beedc17b..ef4da6df 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_parallel_queries.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_parallel_queries.py @@ -1,7 +1,3 @@ -from rhosocial.activerecord.testsuite.feature.query.worker.conftest import ( - order_fixtures_for_worker, - async_order_fixtures_for_worker, -) -from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries import * -from rhosocial.activerecord.testsuite.feature.query.worker.test_parallel_queries_async import * # noqa: F403 - +# tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_parallel_queries.py +"""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_sqlserver_test/feature/query/worker/test_parallel_queries_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_parallel_queries_async.py index c75324b5..3c835a36 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_parallel_queries_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_parallel_queries_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query/worker/test_transaction_isolation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_transaction_isolation.py index 92026dd1..3285adb7 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_transaction_isolation.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_transaction_isolation.py @@ -1,7 +1,3 @@ -from rhosocial.activerecord.testsuite.feature.query.worker.conftest import ( - order_fixtures_for_worker, - async_order_fixtures_for_worker, -) -from rhosocial.activerecord.testsuite.feature.query.worker.test_transaction_isolation import * -from rhosocial.activerecord.testsuite.feature.query.worker.test_transaction_isolation_async import * # noqa: F403 - +# tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_transaction_isolation.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_sqlserver_test/feature/query/worker/test_transaction_isolation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_transaction_isolation_async.py index 8b86db71..ec1af4b2 100644 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_transaction_isolation_async.py +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query/worker/test_transaction_isolation_async.py @@ -1,3 +1,3 @@ # tests/rhosocial/activerecord_sqlserver_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 +"""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_sqlserver_test/feature/query_integration/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/conftest.py new file mode 100644 index 00000000..0ae4f318 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query_integration/test_active_query_set_operation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/test_active_query_set_operation.py new file mode 100644 index 00000000..3d89acde --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/test_active_query_set_operation.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query_integration/test_active_query_set_operation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/test_active_query_set_operation_async.py new file mode 100644 index 00000000..d09effe4 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/test_active_query_set_operation_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query_integration/test_cte_query_active_query.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/test_cte_query_active_query.py new file mode 100644 index 00000000..9e13dc4c --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/test_cte_query_active_query.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query_integration/test_cte_query_active_query_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/test_cte_query_active_query_async.py new file mode 100644 index 00000000..3f570403 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/test_cte_query_active_query_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query_integration/test_cte_query_set_operation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/test_cte_query_set_operation.py new file mode 100644 index 00000000..224eab24 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/test_cte_query_set_operation.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/query_integration/test_cte_query_set_operation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/test_cte_query_set_operation_async.py new file mode 100644 index 00000000..03032303 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/query_integration/test_cte_query_set_operation_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/base/test_base.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/base/test_base.py deleted file mode 100644 index 506e6070..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/base/test_base.py +++ /dev/null @@ -1,6 +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_sqlserver_test/feature/relation/base/test_base_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/base/test_base_async.py deleted file mode 100644 index 5259aa4a..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/base/test_interfaces.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/base/test_interfaces.py deleted file mode 100644 index 6b724a4e..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/base/test_interfaces.py +++ /dev/null @@ -1,6 +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_sqlserver_test/feature/relation/base/test_interfaces_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/base/test_interfaces_async.py deleted file mode 100644 index 688ea916..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/boundary/test_boundary.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/boundary/test_boundary.py deleted file mode 100644 index 0efbbf89..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/boundary/test_boundary_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/boundary/test_boundary_async.py deleted file mode 100644 index 591af194..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/cache/test_cache.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/cache/test_cache.py deleted file mode 100644 index 465f2c04..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/cache/test_cache.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/relation/test_cache.py - -from rhosocial.activerecord.testsuite.feature.relation.cache.test_cache import TestRelationCache # noqa: F401 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/cache/test_cache_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/cache/test_cache_async.py deleted file mode 100644 index 33f8eccb..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/cache/test_cache_clearing.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/cache/test_cache_clearing.py deleted file mode 100644 index ae990e84..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/cache/test_cache_clearing_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/cache/test_cache_clearing_async.py deleted file mode 100644 index 152cff85..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/cache/test_cache_clearing_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/conftest.py deleted file mode 100644 index 1a011dcf..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/conftest.py +++ /dev/null @@ -1 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.conftest import * # noqa: F401,F403 diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field.py deleted file mode 100644 index c438e527..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field.py -"""Bridge file for sync relation derived field tests.""" -from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field import * # noqa: F401, F403, E402 \ No newline at end of file diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field_async.py deleted file mode 100644 index fa6fda71..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field_async.py -"""Bridge file for async relation derived field tests.""" -from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_async import * # noqa: F401, F403, E402 \ No newline at end of file diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field_json.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field_json.py deleted file mode 100644 index 83a4097d..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field_json.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field_json.py -"""Bridge file for JSON-derived field tests.""" -from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json import * # noqa: F401, F403, E402 -from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json_async import * # noqa: F403, E402 \ No newline at end of file diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field_json_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field_json_async.py deleted file mode 100644 index 8a461a5a..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field_json_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/relation/derived/test_derived_field_json_async.py -"""Bridge file for async JSON-derived field tests.""" -from rhosocial.activerecord.testsuite.feature.relation.derived.test_relation_derived_field_json_async import * # noqa: F401, F403, E402 \ No newline at end of file diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/descriptors/test_descriptor_compat.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/descriptors/test_descriptor_compat.py deleted file mode 100644 index e433c58f..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/descriptors/test_descriptor_compat.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/descriptors/test_descriptor_compat_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/descriptors/test_descriptor_compat_async.py deleted file mode 100644 index 494db72d..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/descriptors/test_descriptor_compat_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/descriptors/test_descriptors.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/descriptors/test_descriptors.py deleted file mode 100644 index 25a9db32..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/descriptors/test_descriptors.py +++ /dev/null @@ -1,6 +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_sqlserver_test/feature/relation/descriptors/test_descriptors_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/descriptors/test_descriptors_async.py deleted file mode 100644 index fd4eba97..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/descriptors/test_descriptors_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/eager_loading/test_nested_relationship_access.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/eager_loading/test_nested_relationship_access.py deleted file mode 100644 index 15605d8d..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/eager_loading/test_nested_relationship_access.py +++ /dev/null @@ -1,2 +0,0 @@ -from rhosocial.activerecord.testsuite.feature.relation.eager_loading.test_nested_relationship_access import * # noqa: F401,F403 - diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/eager_loading/test_nested_relationship_access_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/eager_loading/test_nested_relationship_access_async.py deleted file mode 100644 index 6ea7cbbe..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/eager_loading/test_with_method.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/eager_loading/test_with_method.py deleted file mode 100644 index a1ce8686..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/eager_loading/test_with_method_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/eager_loading/test_with_method_async.py deleted file mode 100644 index a2c28563..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/integration/test_integration.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/integration/test_integration.py deleted file mode 100644 index 66a51787..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/integration/test_integration.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/relation/integration/test_integration.py -"""Bridge file for relation integration tests.""" -from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration import * # noqa: F401, F403, E402 -from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration_async import * # noqa: F403, E402 \ No newline at end of file diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/integration/test_integration_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/integration/test_integration_async.py deleted file mode 100644 index 28bb1d41..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/integration/test_integration_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/relation/integration/test_integration_async.py -"""Bridge file for async relation integration tests.""" -from rhosocial.activerecord.testsuite.feature.relation.integration.test_integration_async import * # noqa: F401, F403, E402 \ No newline at end of file diff --git a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/modifiers/test_modifier_behavior.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/modifiers/test_modifier_behavior.py deleted file mode 100644 index 8fc621f3..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/modifiers/test_modifier_behavior_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/modifiers/test_modifier_behavior_async.py deleted file mode 100644 index 797fa5e3..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/modifiers/test_modifier_warning.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/modifiers/test_modifier_warning.py deleted file mode 100644 index 2b7b7bc8..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/modifiers/test_modifier_warning_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/modifiers/test_modifier_warning_async.py deleted file mode 100644 index 6e884253..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/ordering/test_has_many_order_by.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/ordering/test_has_many_order_by.py deleted file mode 100644 index 59300264..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/ordering/test_has_many_order_by.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_test/feature/relation/ordering/test_has_many_order_by.py -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_sqlserver_test/feature/relation/validation/test_path_validation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/validation/test_path_validation.py deleted file mode 100644 index b2b0a150..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/validation/test_path_validation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/validation/test_path_validation_async.py deleted file mode 100644 index b492478f..00000000 --- a/tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/validation/test_validator.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/validation/test_validator.py deleted file mode 100644 index ab553ce5..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/validation/test_validator.py +++ /dev/null @@ -1,4 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/relation/validation/test_validator_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/relation/validation/test_validator_async.py deleted file mode 100644 index 53e1c324..00000000 --- a/tests/rhosocial/activerecord_sqlserver_test/feature/relation/validation/test_validator_async.py +++ /dev/null @@ -1,3 +0,0 @@ -# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/setop/conftest.py b/tests/rhosocial/activerecord_sqlserver_test/feature/setop/conftest.py new file mode 100644 index 00000000..5a265e49 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/setop/conftest.py @@ -0,0 +1,3 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/setop/test_composite_pk_set_operation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/setop/test_composite_pk_set_operation.py new file mode 100644 index 00000000..3809b968 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/setop/test_composite_pk_set_operation.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/setop/test_composite_pk_set_operation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/setop/test_composite_pk_set_operation_async.py new file mode 100644 index 00000000..6f6f6fba --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/setop/test_composite_pk_set_operation_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/setop/test_set_operation.py b/tests/rhosocial/activerecord_sqlserver_test/feature/setop/test_set_operation.py new file mode 100644 index 00000000..6a0195a4 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/setop/test_set_operation.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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_sqlserver_test/feature/setop/test_set_operation_async.py b/tests/rhosocial/activerecord_sqlserver_test/feature/setop/test_set_operation_async.py new file mode 100644 index 00000000..85d2c1d2 --- /dev/null +++ b/tests/rhosocial/activerecord_sqlserver_test/feature/setop/test_set_operation_async.py @@ -0,0 +1,9 @@ +# tests/rhosocial/activerecord_sqlserver_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/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/sqlserver.py b/tests/support/sqlserver.py new file mode 100644 index 00000000..a184a7d0 --- /dev/null +++ b/tests/support/sqlserver.py @@ -0,0 +1,171 @@ +# tests/support/sqlserver.py +"""The SQL Server 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. SQL Server is a +server backend, so a scenario maps to one database on one instance. + +Maintenance work (dropping and creating databases, server-level checks) runs on +the ``master`` database every SQL Server 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 pyodbc +import yaml +from rhosocial.activerecord.backend.options import ExecutionOptions +from rhosocial.activerecord.backend.schema import StatementType +from rhosocial.activerecord.backend.impl.sqlserver.backend import ( + AsyncSQLServerBackend, + SQLServerBackend, +) +from rhosocial.activerecord.backend.impl.sqlserver.config import SQLServerConnectionConfig + +CONFIG_PATH = Path( + os.environ.get("SQLSERVER_SCENARIOS_CONFIG_PATH") + or Path(__file__).resolve().parents[1] / "config" / "sqlserver_scenarios.yaml" +) + +# Every test backend opens and closes its own connection. The ODBC driver's +# connection pool then hands that closed connection to the next test with +# whatever result sets were still pending on it, and SQL Server answers some +# DDL with informational messages -- so the next test's first statement is +# refused with "Connection is busy with results for another command". The +# test tree wants one clean physical connection per backend, so pooling is off +# for this process. +pyodbc.pooling = False + +# 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. +SERVER_ONLY_KEYS = ("database",) + +# The database every SQL Server instance has, used for server-level connections. +MAINTENANCE_DATABASE = "master" + +DDL_OPTIONS = ExecutionOptions(stmt_type=StatementType.DDL) +DQL_OPTIONS = ExecutionOptions(stmt_type=StatementType.DQL) + + +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 SQL Server identifier (database names come from the testsuite).""" + return "[" + name.replace("]", "]]") + "]" + + +@dataclass(frozen=True) +class SQLServerScenario: + """One SQL Server test scenario: an instance plus the backend classes.""" + + name: str + server: Dict[str, Any] + backend_class: Any = SQLServerBackend + async_backend_class: Any = AsyncSQLServerBackend + maintenance_database: str = "master" + + def make_config(self, database: str) -> SQLServerConnectionConfig: + """Return the connection configuration for this database on this instance.""" + return SQLServerConnectionConfig(**self.server, database=database) + + def reset_database(self, database: str) -> None: + """Drop and recreate ``database`` on this scenario's instance. + + ``READ_COMMITTED_SNAPSHOT`` is turned on as part of the creation: the + concurrency tests read while another connection writes, and statement + snapshots are what keep those readers from blocking (or deadlocking) + each other. The CI workflow used to pre-enable the option on its single + ``test_db``; every directory now owns a database of its own, so it is + enabled here, while the database is still free of other connections. + """ + backend = self.backend_class( + connection_config=SQLServerConnectionConfig( + **self.server, database=MAINTENANCE_DATABASE + ) + ) + backend.connect() + try: + identifier = _identifier(database) + exists = bool( + backend.execute( + "SELECT name FROM sys.databases WHERE name = ?", + (database,), + options=DQL_OPTIONS, + ).data + ) + if exists: + # A leftover database may still have connections attached; the + # single-user switch evicts them so the drop cannot block. + backend.execute( + f"ALTER DATABASE {identifier} SET SINGLE_USER WITH ROLLBACK IMMEDIATE", + (), + options=DDL_OPTIONS, + ) + backend.execute( + f"DROP DATABASE IF EXISTS {identifier}", + (), + options=DDL_OPTIONS, + ) + backend.execute( + f"CREATE DATABASE {identifier}", + (), + options=DDL_OPTIONS, + ) + backend.execute( + f"ALTER DATABASE {identifier} SET READ_COMMITTED_SNAPSHOT ON", + (), + options=DDL_OPTIONS, + ) + finally: + backend.disconnect() + + +def scenario(name: str) -> SQLServerScenario: + """Return the scenario called ``name``.""" + try: + server = SCENARIO_MAP[name] + except KeyError: + raise KeyError(f"Unknown SQL Server scenario: {name}") from None + return SQLServerScenario(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)