comdab 0.4.0__tar.gz → 0.4.1__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 (60) hide show
  1. {comdab-0.4.0 → comdab-0.4.1}/.github/workflows/test.yml +1 -1
  2. {comdab-0.4.0 → comdab-0.4.1}/CHANGELOG.md +11 -0
  3. {comdab-0.4.0 → comdab-0.4.1}/PKG-INFO +55 -8
  4. {comdab-0.4.0 → comdab-0.4.1}/README.md +54 -7
  5. {comdab-0.4.0 → comdab-0.4.1}/pyproject.toml +2 -1
  6. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/migrate.py +23 -14
  7. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/__init__.py +2 -1
  8. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/constraint.py +1 -1
  9. {comdab-0.4.0 → comdab-0.4.1}/tests/test_compare.py +32 -1
  10. {comdab-0.4.0 → comdab-0.4.1}/tests/test_migrate.py +118 -33
  11. {comdab-0.4.0 → comdab-0.4.1}/tests/test_models.py +8 -9
  12. {comdab-0.4.0 → comdab-0.4.1}/uv.lock +1 -1
  13. {comdab-0.4.0 → comdab-0.4.1}/.github/workflows/release.yml +0 -0
  14. {comdab-0.4.0 → comdab-0.4.1}/.gitignore +0 -0
  15. {comdab-0.4.0 → comdab-0.4.1}/.pre-commit-config.yaml +0 -0
  16. {comdab-0.4.0 → comdab-0.4.1}/.python-version +0 -0
  17. {comdab-0.4.0 → comdab-0.4.1}/.readthedocs.yaml +0 -0
  18. {comdab-0.4.0 → comdab-0.4.1}/LICENSE +0 -0
  19. {comdab-0.4.0 → comdab-0.4.1}/docs/Makefile +0 -0
  20. {comdab-0.4.0 → comdab-0.4.1}/docs/conf.py +0 -0
  21. {comdab-0.4.0 → comdab-0.4.1}/docs/index.rst +0 -0
  22. {comdab-0.4.0 → comdab-0.4.1}/docs/reference.rst +0 -0
  23. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/__init__.py +0 -0
  24. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/build.py +0 -0
  25. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/compare.py +0 -0
  26. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/exceptions.py +0 -0
  27. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/main.py +0 -0
  28. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/base.py +0 -0
  29. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/column.py +0 -0
  30. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/custom_type.py +0 -0
  31. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/function.py +0 -0
  32. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/index.py +0 -0
  33. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/schema.py +0 -0
  34. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/sequence.py +0 -0
  35. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/table.py +0 -0
  36. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/trigger.py +0 -0
  37. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/type.py +0 -0
  38. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/models/view.py +0 -0
  39. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/path.py +0 -0
  40. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/py.typed +0 -0
  41. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/report.py +0 -0
  42. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/source.py +0 -0
  43. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/specific/__init__.py +0 -0
  44. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/specific/postgresql/__init__.py +0 -0
  45. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/specific/postgresql/build.py +0 -0
  46. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/specific/postgresql/custom_types.py +0 -0
  47. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/specific/postgresql/exclude_constraints.py +0 -0
  48. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/specific/postgresql/functions.py +0 -0
  49. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/specific/postgresql/sequences.py +0 -0
  50. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/specific/postgresql/triggers.py +0 -0
  51. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/specific/postgresql/views.py +0 -0
  52. {comdab-0.4.0 → comdab-0.4.1}/src/comdab/utils.py +0 -0
  53. {comdab-0.4.0 → comdab-0.4.1}/tests/__init__.py +0 -0
  54. {comdab-0.4.0 → comdab-0.4.1}/tests/_mock_module.py +0 -0
  55. {comdab-0.4.0 → comdab-0.4.1}/tests/conftest.py +0 -0
  56. {comdab-0.4.0 → comdab-0.4.1}/tests/test_build.py +0 -0
  57. {comdab-0.4.0 → comdab-0.4.1}/tests/test_main.py +0 -0
  58. {comdab-0.4.0 → comdab-0.4.1}/tests/test_specific/__init__.py +0 -0
  59. {comdab-0.4.0 → comdab-0.4.1}/tests/test_specific/test_postgresql.py +0 -0
  60. {comdab-0.4.0 → comdab-0.4.1}/tests/test_utils.py +0 -0
@@ -11,7 +11,7 @@ jobs:
11
11
  python-version:
12
12
  - "3.13"
13
13
  - "3.14"
14
- - "3.15.0-beta.1"
14
+ - "3.15.0-beta.2"
15
15
 
16
16
  steps:
17
17
  - uses: actions/checkout@v6
