comdab 0.1.0__py3-none-any.whl

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.
comdab/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """comdab - Compare Database Schemas
2
+
3
+ Loïc Simon 2025, MIT License
4
+ """
5
+
6
+ from comdab.main import build_comdab_schema, compare_comdab_schemas, compare_databases
7
+ from comdab.models import ROOT
8
+
9
+ #: The top-level *comdab* path, pointing to a whole :class:`ComdabSchema`.
10
+ #:
11
+ #: It's attributes are, recursively, the corresponding schema attributes:
12
+ #: ``ROOT.tables['foo'].columns`` refer to all columns of the table named ``foo``,
13
+ #: eg. the dictionary ``some_schema.tables['foo'].columns``.
14
+ #:
15
+ #: Dictionary keys can be :mod:`regular expressions <re>` (or ``...``, equivalent to ``'.*'``), so that
16
+ #: ``ROOT.tables['_.*'].columns`` refer to all columns of all tables beginning with an underscore.
17
+ ROOT = ROOT # pyright: ignore[reportConstantRedefinition] # Only here for Sphinx
18
+
19
+
20
+ __all__ = [
21
+ "compare_databases",
22
+ "build_comdab_schema",
23
+ "compare_comdab_schemas",
24
+ "ROOT",
25
+ ]
comdab/build.py ADDED
@@ -0,0 +1,238 @@
1
+ from collections.abc import Iterator
2
+ from typing import Any
3
+
4
+ from sqlalchemy import schema, types
5
+ from sqlalchemy.sql import ClauseElement
6
+
7
+ from comdab.exceptions import ComdabInternalError, UnhandledTypeError
8
+ from comdab.models.column import ComdabColumn
9
+ from comdab.models.constraint import (
10
+ ComdabCheckConstraint,
11
+ ComdabConstraint,
12
+ ComdabForeignKeyConstraint,
13
+ ComdabPrimaryKeyConstraint,
14
+ ComdabUniqueConstraint,
15
+ )
16
+ from comdab.models.function import ComdabFunction
17
+ from comdab.models.index import ComdabIndex
18
+ from comdab.models.schema import ComdabSchema
19
+ from comdab.models.sequence import ComdabSequence
20
+ from comdab.models.table import ComdabTable
21
+ from comdab.models.trigger import ComdabTrigger
22
+ from comdab.models.type import ComdabType, ComdabTypes
23
+ from comdab.models.view import ComdabView
24
+ from comdab.source import ComdabSource
25
+ from comdab.utils import dict_by_name
26
+
27
+ strict = False
28
+
29
+
30
+ class ComdabBuilder:
31
+ """Build a database schema describing an existing database.
32
+
33
+ Built on :meth:`sqlalchemy.Metadata.reflect` machinery, with custom extensions.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ source: ComdabSource,
39
+ allow_unknown_types: bool = False,
40
+ ) -> None:
41
+ self.source = source
42
+ self.allow_unknown_types = allow_unknown_types
43
+
44
+ # Level 0
45
+
46
+ def build_schema(self) -> ComdabSchema:
47
+ sa_metadata = schema.MetaData()
48
+ sa_metadata.reflect(
49
+ bind=self.source.connection,
50
+ views=False,
51
+ schema=self.source.schema_name,
52
+ resolve_fks=False,
53
+ )
54
+
55
+ return ComdabSchema(
56
+ tables=dict_by_name(self.generate_tables(sa_metadata)),
57
+ views=dict_by_name(self.generate_views(sa_metadata)),
58
+ sequences=dict_by_name(self.generate_sequences(sa_metadata)),
59
+ functions=dict_by_name(self.generate_functions(sa_metadata)),
60
+ extra={str(key): val for key, val in sa_metadata.info.items()},
61
+ )
62
+
63
+ # Level 1
64
+
65
+ def generate_tables(self, sa_metadata: schema.MetaData) -> Iterator[ComdabTable]:
66
+ for sa_table in sa_metadata.tables.values():
67
+ yield self.build_table(sa_table)
68
+
69
+ def build_table(self, sa_table: schema.Table) -> ComdabTable:
70
+ return ComdabTable(
71
+ name=sa_table.name,
72
+ columns=dict_by_name(self.generate_columns(sa_table)),
73
+ constraints=dict_by_name(self.generate_constraints(sa_table)),
74
+ indexes=dict_by_name(self.generate_indexes(sa_table)),
75
+ triggers=dict_by_name(self.generate_triggers(sa_table)),
76
+ extra=dict(sa_table.dialect_kwargs),
77
+ )
78
+
79
+ def generate_views(self, sa_metadata: schema.MetaData) -> Iterator[ComdabView]:
80
+ yield from () # No database-agnostic implementation
81
+
82
+ def generate_sequences(self, sa_metadata: schema.MetaData) -> Iterator[ComdabSequence]:
83
+ yield from () # No database-agnostic implementation
84
+
85
+ def generate_functions(self, sa_metadata: schema.MetaData) -> Iterator[ComdabFunction]:
86
+ yield from () # No database-agnostic implementation
87
+
88
+ # Level 2
89
+
90
+ def generate_columns(self, sa_table: schema.Table) -> Iterator[ComdabColumn]:
91
+ for sa_column in sa_table.columns:
92
+ yield self.build_column(sa_column)
93
+
94
+ def generate_constraints(self, sa_table: schema.Table) -> Iterator[ComdabConstraint]:
95
+ for sa_constraint in sa_table.constraints:
96
+ yield self.build_constraint(sa_constraint)
97
+
98
+ def generate_indexes(self, sa_table: schema.Table) -> Iterator[ComdabIndex]:
99
+ for sa_index in sa_table.indexes:
100
+ yield self.build_index(sa_index)
101
+
102
+ def generate_triggers(self, sa_table: schema.Table) -> Iterator[ComdabTrigger]:
103
+ yield from () # No database-agnostic implementation
104
+
105
+ def build_column(self, sa_column: schema.Column[Any]) -> ComdabColumn:
106
+ if sa_column.nullable is None:
107
+ raise ComdabInternalError("Reflected columns should always have nullability defined")
108
+ match sa_column.server_default:
109
+ case None:
110
+ default = generation_expression = None
111
+ case schema.DefaultClause():
112
+ default = _compile(sa_column.server_default.arg)
113
+ generation_expression = None
114
+ case schema.Computed():
115
+ default = None
116
+ generation_expression = _compile(sa_column.server_default.sqltext)
117
+ case _:
118
+ raise ComdabInternalError(f"Unexpected value in Column.server_default: {sa_column.server_default}")
119
+
120
+ return ComdabColumn(
121
+ name=sa_column.name,
122
+ type=self.build_type(sa_column.type),
123
+ nullable=sa_column.nullable,
124
+ default=default,
125
+ generation_expression=generation_expression,
126
+ extra=dict(sa_column.dialect_kwargs),
127
+ )
128
+
129
+ def build_constraint(self, sa_constraint: schema.Constraint) -> ComdabConstraint:
130
+ name = sa_constraint.name
131
+ if not isinstance(name, str):
132
+ raise ComdabInternalError("Reflected constraints should always have a name defined")
133
+ extra = dict[str, Any](sa_constraint.dialect_kwargs)
134
+
135
+ match sa_constraint:
136
+ case schema.UniqueConstraint():
137
+ return ComdabUniqueConstraint(
138
+ name=name,
139
+ columns={col.name for col in sa_constraint.columns},
140
+ deferrable=sa_constraint.deferrable,
141
+ initially=sa_constraint.initially,
142
+ extra=extra,
143
+ )
144
+ case schema.PrimaryKeyConstraint():
145
+ return ComdabPrimaryKeyConstraint(
146
+ name=name,
147
+ columns={col.name for col in sa_constraint.columns},
148
+ deferrable=sa_constraint.deferrable,
149
+ initially=sa_constraint.initially,
150
+ extra=extra,
151
+ )
152
+ case schema.ForeignKeyConstraint():
153
+ return ComdabForeignKeyConstraint(
154
+ name=name,
155
+ columns_mapping={elt.parent.name: elt.target_fullname for elt in sa_constraint.elements},
156
+ on_update=sa_constraint.onupdate,
157
+ on_delete=sa_constraint.ondelete,
158
+ deferrable=sa_constraint.deferrable,
159
+ initially=sa_constraint.initially,
160
+ extra=extra,
161
+ )
162
+ case schema.CheckConstraint():
163
+ return ComdabCheckConstraint(
164
+ name=name,
165
+ sql_text=_compile(sa_constraint.sqltext),
166
+ deferrable=sa_constraint.deferrable,
167
+ initially=sa_constraint.initially,
168
+ extra=extra,
169
+ )
170
+ case _:
171
+ raise ComdabInternalError(f"Unexpected SQLAlchemy Constraint type: {type(sa_constraint)}")
172
+
173
+ def build_index(self, sa_index: schema.Index) -> ComdabIndex:
174
+ if not sa_index.name:
175
+ raise ComdabInternalError("Reflected indexes should always have a name defined")
176
+ return ComdabIndex(
177
+ name=sa_index.name,
178
+ expressions=[_compile(expr) for expr in sa_index.expressions],
179
+ unique=sa_index.unique,
180
+ extra=dict(sa_index.dialect_kwargs),
181
+ )
182
+
183
+ # Level 3
184
+
185
+ def build_type(self, sa_type: types.TypeEngine[Any]) -> ComdabType:
186
+ implem_name = type(sa_type).__name__
187
+ match sa_type:
188
+ case types.Enum(): # Subclass of String -> must appear first
189
+ return ComdabTypes.Enum(
190
+ implem_name=implem_name,
191
+ values=set(sa_type.enums),
192
+ type_name=f"{sa_type.schema}.{sa_type.name}" if sa_type.schema else sa_type.name,
193
+ collation=sa_type.collation,
194
+ )
195
+ case types.String():
196
+ return ComdabTypes.String(implem_name=implem_name, length=sa_type.length, collation=sa_type.collation)
197
+ case types.Integer():
198
+ return ComdabTypes.Integer(implem_name=implem_name)
199
+ case types.Float(): # Subclass of Numeric -> must appear first
200
+ return ComdabTypes.Float(implem_name=implem_name)
201
+ case types.Numeric():
202
+ return ComdabTypes.Numeric(implem_name=implem_name, precision=sa_type.precision, scale=sa_type.scale)
203
+ case types.Boolean():
204
+ return ComdabTypes.Boolean(implem_name=implem_name)
205
+ case types.DateTime():
206
+ return ComdabTypes.DateTime(implem_name=implem_name, with_timezone=sa_type.timezone)
207
+ case types.Date():
208
+ return ComdabTypes.Date(implem_name=implem_name)
209
+ case types.Time():
210
+ return ComdabTypes.Time(implem_name=implem_name)
211
+ case types.Interval():
212
+ return ComdabTypes.Interval(
213
+ implem_name=implem_name,
214
+ second_precision=sa_type.second_precision,
215
+ day_precision=sa_type.day_precision,
216
+ )
217
+ case types.JSON():
218
+ return ComdabTypes.JSON(implem_name=implem_name)
219
+ case types.BINARY():
220
+ return ComdabTypes.Binary(implem_name=implem_name, length=sa_type.length)
221
+ case types.UUID():
222
+ return ComdabTypes.UUID(implem_name=implem_name)
223
+ case types.ARRAY():
224
+ return ComdabTypes.Array(
225
+ implem_name=implem_name,
226
+ item_type=self.build_type(sa_type.item_type),
227
+ dimensions=sa_type.dimensions or 1,
228
+ )
229
+ case _ if self.allow_unknown_types:
230
+ return ComdabTypes.Unknown(implem_name=implem_name)
231
+ case _:
232
+ raise UnhandledTypeError(f"Unhandled SQL type: {type(sa_type)} ({implem_name})")
233
+
234
+
235
+ def _compile(sql_text: str | ClauseElement) -> str:
236
+ if isinstance(sql_text, str):
237
+ return sql_text
238
+ return str(sql_text.compile(compile_kwargs={"literal_binds": True}))
comdab/compare.py ADDED
@@ -0,0 +1,182 @@
1
+ import re
2
+ from collections import defaultdict
3
+ from collections.abc import Iterator
4
+ from dataclasses import dataclass
5
+ from typing import Any, Literal, cast
6
+
7
+ from comdab.exceptions import OverlappingPathsError
8
+ from comdab.models.base import ComdabModel
9
+ from comdab.models.schema import ROOT, ComdabSchema
10
+ from comdab.path import (
11
+ ComdabPath,
12
+ ComdabPathDict,
13
+ PathAttr,
14
+ PathItem,
15
+ get_path_component,
16
+ get_path_depth,
17
+ )
18
+ from comdab.report import ComdabReport
19
+
20
+ type ComdabStrategy = Literal["error", "warning", "ignore"]
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class _Rule:
25
+ path: ComdabPath
26
+ strategy: ComdabStrategy
27
+
28
+ def get_attr_component(self, depth: int) -> str | None:
29
+ comp = get_path_component(self.path, depth - 1)
30
+ return comp.attr if isinstance(comp, PathAttr) else None
31
+
32
+ def get_item_component(self, depth: int) -> str | None:
33
+ comp = get_path_component(self.path, depth - 1)
34
+ return comp.key if isinstance(comp, PathItem) else None
35
+
36
+ def applies_to(self, depth: int) -> bool:
37
+ return get_path_depth(self.path) == depth
38
+
39
+
40
+ class ComdabComparer:
41
+ """Compare two comdab schemas to reveal their differences.
42
+
43
+ Specific differences can be ignored or reported as warnings using custom rules.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ *,
49
+ rules: dict[ComdabPath, ComdabStrategy] | None = None,
50
+ ) -> None:
51
+ self._rules = rules or {}
52
+ self._default_rule = _Rule(path=ROOT, strategy="error")
53
+
54
+ # SEMANTIC: we name
55
+ # * "crule" (Current Rule) -> a rule applying to the current level
56
+ # * "prule" (Potential Rule) -> a rule *maybe* applying the current level, or to a more precise attribute/item
57
+
58
+ def compare(self, left: ComdabSchema, right: ComdabSchema) -> list[ComdabReport]:
59
+ prules = [_Rule(path=path, strategy=strategy) for path, strategy in self._rules.items()]
60
+ crule = next((rule for rule in prules if rule.applies_to(0)), self._default_rule)
61
+ return list(
62
+ self._compare(left, right, path=ROOT, crule=crule, prules=prules),
63
+ )
64
+
65
+ def _compare(
66
+ self,
67
+ left: object,
68
+ right: object,
69
+ *,
70
+ path: ComdabPath,
71
+ crule: _Rule,
72
+ prules: list[_Rule],
73
+ ) -> Iterator[ComdabReport]:
74
+ depth = get_path_depth(path)
75
+
76
+ if crule.strategy == "ignore" and not prules:
77
+ # Don't report errors for this path, and no way to change later: we can abort here
78
+ return
79
+
80
+ if type(left) is not type(right) or not isinstance(left, ComdabModel):
81
+ # Direct comparison
82
+ if left != right and crule.strategy != "ignore":
83
+ yield ComdabReport(level=crule.strategy, path=path, left=left, right=right)
84
+ return
85
+
86
+ # Deep model comparison
87
+ fields = type(left).model_fields.keys()
88
+ field_depth = depth + 1
89
+
90
+ # Get the rules specific to each field
91
+ prules_by_field = defaultdict[str, list[_Rule]](list)
92
+ for rule in prules:
93
+ if attr := rule.get_attr_component(field_depth):
94
+ prules_by_field[attr].append(rule)
95
+
96
+ # Compare field by field
97
+ for field in fields:
98
+ left_attr = getattr(left, field)
99
+ right_attr = getattr(right, field)
100
+ field_path = getattr(path, field) # Exists if path is consistent with model (enforced by tests)
101
+
102
+ field_prules = prules_by_field[field]
103
+ field_crule = next((rule for rule in field_prules if rule.applies_to(field_depth)), crule)
104
+
105
+ if not isinstance(field_path, ComdabPathDict):
106
+ # Scalars: compare attributes directly
107
+ yield from self._compare(
108
+ left_attr,
109
+ right_attr,
110
+ path=field_path,
111
+ crule=field_crule,
112
+ prules=field_prules,
113
+ )
114
+ continue
115
+
116
+ # Mappings: compare key by key
117
+ left_dict = cast(dict[str, Any], left_attr)
118
+ right_dict = cast(dict[str, Any], right_attr)
119
+
120
+ # Use lists instead of sets for consistent reporting order
121
+ left_only = [key for key in left_dict if key not in right_dict]
122
+ right_only = [key for key in right_dict if key not in left_dict]
123
+ both = [key for key in left_dict if key in right_dict]
124
+ key_depth = field_depth + 1
125
+
126
+ if left_only:
127
+ # Keys only in left dict: apply special rule, else field rule
128
+ left_only_crule = next(
129
+ (rule for rule in field_prules if rule.get_attr_component(key_depth) == "left_only"),
130
+ field_crule,
131
+ )
132
+ if left_only_crule.strategy != "ignore":
133
+ for key in left_only:
134
+ yield ComdabReport(
135
+ level=left_only_crule.strategy,
136
+ path=field_path.left_only,
137
+ left={key: left_dict[key]},
138
+ right={},
139
+ )
140
+
141
+ if right_only:
142
+ # Keys only in right dict: apply special rule, else field rule
143
+ right_only_crule = next(
144
+ (rule for rule in field_prules if rule.get_attr_component(key_depth) == "right_only"),
145
+ field_crule,
146
+ )
147
+ if right_only_crule.strategy != "ignore":
148
+ for key in right_only:
149
+ yield ComdabReport(
150
+ level=right_only_crule.strategy,
151
+ path=field_path.right_only,
152
+ left={},
153
+ right={key: right_dict[key]},
154
+ )
155
+
156
+ for key in both:
157
+ # Key in both dicts: compare, using the matching rule, else field rule
158
+ key_prules = [rule for rule in field_prules if _regex_applies(rule.get_item_component(key_depth), key)]
159
+ key_crules = [rule for rule in key_prules if rule.applies_to(key_depth)]
160
+ if len(key_crules) > 1:
161
+ raise OverlappingPathsError(
162
+ f"The key {key!r} matches more than one regex: "
163
+ f"{', '.join(r.get_item_component(key_depth) or '?' for r in key_crules)}"
164
+ )
165
+ elif key_crules:
166
+ key_crule = key_crules[0]
167
+ else:
168
+ key_crule = field_crule
169
+
170
+ yield from self._compare(
171
+ left_dict[key],
172
+ right_dict[key],
173
+ path=field_path[key],
174
+ crule=key_crule,
175
+ prules=key_prules,
176
+ )
177
+
178
+
179
+ def _regex_applies(pattern: str | None, key: str) -> bool:
180
+ if not pattern:
181
+ return False
182
+ return re.fullmatch(pattern, key) is not None
comdab/exceptions.py ADDED
@@ -0,0 +1,18 @@
1
+ class ComdabException(Exception):
2
+ """The root class of exceptions raised by comdab."""
3
+
4
+
5
+ class UnhandledTypeError(ComdabException):
6
+ """A SQL type not handled by comdab was encountered.
7
+
8
+ Consider passing `allow_unknown_types=True`, or opening a feature request!"""
9
+
10
+
11
+ class OverlappingPathsError(ComdabException):
12
+ """Several constraint paths overlap."""
13
+
14
+
15
+ class ComdabInternalError(ComdabException):
16
+ """Something unexpected happened!
17
+
18
+ If it escapes comdab internals, please report a bug."""
comdab/main.py ADDED
@@ -0,0 +1,99 @@
1
+ from sqlalchemy import Connection
2
+ from sqlalchemy.dialects import postgresql
3
+
4
+ from comdab.build import ComdabBuilder
5
+ from comdab.compare import ComdabComparer, ComdabStrategy
6
+ from comdab.models.schema import ComdabSchema
7
+ from comdab.path import ComdabPath
8
+ from comdab.report import ComdabReport
9
+ from comdab.source import ComdabSource
10
+
11
+
12
+ def compare_databases(
13
+ left_connection: Connection,
14
+ right_connection: Connection,
15
+ *,
16
+ left_schema: str = "public",
17
+ right_schema: str = "public",
18
+ rules: dict[ComdabPath, ComdabStrategy] | None = None,
19
+ allow_unknown_types: bool = False,
20
+ ) -> list[ComdabReport]:
21
+ """Build and compare two database schemas, from their SQLAlchemy connection.
22
+
23
+ This is the highest-level, all-in-one *comdab* function.
24
+
25
+ Args:
26
+ left_connection: A SQLAlchemy :class:`~sqlalchemy.Connection<connection>` established
27
+ to the first database to compare.
28
+ right_connection: A SQLAlchemy :class:`~sqlalchemy.Connection<connection>` established
29
+ to the second database to compare.
30
+ left_schema: The name of the database schema to compare for the ``left_connection``.
31
+ right_schema: The name of the database schema to compare for the ``right_connection``.
32
+ rules: An optional set of rules to allow some differences between the schemas,
33
+ or report them as warnings. See :ref:`Ignore rules <ignorerules>` for more details.
34
+ allow_unknown_types: If ``True``, SQL data types not handed (yet) by comdab will be
35
+ modeled as "unknown" and compared based on their name only. If ``False`` (the default),
36
+ encountering an unknown name will raise an :exc:`UnhandledTypeError`.
37
+ """
38
+ left = build_comdab_schema(
39
+ left_connection,
40
+ schema=left_schema,
41
+ allow_unknown_types=allow_unknown_types,
42
+ )
43
+ right = build_comdab_schema(
44
+ right_connection,
45
+ schema=right_schema,
46
+ allow_unknown_types=allow_unknown_types,
47
+ )
48
+ return compare_comdab_schemas(left, right, rules=rules)
49
+
50
+
51
+ def build_comdab_schema(
52
+ connection: Connection,
53
+ *,
54
+ schema: str = "public",
55
+ allow_unknown_types: bool = False,
56
+ ) -> ComdabSchema:
57
+ """Build a database-agnostic, SQLAlchemy-independent representation of a database schema.
58
+
59
+ This is the internal representation used for comparison by *comdab*.
60
+
61
+ Args:
62
+ connection: A SQLAlchemy :class:`~sqlalchemy.Connection<connection>` established
63
+ to the database to reflect.
64
+ schema: The name of the database schema to reflect.
65
+ allow_unknown_types: If ``True``, SQL data types not handed (yet) by comdab will be
66
+ modeled as "unknown" and compared based on their name only. If ``False`` (the default),
67
+ encountering an unknown name will raise an :exc:`UnhandledTypeError`.
68
+ """
69
+ source = ComdabSource(connection=connection, schema_name=schema)
70
+ match connection.dialect:
71
+ case postgresql.dialect():
72
+ from comdab.specific.postgresql.build import ComdabPostgreSQLBuilder
73
+
74
+ builder = ComdabPostgreSQLBuilder(source, allow_unknown_types=allow_unknown_types)
75
+
76
+ case _:
77
+ builder = ComdabBuilder(source, allow_unknown_types=allow_unknown_types)
78
+
79
+ return builder.build_schema()
80
+
81
+
82
+ def compare_comdab_schemas(
83
+ left: ComdabSchema,
84
+ right: ComdabSchema,
85
+ *,
86
+ rules: dict[ComdabPath, ComdabStrategy] | None = None,
87
+ ) -> list[ComdabReport]:
88
+ """Compare two already built database schemas.
89
+
90
+ This is a pure function, needing no connection to a database.
91
+
92
+ Args:
93
+ left: The first schema to compare, as produced by :func:`build_comdab_schema`.
94
+ right: The second schema to compare, as produced by :func:`build_comdab_schema`.
95
+ rules: An optional set of rules to allow some differences between the schemas,
96
+ or report them as warnings. See :ref:`Ignore rules <ignorerules>` for more details.
97
+ """
98
+ comparer = ComdabComparer(rules=rules)
99
+ return comparer.compare(left, right)
@@ -0,0 +1,34 @@
1
+ from comdab.models.column import ComdabColumn
2
+ from comdab.models.constraint import (
3
+ ComdabCheckConstraint,
4
+ ComdabExcludeConstraint,
5
+ ComdabForeignKeyConstraint,
6
+ ComdabPrimaryKeyConstraint,
7
+ ComdabUniqueConstraint,
8
+ )
9
+ from comdab.models.function import ComdabFunction
10
+ from comdab.models.index import ComdabIndex
11
+ from comdab.models.schema import ROOT, ComdabSchema
12
+ from comdab.models.sequence import ComdabSequence
13
+ from comdab.models.table import ComdabTable
14
+ from comdab.models.trigger import ComdabTrigger
15
+ from comdab.models.type import ComdabTypes
16
+ from comdab.models.view import ComdabView
17
+
18
+ __all__ = (
19
+ "ComdabCheckConstraint",
20
+ "ComdabColumn",
21
+ "ComdabExcludeConstraint",
22
+ "ComdabForeignKeyConstraint",
23
+ "ComdabFunction",
24
+ "ComdabIndex",
25
+ "ComdabPrimaryKeyConstraint",
26
+ "ComdabSchema",
27
+ "ComdabSequence",
28
+ "ComdabTable",
29
+ "ComdabTrigger",
30
+ "ComdabTypes",
31
+ "ComdabUniqueConstraint",
32
+ "ComdabView",
33
+ "ROOT",
34
+ )
comdab/models/base.py ADDED
@@ -0,0 +1,5 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class ComdabModel(BaseModel, frozen=True):
5
+ """The base class of all comdab models."""
@@ -0,0 +1,31 @@
1
+ from typing import Any
2
+
3
+ from pydantic import Field
4
+
5
+ from comdab.models.base import ComdabModel
6
+ from comdab.models.type import ComdabType, ComdabType_Path
7
+ from comdab.path import ComdabPath, dict_of_paths, sub_path, terminal_path
8
+
9
+
10
+ class ComdabColumn(ComdabModel, frozen=True):
11
+ """A database column.
12
+
13
+ Equivalent to a :class:`sqlalchemy.Column` object.
14
+ """
15
+
16
+ name: str
17
+ type: ComdabType
18
+ nullable: bool
19
+ default: str | None
20
+ generation_expression: str | None
21
+ extra: dict[str, Any] = Field(default_factory=dict)
22
+
23
+ # PostgreSQL parameters not reflected here: storage, compression, collation, comments
24
+
25
+ class Path(ComdabPath):
26
+ name = terminal_path()
27
+ type = sub_path(ComdabType_Path)
28
+ nullable = terminal_path()
29
+ default = terminal_path()
30
+ generation_expression = terminal_path()
31
+ extra = dict_of_paths(ComdabPath)