xtr-orm 7.1.0__tar.gz → 7.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. xtr_orm-7.1.0/README.md → xtr_orm-7.3.0/PKG-INFO +40 -1
  2. xtr_orm-7.1.0/PKG-INFO → xtr_orm-7.3.0/README.md +11 -30
  3. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/pyproject.toml +10 -10
  4. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/pyproject.toml.orig +10 -10
  5. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/.agents/skills/xtr-orm/SKILL.md +7 -2
  6. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/.agents/skills/xtr-orm/references/commands.md +11 -0
  7. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/.agents/skills/xtr-orm/references/connections.md +4 -0
  8. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/bundle/connection_config.py +13 -0
  9. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/bundle/orm_bundle.py +1 -6
  10. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/bundle/orm_mappings_pass.py +1 -4
  11. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/__init__.py +4 -0
  12. xtr_orm-7.3.0/src/xtr_orm/command/schema_update_command.py +98 -0
  13. xtr_orm-7.3.0/src/xtr_orm/command/schema_validate_command.py +111 -0
  14. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/__init__.py +2 -0
  15. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/_environment.py +46 -11
  16. xtr_orm-7.3.0/src/xtr_orm/migrations/_operations.py +48 -0
  17. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/_revisions.py +3 -2
  18. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/migrator.py +78 -2
  19. xtr_orm-7.3.0/src/xtr_orm/migrations/schema_comparison.py +60 -0
  20. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/LICENSE +0 -0
  21. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/.agents/skills/xtr-orm/references/messenger.md +0 -0
  22. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/.agents/skills/xtr-orm/references/migrations.md +0 -0
  23. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/__init__.py +0 -0
  24. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/bundle/__init__.py +0 -0
  25. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/bundle/_profiler.py +0 -0
  26. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/bundle/orm_config.py +0 -0
  27. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/_reporting.py +0 -0
  28. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/connection_command.py +0 -0
  29. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/database_create_command.py +0 -0
  30. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/database_drop_command.py +0 -0
  31. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/migrations_current_command.py +0 -0
  32. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/migrations_diff_command.py +0 -0
  33. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/migrations_dump_schema_command.py +0 -0
  34. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/migrations_execute_command.py +0 -0
  35. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/migrations_generate_command.py +0 -0
  36. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/migrations_latest_command.py +0 -0
  37. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/migrations_list_command.py +0 -0
  38. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/migrations_migrate_command.py +0 -0
  39. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/migrations_rollup_command.py +0 -0
  40. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/migrations_status_command.py +0 -0
  41. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/migrations_up_to_date_command.py +0 -0
  42. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/migrations_version_command.py +0 -0
  43. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/command/run_sql_command.py +0 -0
  44. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/connection_registry.py +0 -0
  45. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/data_collector/__init__.py +0 -0
  46. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/data_collector/_masking.py +0 -0
  47. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/data_collector/orm_data_collector.py +0 -0
  48. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/data_collector/query_listener.py +0 -0
  49. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/data_collector/recorded_query.py +0 -0
  50. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/database/__init__.py +0 -0
  51. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/database/database_manager.py +0 -0
  52. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/exception/__init__.py +0 -0
  53. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/exception/invalid_argument_error.py +0 -0
  54. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/exception/migration_error.py +0 -0
  55. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/exception/missing_database_error.py +0 -0
  56. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/exception/orm_error.py +0 -0
  57. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/exception/session_unavailable_error.py +0 -0
  58. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/exception/unknown_connection_error.py +0 -0
  59. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/exception/unsupported_database_error.py +0 -0
  60. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/mapping_driver_interface.py +0 -0
  61. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/messenger/__init__.py +0 -0
  62. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/messenger/close_connection_middleware.py +0 -0
  63. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/messenger/open_transaction_logger_middleware.py +0 -0
  64. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/messenger/transaction_middleware.py +0 -0
  65. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/messenger_transport.py +0 -0
  66. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/_history.py +0 -0
  67. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/_schema.py +0 -0
  68. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/available_migration.py +0 -0
  69. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/direction.py +0 -0
  70. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/executed_migration.py +0 -0
  71. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/execution_result.py +0 -0
  72. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/migration_plan.py +0 -0
  73. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/migration_status.py +0 -0
  74. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/migrations_config.py +0 -0
  75. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/migrations/template/script.py.mako +0 -0
  76. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/py.typed +0 -0
  77. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/recipe/__init__.py +0 -0
  78. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/recipe/files/config/orm.py.tmpl +0 -0
  79. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/recipe/manifest.toml +0 -0
  80. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/stickiness_participant.py +0 -0
  81. {xtr_orm-7.1.0 → xtr_orm-7.3.0}/src/xtr_orm/templates/collector/orm.html.j2 +0 -0
@@ -1,3 +1,32 @@
1
+ Metadata-Version: 2.4
2
+ Name: xtr-orm
3
+ Version: 7.3.0
4
+ Summary: Databases for async applications: engines, sessions and versioned schema migrations, configured once per connection.
5
+ Keywords: orm,database,migrations,sqlalchemy,alembic,asyncio
6
+ Author: Xterr
7
+ Author-email: Xterr <me@xterr.dev>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Framework :: AsyncIO
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Topic :: Database
15
+ Classifier: Typing :: Typed
16
+ Requires-Dist: advanced-alchemy>=1.11
17
+ Requires-Dist: alembic>=1.20
18
+ Requires-Dist: sqlalchemy[asyncio]>=2.0.52
19
+ Requires-Dist: xtr-clock>=7.3,<8
20
+ Requires-Dist: xtr-logging-contracts>=7.3,<8
21
+ Requires-Dist: asyncmy>=0.2.12 ; extra == 'mysql'
22
+ Requires-Dist: asyncpg>=0.31 ; extra == 'postgres'
23
+ Requires-Dist: aiosqlite>=0.20 ; extra == 'sqlite'
24
+ Requires-Python: >=3.14.4
25
+ Provides-Extra: mysql
26
+ Provides-Extra: postgres
27
+ Provides-Extra: sqlite
28
+ Description-Content-Type: text/markdown
29
+
1
30
  <div align="center">
2
31
 
3
32
  # xtr-orm
@@ -34,7 +63,7 @@ its engine and session options, where its revisions live — and get:
34
63
  - 📜 **A full history**: every revision applied, when, and how long it took.
35
64
  - 🧾 **One transaction per message** — with [xtr-messenger](../xtr-messenger), every handler of
36
65
  a message shares one session, committed once they all succeeded and rolled back otherwise.
37
- - 🛠️ **Fifteen console commands**, from `orm:database:create` to `orm:migrations:up-to-date`.
66
+ - 🛠️ **Seventeen console commands**, from `orm:database:create` to `orm:schema:validate`.
38
67
 
39
68
  ## Install
40
69
 
@@ -44,6 +73,7 @@ uv add "xtr-orm[postgres]" xtr-dependency-injection # + the container, for the
44
73
  uv add xtr-console # beside it: the orm:* commands
45
74
  uv add xtr-messenger # beside it: the message bus middleware
46
75
  uv add "xtr-messenger[orm]" # beside it: the orm:// transport too
76
+ uv add --dev xtr-orm-fixtures # beside it: seed databases from fixture classes
47
77
  ```
48
78
 
49
79
  | Extra | Brings | For |
@@ -109,6 +139,9 @@ one (`+1`, `-2`, `ae10+1`), or `latest`, `first` (before every revision), `next`
109
139
  | `plan_for_versions(versions, direction)` / `execute(...)` / `execute_sql(...)` | What running exactly those revisions, each up or down, runs — every id resolved and checked / run them, nothing before or after / the SQL it would run |
110
140
  | `generate(message)` | Write an empty revision after the latest |
111
141
  | `diff(message, allow_empty=, from_empty_schema=)` | Write what differs between the database and the table definitions |
142
+ | `compare()` | What differs between the database and the table definitions — nothing written or run |
143
+ | `apply(comparison)` | Run the comparison against the database, recording nothing |
144
+ | `apply_sql(comparison)` | The SQL `apply()` would run |
112
145
  | `dump_schema(message, table_filters=)` | Write a first revision creating every table an existing database has |
113
146
  | `add_versions(versions)` / `add_all_versions()` | Record revisions as applied, running nothing |
114
147
  | `delete_versions(versions)` / `delete_all_versions()` | Record revisions as not applied, running nothing |
@@ -309,6 +342,10 @@ every message is a unit of work: its handlers share one `AsyncSession` per conne
309
342
  | `metadata` | `None` | The table definitions a diff compares with; advanced-alchemy's for `bind_key` when `None` |
310
343
  | `migrations` | `None` | `MigrationsConfig`; `migrations` in the project directory for the default connection, `migrations/<name>` for any other, when `None` |
311
344
 
345
+ `connection.table_definitions()` returns the table definitions in force for a connection —
346
+ its `metadata`, else advanced-alchemy's for its `bind_key` — the ones its migrations compare
347
+ the database with, for any library that must act on the same tables.
348
+
312
349
  ### Options in the URL
313
350
 
314
351
  One environment variable can configure a whole connection. An engine or session option, or
@@ -433,6 +470,8 @@ commands that change the database ask first; `-n` answers yes.
433
470
  | `orm:database:create [--if-not-exists]` | Creates the database, through the server's maintenance database |
434
471
  | `orm:database:drop --force [--if-exists]` | Drops it; refused without `--force` |
435
472
  | `orm:run-sql SQL [--force-fetch]` | Runs a statement as written, committed — a `:word` is never read as a parameter; shows its rows or how many it changed — when the driver can tell |
473
+ | `orm:schema:update [--dump-sql] [--force]` | Brings the database schema to the table definitions, printing or running the changes — no revision written or recorded; orphaned tables are dropped, `MigrationsConfig.include_object` keeps them; without either flag it only describes the changes and exits 1 |
474
+ | `orm:schema:validate [--skip-mapping] [--skip-sync]` | Exits 1 when the mapping does not validate, 2 when the schema differs from the table definitions — 3 for both; `-v` dumps the statements that would bring it in sync |
436
475
  | `orm:migrations:current` | The revisions the database is at — `base` for none |
437
476
  | `orm:migrations:latest` | The revisions no other follows |
438
477
  | `orm:migrations:list` | Every revision with its status, when it ran and how long it took |
@@ -1,32 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: xtr-orm
3
- Version: 7.1.0
4
- Summary: Databases for async applications: engines, sessions and versioned schema migrations, configured once per connection.
5
- Keywords: orm,database,migrations,sqlalchemy,alembic,asyncio
6
- Author: Xterr
7
- Author-email: Xterr <me@xterr.dev>
8
- License-Expression: MIT
9
- License-File: LICENSE
10
- Classifier: Development Status :: 3 - Alpha
11
- Classifier: Framework :: AsyncIO
12
- Classifier: Intended Audience :: Developers
13
- Classifier: Programming Language :: Python :: 3.14
14
- Classifier: Topic :: Database
15
- Classifier: Typing :: Typed
16
- Requires-Dist: advanced-alchemy>=1.11
17
- Requires-Dist: alembic>=1.20
18
- Requires-Dist: sqlalchemy[asyncio]>=2.0.52
19
- Requires-Dist: xtr-clock>=7.0,<8
20
- Requires-Dist: xtr-logging-contracts>=7.0,<8
21
- Requires-Dist: asyncmy>=0.2.12 ; extra == 'mysql'
22
- Requires-Dist: asyncpg>=0.31 ; extra == 'postgres'
23
- Requires-Dist: aiosqlite>=0.20 ; extra == 'sqlite'
24
- Requires-Python: >=3.14.4
25
- Provides-Extra: mysql
26
- Provides-Extra: postgres
27
- Provides-Extra: sqlite
28
- Description-Content-Type: text/markdown
29
-
30
1
  <div align="center">
31
2
 
32
3
  # xtr-orm
@@ -63,7 +34,7 @@ its engine and session options, where its revisions live — and get:
63
34
  - 📜 **A full history**: every revision applied, when, and how long it took.
64
35
  - 🧾 **One transaction per message** — with [xtr-messenger](../xtr-messenger), every handler of
65
36
  a message shares one session, committed once they all succeeded and rolled back otherwise.
66
- - 🛠️ **Fifteen console commands**, from `orm:database:create` to `orm:migrations:up-to-date`.
37
+ - 🛠️ **Seventeen console commands**, from `orm:database:create` to `orm:schema:validate`.
67
38
 
68
39
  ## Install
69
40
 
@@ -73,6 +44,7 @@ uv add "xtr-orm[postgres]" xtr-dependency-injection # + the container, for the
73
44
  uv add xtr-console # beside it: the orm:* commands
74
45
  uv add xtr-messenger # beside it: the message bus middleware
75
46
  uv add "xtr-messenger[orm]" # beside it: the orm:// transport too
47
+ uv add --dev xtr-orm-fixtures # beside it: seed databases from fixture classes
76
48
  ```
77
49
 
78
50
  | Extra | Brings | For |
@@ -138,6 +110,9 @@ one (`+1`, `-2`, `ae10+1`), or `latest`, `first` (before every revision), `next`
138
110
  | `plan_for_versions(versions, direction)` / `execute(...)` / `execute_sql(...)` | What running exactly those revisions, each up or down, runs — every id resolved and checked / run them, nothing before or after / the SQL it would run |
139
111
  | `generate(message)` | Write an empty revision after the latest |
140
112
  | `diff(message, allow_empty=, from_empty_schema=)` | Write what differs between the database and the table definitions |
113
+ | `compare()` | What differs between the database and the table definitions — nothing written or run |
114
+ | `apply(comparison)` | Run the comparison against the database, recording nothing |
115
+ | `apply_sql(comparison)` | The SQL `apply()` would run |
141
116
  | `dump_schema(message, table_filters=)` | Write a first revision creating every table an existing database has |
142
117
  | `add_versions(versions)` / `add_all_versions()` | Record revisions as applied, running nothing |
143
118
  | `delete_versions(versions)` / `delete_all_versions()` | Record revisions as not applied, running nothing |
@@ -338,6 +313,10 @@ every message is a unit of work: its handlers share one `AsyncSession` per conne
338
313
  | `metadata` | `None` | The table definitions a diff compares with; advanced-alchemy's for `bind_key` when `None` |
339
314
  | `migrations` | `None` | `MigrationsConfig`; `migrations` in the project directory for the default connection, `migrations/<name>` for any other, when `None` |
340
315
 
316
+ `connection.table_definitions()` returns the table definitions in force for a connection —
317
+ its `metadata`, else advanced-alchemy's for its `bind_key` — the ones its migrations compare
318
+ the database with, for any library that must act on the same tables.
319
+
341
320
  ### Options in the URL
342
321
 
343
322
  One environment variable can configure a whole connection. An engine or session option, or
@@ -462,6 +441,8 @@ commands that change the database ask first; `-n` answers yes.
462
441
  | `orm:database:create [--if-not-exists]` | Creates the database, through the server's maintenance database |
463
442
  | `orm:database:drop --force [--if-exists]` | Drops it; refused without `--force` |
464
443
  | `orm:run-sql SQL [--force-fetch]` | Runs a statement as written, committed — a `:word` is never read as a parameter; shows its rows or how many it changed — when the driver can tell |
444
+ | `orm:schema:update [--dump-sql] [--force]` | Brings the database schema to the table definitions, printing or running the changes — no revision written or recorded; orphaned tables are dropped, `MigrationsConfig.include_object` keeps them; without either flag it only describes the changes and exits 1 |
445
+ | `orm:schema:validate [--skip-mapping] [--skip-sync]` | Exits 1 when the mapping does not validate, 2 when the schema differs from the table definitions — 3 for both; `-v` dumps the statements that would bring it in sync |
465
446
  | `orm:migrations:current` | The revisions the database is at — `base` for none |
466
447
  | `orm:migrations:latest` | The revisions no other follows |
467
448
  | `orm:migrations:list` | Every revision with its status, when it ran and how long it took |
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "xtr-orm"
3
- version = "7.1.0"
3
+ version = "7.3.0"
4
4
  description = "Databases for async applications: engines, sessions and versioned schema migrations, configured once per connection."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.14.4"
@@ -26,8 +26,8 @@ dependencies = [
26
26
  "advanced-alchemy>=1.11",
27
27
  "alembic>=1.20",
28
28
  "sqlalchemy[asyncio]>=2.0.52",
29
- "xtr-clock>=7.0,<8",
30
- "xtr-logging-contracts>=7.0,<8",
29
+ "xtr-clock>=7.3,<8",
30
+ "xtr-logging-contracts>=7.3,<8",
31
31
  ]
32
32
 
33
33
  [[project.authors]]
@@ -53,14 +53,14 @@ dev = [
53
53
  "pytest-cov>=7.1",
54
54
  "anyio>=4.10",
55
55
  "ty>=0.0.83",
56
- "xtr-http-kernel>=7.0,<8",
56
+ "xtr-http-kernel>=7.3,<8",
57
57
  "aiosqlite>=0.20",
58
- "xtr-console>=7.0,<8",
59
- "xtr-dependency-injection>=7.0,<8",
60
- "xtr-logging>=7.0,<8",
61
- "xtr-messenger>=7.0,<8",
62
- "xtr-orm-messenger>=7.0,<8",
63
- "xtr-service-contracts>=7.0,<8",
58
+ "xtr-console>=7.3,<8",
59
+ "xtr-dependency-injection>=7.3,<8",
60
+ "xtr-logging>=7.3,<8",
61
+ "xtr-messenger>=7.3,<8",
62
+ "xtr-orm-messenger>=7.3,<8",
63
+ "xtr-service-contracts>=7.3,<8",
64
64
  ]
65
65
 
66
66
  [build-system]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "xtr-orm"
3
- version = "7.1.0"
3
+ version = "7.3.0"
4
4
  description = "Databases for async applications: engines, sessions and versioned schema migrations, configured once per connection."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.14.4"
@@ -23,8 +23,8 @@ dependencies = [
23
23
  "alembic>=1.20",
24
24
  "sqlalchemy[asyncio]>=2.0.52",
25
25
  # The profiler panel times each statement on its monotonic clock.
26
- "xtr-clock>=7.0,<8",
27
- "xtr-logging-contracts>=7.0,<8",
26
+ "xtr-clock>=7.3,<8",
27
+ "xtr-logging-contracts>=7.3,<8",
28
28
  ]
29
29
 
30
30
  [project.optional-dependencies]
@@ -56,15 +56,15 @@ dev = [
56
56
  "anyio>=4.10",
57
57
  "ty>=0.0.83",
58
58
  # The profiler panel's collector, tested against the http kernel's profiler.
59
- "xtr-http-kernel>=7.0,<8",
59
+ "xtr-http-kernel>=7.3,<8",
60
60
  # Every test runs on SQLite files under the test's own directory: no server.
61
61
  "aiosqlite>=0.20",
62
- "xtr-console>=7.0,<8",
63
- "xtr-dependency-injection>=7.0,<8",
64
- "xtr-logging>=7.0,<8",
65
- "xtr-messenger>=7.0,<8",
66
- "xtr-orm-messenger>=7.0,<8",
67
- "xtr-service-contracts>=7.0,<8",
62
+ "xtr-console>=7.3,<8",
63
+ "xtr-dependency-injection>=7.3,<8",
64
+ "xtr-logging>=7.3,<8",
65
+ "xtr-messenger>=7.3,<8",
66
+ "xtr-orm-messenger>=7.3,<8",
67
+ "xtr-service-contracts>=7.3,<8",
68
68
  ]
69
69
 
70
70
  [build-system]
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: xtr-orm
3
- description: How to configure database connections, inject async sessions and run versioned schema migrations with xtr-orm. Use when application code needs an AsyncEngine, an AsyncSession, a session per request or per message, read replicas, a DATABASE_URL, a new migration revision, a schema diff against models, the orm:migrations:* or orm:database:* console commands, one transaction per message on a bus, when a library bundle must add tables it builds in code to a connection's definitions, or when adding OrmBundle to an application on xtr-dependency-injection.
3
+ description: How to configure database connections, inject async sessions and run versioned schema migrations with xtr-orm. Use when application code needs an AsyncEngine, an AsyncSession, a session per request or per message, read replicas, a DATABASE_URL, a new migration revision, a schema diff against models, the orm:migrations:*, orm:database:* or orm:schema:* console commands, one transaction per message on a bus, when a library bundle must add tables it builds in code to a connection's definitions, or when adding OrmBundle to an application on xtr-dependency-injection.
4
4
  ---
5
5
 
6
6
  # xtr-orm
@@ -82,6 +82,9 @@ only.
82
82
  | `await migrator.execute(versions, Direction.UP)` | Exactly those revisions, nothing before or after. `plan_for_versions(versions, direction)` and `execute_sql(...)` alongside |
83
83
  | `migrator.generate("message")` | Writes an empty revision after the latest (not awaited) |
84
84
  | `await migrator.diff("message")` | Writes what the table definitions add; takes `allow_empty=`, `from_empty_schema=` |
85
+ | `await migrator.compare()` | What differs between the database and the table definitions — nothing written or run; backs `orm:schema:update` and `orm:schema:validate` |
86
+ | `await migrator.apply(comparison)` | Runs the comparison against the database, recording nothing — `orm:schema:update --force` |
87
+ | `await migrator.apply_sql(comparison)` | The SQL `apply()` would run — `orm:schema:update --dump-sql`, and `orm:schema:validate` at `-v` |
85
88
  | `await migrator.dump_schema("message", table_filters=...)` | A first revision creating every table an existing database has |
86
89
  | `await migrator.add_versions(v)` / `add_all_versions()` | Records revisions as applied, running nothing |
87
90
  | `await migrator.delete_versions(v)` / `delete_all_versions()` | Records them as not applied |
@@ -207,8 +210,10 @@ answers yes.
207
210
  | `orm:migrations:up-to-date` | Exits non-zero when revisions are not applied — for a deploy check |
208
211
  | `orm:database:create` / `:drop --force` | The database itself |
209
212
  | `orm:run-sql SQL` | Runs one statement, committed |
213
+ | `orm:schema:update [--dump-sql] [--force]` | Brings the database schema to the table definitions, printing or running the changes — no revision written or recorded; without either flag it only describes them and exits 1 |
214
+ | `orm:schema:validate [--skip-mapping] [--skip-sync]` | Exits 1 when the mapping does not validate, 2 when the schema differs from the table definitions — 3 for both; `-v` dumps the statements bringing it in sync |
210
215
 
211
- Nine more, and every flag: [references/commands.md](references/commands.md).
216
+ The rest, and every flag: [references/commands.md](references/commands.md).
212
217
 
213
218
  Deploy order: `orm:migrations:migrate` from **one** place, before the application starts —
214
219
  migrations take no lock.
@@ -15,6 +15,17 @@ change the database ask first, and `-n` answers yes. `--message` names the revis
15
15
  | `orm:database:drop` | `--force` / `-f` — required, the confirmation that everything may be lost; `--if-exists` |
16
16
  | `orm:run-sql SQL` | `--force-fetch` — show rows even when the statement does not look like it returns any. The statement is committed |
17
17
 
18
+ ## The schema
19
+
20
+ Both commands compare the live database with the table definitions — the revisions it is at play
21
+ no part — and nothing is written or recorded; tables the database has but the definitions do not
22
+ are dropped, unless `MigrationsConfig.include_object` keeps them.
23
+
24
+ | Command | Flags |
25
+ |---|---|
26
+ | `orm:schema:update` | `--dump-sql` prints the statements bringing the database in sync, and runs nothing; `--force` / `-f` runs them — both together print, then run. With neither it cautions and exits 1; in sync it exits 0 |
27
+ | `orm:schema:validate` | `--skip-mapping` checks the schema only, `--skip-sync` the mapping only. Exits 1 when the mapping does not validate, 2 when the schema differs from the table definitions — 3 for both; `-v` dumps the statements bringing it in sync |
28
+
18
29
  ## Reading where the database stands
19
30
 
20
31
  | Command | Shows |
@@ -14,6 +14,10 @@
14
14
  | `metadata` | `None` | The table definitions a diff compares the database with; those registered for `bind_key` when `None` |
15
15
  | `migrations` | `None` | A `MigrationsConfig`; `%kernel.project_dir%/migrations` for the default connection, `.../migrations/<name>` for any other, when `None` |
16
16
 
17
+ `connection.table_definitions()` returns the definitions in force — `metadata`, else those
18
+ registered for `bind_key` — the ones the connection's migrations compare the database with. Use
19
+ it rather than repeating that rule.
20
+
17
21
  An unknown key in `engine_options`, `session_options` or `alchemy_options` raises
18
22
  `InvalidArgumentError` at configuration time, naming the options that exist. Options the bundle
19
23
  sets itself — `connection_string`, `engine_config`, `session_config`, `bind_key`, `metadata`,
@@ -7,6 +7,7 @@ from collections.abc import Callable, Mapping, Sequence
7
7
  from dataclasses import dataclass, field
8
8
  from typing import Final, cast, override
9
9
 
10
+ from advanced_alchemy.base import metadata_registry
10
11
  from advanced_alchemy.config import AsyncSessionConfig, EngineConfig, SQLAlchemyAsyncConfig
11
12
  from sqlalchemy import MetaData, make_url
12
13
  from sqlalchemy.exc import ArgumentError