@@ -5,6 +5,17 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.4.1] - 2026-06-21
9
+
10
+ ### Fixed
11
+
12
+ - Fix `ComdabInternalError` raised when generating migrations updating some
13
+ model `extra`; `MigrationGeneratorPort.alter_*_extra` methods are now
14
+ correctly called in these cases (fixes [#1](https://github.com/loic-simon/comdab/issues/1))
15
+ - Fix `ComdabForeignKeyConstraint.columns_mapping` not treated as an opaque
16
+ value in comparisons (generated `.left_only` / `.right_only` paths)
17
+ - Fix `ComdabType` not exported in `comdab.models`
18
+
8
19
  ## [0.4.0] - 2026-05-31
9
20
 
10
21
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: comdab
3
- Version: 0.4.0
3
+ Version: 0.4.1
4
4
  Summary: Compare Database Schemas
5
5
  Project-URL: Homepage, https://github.com/loic-simon/comdab
6
6
  Project-URL: Documentation, https://comdab.readthedocs.io/en/latest
@@ -49,16 +49,21 @@ pip install comdab
49
49
 
50
50
  ### Requirements
51
51
 
52
- - Python `>= 3.12`
52
+ - Python `>= 3.13`
53
53
  - [sqlalchemy](https://pypi.org/project/sqlalchemy) `>= 2.0`
54
54
  - [pydantic](https://pypi.org/project/pydantic) `>= 2.0`
55
55
 
56
56
  ## Goals
57
57
 
58
- _comdab_ is especially useful in combination with a migration tool like
59
- [Alembic](https://alembic.sqlalchemy.org), to make sure that applying a
60
- migration to an existing database
61
- and creating a new database from scratch produce **the exact same schema**.
58
+ _comdab_ allows you to compare in depth two database schemas to find
59
+ all differences (missing columns, different nullabilities or defaults,
60
+ slight changes in function or triggers definitions...) and turn these
61
+ reports into model migrations.
62
+
63
+ _comdab_ migration generation supercharges migration tools like
64
+ [Alembic](https://alembic.sqlalchemy.org) to create migrations that,
65
+ when applied to an existing database, produce **the exact same schema**
66
+ than a new database created from scratch.
62
67
 
63
68
  Indeed, while migration tools can auto-detect model changes and write
64
69
  automatically the migrations to apply to pre-existing databases, it does not
@@ -72,11 +77,17 @@ on pre-existing databases with the new migration applied.
72
77
 
73
78
  By running _comdab_, you can ensure the two are the nearly-exact same.
74
79
 
75
- _comdab_ stands on the shoulders of the [SQLAlchemy](https://sqlalchemy.org)
76
- library, used to connect to the database and for most of schema introspection.
80
+ _comdab_ is based on the wonderful [SQLAlchemy](https://sqlalchemy.org) library
81
+ to connect to the database, and for most of schema introspection.
77
82
 
78
83
  ## Usage
79
84
 
85
+ ### Comparing database schemas
86
+
87
+ _comdab_ main reporting function is
88
+ [`.compare_databases`](https://comdab.readthedocs.io/en/latest/reference.html#comdab.compare_databases),
89
+ which needs already established SQLAlchemy connections to the two databases to compare:
90
+
80
91
  ```py
81
92
  from comdab import compare_databases
82
93
  from sqlalchemy import create_engine
@@ -93,6 +104,42 @@ else:
93
104
  print("✅ Database schemas are the same!")
94
105
  ```
95
106
 
107
+ ### Generating migrations
108
+
109
+ To generate migrations, a user-defined
110
+ [`MigrationGeneratorPort`](https://comdab.readthedocs.io/en/latest/reference.html#comdab.MigrationGeneratorPort) /
111
+ [`PartialMigrationGeneratorPort`](https://comdab.readthedocs.io/en/latest/reference.html#comdab.MigrationGeneratorPort)
112
+ subclass is additionally needed:
113
+
114
+ ```py
115
+ from comdab import generate_migrations, PartialMigrationGeneratorPort
116
+ from comdab.models import ComdabTable
117
+ from sqlalchemy import create_engine
118
+
119
+ class MyMigrationGenerator(PartialMigrationGeneratorPort):
120
+ def __init__(self) -> None:
121
+ self.sql_text = ""
122
+
123
+ def create_table(self, *, table: ComdabTable) -> None:
124
+ self.sql_text += f"CREATE TABLE {table.name} [...];\n"
125
+
126
+ def drop_table(self, *, table: ComdabTable) -> None:
127
+ self.sql_text += f"DROP TABLE {table.name};\n"
128
+
129
+ ...
130
+
131
+ generator = MyMigrationGenerator()
132
+ engine_1 = create_engine("postgresql://user:pass@host/source")
133
+ engine_2 = create_engine("postgresql://user:pass@host/target")
134
+
135
+ with engine_1.connect() as source_conn, engine_2.connect() as target_conn:
136
+ generate_migrations(source_conn, target_conn, generator)
137
+
138
+ print(generator.sql_text)
139
+ ```
140
+
141
+ ### Advanced usage
142
+
96
143
  See [documentation](https://comdab.readthedocs.io) for configuration and other details.
97
144
 
98
145
  ## Contributing
@@ -26,16 +26,21 @@ pip install comdab
26
26
 
27
27
  ### Requirements
28
28
 
29
- - Python `>= 3.12`
29
+ - Python `>= 3.13`
30
30
  - [sqlalchemy](https://pypi.org/project/sqlalchemy) `>= 2.0`
31
31
  - [pydantic](https://pypi.org/project/pydantic) `>= 2.0`
32
32
 
33
33
  ## Goals
34
34
 
35
- _comdab_ is especially useful in combination with a migration tool like
36
- [Alembic](https://alembic.sqlalchemy.org), to make sure that applying a
37
- migration to an existing database
38
- and creating a new database from scratch produce **the exact same schema**.
35
+ _comdab_ allows you to compare in depth two database schemas to find
36
+ all differences (missing columns, different nullabilities or defaults,
37
+ slight changes in function or triggers definitions...) and turn these
38
+ reports into model migrations.
39
+
40
+ _comdab_ migration generation supercharges migration tools like
41
+ [Alembic](https://alembic.sqlalchemy.org) to create migrations that,
42
+ when applied to an existing database, produce **the exact same schema**
43
+ than a new database created from scratch.
39
44
 
40
45
  Indeed, while migration tools can auto-detect model changes and write
41
46
  automatically the migrations to apply to pre-existing databases, it does not
@@ -49,11 +54,17 @@ on pre-existing databases with the new migration applied.
49
54
 
50
55
  By running _comdab_, you can ensure the two are the nearly-exact same.
51
56
 
52
- _comdab_ stands on the shoulders of the [SQLAlchemy](https://sqlalchemy.org)
53
- library, used to connect to the database and for most of schema introspection.
57
+ _comdab_ is based on the wonderful [SQLAlchemy](https://sqlalchemy.org) library
58
+ to connect to the database, and for most of schema introspection.
54
59
 
55
60
  ## Usage
56
61
 
62
+ ### Comparing database schemas
63
+
64
+ _comdab_ main reporting function is
65
+ [`.compare_databases`](https://comdab.readthedocs.io/en/latest/reference.html#comdab.compare_databases),
66
+ which needs already established SQLAlchemy connections to the two databases to compare:
67
+
57
68
  ```py
58
69
  from comdab import compare_databases
59
70
  from sqlalchemy import create_engine
@@ -70,6 +81,42 @@ else:
70
81
  print("✅ Database schemas are the same!")
71
82
  ```
72
83
 
84
+ ### Generating migrations
85
+
86
+ To generate migrations, a user-defined
87
+ [`MigrationGeneratorPort`](https://comdab.readthedocs.io/en/latest/reference.html#comdab.MigrationGeneratorPort) /
88
+ [`PartialMigrationGeneratorPort`](https://comdab.readthedocs.io/en/latest/reference.html#comdab.MigrationGeneratorPort)
89
+ subclass is additionally needed:
90
+
91
+ ```py
92
+ from comdab import generate_migrations, PartialMigrationGeneratorPort
93
+ from comdab.models import ComdabTable
94
+ from sqlalchemy import create_engine
95
+
96
+ class MyMigrationGenerator(PartialMigrationGeneratorPort):
97
+ def __init__(self) -> None:
98
+ self.sql_text = ""
99
+
100
+ def create_table(self, *, table: ComdabTable) -> None:
101
+ self.sql_text += f"CREATE TABLE {table.name} [...];\n"
102
+
103
+ def drop_table(self, *, table: ComdabTable) -> None:
104
+ self.sql_text += f"DROP TABLE {table.name};\n"
105
+
106
+ ...
107
+
108
+ generator = MyMigrationGenerator()
109
+ engine_1 = create_engine("postgresql://user:pass@host/source")
110
+ engine_2 = create_engine("postgresql://user:pass@host/target")
111
+
112
+ with engine_1.connect() as source_conn, engine_2.connect() as target_conn:
113
+ generate_migrations(source_conn, target_conn, generator)
114
+
115
+ print(generator.sql_text)
116
+ ```
117
+
118
+ ### Advanced usage
119
+
73
120
  See [documentation](https://comdab.readthedocs.io) for configuration and other details.
74
121
 
75
122
  ## Contributing
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "comdab"
3
- version = "0.4.0"
3
+ version = "0.4.1"
4
4
  description = "Compare Database Schemas"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -39,6 +39,7 @@ docs = [
39
39
  ]
40
40
 
41
41
  [tool.ruff]
42
+ target-version = "py313"
42
43
  line-length = 120
43
44
 
44
45
  [tool.ruff.lint]
@@ -36,8 +36,7 @@ def _register[MF: Callable[..., None]](path: ComdabPath, **kwargs: _ReportGetter
36
36
  raise ValueError(f"Migration already registered for {path}: {_path_to_migration_func_spec[path]}")
37
37
 
38
38
  _path_to_migration_func_spec[path] = (func.__name__, kwargs)
39
- func._registered_path = path # pyright: ignore[reportFunctionMemberAccess] # used for tests only
40
- func._registered_kwargs = kwargs # pyright: ignore[reportFunctionMemberAccess] # used for tests only
39
+ func._comdab_registered = (*getattr(func, "_comdab_registered", ()), (path, kwargs)) # pyright: ignore[reportFunctionMemberAccess] # used for tests only
41
40
  return func
42
41
 
43
42
  return _decorator
@@ -143,7 +142,8 @@ class MigrationGeneratorPort(ABC):
143
142
  self.__default_impl()
144
143
 
145
144
  @abstractmethod
146
- @_register(ROOT.extra, old_extra=_left, new_extra=_right)
145
+ @_register(ROOT.extra.left_only, old_extra=_left, new_extra=_right)
146
+ @_register(ROOT.extra.right_only, old_extra=_left, new_extra=_right)
147
147
  def alter_schema_extra(self, *, old_extra: dict[str, Any], new_extra: dict[str, Any]) -> None:
148
148
  """Change some dialect-specific schema options."""
149
149
  self.__default_impl()
@@ -199,7 +199,8 @@ class MigrationGeneratorPort(ABC):
199
199
  self.__default_impl()
200
200
 
201
201
  @abstractmethod
202
- @_register(ROOT.tables[...].extra, old_extra=_left, new_extra=_right)
202
+ @_register(ROOT.tables[...].extra.left_only, old_extra=_left, new_extra=_right)
203
+ @_register(ROOT.tables[...].extra.right_only, old_extra=_left, new_extra=_right)
203
204
  def alter_table_extra(self, *, table: ComdabTable, old_extra: dict[str, Any], new_extra: dict[str, Any]) -> None:
204
205
  """Change some dialect-specific table options."""
205
206
  self.__default_impl()
@@ -217,7 +218,8 @@ class MigrationGeneratorPort(ABC):
217
218
  self.__default_impl()
218
219
 
219
220
  @abstractmethod
220
- @_register(ROOT.views[...].extra, old_extra=_left, new_extra=_right)
221
+ @_register(ROOT.views[...].extra.left_only, old_extra=_left, new_extra=_right)
222
+ @_register(ROOT.views[...].extra.right_only, old_extra=_left, new_extra=_right)
221
223
  def alter_view_extra(self, *, view: ComdabView, old_extra: dict[str, Any], new_extra: dict[str, Any]) -> None:
222
224
  """Change some dialect-specific view options."""
223
225
  self.__default_impl()
@@ -259,7 +261,8 @@ class MigrationGeneratorPort(ABC):
259
261
  self.__default_impl()
260
262
 
261
263
  @abstractmethod
262
- @_register(ROOT.sequences[...].extra, old_extra=_left, new_extra=_right)
264
+ @_register(ROOT.sequences[...].extra.left_only, old_extra=_left, new_extra=_right)
265
+ @_register(ROOT.sequences[...].extra.right_only, old_extra=_left, new_extra=_right)
263
266
  def alter_sequence_extra(
264
267
  self, *, sequence: ComdabSequence, old_extra: dict[str, Any], new_extra: dict[str, Any]
265
268
  ) -> None:
@@ -273,7 +276,8 @@ class MigrationGeneratorPort(ABC):
273
276
  self.__default_impl()
274
277
 
275
278
  @abstractmethod
276
- @_register(ROOT.functions[...].extra, old_extra=_left, new_extra=_right)
279
+ @_register(ROOT.functions[...].extra.left_only, old_extra=_left, new_extra=_right)
280
+ @_register(ROOT.functions[...].extra.right_only, old_extra=_left, new_extra=_right)
277
281
  def alter_function_extra(
278
282
  self, *, function: ComdabFunction, old_extra: dict[str, Any], new_extra: dict[str, Any]
279
283
  ) -> None:
@@ -289,7 +293,8 @@ class MigrationGeneratorPort(ABC):
289
293
  self.__default_impl()
290
294
 
291
295
  @abstractmethod
292
- @_register(ROOT.custom_types[...].extra, old_extra=_left, new_extra=_right)
296
+ @_register(ROOT.custom_types[...].extra.left_only, old_extra=_left, new_extra=_right)
297
+ @_register(ROOT.custom_types[...].extra.right_only, old_extra=_left, new_extra=_right)
293
298
  def alter_custom_type_extra(
294
299
  self, *, custom_type: ComdabCustomType, old_extra: dict[str, Any], new_extra: dict[str, Any]
295
300
  ) -> None:
@@ -315,9 +320,9 @@ class MigrationGeneratorPort(ABC):
315
320
  self.__default_impl()
316
321
 
317
322
  @abstractmethod
318
- @_register(ROOT.tables[...].columns[...].default, old_type=_left, new_type=_right)
323
+ @_register(ROOT.tables[...].columns[...].default, old_default=_left, new_default=_right)
319
324
  def alter_column_default(
320
- self, *, table: ComdabTable, column: ComdabColumn, old_type: str | None, new_type: str | None
325
+ self, *, table: ComdabTable, column: ComdabColumn, old_default: str | None, new_default: str | None
321
326
  ) -> None:
322
327
  """Change the default value of a column."""
323
328
  self.__default_impl()
@@ -331,7 +336,8 @@ class MigrationGeneratorPort(ABC):
331
336
  self.__default_impl()
332
337
 
333
338
  @abstractmethod
334
- @_register(ROOT.tables[...].columns[...].extra, old_extra=_left, new_extra=_right)
339
+ @_register(ROOT.tables[...].columns[...].extra.left_only, old_extra=_left, new_extra=_right)
340
+ @_register(ROOT.tables[...].columns[...].extra.right_only, old_extra=_left, new_extra=_right)
335
341
  def alter_column_extra(
336
342
  self, *, table: ComdabTable, column: ComdabColumn, old_extra: dict[str, Any], new_extra: dict[str, Any]
337
343
  ) -> None:
@@ -378,7 +384,8 @@ class MigrationGeneratorPort(ABC):
378
384
  self.__default_impl()
379
385
 
380
386
  @abstractmethod
381
- @_register(ROOT.tables[...].constraints[...].extra, old_extra=_left, new_extra=_right)
387
+ @_register(ROOT.tables[...].constraints[...].extra.left_only, old_extra=_left, new_extra=_right)
388
+ @_register(ROOT.tables[...].constraints[...].extra.right_only, old_extra=_left, new_extra=_right)
382
389
  def alter_constraint_extra(
383
390
  self, *, table: ComdabTable, constraint: ComdabConstraint, old_extra: dict[str, Any], new_extra: dict[str, Any]
384
391
  ) -> None:
@@ -477,7 +484,8 @@ class MigrationGeneratorPort(ABC):
477
484
  self.__default_impl()
478
485
 
479
486
  @abstractmethod
480
- @_register(ROOT.tables[...].indexes[...].extra, old_extra=_left, new_extra=_right)
487
+ @_register(ROOT.tables[...].indexes[...].extra.left_only, old_extra=_left, new_extra=_right)
488
+ @_register(ROOT.tables[...].indexes[...].extra.right_only, old_extra=_left, new_extra=_right)
481
489
  def alter_index_extra(
482
490
  self, *, table: ComdabTable, index: ComdabIndex, old_extra: dict[str, Any], new_extra: dict[str, Any]
483
491
  ) -> None:
@@ -493,7 +501,8 @@ class MigrationGeneratorPort(ABC):
493
501
  self.__default_impl()
494
502
 
495
503
  @abstractmethod
496
- @_register(ROOT.tables[...].triggers[...].extra, old_extra=_left, new_extra=_right)
504
+ @_register(ROOT.tables[...].triggers[...].extra.left_only, old_extra=_left, new_extra=_right)
505
+ @_register(ROOT.tables[...].triggers[...].extra.right_only, old_extra=_left, new_extra=_right)
497
506
  def alter_trigger_extra(
498
507
  self, *, table: ComdabTable, trigger: ComdabTrigger, old_extra: dict[str, Any], new_extra: dict[str, Any]
499
508
  ) -> None:
@@ -15,7 +15,7 @@ from comdab.models.schema import ROOT, ComdabSchema
15
15
  from comdab.models.sequence import ComdabSequence
16
16
  from comdab.models.table import ComdabTable
17
17
  from comdab.models.trigger import ComdabTrigger
18
- from comdab.models.type import ComdabTypes
18
+ from comdab.models.type import ComdabType, ComdabTypes
19
19
  from comdab.models.view import ComdabView
20
20
 
21
21
  __all__ = (
@@ -40,5 +40,6 @@ __all__ = (
40
40
  "ComdabIndex",
41
41
  "ComdabTrigger",
42
42
  # Level 3
43
+ "ComdabType",
43
44
  "ComdabTypes",
44
45
  )
@@ -35,7 +35,7 @@ class _BaseComdabConstraint(ComdabModel, frozen=True):
35
35
 
36
36
  # Union of fields of all constraint types
37
37
  columns = terminal_path()
38
- columns_mapping = dict_of_paths(ComdabPath)
38
+ columns_mapping = terminal_path()
39
39
  on_update = terminal_path()
40
40
  on_delete = terminal_path()
41
41
  sql_text = terminal_path()
@@ -7,6 +7,8 @@ from comdab.compare import ComdabComparer, ComdabStrategy
7
7
  from comdab.models import (
8
8
  ROOT,
9
9
  ComdabColumn,
10
+ ComdabCustomType,
11
+ ComdabForeignKeyConstraint,
10
12
  ComdabFunction,
11
13
  ComdabIndex,
12
14
  ComdabPrimaryKeyConstraint,
@@ -18,7 +20,6 @@ from comdab.models import (
18
20
  ComdabUniqueConstraint,
19
21
  ComdabView,
20
22
  )
21
- from comdab.models.custom_type import ComdabCustomType
22
23
  from comdab.path import ComdabPath
23
24
  from comdab.report import ComdabReport
24
25
 
@@ -63,6 +64,14 @@ FULL_SCHEMA = ComdabSchema(
63
64
  "col1_col2_uq": ComdabUniqueConstraint(
64
65
  name="col1_col2_uq", deferrable=True, initially="DEFERRED", columns={"col1", "col2"}
65
66
  ),
67
+ "col2_fk": ComdabForeignKeyConstraint(
68
+ name="col2_fk",
69
+ deferrable=None,
70
+ initially=None,
71
+ columns_mapping={"col2": "table2.col3"},
72
+ on_update=None,
73
+ on_delete=None,
74
+ ),
66
75
  },
67
76
  indexes={
68
77
  "ix_col1": ComdabIndex(
@@ -239,6 +248,28 @@ def test_empty_vs_full() -> None:
239
248
  {"key1": True},
240
249
  {"key1": True, "key2": False},
241
250
  ),
251
+ (
252
+ replace(
253
+ (s := FULL_SCHEMA),
254
+ tables={
255
+ **s.tables,
256
+ "table1": replace(
257
+ (t := s.tables["table1"]),
258
+ constraints={
259
+ **t.constraints,
260
+ "col2_fk": replace(
261
+ (c := t.constraints["col2_fk"]),
262
+ columns_mapping={"col2": "table2.col3", "col1": "table2.col3"},
263
+ ),
264
+ },
265
+ ),
266
+ },
267
+ ),
268
+ # No deep comparison of FK columns_mapping
269
+ ROOT.tables["table1"].constraints["col2_fk"].columns_mapping,
270
+ {"col2": "table2.col3", "col1": "table2.col3"},
271
+ {"col2": "table2.col3"},
272
+ ),
242
273
  ],
243
274
  )
244
275
  def test_subtil_differences(
@@ -25,36 +25,48 @@ from comdab.models.table import ComdabTable
25
25
  from comdab.models.trigger import ComdabTrigger
26
26
  from comdab.models.type import ComdabTypes
27
27
  from comdab.models.view import ComdabView
28
- from comdab.path import ComdabPath, ComdabPathDict, PathItem
28
+ from comdab.path import ComdabPath, ComdabPathDict, PathAttr, PathItem
29
29
  from comdab.report import ComdabReport
30
30
 
31
31
  if TYPE_CHECKING:
32
32
 
33
33
  class _RegisteredMethod(FunctionType): # pyright: ignore[reportGeneralTypeIssues]
34
- _registered_path: ComdabPath
35
- _registered_kwargs: dict[str, Any]
34
+ _comdab_registered: tuple[tuple[ComdabPath, dict[str, Any]], ...]
36
35
 
37
36
 
38
37
  def _is_registered_method(obj: object) -> TypeGuard["_RegisteredMethod"]:
39
- return inspect.isfunction(obj) and hasattr(obj, "_registered_path")
38
+ return inspect.isfunction(obj) and hasattr(obj, "_comdab_registered")
40
39
 
41
40
 
42
- @pytest.mark.parametrize(["name", "method"], inspect.getmembers(MigrationGeneratorPort, _is_registered_method))
43
- def test_register_signature_consistency(name: str, method: "_RegisteredMethod") -> None:
41
+ def _get_registrations() -> Iterator[tuple["_RegisteredMethod", ComdabPath[Any], dict[str, Any]]]:
42
+ for _, method in inspect.getmembers(MigrationGeneratorPort, _is_registered_method):
43
+ for registered_path, registered_kwargs in method._comdab_registered: # pyright: ignore[reportPrivateUsage]
44
+ yield method, registered_path, registered_kwargs
45
+
46
+
47
+ @pytest.mark.parametrize(
48
+ ["method", "registered_path", "registered_kwargs"],
49
+ list(_get_registrations()),
50
+ ids=lambda obj: str(obj) if isinstance(obj, ComdabPath) else obj,
51
+ )
52
+ def test_register_signature_consistency(
53
+ method: "_RegisteredMethod", registered_path: ComdabPath[Any], registered_kwargs: dict[str, Any]
54
+ ) -> None:
44
55
  self, *func_parameters = list(inspect.signature(method).parameters.values())
45
56
  assert self.name == "self"
46
57
  assert all(param.kind.name == "KEYWORD_ONLY" for param in func_parameters)
47
58
  declared_kwargs = {param.name: param.annotation for param in func_parameters}
48
59
 
49
- template, keys = method._registered_path.to_template() # pyright: ignore[reportPrivateUsage]
60
+ template, keys = registered_path.to_template()
50
61
  registered_kwargs_path = {_path_dict_to_migration_function_kwarg[key] for key in keys}
51
- registered_kwargs_report = method._registered_kwargs.keys() # pyright: ignore[reportPrivateUsage]
62
+ registered_kwargs_report = registered_kwargs.keys()
52
63
 
53
64
  assert not registered_kwargs_path & registered_kwargs_report
54
65
  assert declared_kwargs.keys() == registered_kwargs_path | registered_kwargs_report
55
66
 
56
67
  # Find type of the value corresponding to the registered path
57
68
  ann = ComdabSchema
69
+ old_comp: PathItem | PathAttr | None = None
58
70
  for comp in template._components: # pyright: ignore[reportPrivateUsage]
59
71
  if isinstance(comp, PathItem):
60
72
  assert comp.key == ".*"
@@ -62,7 +74,9 @@ def test_register_signature_consistency(name: str, method: "_RegisteredMethod")
62
74
  ann = get_args(ann)[1]
63
75
  elif comp.attr in ("right_only", "left_only"):
64
76
  assert get_origin(ann) is dict, ann
65
- ann = get_args(ann)[1]
77
+ if not (isinstance(old_comp, PathAttr) and old_comp.attr == "extra"):
78
+ # Special case: <path>.extra.left_only/right_only are treated as <path>.extra
79
+ ann = get_args(ann)[1]
66
80
  else:
67
81
  if isinstance(ann, type) and issubclass(ann, ComdabModel):
68
82
  ann = ann.model_fields[comp.attr].annotation
@@ -79,10 +93,11 @@ def test_register_signature_consistency(name: str, method: "_RegisteredMethod")
79
93
  )
80
94
  else:
81
95
  raise AssertionError(ann)
96
+ old_comp = comp
82
97
 
83
98
  # Ensure it's the same type as the function kwarg annotation
84
99
  for kwarg in registered_kwargs_report:
85
- assert declared_kwargs[kwarg] == ann
100
+ assert declared_kwargs[kwarg] == ann, f"Mismatch: {kwarg}"
86
101
 
87
102
 
88
103
  sch = ComdabSchema(
@@ -117,7 +132,7 @@ generator = cast(MigrationGeneratorPort, mock.call)
117
132
 
118
133
  @pytest.mark.parametrize(
119
134
  ["report", "expected_calls"],
120
- [
135
+ _test_cases := [
121
136
  (
122
137
  report(path=ROOT.tables.right_only, left=None, right={"foo": sch.tables["foo"]}),
123
138
  [generator.create_table(table=sch.tables["foo"])],
@@ -163,8 +178,12 @@ generator = cast(MigrationGeneratorPort, mock.call)
163
178
  [generator.drop_custom_type(custom_type=sch.custom_types["mt"])],
164
179
  ),
165
180
  (
166
- report(path=ROOT.extra, left={"goo": "goo"}, right={"ga": "gack"}),
167
- [generator.alter_schema_extra(old_extra={"goo": "goo"}, new_extra={"ga": "gack"})],
181
+ report(path=ROOT.extra.left_only, left={"goo": "goo"}, right={}),
182
+ [generator.alter_schema_extra(old_extra={"goo": "goo"}, new_extra={})],
183
+ ),
184
+ (
185
+ report(path=ROOT.extra.right_only, left={}, right={"ga": "gack"}),
186
+ [generator.alter_schema_extra(old_extra={}, new_extra={"ga": "gack"})],
168
187
  ),
169
188
  # Level 2
170
189
  (
@@ -240,8 +259,12 @@ generator = cast(MigrationGeneratorPort, mock.call)
240
259
  [generator.drop_trigger(table=sch.tables["foo"], trigger=sch.tables["foo"].triggers["tri"])],
241
260
  ),
242
261
  (
243
- report(path=ROOT.tables["foo"].extra, left={"a": 2}, right={"a": 3}),
244
- [generator.alter_table_extra(table=sch.tables["foo"], old_extra={"a": 2}, new_extra={"a": 3})],
262
+ report(path=ROOT.tables["foo"].extra.left_only, left={"a": 2}, right={}),
263
+ [generator.alter_table_extra(table=sch.tables["foo"], old_extra={"a": 2}, new_extra={})],
264
+ ),
265
+ (
266
+ report(path=ROOT.tables["foo"].extra.right_only, left={}, right={"a": 3}),
267
+ [generator.alter_table_extra(table=sch.tables["foo"], old_extra={}, new_extra={"a": 3})],
245
268
  ),
246
269
  (
247
270
  report(path=ROOT.views["vue"].definition, left="left", right="right"),
@@ -252,8 +275,12 @@ generator = cast(MigrationGeneratorPort, mock.call)
252
275
  [generator.alter_view_materialized(view=sch.views["vue"], old_materialized=False, new_materialized=True)],
253
276
  ),
254
277
  (
255
- report(path=ROOT.views["vue"].extra, left={"?": "left"}, right={"?": "right"}),
256
- [generator.alter_view_extra(view=sch.views["vue"], old_extra={"?": "left"}, new_extra={"?": "right"})],
278
+ report(path=ROOT.views["vue"].extra.left_only, left={"?": "left"}, right={}),
279
+ [generator.alter_view_extra(view=sch.views["vue"], old_extra={"?": "left"}, new_extra={})],
280
+ ),
281
+ (
282
+ report(path=ROOT.views["vue"].extra.right_only, left={}, right={"?": "right"}),
283
+ [generator.alter_view_extra(view=sch.views["vue"], old_extra={}, new_extra={"?": "right"})],
257
284
  ),
258
285
  (
259
286
  report(path=ROOT.sequences["sek"].type_name, left="left", right="right"),
@@ -284,8 +311,12 @@ generator = cast(MigrationGeneratorPort, mock.call)
284
311
  [generator.alter_sequence_cycle(sequence=sch.sequences["sek"], old_cycle=False, new_cycle=True)],
285
312
  ),
286
313
  (
287
- report(path=ROOT.sequences["sek"].extra, left={"a": 1}, right={"a": 2}),
288
- [generator.alter_sequence_extra(sequence=sch.sequences["sek"], old_extra={"a": 1}, new_extra={"a": 2})],
314
+ report(path=ROOT.sequences["sek"].extra.left_only, left={"a": 1}, right={}),
315
+ [generator.alter_sequence_extra(sequence=sch.sequences["sek"], old_extra={"a": 1}, new_extra={})],
316
+ ),
317
+ (
318
+ report(path=ROOT.sequences["sek"].extra.right_only, left={}, right={"a": 2}),
319
+ [generator.alter_sequence_extra(sequence=sch.sequences["sek"], old_extra={}, new_extra={"a": 2})],
289
320
  ),
290
321
  (
291
322
  report(path=ROOT.functions["fn"].definition, left="left", right="right"),
@@ -296,8 +327,12 @@ generator = cast(MigrationGeneratorPort, mock.call)
296
327
  ],
297
328
  ),
298
329
  (
299
- report(path=ROOT.functions["fn"].extra, left={"a": 1}, right={"a": 2}),
300
- [generator.alter_function_extra(function=sch.functions["fn"], old_extra={"a": 1}, new_extra={"a": 2})],
330
+ report(path=ROOT.functions["fn"].extra.left_only, left={"a": 1}, right={}),
331
+ [generator.alter_function_extra(function=sch.functions["fn"], old_extra={"a": 1}, new_extra={})],
332
+ ),
333
+ (
334
+ report(path=ROOT.functions["fn"].extra.right_only, left={}, right={"a": 2}),
335
+ [generator.alter_function_extra(function=sch.functions["fn"], old_extra={}, new_extra={"a": 2})],
301
336
  ),
302
337
  (
303
338
  report(path=ROOT.custom_types["mt"].values, left=["a", "b"], right=["a", "c"]),
@@ -308,12 +343,12 @@ generator = cast(MigrationGeneratorPort, mock.call)
308
343
  ],
309
344
  ),
310
345
  (
311
- report(path=ROOT.custom_types["mt"].extra, left={"a": 1}, right={"a": 2}),
312
- [
313
- generator.alter_custom_type_extra(
314
- custom_type=sch.custom_types["mt"], old_extra={"a": 1}, new_extra={"a": 2}
315
- )
316
- ],
346
+ report(path=ROOT.custom_types["mt"].extra.left_only, left={"a": 1}, right={}),
347
+ [generator.alter_custom_type_extra(custom_type=sch.custom_types["mt"], old_extra={"a": 1}, new_extra={})],
348
+ ),
349
+ (
350
+ report(path=ROOT.custom_types["mt"].extra.right_only, left={}, right={"a": 2}),
351
+ [generator.alter_custom_type_extra(custom_type=sch.custom_types["mt"], old_extra={}, new_extra={"a": 2})],
317
352
  ),
318
353
  # Level 3
319
354
  (
@@ -346,7 +381,7 @@ generator = cast(MigrationGeneratorPort, mock.call)
346
381
  report(path=ROOT.tables["foo"].columns["bar"].default, left="o", right=None),
347
382
  [
348
383
  generator.alter_column_default(
349
- table=sch.tables["foo"], column=sch.tables["foo"].columns["bar"], old_type="o", new_type=None
384
+ table=sch.tables["foo"], column=sch.tables["foo"].columns["bar"], old_default="o", new_default=None
350
385
  )
351
386
  ],
352
387
  ),
@@ -359,12 +394,23 @@ generator = cast(MigrationGeneratorPort, mock.call)
359
394
  ],
360
395
  ),
361
396
  (
362
- report(path=ROOT.tables["foo"].columns["bar"].extra, left={"a": 1}, right={"a": 2}),
397
+ report(path=ROOT.tables["foo"].columns["bar"].extra.left_only, left={"a": 1}, right={}),
363
398
  [
364
399
  generator.alter_column_extra(
365
400
  table=sch.tables["foo"],
366
401
  column=sch.tables["foo"].columns["bar"],
367
402
  old_extra={"a": 1},
403
+ new_extra={},
404
+ )
405
+ ],
406
+ ),
407
+ (
408
+ report(path=ROOT.tables["foo"].columns["bar"].extra.right_only, left={}, right={"a": 2}),
409
+ [
410
+ generator.alter_column_extra(
411
+ table=sch.tables["foo"],
412
+ column=sch.tables["foo"].columns["bar"],
413
+ old_extra={},
368
414
  new_extra={"a": 2},
369
415
  )
370
416
  ],
@@ -403,12 +449,23 @@ generator = cast(MigrationGeneratorPort, mock.call)
403
449
  ],
404
450
  ),
405
451
  (
406
- report(path=ROOT.tables["foo"].constraints["con"].extra, left={"a": 1}, right={"a": 2}),
452
+ report(path=ROOT.tables["foo"].constraints["con"].extra.left_only, left={"a": 1}, right={}),
407
453
  [
408
454
  generator.alter_constraint_extra(
409
455
  table=sch.tables["foo"],
410
456
  constraint=sch.tables["foo"].constraints["con"],
411
457
  old_extra={"a": 1},
458
+ new_extra={},
459
+ )
460
+ ],
461
+ ),
462
+ (
463
+ report(path=ROOT.tables["foo"].constraints["con"].extra.right_only, left={}, right={"a": 2}),
464
+ [
465
+ generator.alter_constraint_extra(
466
+ table=sch.tables["foo"],
467
+ constraint=sch.tables["foo"].constraints["con"],
468
+ old_extra={},
412
469
  new_extra={"a": 2},
413
470
  )
414
471
  ],
@@ -503,12 +560,23 @@ generator = cast(MigrationGeneratorPort, mock.call)
503
560
  ],
504
561
  ),
505
562
  (
506
- report(path=ROOT.tables["foo"].indexes["ix"].extra, left={"a": 1}, right={"a": 2}),
563
+ report(path=ROOT.tables["foo"].indexes["ix"].extra.left_only, left={"a": 1}, right={}),
507
564
  [
508
565
  generator.alter_index_extra(
509
566
  table=sch.tables["foo"],
510
567
  index=sch.tables["foo"].indexes["ix"],
511
568
  old_extra={"a": 1},
569
+ new_extra={},
570
+ )
571
+ ],
572
+ ),
573
+ (
574
+ report(path=ROOT.tables["foo"].indexes["ix"].extra.right_only, left={}, right={"a": 2}),
575
+ [
576
+ generator.alter_index_extra(
577
+ table=sch.tables["foo"],
578
+ index=sch.tables["foo"].indexes["ix"],
579
+ old_extra={},
512
580
  new_extra={"a": 2},
513
581
  )
514
582
  ],
@@ -525,12 +593,23 @@ generator = cast(MigrationGeneratorPort, mock.call)
525
593
  ],
526
594
  ),
527
595
  (
528
- report(path=ROOT.tables["foo"].triggers["tri"].extra, left={"a": 1}, right={"a": 2}),
596
+ report(path=ROOT.tables["foo"].triggers["tri"].extra.left_only, left={"a": 1}, right={}),
529
597
  [
530
598
  generator.alter_trigger_extra(
531
599
  table=sch.tables["foo"],
532
600
  trigger=sch.tables["foo"].triggers["tri"],
533
601
  old_extra={"a": 1},
602
+ new_extra={},
603
+ )
604
+ ],
605
+ ),
606
+ (
607
+ report(path=ROOT.tables["foo"].triggers["tri"].extra.right_only, left={}, right={"a": 2}),
608
+ [
609
+ generator.alter_trigger_extra(
610
+ table=sch.tables["foo"],
611
+ trigger=sch.tables["foo"].triggers["tri"],
612
+ old_extra={},
534
613
  new_extra={"a": 2},
535
614
  )
536
615
  ],
@@ -552,7 +631,7 @@ def _generate_all_possible_paths(root: ComdabPath) -> Iterator[ComdabPath]:
552
631
  for name, attr in inspect.getmembers(root, lambda x: isinstance(x, ComdabPath)):
553
632
  if name == "name": # cannot change
554
633
  continue
555
- if isinstance(attr, ComdabPathDict) and attr._generic_type is not ComdabPath: # pyright: ignore[reportPrivateUsage]
634
+ if isinstance(attr, ComdabPathDict): # pyright: ignore[reportPrivateUsage]
556
635
  yield attr.left_only
557
636
  yield attr.right_only
558
637
  yield from _generate_all_possible_paths(attr[...])
@@ -560,6 +639,12 @@ def _generate_all_possible_paths(root: ComdabPath) -> Iterator[ComdabPath]:
560
639
  yield attr
561
640
 
562
641
 
642
+ def test_all_migrations_are_tested() -> None:
643
+ tested = {report.path.to_template()[0] for report, _ in _test_cases}
644
+ possible = {path for path in _generate_all_possible_paths(ROOT)}
645
+ assert tested == possible
646
+
647
+
563
648
  @pytest.mark.parametrize(["path"], [(x,) for x in _generate_all_possible_paths(ROOT)], ids=str)
564
649
  def test_migration_generator_full_coverage(path: ComdabPath) -> None:
565
650
  generator = mock.Mock(MigrationGeneratorPort)
@@ -119,16 +119,15 @@ class TestPathsConsistency:
119
119
  self._validate_schema(value_ann, _validated_schemas)
120
120
 
121
121
  else:
122
- # Schema field is a dict of non-schemas: check the path field is a dict of terminal ComdabPaths
123
- assert get_origin(path_type) is ComdabPathDict, (
124
- f"{base_model.__name__}.Path.{name} describes a {path_type}, expected a dictionary "
125
- "of ComdabPath!"
122
+ # Schema field is a dict of non-schemas: check the path field is either
123
+ # * a dict of terminal ComdabPaths (eg. extra)
124
+ # * a normal terminal path (eg. columns_mapping)
125
+ assert (
126
+ get_origin(path_type) is ComdabPathDict and get_args(path_type)[0] is ComdabPath
127
+ ) or path_type is ComdabPath, (
128
+ f"{base_model.__name__}.Path.{name} describes a {path_type}, expected either a dictionary "
129
+ "of ComdabPath or a terminal ComdabPath!"
126
130
  )
127
- assert get_args(path_type)[0] is ComdabPath, (
128
- f"{base_model.__name__}.Path.{name} describes a {path_type}, expected a dictionary "
129
- "of ComdabPath!"
130
- )
131
-
132
131
  case _:
133
132
  # Schema field is any other value: check the path field is a terminal ComdabPath
134
133
  assert path_type is ComdabPath, (
@@ -106,7 +106,7 @@ wheels = [
106
106
 
107
107
  [[package]]
108
108
  name = "comdab"
109
- version = "0.4.0"
109
+ version = "0.4.1"
110
110
  source = { editable = "." }
111
111
  dependencies = [
112
112
  { name = "pydantic" },
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes