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
narabi/migrations/dsl.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""Record structural changes without opening a database connection."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterator
|
|
4
|
+
from contextlib import asynccontextmanager
|
|
5
|
+
from dataclasses import replace
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
from ..fields import Indexed, Primary, Unique, describe
|
|
10
|
+
from .schema import COLUMN_KINDS, Column, Index, Reference, Schema, Table
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
_UNCHANGED = object()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _reference(value):
|
|
17
|
+
if value is None:
|
|
18
|
+
return None
|
|
19
|
+
if not isinstance(value, tuple) or len(value) != 2:
|
|
20
|
+
raise TypeError("references must be a (table, field) pair")
|
|
21
|
+
return Reference(*value)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
_COLUMN_MARKERS = {(Primary,), (Unique,), (Indexed,)}
|
|
25
|
+
_SQL_NAMES = re.compile(r"""'(?:''|[^'])*'|"(?:""|[^"])*"|\[(?:\]\]|[^\]])*\]|`(?:``|[^`])*`|[^\W\d][\w$]*""")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TableBuilder:
|
|
29
|
+
"""Collect a single table's historical columns, indexes, and checks."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, name: str):
|
|
32
|
+
self._name = name
|
|
33
|
+
self._columns: list[Column] = []
|
|
34
|
+
self._indexes: list[Index] = []
|
|
35
|
+
self._checks: list[str] = []
|
|
36
|
+
|
|
37
|
+
def add(
|
|
38
|
+
self,
|
|
39
|
+
name: str,
|
|
40
|
+
annotation: object,
|
|
41
|
+
*,
|
|
42
|
+
references: tuple[str, str] | None = None,
|
|
43
|
+
auto_increment: bool = False,
|
|
44
|
+
) -> None:
|
|
45
|
+
if any(column.name == name for column in self._columns):
|
|
46
|
+
raise ValueError(f"{self._name}: column {name!r} already exists")
|
|
47
|
+
field = self._describe(name, annotation)
|
|
48
|
+
self._columns.append(Column(
|
|
49
|
+
name,
|
|
50
|
+
COLUMN_KINDS[field.type],
|
|
51
|
+
primary=(Primary,) in field.markers,
|
|
52
|
+
nullable=field.nullable,
|
|
53
|
+
unique=(Unique,) in field.markers,
|
|
54
|
+
auto_increment=auto_increment,
|
|
55
|
+
references=_reference(references),
|
|
56
|
+
))
|
|
57
|
+
if (Indexed,) in field.markers:
|
|
58
|
+
self.index(name)
|
|
59
|
+
|
|
60
|
+
def _describe(self, name, annotation):
|
|
61
|
+
field = describe(annotation)
|
|
62
|
+
if field.type not in COLUMN_KINDS or any(marker not in _COLUMN_MARKERS for marker in field.markers):
|
|
63
|
+
raise TypeError(f"Unsupported migration column annotation for {self._name}.{name}")
|
|
64
|
+
return field
|
|
65
|
+
|
|
66
|
+
def timestamps(self) -> None:
|
|
67
|
+
self.add("created_at", datetime)
|
|
68
|
+
self.add("updated_at", datetime)
|
|
69
|
+
|
|
70
|
+
def _default_index_name(self, number):
|
|
71
|
+
return f"{self._name}_idx_{number}"
|
|
72
|
+
|
|
73
|
+
def index(self, *fields: str, name: str | None = None, unique: bool = False) -> None:
|
|
74
|
+
if name is None:
|
|
75
|
+
existing = {
|
|
76
|
+
index.name or self._default_index_name(number)
|
|
77
|
+
for number, index in enumerate(self._indexes, 1)
|
|
78
|
+
}
|
|
79
|
+
number = len(self._indexes) + 1
|
|
80
|
+
if self._default_index_name(number) in existing:
|
|
81
|
+
while self._default_index_name(number) in existing:
|
|
82
|
+
number += 1
|
|
83
|
+
name = self._default_index_name(number)
|
|
84
|
+
self._indexes.append(Index(fields, name=name, unique=unique))
|
|
85
|
+
|
|
86
|
+
def check(self, expression: str) -> None:
|
|
87
|
+
self._checks.append(expression)
|
|
88
|
+
|
|
89
|
+
def _build(self) -> Table:
|
|
90
|
+
return Table(self._name, tuple(self._columns), tuple(self._indexes), tuple(self._checks))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class TableEditor(TableBuilder):
|
|
94
|
+
"""Record changes to a table already present in the replayed schema."""
|
|
95
|
+
|
|
96
|
+
def __init__(self, table: Table):
|
|
97
|
+
super().__init__(table.name)
|
|
98
|
+
self._columns = list(table.columns)
|
|
99
|
+
self._indexes = list(table.indexes)
|
|
100
|
+
self._checks = list(table.checks)
|
|
101
|
+
self._renames: list[tuple[str, str]] = []
|
|
102
|
+
self._origins = {column.name: column.name for column in table.columns}
|
|
103
|
+
self._stored_renames: list[tuple[str, str]] = []
|
|
104
|
+
|
|
105
|
+
def _position(self, name: str) -> int:
|
|
106
|
+
for position, column in enumerate(self._columns):
|
|
107
|
+
if column.name == name:
|
|
108
|
+
return position
|
|
109
|
+
raise ValueError(f"{self._name}: unknown column {name!r}")
|
|
110
|
+
|
|
111
|
+
def _check_dependencies(self, name: str) -> None:
|
|
112
|
+
for check in self._checks:
|
|
113
|
+
names = set()
|
|
114
|
+
for token in _SQL_NAMES.findall(check):
|
|
115
|
+
if token.startswith("'"):
|
|
116
|
+
continue
|
|
117
|
+
if token[0] in '"`[':
|
|
118
|
+
quote = token[-1]
|
|
119
|
+
token = token[1:-1].replace(quote * 2, quote)
|
|
120
|
+
names.add(token.casefold())
|
|
121
|
+
if name.casefold() in names:
|
|
122
|
+
raise ValueError(
|
|
123
|
+
f"{self._name}.{name}: remove the dependent CHECK with drop_check() first"
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
def rename(self, name: str, *, to: str) -> None:
|
|
127
|
+
position = self._position(name)
|
|
128
|
+
if any(column.name == to for column in self._columns):
|
|
129
|
+
raise ValueError(f"{self._name}: column {to!r} already exists")
|
|
130
|
+
self._check_dependencies(name)
|
|
131
|
+
self._columns[position] = replace(self._columns[position], name=to)
|
|
132
|
+
self._columns = [self._rename_reference(column, name, to) for column in self._columns]
|
|
133
|
+
self._indexes = [
|
|
134
|
+
replace(index, fields=tuple(to if field == name else field for field in index.fields))
|
|
135
|
+
for index in self._indexes
|
|
136
|
+
]
|
|
137
|
+
self._renames.append((name, to))
|
|
138
|
+
if name in self._origins:
|
|
139
|
+
self._origins[to] = self._origins.pop(name)
|
|
140
|
+
self._stored_renames.append((name, to))
|
|
141
|
+
|
|
142
|
+
def _rename_reference(self, column: Column, old: str, new: str) -> Column:
|
|
143
|
+
if column.references == Reference(self._name, old):
|
|
144
|
+
return replace(column, references=Reference(self._name, new))
|
|
145
|
+
return column
|
|
146
|
+
|
|
147
|
+
def change(
|
|
148
|
+
self, name: str, annotation: object, *,
|
|
149
|
+
primary: bool | None = None, unique: bool | None = None,
|
|
150
|
+
auto_increment: bool | None = None, references: object = _UNCHANGED,
|
|
151
|
+
) -> None:
|
|
152
|
+
position = self._position(name)
|
|
153
|
+
current = self._columns[position]
|
|
154
|
+
field = self._describe(name, annotation)
|
|
155
|
+
self._columns[position] = replace(
|
|
156
|
+
current, kind=COLUMN_KINDS[field.type], nullable=field.nullable,
|
|
157
|
+
primary=(current.primary or (Primary,) in field.markers) if primary is None else primary,
|
|
158
|
+
unique=(current.unique or (Unique,) in field.markers) if unique is None else unique,
|
|
159
|
+
auto_increment=current.auto_increment if auto_increment is None else auto_increment,
|
|
160
|
+
references=current.references if references is _UNCHANGED else _reference(references),
|
|
161
|
+
)
|
|
162
|
+
if (Indexed,) in field.markers and not any(index.fields == (name,) for index in self._indexes):
|
|
163
|
+
self.index(name)
|
|
164
|
+
|
|
165
|
+
def require(self, name: str) -> None:
|
|
166
|
+
position = self._position(name)
|
|
167
|
+
self._columns[position] = replace(self._columns[position], nullable=False)
|
|
168
|
+
|
|
169
|
+
def optional(self, name: str) -> None:
|
|
170
|
+
position = self._position(name)
|
|
171
|
+
self._columns[position] = replace(self._columns[position], nullable=True)
|
|
172
|
+
|
|
173
|
+
def unique(self, *fields: str) -> None:
|
|
174
|
+
if len(fields) == 1:
|
|
175
|
+
position = self._position(fields[0])
|
|
176
|
+
self._columns[position] = replace(self._columns[position], unique=True)
|
|
177
|
+
else:
|
|
178
|
+
self.index(*fields, unique=True)
|
|
179
|
+
|
|
180
|
+
def remove(self, name: str) -> None:
|
|
181
|
+
position = self._position(name)
|
|
182
|
+
self._check_dependencies(name)
|
|
183
|
+
del self._columns[position]
|
|
184
|
+
self._origins.pop(name, None)
|
|
185
|
+
self._remove_indexes({number for number, index in enumerate(self._indexes, 1) if name in index.fields})
|
|
186
|
+
|
|
187
|
+
def drop_index(self, name: str) -> None:
|
|
188
|
+
for number, index in enumerate(self._indexes, 1):
|
|
189
|
+
if (index.name or self._default_index_name(number)) == name:
|
|
190
|
+
self._remove_indexes({number})
|
|
191
|
+
return
|
|
192
|
+
raise ValueError(f"{self._name}: unknown index {name!r}")
|
|
193
|
+
|
|
194
|
+
def _remove_indexes(self, removed: set[int]) -> None:
|
|
195
|
+
retained = []
|
|
196
|
+
for number, index in enumerate(self._indexes, 1):
|
|
197
|
+
if number in removed:
|
|
198
|
+
continue
|
|
199
|
+
if index.name is None and number != len(retained) + 1:
|
|
200
|
+
index = replace(index, name=self._default_index_name(number))
|
|
201
|
+
retained.append(index)
|
|
202
|
+
self._indexes = retained
|
|
203
|
+
|
|
204
|
+
def drop_check(self, expression: str) -> None:
|
|
205
|
+
checks = [check for check in self._checks if check.strip() != expression.strip()]
|
|
206
|
+
if len(checks) == len(self._checks):
|
|
207
|
+
raise ValueError(f"{self._name}: unknown CHECK {expression!r}")
|
|
208
|
+
self._checks = checks
|
|
209
|
+
|
|
210
|
+
def _apply(self, schema: Schema) -> Schema:
|
|
211
|
+
updated = []
|
|
212
|
+
for table in schema.tables:
|
|
213
|
+
if table.name == self._name:
|
|
214
|
+
updated.append(self._build())
|
|
215
|
+
continue
|
|
216
|
+
columns = table.columns
|
|
217
|
+
for old, new in self._renames:
|
|
218
|
+
columns = tuple(self._rename_reference(column, old, new) for column in columns)
|
|
219
|
+
updated.append(table if columns == table.columns else replace(table, columns=columns))
|
|
220
|
+
return replace(schema, tables=tuple(updated))
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class StructuralQuery:
|
|
224
|
+
"""The schema-only operations available to a structural migration step."""
|
|
225
|
+
|
|
226
|
+
def __init__(self, schema: Schema):
|
|
227
|
+
self._schema = schema
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def schema(self) -> Schema:
|
|
231
|
+
return self._schema
|
|
232
|
+
|
|
233
|
+
@asynccontextmanager
|
|
234
|
+
async def create(self, name: str) -> AsyncIterator[TableBuilder]:
|
|
235
|
+
builder = TableBuilder(name)
|
|
236
|
+
yield builder
|
|
237
|
+
self._schema = self._schema.add_table(builder._build())
|
|
238
|
+
|
|
239
|
+
def drop(self, name: str) -> None:
|
|
240
|
+
tables = tuple(table for table in self._schema.tables if table.name != name)
|
|
241
|
+
if len(tables) == len(self._schema.tables):
|
|
242
|
+
raise ValueError(f"Unknown table {name!r}")
|
|
243
|
+
self._schema = replace(self._schema, tables=tables)
|
|
244
|
+
|
|
245
|
+
@asynccontextmanager
|
|
246
|
+
async def table(self, name: str) -> AsyncIterator[TableEditor]:
|
|
247
|
+
try:
|
|
248
|
+
original = self._schema.table(name)
|
|
249
|
+
except KeyError as error:
|
|
250
|
+
raise ValueError(f"Unknown table {name!r}") from error
|
|
251
|
+
editor = TableEditor(original)
|
|
252
|
+
yield editor
|
|
253
|
+
if self._schema.table(name) != original:
|
|
254
|
+
raise ValueError(f"{name}: table changed while its editor was open")
|
|
255
|
+
self._schema = editor._apply(self._schema)
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
"""Apply recorded structural migrations to SQLite."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from contextlib import asynccontextmanager
|
|
5
|
+
from dataclasses import dataclass, replace
|
|
6
|
+
from types import FunctionType, ModuleType
|
|
7
|
+
from uuid import uuid4
|
|
8
|
+
|
|
9
|
+
from ..database import Database, identifier
|
|
10
|
+
from ..schema import _field_sql
|
|
11
|
+
from .diff import _indexes
|
|
12
|
+
from .dsl import StructuralQuery
|
|
13
|
+
from .errors import MigrationError
|
|
14
|
+
from .preview import _index_sql, _table_sql
|
|
15
|
+
from .replay import migration_steps, replay, replay_steps
|
|
16
|
+
from .schema import Schema, Table
|
|
17
|
+
from .sqlite import HISTORY_TABLE, sqlite_drift
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class _DataStep:
|
|
22
|
+
function: FunctionType
|
|
23
|
+
kind: str
|
|
24
|
+
schema: Schema
|
|
25
|
+
location: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True, slots=True)
|
|
29
|
+
class _Edit:
|
|
30
|
+
before: Table | None
|
|
31
|
+
after: Table | None
|
|
32
|
+
origins: tuple[tuple[str, str], ...] = ()
|
|
33
|
+
renames: tuple[tuple[str, str], ...] = ()
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def name(self):
|
|
37
|
+
return (self.after or self.before).name
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def destructive(self):
|
|
41
|
+
if self.before is None:
|
|
42
|
+
return False
|
|
43
|
+
if self.after is None or len(self.origins) < len(self.before.columns):
|
|
44
|
+
return True
|
|
45
|
+
old = {column.name: column.kind for column in self.before.columns}
|
|
46
|
+
current = {column.name: column.kind for column in self.after.columns}
|
|
47
|
+
return any(old[source] != current[destination] for destination, source in self.origins)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _RecordingQuery(StructuralQuery):
|
|
51
|
+
def __init__(self, schema):
|
|
52
|
+
super().__init__(schema)
|
|
53
|
+
self.edits: list[_Edit] = []
|
|
54
|
+
|
|
55
|
+
@asynccontextmanager
|
|
56
|
+
async def create(self, name):
|
|
57
|
+
async with super().create(name) as builder:
|
|
58
|
+
yield builder
|
|
59
|
+
self.edits.append(_Edit(None, self.schema.table(name)))
|
|
60
|
+
|
|
61
|
+
@asynccontextmanager
|
|
62
|
+
async def table(self, name):
|
|
63
|
+
async with super().table(name) as editor:
|
|
64
|
+
before = self.schema.table(name)
|
|
65
|
+
yield editor
|
|
66
|
+
after = self.schema.table(name)
|
|
67
|
+
origins = tuple(editor._origins.items())
|
|
68
|
+
if before != after or origins != tuple((column.name, column.name) for column in before.columns):
|
|
69
|
+
self.edits.append(_Edit(before, after, origins, tuple(editor._stored_renames)))
|
|
70
|
+
|
|
71
|
+
def drop(self, name):
|
|
72
|
+
try:
|
|
73
|
+
before = self.schema.table(name)
|
|
74
|
+
except KeyError as error:
|
|
75
|
+
raise ValueError(f"Unknown table {name!r}") from error
|
|
76
|
+
super().drop(name)
|
|
77
|
+
self.edits.append(_Edit(before, None))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _renamed_table(edit):
|
|
81
|
+
previous = edit.before
|
|
82
|
+
names = {column.name: column.name for column in previous.columns}
|
|
83
|
+
for old, new in edit.renames:
|
|
84
|
+
names = {original: new if current == old else current for original, current in names.items()}
|
|
85
|
+
columns = []
|
|
86
|
+
for column in previous.columns:
|
|
87
|
+
reference = column.references
|
|
88
|
+
if reference is not None and reference.table == previous.name:
|
|
89
|
+
reference = replace(reference, field=names.get(reference.field, reference.field))
|
|
90
|
+
columns.append(replace(column, name=names[column.name], references=reference))
|
|
91
|
+
indexes = tuple(
|
|
92
|
+
replace(index, fields=tuple(names[field] for field in index.fields))
|
|
93
|
+
for index in previous.indexes
|
|
94
|
+
)
|
|
95
|
+
return replace(previous, columns=tuple(columns), indexes=indexes)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
async def _native_alter(database, before, after, edit):
|
|
99
|
+
if before.checks != after.checks or len(edit.origins) != len(before.columns):
|
|
100
|
+
return False
|
|
101
|
+
previous = {column.name: column for column in before.columns}
|
|
102
|
+
current = {column.name: column for column in after.columns}
|
|
103
|
+
if any(current.get(name) != column for name, column in previous.items()):
|
|
104
|
+
return False
|
|
105
|
+
new_columns = [column for column in after.columns if column.name not in previous]
|
|
106
|
+
if any(not column.nullable or column.primary or column.unique for column in new_columns):
|
|
107
|
+
return False
|
|
108
|
+
|
|
109
|
+
existing_indexes, desired_indexes = _indexes(before), _indexes(after)
|
|
110
|
+
for name, index in existing_indexes.items():
|
|
111
|
+
if desired_indexes.get(name) != index:
|
|
112
|
+
await database.execute(f"DROP INDEX {identifier(name)}")
|
|
113
|
+
for column in new_columns:
|
|
114
|
+
definition = _field_sql(column._definition(), "sqlite")
|
|
115
|
+
await database.execute(f"ALTER TABLE {identifier(after.name)} ADD COLUMN {definition}")
|
|
116
|
+
for name, index in desired_indexes.items():
|
|
117
|
+
if existing_indexes.get(name) != index:
|
|
118
|
+
await database.execute(_index_sql(after.name, index, name=name))
|
|
119
|
+
return True
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
async def _rebuild(database, edit):
|
|
123
|
+
before, after = edit.before, edit.after
|
|
124
|
+
table = identifier(after.name)
|
|
125
|
+
triggers = await database.execute(
|
|
126
|
+
"SELECT name FROM sqlite_schema WHERE type = 'trigger' AND tbl_name = ?",
|
|
127
|
+
(after.name,), fetch=True,
|
|
128
|
+
)
|
|
129
|
+
if triggers:
|
|
130
|
+
raise MigrationError(f"{after.name}: table rebuild requires explicit trigger handling")
|
|
131
|
+
|
|
132
|
+
old_identity = next((column for column in before.columns if column.auto_increment), None)
|
|
133
|
+
new_identity = next((column for column in after.columns if column.auto_increment), None)
|
|
134
|
+
origins = dict(edit.origins)
|
|
135
|
+
sequence = []
|
|
136
|
+
if old_identity is not None and new_identity is not None and origins.get(new_identity.name) == old_identity.name:
|
|
137
|
+
sequence = await database.execute(
|
|
138
|
+
"SELECT seq FROM sqlite_sequence WHERE name = ?", (after.name,), fetch=True,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
temporary_name = f"_narabi_rebuild_{uuid4().hex}"
|
|
142
|
+
temporary = identifier(temporary_name)
|
|
143
|
+
create, = _table_sql(replace(after, name=temporary_name, indexes=()), "sqlite")
|
|
144
|
+
await database.execute(create)
|
|
145
|
+
retained = [identifier(column.name) for column in after.columns if column.name in origins]
|
|
146
|
+
if retained:
|
|
147
|
+
names = ", ".join(retained)
|
|
148
|
+
await database.execute(f"INSERT INTO {temporary} ({names}) SELECT {names} FROM {table}")
|
|
149
|
+
else:
|
|
150
|
+
target = identifier(after.columns[0].name)
|
|
151
|
+
await database.execute(f"INSERT INTO {temporary} ({target}) SELECT NULL FROM {table}")
|
|
152
|
+
|
|
153
|
+
kinds = {"boolean": "integer", "integer": "integer", "real": "real", "text": "text", "datetime": "text"}
|
|
154
|
+
former_kinds = {column.name: column.kind for column in before.columns}
|
|
155
|
+
for column in after.columns:
|
|
156
|
+
source = origins.get(column.name)
|
|
157
|
+
if source is None or former_kinds[source] == column.kind:
|
|
158
|
+
continue
|
|
159
|
+
target = identifier(column.name)
|
|
160
|
+
incompatible = await database.execute(
|
|
161
|
+
f"SELECT 1 FROM {temporary} WHERE {target} IS NOT NULL AND typeof({target}) <> ? LIMIT 1",
|
|
162
|
+
(kinds[column.kind],), fetch=True,
|
|
163
|
+
)
|
|
164
|
+
if incompatible:
|
|
165
|
+
raise MigrationError(f"{after.name}.{column.name}: existing values cannot be converted to {column.kind}")
|
|
166
|
+
|
|
167
|
+
await database.execute(f"DROP TABLE {table}")
|
|
168
|
+
await database.execute(f"ALTER TABLE {temporary} RENAME TO {table}")
|
|
169
|
+
for name, index in _indexes(after).items():
|
|
170
|
+
await database.execute(_index_sql(after.name, index, name=name))
|
|
171
|
+
if sequence:
|
|
172
|
+
updated = await database.execute(
|
|
173
|
+
"UPDATE sqlite_sequence SET seq = MAX(seq, ?) WHERE name = ?", (sequence[0][0], after.name),
|
|
174
|
+
)
|
|
175
|
+
if not updated:
|
|
176
|
+
await database.execute(
|
|
177
|
+
"INSERT INTO sqlite_sequence (name, seq) VALUES (?, ?)", (after.name, sequence[0][0]),
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
async def _apply_edit(database, edit):
|
|
182
|
+
if edit.before is None:
|
|
183
|
+
for statement in _table_sql(edit.after, "sqlite"):
|
|
184
|
+
await database.execute(statement)
|
|
185
|
+
return
|
|
186
|
+
if edit.after is None:
|
|
187
|
+
await database.execute(f"DROP TABLE {identifier(edit.name)}")
|
|
188
|
+
return
|
|
189
|
+
for old, new in edit.renames:
|
|
190
|
+
await database.execute(
|
|
191
|
+
f"ALTER TABLE {identifier(edit.name)} RENAME COLUMN {identifier(old)} TO {identifier(new)}"
|
|
192
|
+
)
|
|
193
|
+
if not await _native_alter(database, _renamed_table(edit), edit.after, edit):
|
|
194
|
+
await _rebuild(database, edit)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _require_backend(database):
|
|
198
|
+
if database.backend not in ("sqlite", "postgresql"):
|
|
199
|
+
raise MigrationError(f"Unsupported migration backend {database.backend!r}")
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@asynccontextmanager
|
|
203
|
+
async def _migration_transaction(database):
|
|
204
|
+
_require_backend(database)
|
|
205
|
+
async with database.transaction(_migration=True):
|
|
206
|
+
if database.backend == "postgresql":
|
|
207
|
+
await database.execute(
|
|
208
|
+
"SELECT pg_advisory_xact_lock(hashtext(current_database()), "
|
|
209
|
+
"hashtext(current_schema() || ':narabi:migrations'))",
|
|
210
|
+
fetch=True,
|
|
211
|
+
)
|
|
212
|
+
yield
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
async def _drift(database, expected):
|
|
216
|
+
if database.backend == "postgresql":
|
|
217
|
+
from .postgresql import postgresql_drift
|
|
218
|
+
|
|
219
|
+
return await postgresql_drift(database, expected)
|
|
220
|
+
return await sqlite_drift(database, expected)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
async def _prepare(modules, previous, *, allow_destructive):
|
|
224
|
+
existing = await replay(*previous)
|
|
225
|
+
query = _RecordingQuery(existing)
|
|
226
|
+
actions = []
|
|
227
|
+
for module, step, kind in migration_steps(modules):
|
|
228
|
+
if kind == "migrate":
|
|
229
|
+
boundary = len(query.edits)
|
|
230
|
+
await replay_steps(query, ((module, step, kind),), validate=False)
|
|
231
|
+
actions.extend(query.edits[boundary:])
|
|
232
|
+
elif kind in ("transform", "seed", "verify"):
|
|
233
|
+
path = getattr(module, "__file__", module.__name__)
|
|
234
|
+
actions.append(_DataStep(step, kind, query.schema, f"{path}.{step.__name__}"))
|
|
235
|
+
desired = query.schema
|
|
236
|
+
desired.validate()
|
|
237
|
+
_validate_edits(existing, query.edits, allow_destructive=allow_destructive)
|
|
238
|
+
return existing, desired, actions
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _validate_edits(existing, edits, *, allow_destructive):
|
|
242
|
+
names = [table.name for table in existing.tables] + [edit.name for edit in edits]
|
|
243
|
+
if any(name.casefold() == HISTORY_TABLE for name in names):
|
|
244
|
+
raise MigrationError(f"The table {HISTORY_TABLE!r} is reserved for migration history")
|
|
245
|
+
for edit in edits:
|
|
246
|
+
if edit.destructive and not allow_destructive:
|
|
247
|
+
raise MigrationError(f"{edit.name}: destructive migration requires allow_destructive=True")
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
async def _run_data_step(database, step):
|
|
251
|
+
from .historical import HistoricalQuery
|
|
252
|
+
|
|
253
|
+
query = HistoricalQuery(database, step.schema, readonly=step.kind == "verify")
|
|
254
|
+
try:
|
|
255
|
+
passed = await step.function(query)
|
|
256
|
+
if step.kind == "verify" and passed is not True:
|
|
257
|
+
raise MigrationError(f"{step.location}: migration verification failed")
|
|
258
|
+
except Exception as error:
|
|
259
|
+
error.add_note(f"While executing @{step.kind} step {step.location}")
|
|
260
|
+
raise
|
|
261
|
+
finally:
|
|
262
|
+
query.close()
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
async def _execute(database, existing, desired, actions, *, before_edit=None):
|
|
266
|
+
backend = "PostgreSQL" if database.backend == "postgresql" else "SQLite"
|
|
267
|
+
if await _drift(database, existing):
|
|
268
|
+
raise MigrationError(f"Live {backend} schema differs from the supplied migration history")
|
|
269
|
+
deferred = []
|
|
270
|
+
if database.backend == "postgresql":
|
|
271
|
+
from .postgres_executor import apply_postgresql_edit, finish_postgresql_edits
|
|
272
|
+
for action in actions:
|
|
273
|
+
if isinstance(action, _DataStep):
|
|
274
|
+
await _run_data_step(database, action)
|
|
275
|
+
continue
|
|
276
|
+
if before_edit is not None:
|
|
277
|
+
await before_edit(action)
|
|
278
|
+
if database.backend == "postgresql":
|
|
279
|
+
await apply_postgresql_edit(database, action, deferred=deferred)
|
|
280
|
+
else:
|
|
281
|
+
await _apply_edit(database, action)
|
|
282
|
+
if database.backend == "postgresql":
|
|
283
|
+
await finish_postgresql_edits(database, deferred)
|
|
284
|
+
elif await database.execute("PRAGMA foreign_key_check", fetch=True):
|
|
285
|
+
raise MigrationError("Migration would leave broken SQLite foreign keys")
|
|
286
|
+
if await _drift(database, desired):
|
|
287
|
+
raise MigrationError(f"{backend} migration did not produce the replayed schema")
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
async def apply_migrations(
|
|
291
|
+
database: Database, *modules: ModuleType,
|
|
292
|
+
previous: Iterable[ModuleType] = (), allow_destructive: bool = False,
|
|
293
|
+
) -> Schema:
|
|
294
|
+
"""Apply migration modules with caller-supplied history."""
|
|
295
|
+
_require_backend(database)
|
|
296
|
+
plan = await _prepare(modules, previous, allow_destructive=allow_destructive)
|
|
297
|
+
async with _migration_transaction(database):
|
|
298
|
+
await _execute(database, *plan)
|
|
299
|
+
return plan[1]
|