narabi-orm 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.
- narabi/__init__.py +27 -0
- narabi/__main__.py +5 -0
- narabi/cli.py +338 -0
- narabi/console.py +102 -0
- narabi/database.py +310 -0
- narabi/fields/__init__.py +13 -0
- narabi/fields/defaults.py +59 -0
- narabi/fields/markers.py +74 -0
- narabi/migrations/__init__.py +22 -0
- narabi/migrations/bootstrap.py +30 -0
- narabi/migrations/decorators.py +22 -0
- narabi/migrations/diff.py +96 -0
- narabi/migrations/dsl.py +255 -0
- narabi/migrations/errors.py +5 -0
- narabi/migrations/executor.py +299 -0
- narabi/migrations/generate.py +149 -0
- narabi/migrations/historical.py +158 -0
- narabi/migrations/history.py +160 -0
- narabi/migrations/models.py +57 -0
- narabi/migrations/postgres_executor.py +239 -0
- narabi/migrations/postgresql.py +268 -0
- narabi/migrations/preview.py +150 -0
- narabi/migrations/replay.py +40 -0
- narabi/migrations/reverse.py +127 -0
- narabi/migrations/schema.py +169 -0
- narabi/migrations/snapshot.py +52 -0
- narabi/migrations/sqlite.py +131 -0
- narabi/models/__init__.py +1 -0
- narabi/models/bulk.py +123 -0
- narabi/models/core.py +440 -0
- narabi/models/inflection.py +37 -0
- narabi/models/lifecycle.py +125 -0
- narabi/models/privacy.py +19 -0
- narabi/models/serialization.py +145 -0
- narabi/models/soft_delete.py +59 -0
- narabi/models/timestamps.py +47 -0
- narabi/models/validation.py +149 -0
- narabi/models/values.py +167 -0
- narabi/project.py +108 -0
- narabi/py.typed +0 -0
- narabi/pytest.py +11 -0
- narabi/query/__init__.py +7 -0
- narabi/query/expressions.py +180 -0
- narabi/query/relation.py +562 -0
- narabi/query/scopes.py +36 -0
- narabi/relations/__init__.py +6 -0
- narabi/relations/prefetch.py +66 -0
- narabi/relations/references.py +196 -0
- narabi/relations/relationships.py +185 -0
- narabi/schema.py +132 -0
- narabi/stubs.py +275 -0
- narabi_orm-0.1.0.dist-info/METADATA +104 -0
- narabi_orm-0.1.0.dist-info/RECORD +56 -0
- narabi_orm-0.1.0.dist-info/WHEEL +4 -0
- narabi_orm-0.1.0.dist-info/entry_points.txt +2 -0
- narabi_orm-0.1.0.dist-info/licenses/LICENSE +29 -0
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Apply structural edits using PostgreSQL DDL."""
|
|
2
|
+
|
|
3
|
+
from collections import Counter
|
|
4
|
+
from dataclasses import dataclass, replace
|
|
5
|
+
|
|
6
|
+
from ..database import identifier
|
|
7
|
+
from ..schema import _field_sql
|
|
8
|
+
from .diff import _indexes
|
|
9
|
+
from .errors import MigrationError
|
|
10
|
+
from .postgresql import constraints, normalize_check
|
|
11
|
+
from .preview import _index_sql, _table_sql
|
|
12
|
+
from .schema import Column, Reference
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class _ForeignKey:
|
|
17
|
+
table: str
|
|
18
|
+
column: str
|
|
19
|
+
reference: Reference
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
async def finish_postgresql_edits(database, deferred):
|
|
23
|
+
for key in deferred:
|
|
24
|
+
reference = key.reference
|
|
25
|
+
await database.execute(
|
|
26
|
+
f"ALTER TABLE {identifier(key.table)} ADD FOREIGN KEY ({identifier(key.column)}) "
|
|
27
|
+
f"REFERENCES {identifier(reference.table)} ({identifier(reference.field)})"
|
|
28
|
+
)
|
|
29
|
+
deferred.clear()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _physical_renames(edit):
|
|
33
|
+
live = {column.name: column.name for column in edit.before.columns}
|
|
34
|
+
retained = {source for _, source in edit.origins}
|
|
35
|
+
for old, new in edit.renames:
|
|
36
|
+
original = live.pop(old)
|
|
37
|
+
live[new] = original
|
|
38
|
+
if original in retained:
|
|
39
|
+
yield old, new
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _rename_links(deferred, table, renames):
|
|
43
|
+
for old, new in renames:
|
|
44
|
+
for position, key in enumerate(deferred):
|
|
45
|
+
source = new if key.table == table and key.column == old else key.column
|
|
46
|
+
target = key.reference
|
|
47
|
+
if target.table == table and target.field == old:
|
|
48
|
+
target = replace(target, field=new)
|
|
49
|
+
deferred[position] = _ForeignKey(key.table, source, target)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _column_changes(before, after, origins):
|
|
53
|
+
old_columns = {column.name: column for column in before.columns}
|
|
54
|
+
new_columns = {column.name: column for column in after.columns}
|
|
55
|
+
names = {source: destination for destination, source in origins}
|
|
56
|
+
for old, new in names.items():
|
|
57
|
+
previous = old_columns[old]
|
|
58
|
+
reference = previous.references
|
|
59
|
+
if reference is not None and reference.table == before.name and reference.field in names:
|
|
60
|
+
reference = replace(reference, field=names[reference.field])
|
|
61
|
+
yield previous, replace(previous, name=new, references=reference), new_columns[new]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
async def _drop_constraints(database, table, keys, checks):
|
|
65
|
+
if not keys and not checks:
|
|
66
|
+
return
|
|
67
|
+
discovered = await constraints(database, table)
|
|
68
|
+
seen = set()
|
|
69
|
+
for constraint in discovered:
|
|
70
|
+
key = (constraint.kind, constraint.fields)
|
|
71
|
+
if key in keys:
|
|
72
|
+
seen.add(key)
|
|
73
|
+
elif constraint.kind == "c":
|
|
74
|
+
normalized = normalize_check(constraint.check)
|
|
75
|
+
if not checks[normalized]:
|
|
76
|
+
continue
|
|
77
|
+
checks[normalized] -= 1
|
|
78
|
+
else:
|
|
79
|
+
continue
|
|
80
|
+
await database.execute(
|
|
81
|
+
f"ALTER TABLE {identifier(table)} DROP CONSTRAINT {identifier(constraint.name)}"
|
|
82
|
+
)
|
|
83
|
+
if keys - seen or +checks:
|
|
84
|
+
raise MigrationError(f"{table}: could not find the constraints required by the migration")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
async def _defer_incoming(database, table, columns, deferred):
|
|
88
|
+
if columns is not None and not columns:
|
|
89
|
+
return
|
|
90
|
+
rows = await database.execute(
|
|
91
|
+
"""
|
|
92
|
+
SELECT source.relname, source_col.attname, c.conname, target_col.attname
|
|
93
|
+
FROM pg_catalog.pg_constraint AS c
|
|
94
|
+
JOIN pg_catalog.pg_class AS source ON source.oid = c.conrelid
|
|
95
|
+
JOIN pg_catalog.pg_class AS target ON target.oid = c.confrelid
|
|
96
|
+
JOIN pg_catalog.pg_namespace AS source_ns ON source_ns.oid = source.relnamespace
|
|
97
|
+
JOIN pg_catalog.pg_namespace AS target_ns ON target_ns.oid = target.relnamespace
|
|
98
|
+
JOIN pg_catalog.pg_attribute AS source_col
|
|
99
|
+
ON source_col.attrelid = source.oid AND source_col.attnum = c.conkey[1]
|
|
100
|
+
JOIN pg_catalog.pg_attribute AS target_col
|
|
101
|
+
ON target_col.attrelid = target.oid AND target_col.attnum = c.confkey[1]
|
|
102
|
+
WHERE c.contype = 'f' AND cardinality(c.conkey) = 1
|
|
103
|
+
AND source_ns.nspname = current_schema() AND target_ns.nspname = current_schema()
|
|
104
|
+
AND target.relname = %s
|
|
105
|
+
ORDER BY source.relname, c.conname
|
|
106
|
+
""",
|
|
107
|
+
(table,), fetch=True,
|
|
108
|
+
)
|
|
109
|
+
for source, column, constraint, referenced in rows:
|
|
110
|
+
if columns is not None and referenced not in columns:
|
|
111
|
+
continue
|
|
112
|
+
await database.execute(f"ALTER TABLE {identifier(source)} DROP CONSTRAINT {identifier(constraint)}")
|
|
113
|
+
deferred.append(_ForeignKey(source, column, Reference(table, referenced)))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
async def _alter_column(database, table, previous: Column, current: Column):
|
|
117
|
+
column = identifier(current.name)
|
|
118
|
+
alter = f"ALTER TABLE {identifier(table)} ALTER COLUMN {column}"
|
|
119
|
+
if previous.auto_increment and not current.auto_increment:
|
|
120
|
+
await database.execute(f"{alter} DROP IDENTITY")
|
|
121
|
+
if previous.kind != current.kind:
|
|
122
|
+
kind = "TIMESTAMPTZ" if current.kind == "datetime" else current.kind.upper()
|
|
123
|
+
await database.execute(f"{alter} TYPE {kind} USING {column}::{kind}")
|
|
124
|
+
if previous.nullable != current.nullable:
|
|
125
|
+
action = "DROP" if current.nullable else "SET"
|
|
126
|
+
await database.execute(f"{alter} {action} NOT NULL")
|
|
127
|
+
if current.auto_increment and not previous.auto_increment:
|
|
128
|
+
await database.execute(f"{alter} ADD GENERATED BY DEFAULT AS IDENTITY")
|
|
129
|
+
rows = await database.execute(f"SELECT MAX({column}) FROM {identifier(table)}", fetch=True)
|
|
130
|
+
next_value = max(1, (rows[0][0] or 0) + 1)
|
|
131
|
+
await database.execute(f"{alter} RESTART WITH {next_value}")
|
|
132
|
+
if current.primary and not previous.primary:
|
|
133
|
+
await database.execute(f"ALTER TABLE {identifier(table)} ADD PRIMARY KEY ({column})")
|
|
134
|
+
if current.unique and not previous.unique:
|
|
135
|
+
await database.execute(f"ALTER TABLE {identifier(table)} ADD UNIQUE ({column})")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
async def apply_postgresql_edit(database, edit, *, deferred=None):
|
|
139
|
+
"""Apply an edit, optionally saving new foreign keys until the batch finishes."""
|
|
140
|
+
own_queue = deferred is None
|
|
141
|
+
deferred = [] if own_queue else deferred
|
|
142
|
+
before, after = edit.before, edit.after
|
|
143
|
+
table = edit.name
|
|
144
|
+
|
|
145
|
+
if before is None:
|
|
146
|
+
columns = tuple(replace(column, references=None) for column in after.columns)
|
|
147
|
+
for statement in _table_sql(replace(after, columns=columns), "postgresql"):
|
|
148
|
+
await database.execute(statement)
|
|
149
|
+
deferred.extend(
|
|
150
|
+
_ForeignKey(table, column.name, column.references)
|
|
151
|
+
for column in after.columns if column.references is not None
|
|
152
|
+
)
|
|
153
|
+
elif after is None:
|
|
154
|
+
await _defer_incoming(database, table, None, deferred)
|
|
155
|
+
await database.execute(f"DROP TABLE {identifier(table)}")
|
|
156
|
+
deferred[:] = [key for key in deferred if key.table != table]
|
|
157
|
+
else:
|
|
158
|
+
await _edit_table(database, edit, deferred)
|
|
159
|
+
|
|
160
|
+
if own_queue:
|
|
161
|
+
await finish_postgresql_edits(database, deferred)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
async def _edit_table(database, edit, deferred):
|
|
165
|
+
before, after = edit.before, edit.after
|
|
166
|
+
table = edit.name
|
|
167
|
+
alter = f"ALTER TABLE {identifier(table)}"
|
|
168
|
+
retained = {source for _, source in edit.origins}
|
|
169
|
+
renamed = {source: target for target, source in edit.origins}
|
|
170
|
+
removed = [column.name for column in before.columns if column.name not in retained]
|
|
171
|
+
changes = tuple(_column_changes(before, after, edit.origins))
|
|
172
|
+
|
|
173
|
+
affected = set(removed)
|
|
174
|
+
for old, previous, current in changes:
|
|
175
|
+
if (
|
|
176
|
+
previous.kind != current.kind or (old.primary and not current.primary)
|
|
177
|
+
or (old.unique and not current.unique)
|
|
178
|
+
):
|
|
179
|
+
affected.add(old.name)
|
|
180
|
+
await _defer_incoming(database, table, affected, deferred)
|
|
181
|
+
pending = {key.column for key in deferred if key.table == table}
|
|
182
|
+
canceled = set(removed)
|
|
183
|
+
drops = set()
|
|
184
|
+
for old, previous, current in changes:
|
|
185
|
+
if old.primary and not current.primary:
|
|
186
|
+
drops.add(("p", (old.name,)))
|
|
187
|
+
if old.unique and not current.unique:
|
|
188
|
+
drops.add(("u", (old.name,)))
|
|
189
|
+
if previous.references != current.references:
|
|
190
|
+
canceled.add(old.name)
|
|
191
|
+
if previous.references is not None and old.name not in pending:
|
|
192
|
+
drops.add(("f", (old.name,)))
|
|
193
|
+
|
|
194
|
+
original_checks = Counter(map(normalize_check, before.checks))
|
|
195
|
+
final_checks = Counter(map(normalize_check, after.checks))
|
|
196
|
+
await _drop_constraints(database, table, drops, original_checks - final_checks)
|
|
197
|
+
|
|
198
|
+
original_indexes = _indexes(before)
|
|
199
|
+
final_indexes = _indexes(after)
|
|
200
|
+
renamed_indexes = {
|
|
201
|
+
name: replace(index, fields=tuple(renamed.get(field, field) for field in index.fields))
|
|
202
|
+
for name, index in original_indexes.items()
|
|
203
|
+
}
|
|
204
|
+
retained_indexes = {
|
|
205
|
+
name for name, index in renamed_indexes.items()
|
|
206
|
+
if not set(original_indexes[name].fields).intersection(removed) and final_indexes.get(name) == index
|
|
207
|
+
}
|
|
208
|
+
for name in sorted(original_indexes.keys() - retained_indexes):
|
|
209
|
+
await database.execute(f"DROP INDEX {identifier(name)}")
|
|
210
|
+
for column in removed:
|
|
211
|
+
await database.execute(f"{alter} DROP COLUMN {identifier(column)}")
|
|
212
|
+
|
|
213
|
+
deferred[:] = [key for key in deferred if key.table != table or key.column not in canceled]
|
|
214
|
+
renames = tuple(_physical_renames(edit))
|
|
215
|
+
for old, new in renames:
|
|
216
|
+
await database.execute(f"{alter} RENAME COLUMN {identifier(old)} TO {identifier(new)}")
|
|
217
|
+
_rename_links(deferred, table, renames)
|
|
218
|
+
|
|
219
|
+
for _, previous, current in changes:
|
|
220
|
+
await _alter_column(database, table, previous, current)
|
|
221
|
+
if current.references is not None and previous.references != current.references:
|
|
222
|
+
deferred.append(_ForeignKey(table, current.name, current.references))
|
|
223
|
+
for column in after.columns:
|
|
224
|
+
if column.name in renamed.values():
|
|
225
|
+
continue
|
|
226
|
+
definition = _field_sql(replace(column, references=None)._definition(), "postgresql")
|
|
227
|
+
await database.execute(f"{alter} ADD COLUMN {definition}")
|
|
228
|
+
if column.references is not None:
|
|
229
|
+
deferred.append(_ForeignKey(table, column.name, column.references))
|
|
230
|
+
|
|
231
|
+
new_checks = final_checks - original_checks
|
|
232
|
+
for expression in after.checks:
|
|
233
|
+
normalized = normalize_check(expression)
|
|
234
|
+
if new_checks[normalized]:
|
|
235
|
+
await database.execute(f"{alter} ADD CHECK ({expression})")
|
|
236
|
+
new_checks[normalized] -= 1
|
|
237
|
+
for name, index in final_indexes.items():
|
|
238
|
+
if name not in retained_indexes:
|
|
239
|
+
await database.execute(_index_sql(table, index, name=name))
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""Inspect PostgreSQL schema shapes supported by Narabi migrations."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, replace
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from ..database import Database
|
|
7
|
+
from .diff import Change, diff
|
|
8
|
+
from .schema import Column, Index, Reference, Schema, Table
|
|
9
|
+
from .sqlite import HISTORY_TABLE
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
_TYPES = {
|
|
13
|
+
"integer": "integer",
|
|
14
|
+
"text": "text",
|
|
15
|
+
"boolean": "boolean",
|
|
16
|
+
"real": "real",
|
|
17
|
+
"timestamp with time zone": "datetime",
|
|
18
|
+
}
|
|
19
|
+
_CHECK_TOKENS = re.compile(
|
|
20
|
+
r"""--[^\n]*|/\*.*?\*/|'(?:''|[^'])*'|"(?:""|[^"])*"
|
|
21
|
+
|[^\W\d][\w$]*|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?
|
|
22
|
+
|::|<=|>=|<>|!=|\|\||\S""",
|
|
23
|
+
re.DOTALL | re.VERBOSE,
|
|
24
|
+
)
|
|
25
|
+
_TABLES = """
|
|
26
|
+
SELECT relation.relname, relation.relkind, relation.relpersistence,
|
|
27
|
+
EXISTS (SELECT 1 FROM pg_catalog.pg_inherits WHERE inhrelid = relation.oid)
|
|
28
|
+
FROM pg_catalog.pg_class AS relation
|
|
29
|
+
JOIN pg_catalog.pg_namespace AS namespace ON namespace.oid = relation.relnamespace
|
|
30
|
+
WHERE namespace.nspname = pg_catalog.current_schema()
|
|
31
|
+
AND relation.relkind IN ('r', 'p', 'f')
|
|
32
|
+
AND relation.relname <> %s
|
|
33
|
+
ORDER BY relation.relname
|
|
34
|
+
"""
|
|
35
|
+
_COLUMNS = """
|
|
36
|
+
SELECT attribute.attname, pg_catalog.format_type(attribute.atttypid, attribute.atttypmod),
|
|
37
|
+
attribute.attnotnull, attribute.attidentity, attribute.atthasdef,
|
|
38
|
+
attribute.attgenerated, attribute.attcollation = kind.typcollation,
|
|
39
|
+
EXISTS (
|
|
40
|
+
SELECT 1
|
|
41
|
+
FROM pg_catalog.pg_depend AS dependency
|
|
42
|
+
JOIN pg_catalog.pg_sequence AS sequence ON sequence.seqrelid = dependency.objid
|
|
43
|
+
WHERE dependency.classid = 'pg_catalog.pg_class'::pg_catalog.regclass
|
|
44
|
+
AND dependency.refclassid = 'pg_catalog.pg_class'::pg_catalog.regclass
|
|
45
|
+
AND dependency.refobjid = relation.oid AND dependency.refobjsubid = attribute.attnum
|
|
46
|
+
AND dependency.deptype = 'i'
|
|
47
|
+
AND sequence.seqstart = 1 AND sequence.seqincrement = 1 AND sequence.seqmin = 1
|
|
48
|
+
AND sequence.seqmax = 2147483647 AND sequence.seqcache = 1 AND NOT sequence.seqcycle
|
|
49
|
+
)
|
|
50
|
+
FROM pg_catalog.pg_class AS relation
|
|
51
|
+
JOIN pg_catalog.pg_namespace AS namespace ON namespace.oid = relation.relnamespace
|
|
52
|
+
JOIN pg_catalog.pg_attribute AS attribute ON attribute.attrelid = relation.oid
|
|
53
|
+
JOIN pg_catalog.pg_type AS kind ON kind.oid = attribute.atttypid
|
|
54
|
+
WHERE namespace.nspname = pg_catalog.current_schema() AND relation.relname = %s
|
|
55
|
+
AND attribute.attnum > 0 AND NOT attribute.attisdropped
|
|
56
|
+
ORDER BY attribute.attnum
|
|
57
|
+
"""
|
|
58
|
+
_CONSTRAINTS = """
|
|
59
|
+
SELECT con.conname, con.contype,
|
|
60
|
+
ARRAY(
|
|
61
|
+
SELECT attribute.attname::text
|
|
62
|
+
FROM pg_catalog.unnest(con.conkey) WITH ORDINALITY AS key(number, position)
|
|
63
|
+
JOIN pg_catalog.pg_attribute AS attribute
|
|
64
|
+
ON attribute.attrelid = relation.oid AND attribute.attnum = key.number
|
|
65
|
+
ORDER BY key.position
|
|
66
|
+
),
|
|
67
|
+
target_namespace.nspname = namespace.nspname, target.relname,
|
|
68
|
+
ARRAY(
|
|
69
|
+
SELECT attribute.attname::text
|
|
70
|
+
FROM pg_catalog.unnest(con.confkey) WITH ORDINALITY AS key(number, position)
|
|
71
|
+
JOIN pg_catalog.pg_attribute AS attribute
|
|
72
|
+
ON attribute.attrelid = target.oid AND attribute.attnum = key.number
|
|
73
|
+
ORDER BY key.position
|
|
74
|
+
),
|
|
75
|
+
pg_catalog.pg_get_expr(con.conbin, relation.oid),
|
|
76
|
+
con.condeferrable, con.convalidated, con.coninhcount, con.connoinherit,
|
|
77
|
+
con.confupdtype, con.confdeltype, con.confmatchtype
|
|
78
|
+
FROM pg_catalog.pg_constraint AS con
|
|
79
|
+
JOIN pg_catalog.pg_class AS relation ON relation.oid = con.conrelid
|
|
80
|
+
JOIN pg_catalog.pg_namespace AS namespace ON namespace.oid = relation.relnamespace
|
|
81
|
+
LEFT JOIN pg_catalog.pg_class AS target ON target.oid = con.confrelid
|
|
82
|
+
LEFT JOIN pg_catalog.pg_namespace AS target_namespace ON target_namespace.oid = target.relnamespace
|
|
83
|
+
WHERE namespace.nspname = pg_catalog.current_schema() AND relation.relname = %s
|
|
84
|
+
ORDER BY con.conname
|
|
85
|
+
"""
|
|
86
|
+
_INDEXES = """
|
|
87
|
+
SELECT idx.relname, info.indisunique, method.amname, info.indisvalid AND info.indisready,
|
|
88
|
+
info.indpred IS NOT NULL, info.indexprs IS NOT NULL,
|
|
89
|
+
info.indnatts <> info.indnkeyatts,
|
|
90
|
+
COALESCE((pg_catalog.to_jsonb(info)->>'indnullsnotdistinct')::boolean, false),
|
|
91
|
+
EXISTS (
|
|
92
|
+
SELECT 1
|
|
93
|
+
FROM pg_catalog.pg_constraint AS con
|
|
94
|
+
WHERE con.conindid = idx.oid AND con.conrelid = relation.oid
|
|
95
|
+
AND con.contype IN ('p', 'u')
|
|
96
|
+
),
|
|
97
|
+
ARRAY(
|
|
98
|
+
SELECT attribute.attname::text
|
|
99
|
+
FROM pg_catalog.unnest(info.indkey::smallint[]) WITH ORDINALITY AS key(number, position)
|
|
100
|
+
LEFT JOIN pg_catalog.pg_attribute AS attribute
|
|
101
|
+
ON attribute.attrelid = relation.oid AND attribute.attnum = key.number
|
|
102
|
+
ORDER BY key.position
|
|
103
|
+
),
|
|
104
|
+
EXISTS (
|
|
105
|
+
SELECT 1
|
|
106
|
+
FROM ROWS FROM (
|
|
107
|
+
pg_catalog.unnest(info.indkey::smallint[]),
|
|
108
|
+
pg_catalog.unnest(info.indclass::oid[]),
|
|
109
|
+
pg_catalog.unnest(info.indcollation::oid[]),
|
|
110
|
+
pg_catalog.unnest(info.indoption::smallint[])
|
|
111
|
+
) AS key(number, opclass_oid, collation_oid, option_flags)
|
|
112
|
+
JOIN pg_catalog.pg_attribute AS attribute
|
|
113
|
+
ON attribute.attrelid = relation.oid AND attribute.attnum = key.number
|
|
114
|
+
JOIN pg_catalog.pg_opclass AS opclass ON opclass.oid = key.opclass_oid
|
|
115
|
+
WHERE key.option_flags <> 0 OR NOT opclass.opcdefault
|
|
116
|
+
OR key.collation_oid <> attribute.attcollation
|
|
117
|
+
)
|
|
118
|
+
FROM pg_catalog.pg_index AS info
|
|
119
|
+
JOIN pg_catalog.pg_class AS relation ON relation.oid = info.indrelid
|
|
120
|
+
JOIN pg_catalog.pg_namespace AS namespace ON namespace.oid = relation.relnamespace
|
|
121
|
+
JOIN pg_catalog.pg_class AS idx ON idx.oid = info.indexrelid
|
|
122
|
+
JOIN pg_catalog.pg_am AS method ON method.oid = idx.relam
|
|
123
|
+
WHERE namespace.nspname = pg_catalog.current_schema() AND relation.relname = %s
|
|
124
|
+
ORDER BY idx.relname
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass(frozen=True, slots=True)
|
|
129
|
+
class _Constraint:
|
|
130
|
+
name: str
|
|
131
|
+
kind: str
|
|
132
|
+
fields: tuple[str, ...]
|
|
133
|
+
reference: Reference | None = None
|
|
134
|
+
check: str | None = None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def normalize_check(expression: str) -> str:
|
|
138
|
+
"""Remove insignificant outer parentheses and formatting from a check."""
|
|
139
|
+
tokens = [
|
|
140
|
+
token[1:-1] if re.fullmatch(r'"[a-z_][a-z0-9_$]*"', token) else token
|
|
141
|
+
for token in _CHECK_TOKENS.findall(expression)
|
|
142
|
+
if not token.startswith(("--", "/*"))
|
|
143
|
+
]
|
|
144
|
+
while len(tokens) > 2 and tokens[0] == "(" and tokens[-1] == ")":
|
|
145
|
+
depth = 0
|
|
146
|
+
for end, token in enumerate(tokens):
|
|
147
|
+
depth += (token == "(") - (token == ")")
|
|
148
|
+
if depth == 0:
|
|
149
|
+
break
|
|
150
|
+
if end != len(tokens) - 1:
|
|
151
|
+
break
|
|
152
|
+
tokens = tokens[1:-1]
|
|
153
|
+
# PostgreSQL also groups each simple comparison within AND and OR expressions.
|
|
154
|
+
comparisons = {"=", "<", ">", "<=", ">=", "<>", "!="}
|
|
155
|
+
combined = []
|
|
156
|
+
position = 0
|
|
157
|
+
while position < len(tokens):
|
|
158
|
+
group = tokens[position:position + 5]
|
|
159
|
+
before = tokens[position - 1].upper() if position else ""
|
|
160
|
+
after = tokens[position + 5].upper() if position + 5 < len(tokens) else ""
|
|
161
|
+
if (
|
|
162
|
+
len(group) == 5 and group[0] == "(" and group[-1] == ")"
|
|
163
|
+
and group[2] in comparisons and group[1] not in "()" and group[3] not in "()"
|
|
164
|
+
and before in ("", "(", "AND", "OR") and after in ("", ")", "AND", "OR")
|
|
165
|
+
):
|
|
166
|
+
combined.extend(group[1:-1])
|
|
167
|
+
position += 5
|
|
168
|
+
else:
|
|
169
|
+
combined.append(tokens[position])
|
|
170
|
+
position += 1
|
|
171
|
+
return " ".join(combined)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
async def constraints(database: Database, table: str) -> tuple[_Constraint, ...]:
|
|
175
|
+
"""Read supported constraints in the current schema, retaining their names."""
|
|
176
|
+
rows = await database.execute(_CONSTRAINTS, (table,), fetch=True)
|
|
177
|
+
result = []
|
|
178
|
+
for row in rows:
|
|
179
|
+
(
|
|
180
|
+
name, kind, fields, same_schema, target, target_fields, check,
|
|
181
|
+
deferrable, validated, inherited, no_inherit, on_update, on_delete, match,
|
|
182
|
+
) = row
|
|
183
|
+
location = f"{table}: constraint {name!r}"
|
|
184
|
+
if deferrable or not validated or inherited:
|
|
185
|
+
raise ValueError(f"{location} has unsupported PostgreSQL options")
|
|
186
|
+
if kind == "n":
|
|
187
|
+
# PostgreSQL 18 also stores not-null constraints in pg_constraint.
|
|
188
|
+
continue
|
|
189
|
+
if kind == "c" and check is not None and not no_inherit:
|
|
190
|
+
result.append(_Constraint(name, kind, tuple(fields), check=check))
|
|
191
|
+
elif kind in ("p", "u") and len(fields) == 1:
|
|
192
|
+
result.append(_Constraint(name, kind, tuple(fields)))
|
|
193
|
+
elif kind == "f" and len(fields) == len(target_fields) == 1 and (on_update, on_delete, match) == ("a", "a", "s"):
|
|
194
|
+
if not same_schema or target is None:
|
|
195
|
+
raise ValueError(f"{location} has a PostgreSQL reference outside the current schema")
|
|
196
|
+
result.append(_Constraint(name, kind, tuple(fields), Reference(target, target_fields[0])))
|
|
197
|
+
else:
|
|
198
|
+
raise ValueError(f"{location} has an unsupported PostgreSQL definition")
|
|
199
|
+
return tuple(result)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
async def _indexes(database: Database, table: str) -> tuple[Index, ...]:
|
|
203
|
+
indexes = []
|
|
204
|
+
for row in await database.execute(_INDEXES, (table,), fetch=True):
|
|
205
|
+
name, unique, method, valid, partial, expression, included, nulls_equal, constraint, fields, custom = row
|
|
206
|
+
if (
|
|
207
|
+
method != "btree" or not valid or partial or expression or included
|
|
208
|
+
or nulls_equal or custom or not fields or None in fields
|
|
209
|
+
):
|
|
210
|
+
raise ValueError(f"{table}: unsupported PostgreSQL index {name!r}")
|
|
211
|
+
if not constraint:
|
|
212
|
+
indexes.append(Index(tuple(fields), name=name, unique=unique))
|
|
213
|
+
return tuple(indexes)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
async def _table(database: Database, name: str) -> Table:
|
|
217
|
+
primary, uniques, references, checks = set(), set(), {}, []
|
|
218
|
+
for constraint in await constraints(database, name):
|
|
219
|
+
if constraint.kind == "p":
|
|
220
|
+
primary.update(constraint.fields)
|
|
221
|
+
elif constraint.kind == "u":
|
|
222
|
+
uniques.update(constraint.fields)
|
|
223
|
+
elif constraint.kind == "c":
|
|
224
|
+
checks.append(constraint.check)
|
|
225
|
+
else:
|
|
226
|
+
column, = constraint.fields
|
|
227
|
+
if column in references:
|
|
228
|
+
raise ValueError(f"{name}.{column}: multiple PostgreSQL references")
|
|
229
|
+
references[column] = constraint.reference
|
|
230
|
+
|
|
231
|
+
columns = []
|
|
232
|
+
for column, declared, not_null, identity, default, generated, ordinary_collation, default_sequence in (
|
|
233
|
+
await database.execute(_COLUMNS, (name,), fetch=True)
|
|
234
|
+
):
|
|
235
|
+
kind = _TYPES.get(declared)
|
|
236
|
+
if (
|
|
237
|
+
kind is None or generated or not ordinary_collation
|
|
238
|
+
or identity not in ("", "d") or (identity and not default_sequence)
|
|
239
|
+
or (default and not identity)
|
|
240
|
+
):
|
|
241
|
+
raise ValueError(f"{name}.{column}: unsupported PostgreSQL column definition")
|
|
242
|
+
columns.append(Column(
|
|
243
|
+
column, kind, primary=column in primary, nullable=not not_null,
|
|
244
|
+
unique=column in uniques, auto_increment=bool(identity), references=references.get(column),
|
|
245
|
+
))
|
|
246
|
+
return Table(name, tuple(columns), await _indexes(database, name), tuple(checks))
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _canonical_checks(schema: Schema) -> Schema:
|
|
250
|
+
return replace(schema, tables=tuple(
|
|
251
|
+
replace(table, checks=tuple(normalize_check(check) for check in table.checks))
|
|
252
|
+
for table in schema.tables
|
|
253
|
+
))
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
async def postgresql_drift(database: Database, expected: Schema) -> tuple[Change, ...]:
|
|
257
|
+
"""Report structural differences from history in the current PostgreSQL schema."""
|
|
258
|
+
if database.backend != "postgresql":
|
|
259
|
+
raise ValueError("PostgreSQL schema drift inspection requires PostgreSQL")
|
|
260
|
+
expected.validate()
|
|
261
|
+
tables = []
|
|
262
|
+
async with database._operation():
|
|
263
|
+
rows = await database.execute(_TABLES, (HISTORY_TABLE,), fetch=True)
|
|
264
|
+
for name, kind, persistence, inherited in rows:
|
|
265
|
+
if kind != "r" or persistence != "p" or inherited:
|
|
266
|
+
raise ValueError(f"{name}: unsupported PostgreSQL table definition")
|
|
267
|
+
tables.append(await _table(database, name))
|
|
268
|
+
return diff(_canonical_checks(expected), _canonical_checks(Schema(tuple(tables))), allow_drop_add=True)
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Preview SQL for structural changes without executing it."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from graphlib import CycleError, TopologicalSorter
|
|
6
|
+
from itertools import groupby
|
|
7
|
+
|
|
8
|
+
from ..database import identifier
|
|
9
|
+
from ..schema import _field_sql
|
|
10
|
+
from .diff import Change
|
|
11
|
+
from .generate import _PHASES, destructive, ordered_changes
|
|
12
|
+
from .schema import Index, Table
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class SQLPreview:
|
|
17
|
+
statements: tuple[str, ...]
|
|
18
|
+
destructive: tuple[Change, ...]
|
|
19
|
+
deferred: tuple[tuple[Change, str], ...]
|
|
20
|
+
notes: tuple[str, ...]
|
|
21
|
+
|
|
22
|
+
def __str__(self) -> str:
|
|
23
|
+
lines = ["-- Preview only."]
|
|
24
|
+
for change in self.destructive:
|
|
25
|
+
lines.append(f"-- Destructive change: {change.kind} in {change.table!r}")
|
|
26
|
+
for change, reason in self.deferred:
|
|
27
|
+
lines.append(f"-- Deferred {change.kind} in {change.table!r}: {reason}")
|
|
28
|
+
lines.extend(f"-- {note}" for note in self.notes)
|
|
29
|
+
if self.statements:
|
|
30
|
+
lines.extend(["", *self.statements])
|
|
31
|
+
return "\n".join(lines) + "\n"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _index_sql(table: str, index: Index, *, name: str) -> str:
|
|
35
|
+
unique = "UNIQUE " if index.unique else ""
|
|
36
|
+
columns = ", ".join(map(identifier, index.fields))
|
|
37
|
+
return f"CREATE {unique}INDEX {identifier(name)} ON {identifier(table)} ({columns});"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _table_sql(table: Table, dialect: str) -> tuple[str, ...]:
|
|
41
|
+
fields = [
|
|
42
|
+
*(_field_sql(column._definition(), dialect) for column in table.columns),
|
|
43
|
+
*(f"CHECK ({check})" for check in table.checks),
|
|
44
|
+
]
|
|
45
|
+
definitions = ",\n ".join(fields)
|
|
46
|
+
return (
|
|
47
|
+
f"CREATE TABLE {identifier(table.name)} (\n {definitions}\n);",
|
|
48
|
+
*(
|
|
49
|
+
_index_sql(table.name, index, name=index.name or f"{table.name}_idx_{number}")
|
|
50
|
+
for number, index in enumerate(table.indexes, 1)
|
|
51
|
+
),
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _order_tables(changes: list[Change], *, adding: bool) -> list[Change]:
|
|
56
|
+
definitions = {change.table: change for change in changes}
|
|
57
|
+
graph = TopologicalSorter()
|
|
58
|
+
for name, change in definitions.items():
|
|
59
|
+
table = change.after if adding else change.before
|
|
60
|
+
graph.add(name, *dict.fromkeys(
|
|
61
|
+
column.references.table
|
|
62
|
+
for column in table.columns
|
|
63
|
+
if column.references is not None
|
|
64
|
+
and column.references.table in definitions
|
|
65
|
+
and column.references.table != name
|
|
66
|
+
))
|
|
67
|
+
names = tuple(graph.static_order())
|
|
68
|
+
return [definitions[name] for name in (names if adding else reversed(names))]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _postgres_column_changes(table, old, new):
|
|
72
|
+
column = identifier(new.name)
|
|
73
|
+
if (
|
|
74
|
+
old.primary != new.primary or old.auto_increment != new.auto_increment
|
|
75
|
+
or old.references != new.references or (old.unique and not new.unique)
|
|
76
|
+
):
|
|
77
|
+
return (), "requires planning identity or database constraint changes"
|
|
78
|
+
statements = []
|
|
79
|
+
if old.kind != new.kind:
|
|
80
|
+
sql_type = "TIMESTAMPTZ" if new.kind == "datetime" else new.kind.upper()
|
|
81
|
+
statements.append(f"{table} ALTER COLUMN {column} TYPE {sql_type};")
|
|
82
|
+
if old.nullable != new.nullable:
|
|
83
|
+
action = "DROP" if new.nullable else "SET"
|
|
84
|
+
statements.append(f"{table} ALTER COLUMN {column} {action} NOT NULL;")
|
|
85
|
+
if new.unique and not old.unique:
|
|
86
|
+
statements.append(f"{table} ADD UNIQUE ({column});")
|
|
87
|
+
return tuple(statements), None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _sql(change: Change, dialect: str):
|
|
91
|
+
old, new = change.before, change.after
|
|
92
|
+
name = identifier(change.table)
|
|
93
|
+
table = f"ALTER TABLE {name}"
|
|
94
|
+
match change.kind:
|
|
95
|
+
case "add_table":
|
|
96
|
+
return _table_sql(new, dialect), None
|
|
97
|
+
case "drop_table":
|
|
98
|
+
return (f"DROP TABLE {name};",), None
|
|
99
|
+
case "rename_column":
|
|
100
|
+
return (f"{table} RENAME COLUMN {identifier(old.name)} TO {identifier(new.name)};",), None
|
|
101
|
+
case "add_column":
|
|
102
|
+
if dialect == "sqlite" and (new.unique or new.primary):
|
|
103
|
+
return (), "SQLite requires a table rebuild to add this column constraint"
|
|
104
|
+
return (f"{table} ADD COLUMN {_field_sql(new._definition(), dialect)};",), None
|
|
105
|
+
case "drop_column":
|
|
106
|
+
if dialect == "sqlite":
|
|
107
|
+
return (), "requires SQLite table rebuild planning"
|
|
108
|
+
return (f"{table} DROP COLUMN {identifier(old.name)};",), None
|
|
109
|
+
case "change_column":
|
|
110
|
+
if dialect == "sqlite":
|
|
111
|
+
return (), "requires SQLite table rebuild planning"
|
|
112
|
+
return _postgres_column_changes(table, old, new)
|
|
113
|
+
case "drop_index" | "change_index":
|
|
114
|
+
return (f"DROP INDEX {identifier(old.name)};",), None
|
|
115
|
+
case "add_index":
|
|
116
|
+
return (_index_sql(change.table, new, name=new.name),), None
|
|
117
|
+
case "drop_check":
|
|
118
|
+
return (), "requires finding or rebuilding the existing check constraint"
|
|
119
|
+
case "add_check":
|
|
120
|
+
if dialect == "sqlite":
|
|
121
|
+
return (), "SQLite requires a table rebuild to add a check"
|
|
122
|
+
return (f"{table} ADD CHECK ({new});",), None
|
|
123
|
+
raise ValueError(f"Unsupported migration change {change.kind!r}")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def preview_sql(changes: Iterable[Change], dialect: str) -> SQLPreview:
|
|
127
|
+
"""Preview native statements and identify changes still requiring planning."""
|
|
128
|
+
if dialect not in ("sqlite", "postgresql"):
|
|
129
|
+
raise ValueError(f"Unsupported dialect: {dialect}")
|
|
130
|
+
steps = ordered_changes(changes)
|
|
131
|
+
statements, blocked, reviews = [], [], []
|
|
132
|
+
for phase, group in groupby(steps, key=lambda change: _PHASES[change.kind]):
|
|
133
|
+
changes_in_phase = list(group)
|
|
134
|
+
if phase in (_PHASES["add_table"], _PHASES["drop_table"]):
|
|
135
|
+
try:
|
|
136
|
+
changes_in_phase = _order_tables(changes_in_phase, adding=phase == _PHASES["add_table"])
|
|
137
|
+
except CycleError:
|
|
138
|
+
blocked.extend((change, "cyclic table references require separate planning") for change in changes_in_phase)
|
|
139
|
+
continue
|
|
140
|
+
for change in changes_in_phase:
|
|
141
|
+
sql, reason = _sql(change, dialect)
|
|
142
|
+
statements.extend(sql)
|
|
143
|
+
if reason is not None:
|
|
144
|
+
blocked.append((change, reason))
|
|
145
|
+
if change.kind == "add_column" and not change.after.nullable:
|
|
146
|
+
reviews.append(f"Required column {change.table!r}.{change.after.name!r} may need a backfill.")
|
|
147
|
+
return SQLPreview(
|
|
148
|
+
tuple(statements), tuple(change for change in steps if destructive(change)),
|
|
149
|
+
tuple(blocked), tuple(reviews),
|
|
150
|
+
)
|