@@ -217,6 +218,18 @@ class ConnectionConfig:
217
218
  "alchemy", SQLAlchemyAsyncConfig, self.alchemy_options, exclude=_SET_BY_THE_BUNDLE
218
219
  )
219
220
 
221
+ def table_definitions(self) -> MetaData | Sequence[MetaData]:
222
+ """Return the table definitions this connection's migrations compare the database with.
223
+
224
+ Its own :attr:`metadata` when set, else those advanced-alchemy
225
+ registers for its :attr:`bind_key`. Read from the configuration as
226
+ written: neither rides on the URL, which may still be an ``env(...)``
227
+ placeholder.
228
+ """
229
+ if self.metadata is not None:
230
+ return self.metadata
231
+ return metadata_registry.get(self.bind_key)
232
+
220
233
  def with_url_options(self) -> ConnectionConfig:
221
234
  """Return this connection with the options its URL carries merged into it.
222
235
 
@@ -41,7 +41,6 @@ from importlib.util import find_spec
41
41
  from operator import contains
42
42
  from typing import Annotated, Final, cast, final, override
43
43
 
44
- from advanced_alchemy.base import metadata_registry
45
44
  from advanced_alchemy.config import AsyncSessionConfig, EngineConfig, SQLAlchemyAsyncConfig
46
45
  from advanced_alchemy.config.routing import EngineConfig as ReplicaEngine
47
46
  from advanced_alchemy.config.routing import RoutingConfig, RoutingStrategy
@@ -389,11 +388,7 @@ def _migrator_factory(
389
388
 
390
389
  async def migrator(container: ContainerInterface) -> Migrator:
391
390
  resolved = connection.with_url_options()
392
- metadata = (
393
- resolved.metadata
394
- if resolved.metadata is not None
395
- else metadata_registry.get(resolved.bind_key)
396
- )
391
+ metadata = resolved.table_definitions()
397
392
  if messages_tables:
398
393
  await _map_messages_tables(container, name, default, metadata)
399
394
  built = Migrator(
@@ -4,7 +4,6 @@ from __future__ import annotations
4
4
 
5
5
  from typing import Final, final
6
6
 
7
- from advanced_alchemy.base import metadata_registry
8
7
  from sqlalchemy import MetaData
9
8
  from xtr_dependency_injection import ContainerBuilder
10
9
 
@@ -199,9 +198,7 @@ def _definitions_of(name: str, connection: ConnectionConfig) -> MetaData:
199
198
  Raises:
200
199
  InvalidArgumentError: When the connection keeps several sets.
201
200
  """
202
- definitions = connection.metadata
203
- if definitions is None:
204
- return metadata_registry.get(connection.bind_key)
201
+ definitions = connection.table_definitions()
205
202
  if isinstance(definitions, MetaData):
206
203
  return definitions
207
204
  raise InvalidArgumentError(
@@ -37,6 +37,8 @@ from .migrations_status_command import MigrationsStatusCommand
37
37
  from .migrations_up_to_date_command import MigrationsUpToDateCommand
38
38
  from .migrations_version_command import MigrationsVersionCommand
39
39
  from .run_sql_command import RunSqlCommand
40
+ from .schema_update_command import SchemaUpdateCommand
41
+ from .schema_validate_command import SchemaValidateCommand
40
42
 
41
43
  __all__ = [
42
44
  "DatabaseCreateCommand",
@@ -54,4 +56,6 @@ __all__ = [
54
56
  "MigrationsUpToDateCommand",
55
57
  "MigrationsVersionCommand",
56
58
  "RunSqlCommand",
59
+ "SchemaUpdateCommand",
60
+ "SchemaValidateCommand",
57
61
  ]
@@ -0,0 +1,98 @@
1
+ """``orm:schema:update``: bring the database schema to the table definitions, without a revision."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Annotated, final
6
+
7
+ from sqlalchemy.exc import SQLAlchemyError
8
+ from xtr_console import ConsoleStyle, ExitCode, Option, as_command, escape
9
+
10
+ from xtr_orm.exception import MigrationError
11
+
12
+ from .connection_command import ConnectionCommand
13
+
14
+ __all__ = ["SchemaUpdateCommand"]
15
+
16
+
17
+ @as_command("orm:schema:update")
18
+ @final
19
+ class SchemaUpdateCommand(ConnectionCommand):
20
+ """Brings the database schema to the table definitions, without a revision."""
21
+
22
+ __slots__ = ()
23
+
24
+ async def __call__( # noqa: PLR0911 — each way out says why it stopped
25
+ self,
26
+ io: ConsoleStyle,
27
+ *,
28
+ dump_sql: bool = False,
29
+ force: Annotated[bool, Option(alias="-f")] = False,
30
+ connection: str | None = None,
31
+ ) -> int:
32
+ """Compare the database with the table definitions, and print or run what differs.
33
+
34
+ The database is compared as it is — the revisions it is at play no
35
+ part — and nothing is written or recorded: no revision file, no row
36
+ in the version or history tables. Tables the database has but the
37
+ definitions do not are dropped; MigrationsConfig.include_object is
38
+ the escape hatch keeping them.
39
+
40
+ Args:
41
+ io: Where the command writes.
42
+ dump_sql: Print the statements bringing the database in sync,
43
+ and run nothing.
44
+ force: Run the statements.
45
+ connection: The connection to update; the default one when left
46
+ out.
47
+ """
48
+ migrator = await self._migrator(io, connection)
49
+ if migrator is None:
50
+ return ExitCode.FAILURE
51
+ try:
52
+ comparison = await migrator.compare()
53
+ except MigrationError as error:
54
+ io.error(escape(error.reason))
55
+ return ExitCode.FAILURE
56
+ name = escape(self._name(connection))
57
+ if comparison.is_empty:
58
+ io.success(
59
+ f'Nothing to update: the "{name}" connection\'s database schema is in sync '
60
+ "with the table definitions."
61
+ )
62
+ return ExitCode.SUCCESS
63
+ changes = comparison.changes
64
+ plural = "" if changes == 1 else "s"
65
+ if dump_sql:
66
+ io.text(escape(await migrator.apply_sql(comparison)))
67
+ if force:
68
+ try:
69
+ await migrator.apply(comparison)
70
+ except (MigrationError, SQLAlchemyError) as error:
71
+ io.error(
72
+ f'Could not update the "{name}" connection\'s database schema: '
73
+ f"{escape(str(error))}"
74
+ )
75
+ return ExitCode.FAILURE
76
+ io.success(
77
+ f'Updated the "{name}" connection\'s database schema: '
78
+ f"{changes} change{plural} applied."
79
+ )
80
+ return ExitCode.SUCCESS
81
+ if dump_sql:
82
+ return ExitCode.SUCCESS
83
+ lines = [
84
+ "This operation should not be executed in a production environment.",
85
+ (
86
+ f'The "{name}" connection\'s database schema is not in sync with the '
87
+ f"table definitions: {changes} change{plural} would bring it in sync."
88
+ ),
89
+ ]
90
+ if comparison.dropped_tables:
91
+ dropped = ", ".join(f'"{escape(each)}"' for each in comparison.dropped_tables)
92
+ lines.append(
93
+ f"The tables the database has but the definitions do not would be "
94
+ f"dropped: {dropped}."
95
+ )
96
+ lines.append("Re-run with --dump-sql to see the statements, or with --force to run them.")
97
+ io.caution("\n".join(lines))
98
+ return ExitCode.FAILURE
@@ -0,0 +1,111 @@
1
+ """``orm:schema:validate``: check the mapping and the schema against the table definitions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+ from typing import TYPE_CHECKING, Final, final
7
+
8
+ from sqlalchemy import MetaData
9
+ from sqlalchemy.exc import SQLAlchemyError
10
+ from sqlalchemy.orm import configure_mappers
11
+ from xtr_console import ConsoleStyle, ExitCode, Verbosity, as_command, escape
12
+
13
+ from xtr_orm.exception import MigrationError
14
+
15
+ from .connection_command import ConnectionCommand
16
+
17
+ if TYPE_CHECKING:
18
+ from collections.abc import Sequence
19
+
20
+ __all__ = ["SchemaValidateCommand"]
21
+
22
+ _INVALID_MAPPING: Final = 1
23
+ """The exit-code part of a mapping that does not validate."""
24
+ _OUT_OF_SYNC: Final = 2
25
+ """The exit-code part of a schema not matching the table definitions."""
26
+
27
+
28
+ @as_command("orm:schema:validate")
29
+ @final
30
+ class SchemaValidateCommand(ConnectionCommand):
31
+ """Checks the mapping and the database schema against the table definitions."""
32
+
33
+ __slots__ = ()
34
+
35
+ async def __call__(
36
+ self,
37
+ io: ConsoleStyle,
38
+ *,
39
+ skip_mapping: bool = False,
40
+ skip_sync: bool = False,
41
+ connection: str | None = None,
42
+ ) -> int:
43
+ """Check the mapping and the database schema; the exit code says what failed.
44
+
45
+ The mapping check runs ``configure_mappers()`` — which configures
46
+ every mapper in the process, not only this connection's — and names
47
+ the tables the definitions hold more than once. The sync check
48
+ compares the database with the table definitions as it is — the
49
+ revisions it is at play no part — and, when they differ, shows the
50
+ statements bringing it in sync at ``-v``. Each failing check adds to
51
+ the exit code: 1 for the mapping, 2 for the schema — 3 for both.
52
+
53
+ Args:
54
+ io: Where the command writes.
55
+ skip_mapping: Check the database schema only.
56
+ skip_sync: Check the mapping only.
57
+ connection: The connection to validate; the default one when
58
+ left out.
59
+ """
60
+ migrator = await self._migrator(io, connection)
61
+ if migrator is None:
62
+ return ExitCode.FAILURE
63
+ code = 0
64
+ if not skip_mapping:
65
+ valid = True
66
+ for name in _duplicated_tables(migrator.metadata):
67
+ io.error(escape(f'The table definitions name "{name}" more than once.'))
68
+ valid = False
69
+ try:
70
+ configure_mappers()
71
+ except SQLAlchemyError as error:
72
+ io.error(escape(f"The mapping does not configure: {error}"))
73
+ valid = False
74
+ if valid:
75
+ io.success("The mapping is valid.")
76
+ else:
77
+ code += _INVALID_MAPPING
78
+ if not skip_sync:
79
+ name = escape(self._name(connection))
80
+ try:
81
+ comparison = await migrator.compare()
82
+ except MigrationError as error:
83
+ io.error(escape(error.reason))
84
+ code += _OUT_OF_SYNC
85
+ else:
86
+ if comparison.is_empty:
87
+ io.success(
88
+ f'The "{name}" connection\'s database schema is in sync '
89
+ "with the table definitions."
90
+ )
91
+ else:
92
+ io.error(
93
+ f'The "{name}" connection\'s database schema is not in sync '
94
+ "with the table definitions."
95
+ )
96
+ code += _OUT_OF_SYNC
97
+ io.text(
98
+ escape(await migrator.apply_sql(comparison)),
99
+ verbosity=Verbosity.VERBOSE,
100
+ )
101
+ return code
102
+
103
+
104
+ def _duplicated_tables(metadata: MetaData | Sequence[MetaData] | None) -> list[str]:
105
+ """Return the qualified names the definitions hold more than once, sorted."""
106
+ # Branching the union mirrors migrations/_schema.tables_of, which stays
107
+ # private to its subpackage rather than widening the public API for these
108
+ # three lines.
109
+ each = [metadata] if isinstance(metadata, MetaData) else metadata or ()
110
+ counts = Counter(table.fullname for one in each for table in one.sorted_tables)
111
+ return sorted(name for name, count in counts.items() if count > 1)
@@ -16,6 +16,7 @@ from .migration_plan import MigrationPlan
16
16
  from .migration_status import MigrationStatus
17
17
  from .migrations_config import MigrationsConfig
18
18
  from .migrator import Migrator
19
+ from .schema_comparison import SchemaComparison
19
20
 
20
21
  __all__ = [
21
22
  "AvailableMigration",
@@ -26,4 +27,5 @@ __all__ = [
26
27
  "MigrationStatus",
27
28
  "MigrationsConfig",
28
29
  "Migrator",
30
+ "SchemaComparison",
29
31
  ]
@@ -85,6 +85,29 @@ class Environment:
85
85
  },
86
86
  )
87
87
 
88
+ def comparison(self, connection: Connection) -> MigrationContext:
89
+ """Return a context comparing the database with the table definitions."""
90
+ options = self._schema_options()
91
+ options.update(self._config.context_options)
92
+ return MigrationContext.configure(connection, opts=options)
93
+
94
+ def invocation(
95
+ self, connection: Connection, *, output: IO[str] | None = None
96
+ ) -> MigrationContext:
97
+ """Return a context running the operations a comparison produced.
98
+
99
+ With ``output`` the context renders rather than runs: every
100
+ statement's SQL is written to it.
101
+ """
102
+ config = self._config
103
+ options: dict[str, object] = {}
104
+ if output is not None:
105
+ options = {"as_sql": True, "literal_binds": True, "output_buffer": output}
106
+ if config.transactional_ddl is not None:
107
+ options["transactional_ddl"] = config.transactional_ddl
108
+ options.update(config.context_options)
109
+ return MigrationContext.configure(connection, opts=options)
110
+
88
111
  def run( # noqa: PLR0913 — every runner option, each passed by keyword
89
112
  self,
90
113
  connection: Connection,
@@ -120,16 +143,7 @@ class Environment:
120
143
  ) as environment:
121
144
  options: dict[str, object] = {
122
145
  "connection": connection,
123
- "target_metadata": self._metadata,
124
- "version_table": config.version_table,
125
- "version_table_schema": config.version_table_schema,
126
146
  "transaction_per_migration": config.transaction_per_migration,
127
- "compare_type": config.compare_type,
128
- "compare_server_default": config.compare_server_default,
129
- "render_as_batch": config.render_as_batch,
130
- "include_schemas": config.include_schemas,
131
- "include_name": _include_name(config.include_name, config.history_table),
132
- "include_object": config.include_object,
133
147
  "render_item": _render_item(config.render_item, config.user_module_prefix),
134
148
  # Not "process_revision_directives": the migrator runs it inside its own,
135
149
  # which the runner would call first, before the revision is complete.
@@ -138,9 +152,8 @@ class Environment:
138
152
  "output_buffer": output,
139
153
  "on_version_apply": on_version_apply,
140
154
  "dont_mutate": read_only,
155
+ **self._schema_options(),
141
156
  }
142
- if config.transactional_ddl is not None:
143
- options["transactional_ddl"] = config.transactional_ddl
144
157
  options.update(config.context_options)
145
158
  # Forwarded by name, the application's own options included; the
146
159
  # runner checks each as it reads it.
@@ -149,6 +162,28 @@ class Environment:
149
162
  with environment.begin_transaction():
150
163
  environment.run_migrations()
151
164
 
165
+ def _schema_options(self) -> dict[str, object]:
166
+ """The options every comparison of the database with the definitions shares.
167
+
168
+ The runner diffs with exactly these, so a comparison reads what a diff
169
+ would write.
170
+ """
171
+ config = self._config
172
+ options: dict[str, object] = {
173
+ "target_metadata": self._metadata,
174
+ "version_table": config.version_table,
175
+ "version_table_schema": config.version_table_schema,
176
+ "compare_type": config.compare_type,
177
+ "compare_server_default": config.compare_server_default,
178
+ "render_as_batch": config.render_as_batch,
179
+ "include_schemas": config.include_schemas,
180
+ "include_name": _include_name(config.include_name, config.history_table),
181
+ "include_object": config.include_object,
182
+ }
183
+ if config.transactional_ddl is not None:
184
+ options["transactional_ddl"] = config.transactional_ddl
185
+ return options
186
+
152
187
 
153
188
  def _include_name(
154
189
  custom: Callable[..., bool] | None, history_table: str
@@ -0,0 +1,48 @@
1
+ """Invoking the operations a comparison produced. Private to the package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from alembic.operations.ops import ModifyTableOps
8
+ from sqlalchemy import MetaData, Table, inspect
9
+
10
+ if TYPE_CHECKING:
11
+ from alembic.operations import Operations
12
+ from sqlalchemy.engine import Connection
13
+
14
+ from .schema_comparison import SchemaComparison
15
+
16
+ __all__ = ["invoke"]
17
+
18
+
19
+ def invoke(
20
+ operations: Operations, comparison: SchemaComparison, connection: Connection, *, batch: bool
21
+ ) -> None:
22
+ """Invoke each operation ``comparison`` holds, batching a table's changes when ``batch``."""
23
+ # ModifyTableOps is organizational only — unroll it. OpContainer exposes
24
+ # .ops and defines no __iter__.
25
+ for op in comparison.ops:
26
+ if not isinstance(op, ModifyTableOps):
27
+ operations.invoke(op)
28
+ elif not batch:
29
+ for inner in op.ops:
30
+ operations.invoke(inner)
31
+ else:
32
+ with operations.batch_alter_table(
33
+ op.table_name, schema=op.schema, copy_from=_reflected(connection, op)
34
+ ) as batch_op:
35
+ for inner in op.ops:
36
+ batch_op.invoke(inner)
37
+
38
+
39
+ def _reflected(connection: Connection, op: ModifyTableOps) -> Table | None:
40
+ """Reflect the table a batch rebuilds, or None when it is not there.
41
+
42
+ ``connection`` is the real one: a context rendering SQL wraps its own in
43
+ a stub returning no rows, so reflection cannot go through it — and a batch
44
+ recreate rendered without the table refuses to run.
45
+ """
46
+ if not inspect(connection).has_table(op.table_name, op.schema):
47
+ return None
48
+ return Table(op.table_name, MetaData(), schema=op.schema, autoload_with=connection)
@@ -185,10 +185,11 @@ def _as_tuple(value: str | Sequence[str] | None) -> tuple[str, ...]:
185
185
 
186
186
  @contextmanager
187
187
  def refusing() -> Generator[None]:
188
- """Turn the revision reader's own errors into :class:`MigrationError`."""
188
+ """Turn the migration tooling's refusals into :class:`MigrationError`."""
189
189
  try:
190
190
  yield
191
- except (CommandError, ResolutionError, RevisionError) as error:
191
+ except (CommandError, ResolutionError, RevisionError, ValueError) as error:
192
+ # ValueError is how a comparison refuses definitions naming one table twice.
192
193
  raise MigrationError(str(error)) from error
193
194
  except KeyError as error:
194
195
  # The reader indexes its map by the ids revisions name; one naming a
@@ -3,10 +3,11 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from io import StringIO
6
- from typing import TYPE_CHECKING, Final, final
6
+ from typing import TYPE_CHECKING, Final, cast, final
7
7
 
8
- from alembic.autogenerate import RevisionContext
8
+ from alembic.autogenerate import RevisionContext, produce_migrations
9
9
  from alembic.config import Config
10
+ from alembic.operations import Operations
10
11
  from sqlalchemy import Column, MetaData, String, Table, delete
11
12
  from xtr_logging_contracts import LoggerAware
12
13
 
@@ -14,6 +15,7 @@ from xtr_orm.exception import MigrationError
14
15
 
15
16
  from ._environment import Environment
16
17
  from ._history import HistoryRecorder, HistoryTable
18
+ from ._operations import invoke
17
19
  from ._revisions import (
18
20
  applied,
19
21
  available,
@@ -32,6 +34,7 @@ from .executed_migration import ExecutedMigration
32
34
  from .migration_plan import MigrationPlan
33
35
  from .migration_status import MigrationStatus
34
36
  from .migrations_config import MigrationsConfig
37
+ from .schema_comparison import SchemaComparison
35
38
 
36
39
  if TYPE_CHECKING:
37
40
  from collections.abc import Callable, Iterator, Sequence
@@ -117,6 +120,11 @@ class Migrator(LoggerAware):
117
120
  """Where the revisions are and how they are recorded."""
118
121
  return self._config
119
122
 
123
+ @property
124
+ def metadata(self) -> MetaData | Sequence[MetaData] | None:
125
+ """The table definitions a diff or a comparison compares the database with."""
126
+ return self._metadata
127
+
120
128
  async def status(self) -> MigrationStatus:
121
129
  """Read where the database stands against the revision files."""
122
130
  return await self._connected(self._status)
@@ -377,6 +385,74 @@ class Migrator(LoggerAware):
377
385
 
378
386
  return await self._connected(work)
379
387
 
388
+ async def compare(self) -> SchemaComparison:
389
+ """Return what differs between the database and the table definitions.
390
+
391
+ The database is compared with the table definitions as it is — the
392
+ revisions it is at play no part — and nothing is written, run or
393
+ recorded; the version and history tables stay out of the comparison.
394
+
395
+ Raises:
396
+ MigrationError: With no table definitions to compare with.
397
+ """
398
+ # None, or definitions holding no table: against nothing the comparison
399
+ # would drop every table there is.
400
+ if not tables_of(self._metadata):
401
+ raise MigrationError(
402
+ f'The "{self._name}" connection has no table definitions to compare with.',
403
+ )
404
+
405
+ def work(connection: Connection) -> SchemaComparison:
406
+ with refusing():
407
+ # produce_migrations types the definitions MetaData, but the autogen
408
+ # context it builds takes a sequence too.
409
+ script = produce_migrations(
410
+ self._environment.comparison(connection), cast("MetaData", self._metadata)
411
+ )
412
+ upgrade = script.upgrade_ops
413
+ if upgrade is None: # pragma: no cover — a comparison always has its operations
414
+ raise MigrationError("No comparison was produced.")
415
+ # Alembic leaves as_diffs() untyped; the flattened count is all the
416
+ # comparison reports of it.
417
+ changes = len(cast("list[object]", upgrade.as_diffs()))
418
+ return SchemaComparison(changes, upgrade.ops)
419
+
420
+ return await self._connected(work)
421
+
422
+ async def apply(self, comparison: SchemaComparison) -> None:
423
+ """Run ``comparison`` against the database, committing it; nothing is recorded.
424
+
425
+ The run is one transaction, but a dialect without transactional DDL
426
+ cannot make it all-or-nothing: what ran before a failure stays.
427
+ """
428
+
429
+ def work(connection: Connection) -> None:
430
+ context = self._environment.invocation(connection)
431
+ with refusing():
432
+ invoke(
433
+ Operations(context), comparison, connection, batch=self._config.render_as_batch
434
+ )
435
+
436
+ await self._connected(work)
437
+
438
+ async def apply_sql(self, comparison: SchemaComparison) -> str:
439
+ """Return the SQL running ``comparison`` against the database would produce.
440
+
441
+ The operations run against a context that only renders: the database
442
+ stays as it is, and nothing is recorded.
443
+ """
444
+
445
+ def work(connection: Connection) -> str:
446
+ output = StringIO()
447
+ context = self._environment.invocation(connection, output=output)
448
+ with refusing():
449
+ invoke(
450
+ Operations(context), comparison, connection, batch=self._config.render_as_batch
451
+ )
452
+ return output.getvalue()
453
+
454
+ return await self._connected(work)
455
+
380
456
  async def add_versions(self, versions: Sequence[str]) -> tuple[str, ...]:
381
457
  """Mark ``versions`` applied without running them, in order, and return them.
382
458
 
@@ -0,0 +1,60 @@
1
+ """What a comparison of the database with the table definitions found."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, final
6
+
7
+ from alembic.operations.ops import DropTableOp
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Sequence
11
+
12
+ from alembic.operations.ops import MigrateOperation
13
+
14
+ __all__ = ["SchemaComparison"]
15
+
16
+
17
+ @final
18
+ class SchemaComparison:
19
+ """What a comparison of the database with the table definitions found.
20
+
21
+ Nothing was written, run or recorded to find it; what it found runs
22
+ through the migrator, and reads here as a count, the tables that would
23
+ be dropped, and the operations themselves.
24
+ """
25
+
26
+ __slots__ = ("_changes", "_dropped_tables", "_ops")
27
+
28
+ _changes: int
29
+ _dropped_tables: tuple[str, ...]
30
+ _ops: tuple[MigrateOperation, ...]
31
+
32
+ def __init__(self, changes: int, ops: Sequence[MigrateOperation]) -> None:
33
+ """Hold the ``changes`` counted in the comparison and the operations behind them."""
34
+ self._changes = changes
35
+ self._ops = tuple(ops)
36
+ self._dropped_tables = tuple(
37
+ f"{op.schema}.{op.table_name}" if op.schema is not None else op.table_name
38
+ for op in self._ops
39
+ if isinstance(op, DropTableOp)
40
+ )
41
+
42
+ @property
43
+ def is_empty(self) -> bool:
44
+ """Whether the comparison found nothing to do."""
45
+ return not self._ops
46
+
47
+ @property
48
+ def changes(self) -> int:
49
+ """Every change the comparison found, counted flat."""
50
+ return self._changes
51
+
52
+ @property
53
+ def dropped_tables(self) -> tuple[str, ...]:
54
+ """The schema-qualified names of the tables the comparison would drop."""
55
+ return self._dropped_tables
56
+
57
+ @property
58
+ def ops(self) -> tuple[MigrateOperation, ...]:
59
+ """The operations the comparison holds; applied through the migrator."""
60
+ return self._ops
File without changes
File without changes
File without changes