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,40 @@
|
|
|
1
|
+
"""Reconstruct a schema from structural migration steps."""
|
|
2
|
+
|
|
3
|
+
from types import FunctionType, ModuleType
|
|
4
|
+
|
|
5
|
+
from .dsl import StructuralQuery
|
|
6
|
+
from .schema import Schema
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def migration_steps(modules):
|
|
10
|
+
for module in modules:
|
|
11
|
+
if not isinstance(module, ModuleType):
|
|
12
|
+
raise TypeError("replay() expects imported migration modules")
|
|
13
|
+
seen: set[FunctionType] = set()
|
|
14
|
+
for step in tuple(vars(module).values()):
|
|
15
|
+
if not isinstance(step, FunctionType) or step.__module__ != module.__name__ or step in seen:
|
|
16
|
+
continue
|
|
17
|
+
kind = getattr(step, "_record_migration_kind", None)
|
|
18
|
+
if kind is not None:
|
|
19
|
+
seen.add(step)
|
|
20
|
+
yield module, step, kind
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def replay_steps(query, steps, *, phase="migrate", validate=True):
|
|
24
|
+
for module, step, kind in steps:
|
|
25
|
+
if kind != phase:
|
|
26
|
+
continue
|
|
27
|
+
try:
|
|
28
|
+
await step(query)
|
|
29
|
+
except Exception as error:
|
|
30
|
+
location = getattr(module, "__file__", module.__name__)
|
|
31
|
+
error.add_note(f"While replaying {location}.{step.__name__}")
|
|
32
|
+
raise
|
|
33
|
+
if validate:
|
|
34
|
+
query.schema.validate()
|
|
35
|
+
return query.schema
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def replay(*modules: ModuleType) -> Schema:
|
|
39
|
+
"""Apply each module's structural steps in declaration order."""
|
|
40
|
+
return await replay_steps(StructuralQuery(Schema()), migration_steps(modules))
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Reverse recorded structural migrations without discarding data implicitly."""
|
|
2
|
+
|
|
3
|
+
from inspect import iscoroutinefunction
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from ..database import Database, identifier
|
|
7
|
+
from .diff import diff
|
|
8
|
+
from .errors import MigrationError
|
|
9
|
+
from .executor import _DataStep, _Edit, _RecordingQuery, _execute, _migration_transaction, _require_backend, _validate_edits
|
|
10
|
+
from .history import _TABLE, _load, _read, _sources, _verify
|
|
11
|
+
from .replay import migration_steps, replay_steps
|
|
12
|
+
from .schema import Schema
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _inverse(edits, name):
|
|
16
|
+
result = []
|
|
17
|
+
for edit in reversed(edits):
|
|
18
|
+
changes_identity = False
|
|
19
|
+
if edit.before is not None and edit.after is not None:
|
|
20
|
+
before = {column.name: column.auto_increment for column in edit.before.columns}
|
|
21
|
+
after = {column.name: column.auto_increment for column in edit.after.columns}
|
|
22
|
+
changes_identity = any(before[old] != after[new] for new, old in edit.origins)
|
|
23
|
+
if edit.destructive or changes_identity:
|
|
24
|
+
raise MigrationError(f"{name}: cannot infer a data-preserving reversal; define @rollback")
|
|
25
|
+
origins = tuple((source, target) for target, source in edit.origins)
|
|
26
|
+
renames = tuple((new, old) for old, new in reversed(edit.renames))
|
|
27
|
+
result.append(_Edit(edit.after, edit.before, origins, renames))
|
|
28
|
+
return result
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def _protect_data(database, edit, name):
|
|
32
|
+
if edit.before is None:
|
|
33
|
+
return
|
|
34
|
+
table = identifier(edit.name)
|
|
35
|
+
if edit.after is None:
|
|
36
|
+
rows = await database.execute(f"SELECT 1 FROM {table} LIMIT 1", fetch=True)
|
|
37
|
+
if rows:
|
|
38
|
+
raise MigrationError(f"{name}: rollback would drop populated table {edit.name!r}; define @rollback")
|
|
39
|
+
return
|
|
40
|
+
retained = {source for _, source in edit.origins}
|
|
41
|
+
for column in edit.before.columns:
|
|
42
|
+
if column.name in retained:
|
|
43
|
+
continue
|
|
44
|
+
field = identifier(column.name)
|
|
45
|
+
rows = await database.execute(f"SELECT 1 FROM {table} WHERE {field} IS NOT NULL LIMIT 1", fetch=True)
|
|
46
|
+
if rows:
|
|
47
|
+
raise MigrationError(
|
|
48
|
+
f"{name}: rollback would drop populated column {edit.name}.{column.name}; define @rollback"
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _RollbackQuery(_RecordingQuery):
|
|
53
|
+
def __init__(self, schema, name):
|
|
54
|
+
super().__init__(schema)
|
|
55
|
+
self._location = name
|
|
56
|
+
self._data = []
|
|
57
|
+
|
|
58
|
+
def data(self, function):
|
|
59
|
+
if not iscoroutinefunction(function):
|
|
60
|
+
raise TypeError("Rollback data steps must be async functions")
|
|
61
|
+
step = _DataStep(function, "rollback", self.schema, f"{self._location}.{function.__name__}")
|
|
62
|
+
self._data.append((len(self.edits), step))
|
|
63
|
+
|
|
64
|
+
def actions(self):
|
|
65
|
+
boundary = 0
|
|
66
|
+
for stop, step in self._data:
|
|
67
|
+
yield from self.edits[boundary:stop]
|
|
68
|
+
yield step
|
|
69
|
+
boundary = stop
|
|
70
|
+
yield from self.edits[boundary:]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def rollback_migrations(
|
|
74
|
+
database: Database, *paths: str | Path, steps: int = 1,
|
|
75
|
+
allow_destructive: bool = False,
|
|
76
|
+
) -> Schema:
|
|
77
|
+
"""Reverse the latest applied files in a single transaction."""
|
|
78
|
+
_require_backend(database)
|
|
79
|
+
if type(steps) is not int or steps < 1:
|
|
80
|
+
raise ValueError("steps must be a positive integer")
|
|
81
|
+
sources = _sources(paths)
|
|
82
|
+
async with _migration_transaction(database):
|
|
83
|
+
applied = await _read(database)
|
|
84
|
+
_verify(applied, sources)
|
|
85
|
+
if steps > len(applied):
|
|
86
|
+
raise MigrationError(f"Cannot roll back {steps} migrations; only {len(applied)} applied")
|
|
87
|
+
|
|
88
|
+
boundary = len(applied) - steps
|
|
89
|
+
marker = await database.execute(
|
|
90
|
+
f"SELECT checksum FROM {_TABLE} WHERE position = 0", fetch=True,
|
|
91
|
+
)
|
|
92
|
+
if marker and boundary < int(marker[0][0]):
|
|
93
|
+
raise MigrationError("Cannot roll back across a loaded snapshot baseline")
|
|
94
|
+
with _load(sources[:len(applied)]) as modules:
|
|
95
|
+
recorded = _RecordingQuery(Schema())
|
|
96
|
+
states = [(recorded.schema, 0)]
|
|
97
|
+
file_steps = [tuple(migration_steps((module,))) for module in modules]
|
|
98
|
+
for declaration in file_steps:
|
|
99
|
+
await replay_steps(recorded, declaration, validate=False)
|
|
100
|
+
states.append((recorded.schema, len(recorded.edits)))
|
|
101
|
+
|
|
102
|
+
for index in range(len(modules) - 1, boundary - 1, -1):
|
|
103
|
+
existing, stop = states[index + 1]
|
|
104
|
+
desired, start = states[index]
|
|
105
|
+
name = applied[index].name
|
|
106
|
+
declarations = file_steps[index]
|
|
107
|
+
rollback_steps = tuple(step for step in declarations if step[2] == "rollback")
|
|
108
|
+
if rollback_steps:
|
|
109
|
+
query = _RollbackQuery(existing, name)
|
|
110
|
+
result = await replay_steps(query, reversed(rollback_steps), phase="rollback")
|
|
111
|
+
if diff(desired, result, allow_drop_add=True):
|
|
112
|
+
raise MigrationError(f"{name}: explicit rollback did not restore the previous schema")
|
|
113
|
+
_validate_edits(existing, query.edits, allow_destructive=allow_destructive)
|
|
114
|
+
await _execute(database, existing, desired, query.actions())
|
|
115
|
+
else:
|
|
116
|
+
if any(kind in ("transform", "seed") for _, _, kind in declarations):
|
|
117
|
+
raise MigrationError(f"{name}: data migrations require an explicit @rollback")
|
|
118
|
+
edits = _inverse(recorded.edits[start:stop], name)
|
|
119
|
+
await _execute(
|
|
120
|
+
database, existing, desired, edits,
|
|
121
|
+
before_edit=lambda edit: _protect_data(database, edit, name),
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
await database.execute(
|
|
125
|
+
f"DELETE FROM {_TABLE} WHERE position = {database.placeholder}", (applied[index].position,),
|
|
126
|
+
)
|
|
127
|
+
return states[boundary][0]
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Immutable schema declarations produced by migration replay."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, replace
|
|
4
|
+
|
|
5
|
+
from ..schema import _TYPES, generate_sql
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
COLUMN_KINDS = {annotation: kind for kind, annotation in _TYPES.items()}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _validate_name(name: str) -> None:
|
|
12
|
+
if not isinstance(name, str) or not name or "\0" in name:
|
|
13
|
+
raise ValueError("Expected a nonempty name without null characters")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class Reference:
|
|
18
|
+
table: str
|
|
19
|
+
field: str
|
|
20
|
+
|
|
21
|
+
def __post_init__(self) -> None:
|
|
22
|
+
_validate_name(self.table)
|
|
23
|
+
_validate_name(self.field)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class Column:
|
|
28
|
+
name: str
|
|
29
|
+
kind: str
|
|
30
|
+
primary: bool = False
|
|
31
|
+
nullable: bool = False
|
|
32
|
+
unique: bool = False
|
|
33
|
+
auto_increment: bool = False
|
|
34
|
+
references: Reference | None = None
|
|
35
|
+
|
|
36
|
+
def __post_init__(self) -> None:
|
|
37
|
+
_validate_name(self.name)
|
|
38
|
+
if self.kind not in _TYPES:
|
|
39
|
+
raise ValueError(f"{self.name}: unsupported column type {self.kind!r}")
|
|
40
|
+
for name in ("primary", "nullable", "unique", "auto_increment"):
|
|
41
|
+
if type(getattr(self, name)) is not bool:
|
|
42
|
+
raise ValueError(f"{self.name}: {name} must be a boolean")
|
|
43
|
+
if self.primary and self.nullable:
|
|
44
|
+
raise ValueError(f"{self.name}: primary columns cannot be nullable")
|
|
45
|
+
if self.auto_increment and (self.kind != "integer" or not self.primary):
|
|
46
|
+
raise ValueError(f"{self.name}: generated IDs require an integer primary column")
|
|
47
|
+
|
|
48
|
+
def _definition(self) -> dict:
|
|
49
|
+
result = {
|
|
50
|
+
"name": self.name,
|
|
51
|
+
"type": self.kind,
|
|
52
|
+
"primary": self.primary,
|
|
53
|
+
"nullable": self.nullable,
|
|
54
|
+
"unique": self.unique,
|
|
55
|
+
"auto_increment": self.auto_increment,
|
|
56
|
+
}
|
|
57
|
+
if self.references is not None:
|
|
58
|
+
result["references"] = {"table": self.references.table, "field": self.references.field}
|
|
59
|
+
return result
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True, slots=True)
|
|
63
|
+
class Index:
|
|
64
|
+
fields: tuple[str, ...]
|
|
65
|
+
name: str | None = None
|
|
66
|
+
unique: bool = False
|
|
67
|
+
|
|
68
|
+
def __post_init__(self) -> None:
|
|
69
|
+
object.__setattr__(self, "fields", tuple(self.fields))
|
|
70
|
+
for name in self.fields:
|
|
71
|
+
_validate_name(name)
|
|
72
|
+
if not self.fields or len(set(self.fields)) != len(self.fields):
|
|
73
|
+
raise ValueError("Index fields must be nonempty and unique")
|
|
74
|
+
if self.name is not None:
|
|
75
|
+
_validate_name(self.name)
|
|
76
|
+
if type(self.unique) is not bool:
|
|
77
|
+
raise ValueError("Index unique flag must be a boolean")
|
|
78
|
+
|
|
79
|
+
def _definition(self) -> dict:
|
|
80
|
+
result = {"fields": self.fields, "unique": self.unique}
|
|
81
|
+
if self.name is not None:
|
|
82
|
+
result["name"] = self.name
|
|
83
|
+
return result
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True, slots=True)
|
|
87
|
+
class Table:
|
|
88
|
+
name: str
|
|
89
|
+
columns: tuple[Column, ...]
|
|
90
|
+
indexes: tuple[Index, ...] = ()
|
|
91
|
+
checks: tuple[str, ...] = ()
|
|
92
|
+
|
|
93
|
+
def __post_init__(self) -> None:
|
|
94
|
+
_validate_name(self.name)
|
|
95
|
+
object.__setattr__(self, "columns", tuple(self.columns))
|
|
96
|
+
object.__setattr__(self, "indexes", tuple(self.indexes))
|
|
97
|
+
object.__setattr__(self, "checks", tuple(self.checks))
|
|
98
|
+
names = {column.name for column in self.columns}
|
|
99
|
+
if not names or len(names) != len(self.columns):
|
|
100
|
+
raise ValueError(f"{self.name}: columns must be nonempty and unique")
|
|
101
|
+
if sum(column.primary for column in self.columns) > 1:
|
|
102
|
+
raise ValueError(f"{self.name}: only one primary column is supported")
|
|
103
|
+
for index in self.indexes:
|
|
104
|
+
if not names.issuperset(index.fields):
|
|
105
|
+
raise ValueError(f"{self.name}: index must name existing columns")
|
|
106
|
+
for check in self.checks:
|
|
107
|
+
if not isinstance(check, str) or not check.strip() or "\0" in check:
|
|
108
|
+
raise ValueError(f"{self.name}: check must be a nonempty SQL expression")
|
|
109
|
+
|
|
110
|
+
def _definition(self) -> dict:
|
|
111
|
+
return {
|
|
112
|
+
"name": self.name,
|
|
113
|
+
"fields": [field._definition() for field in self.columns],
|
|
114
|
+
"indexes": [index._definition() for index in self.indexes],
|
|
115
|
+
"checks": self.checks,
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@dataclass(frozen=True, slots=True)
|
|
120
|
+
class Schema:
|
|
121
|
+
tables: tuple[Table, ...] = ()
|
|
122
|
+
|
|
123
|
+
def __post_init__(self) -> None:
|
|
124
|
+
object.__setattr__(self, "tables", tuple(self.tables))
|
|
125
|
+
names = set()
|
|
126
|
+
for table in self.tables:
|
|
127
|
+
if table.name in names:
|
|
128
|
+
raise ValueError(f"Schema contains duplicate table {table.name!r}")
|
|
129
|
+
names.add(table.name)
|
|
130
|
+
|
|
131
|
+
def table(self, name: str) -> Table:
|
|
132
|
+
for table in self.tables:
|
|
133
|
+
if table.name == name:
|
|
134
|
+
return table
|
|
135
|
+
raise KeyError(name)
|
|
136
|
+
|
|
137
|
+
def add_table(self, table: Table) -> "Schema":
|
|
138
|
+
return replace(self, tables=(*self.tables, table))
|
|
139
|
+
|
|
140
|
+
def validate(self) -> None:
|
|
141
|
+
"""Validate references after all tables have been declared."""
|
|
142
|
+
columns = {
|
|
143
|
+
(table.name, column.name): column
|
|
144
|
+
for table in self.tables
|
|
145
|
+
for column in table.columns
|
|
146
|
+
}
|
|
147
|
+
indexes = set()
|
|
148
|
+
for table in self.tables:
|
|
149
|
+
for number, index in enumerate(table.indexes, 1):
|
|
150
|
+
index_name = index.name or f"{table.name}_idx_{number}"
|
|
151
|
+
if index_name in indexes:
|
|
152
|
+
raise ValueError(f"Duplicate index: {index_name}")
|
|
153
|
+
indexes.add(index_name)
|
|
154
|
+
for column in table.columns:
|
|
155
|
+
reference = column.references
|
|
156
|
+
if reference is None:
|
|
157
|
+
continue
|
|
158
|
+
target = columns.get((reference.table, reference.field))
|
|
159
|
+
location = f"{table.name}.{column.name}"
|
|
160
|
+
if target is None:
|
|
161
|
+
raise ValueError(f"{location}: unknown reference {reference.table}.{reference.field}")
|
|
162
|
+
if target.kind != column.kind:
|
|
163
|
+
raise ValueError(f"{location}: referenced column must have the same type")
|
|
164
|
+
if not (target.primary or target.unique):
|
|
165
|
+
raise ValueError(f"{location}: referenced column must be primary or unique")
|
|
166
|
+
|
|
167
|
+
def to_sql(self, dialect: str) -> str:
|
|
168
|
+
self.validate()
|
|
169
|
+
return generate_sql({"tables": [table._definition() for table in self.tables]}, dialect)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Versioned snapshots of replayed migration schemas."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
from ..models.timestamps import utc_now
|
|
6
|
+
from .bootstrap import load_schema
|
|
7
|
+
from .errors import MigrationError
|
|
8
|
+
from .history import _TABLE, _ensure_history, _load, _sources
|
|
9
|
+
from .replay import migration_steps, replay
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
async def _snapshot(sources):
|
|
13
|
+
with _load(sources) as modules:
|
|
14
|
+
if any(kind in {"seed", "transform", "verify"}
|
|
15
|
+
for _, _, kind in migration_steps(modules)):
|
|
16
|
+
raise MigrationError("Snapshot baselines must contain only structural migrations")
|
|
17
|
+
schema = await replay(*modules)
|
|
18
|
+
document = {
|
|
19
|
+
"version": 1,
|
|
20
|
+
"migrations": [[source.name, source.checksum] for source in sources],
|
|
21
|
+
"tables": [table._definition() for table in schema.tables],
|
|
22
|
+
}
|
|
23
|
+
return schema, document
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
async def dump_snapshot(path, paths):
|
|
27
|
+
_, document = await _snapshot(_sources(paths))
|
|
28
|
+
path.write_text(json.dumps(document, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def load_snapshot(database, path, paths):
|
|
32
|
+
document = json.loads(path.read_text(encoding="utf-8"))
|
|
33
|
+
if not isinstance(document, dict) or document.get("version") != 1:
|
|
34
|
+
raise MigrationError("Unsupported schema snapshot version")
|
|
35
|
+
migrations = document.get("migrations")
|
|
36
|
+
if not isinstance(migrations, list):
|
|
37
|
+
raise MigrationError("Invalid snapshot migration list")
|
|
38
|
+
sources = _sources(paths)[:len(migrations)]
|
|
39
|
+
schema, expected = await _snapshot(sources)
|
|
40
|
+
if json.dumps(document, sort_keys=True) != json.dumps(expected, sort_keys=True):
|
|
41
|
+
raise MigrationError("Snapshot does not match the configured migration prefix")
|
|
42
|
+
|
|
43
|
+
async def record_baseline(db):
|
|
44
|
+
await _ensure_history(db)
|
|
45
|
+
placeholders = ", ".join([db.placeholder] * 4)
|
|
46
|
+
insert = f"INSERT INTO {_TABLE} (position, name, checksum, applied_at) VALUES ({placeholders})"
|
|
47
|
+
applied_at = utc_now().isoformat()
|
|
48
|
+
await db.execute(insert, (0, "<snapshot>", str(len(sources)), applied_at))
|
|
49
|
+
for position, source in enumerate(sources, 1):
|
|
50
|
+
await db.execute(insert, (position, source.name, source.checksum, applied_at))
|
|
51
|
+
|
|
52
|
+
await load_schema(database, schema, record_baseline=record_baseline)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Inspect the SQLite schema shapes supported by Narabi migrations."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from ..database import Database
|
|
6
|
+
from .diff import Change, diff
|
|
7
|
+
from .schema import Column, Index, Reference, Schema, Table
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
HISTORY_TABLE = "_narabi_migrations"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
_TYPES = {"INTEGER": "integer", "TEXT": "text", "BOOLEAN": "boolean", "REAL": "real"}
|
|
14
|
+
_TOKENS = re.compile(
|
|
15
|
+
r"""--[^\n]*|/\*.*?\*/|'(?:''|[^'])*'|"(?:""|[^"])*"|\[[^\]]*\]|`(?:``|[^`])*`|[A-Za-z_][\w$]*|[()]""",
|
|
16
|
+
re.DOTALL,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _sql_tokens(sql):
|
|
21
|
+
return [match for match in _TOKENS.finditer(sql) if not match[0].startswith(("--", "/*"))]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _checks(sql, tokens):
|
|
25
|
+
checks = []
|
|
26
|
+
for position, token in enumerate(tokens[:-1]):
|
|
27
|
+
if token[0].upper() != "CHECK" or tokens[position + 1][0] != "(":
|
|
28
|
+
continue
|
|
29
|
+
start = tokens[position + 1].end()
|
|
30
|
+
depth = 1
|
|
31
|
+
for item in tokens[position + 2:]:
|
|
32
|
+
if item[0] == "(":
|
|
33
|
+
depth += 1
|
|
34
|
+
elif item[0] == ")":
|
|
35
|
+
depth -= 1
|
|
36
|
+
if depth == 0:
|
|
37
|
+
checks.append(sql[start:item.start()].strip())
|
|
38
|
+
break
|
|
39
|
+
return tuple(checks)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def _foreign_keys(database, table):
|
|
43
|
+
rows = await database.execute(
|
|
44
|
+
'SELECT id, seq, "table", "from", "to", on_update, on_delete, match '
|
|
45
|
+
'FROM pragma_foreign_key_list(?)', (table,), fetch=True,
|
|
46
|
+
)
|
|
47
|
+
references = {}
|
|
48
|
+
for _, sequence, target, source, column, on_update, on_delete, match in rows:
|
|
49
|
+
if sequence or source in references or column is None or (
|
|
50
|
+
on_update, on_delete, match
|
|
51
|
+
) != ("NO ACTION", "NO ACTION", "NONE"):
|
|
52
|
+
raise ValueError(f"{table}: unsupported SQLite foreign key")
|
|
53
|
+
references[source] = Reference(target, column)
|
|
54
|
+
return references
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def _indexes(database, table):
|
|
58
|
+
rows = await database.execute(
|
|
59
|
+
'SELECT name, "unique", origin, partial FROM pragma_index_list(?) ORDER BY name',
|
|
60
|
+
(table,), fetch=True,
|
|
61
|
+
)
|
|
62
|
+
uniques = set()
|
|
63
|
+
indexes = []
|
|
64
|
+
for name, unique, origin, partial in rows:
|
|
65
|
+
if origin == "pk":
|
|
66
|
+
continue
|
|
67
|
+
index_fields = await database.execute(
|
|
68
|
+
'SELECT name, "desc", coll FROM pragma_index_xinfo(?) WHERE "key" ORDER BY seqno',
|
|
69
|
+
(name,), fetch=True,
|
|
70
|
+
)
|
|
71
|
+
if partial or any(
|
|
72
|
+
field is None or descending or collation.upper() != "BINARY"
|
|
73
|
+
for field, descending, collation in index_fields
|
|
74
|
+
):
|
|
75
|
+
raise ValueError(f"{table}: unsupported SQLite index {name!r}")
|
|
76
|
+
fields = tuple(field for field, _, _ in index_fields)
|
|
77
|
+
if origin == "u":
|
|
78
|
+
if len(fields) != 1:
|
|
79
|
+
raise ValueError(f"{table}: unsupported SQLite unique constraint {name!r}")
|
|
80
|
+
uniques.add(fields[0])
|
|
81
|
+
else:
|
|
82
|
+
indexes.append(Index(fields, name=name, unique=bool(unique)))
|
|
83
|
+
return uniques, tuple(indexes)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
async def _table(database, name, sql, datetime_columns):
|
|
87
|
+
tokens = _sql_tokens(sql)
|
|
88
|
+
words = {token[0].upper() for token in tokens}
|
|
89
|
+
references = await _foreign_keys(database, name)
|
|
90
|
+
uniques, indexes = await _indexes(database, name)
|
|
91
|
+
rows = await database.execute(
|
|
92
|
+
'SELECT name, type, "notnull", dflt_value, pk, hidden '
|
|
93
|
+
'FROM pragma_table_xinfo(?) ORDER BY cid', (name,), fetch=True,
|
|
94
|
+
)
|
|
95
|
+
columns = []
|
|
96
|
+
for column, declared, not_null, default, primary, hidden in rows:
|
|
97
|
+
kind = _TYPES.get(declared.upper())
|
|
98
|
+
if kind is None or hidden or default is not None or primary > 1:
|
|
99
|
+
raise ValueError(f"{name}.{column}: unsupported SQLite column definition")
|
|
100
|
+
if primary and not not_null and kind != "integer":
|
|
101
|
+
raise ValueError(f"{name}.{column}: unsupported nullable SQLite primary key")
|
|
102
|
+
if kind == "text" and (name, column) in datetime_columns:
|
|
103
|
+
kind = "datetime"
|
|
104
|
+
columns.append(Column(
|
|
105
|
+
column, kind, primary=bool(primary), nullable=not (primary or not_null),
|
|
106
|
+
unique=column in uniques, auto_increment=bool(primary and "AUTOINCREMENT" in words),
|
|
107
|
+
references=references.get(column),
|
|
108
|
+
))
|
|
109
|
+
return Table(name, tuple(columns), indexes, _checks(sql, tokens))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
async def sqlite_drift(database: Database, expected: Schema) -> tuple[Change, ...]:
|
|
113
|
+
"""Report structural differences from expected history to a live SQLite database."""
|
|
114
|
+
if database.backend != "sqlite":
|
|
115
|
+
raise ValueError("Live schema drift inspection currently supports SQLite")
|
|
116
|
+
expected.validate()
|
|
117
|
+
datetime_columns = {
|
|
118
|
+
(table.name, column.name)
|
|
119
|
+
for table in expected.tables for column in table.columns
|
|
120
|
+
if column.kind == "datetime"
|
|
121
|
+
}
|
|
122
|
+
tables = []
|
|
123
|
+
async with database._operation():
|
|
124
|
+
rows = await database.execute(
|
|
125
|
+
"SELECT name, sql FROM sqlite_schema WHERE type = 'table' "
|
|
126
|
+
"AND name NOT GLOB 'sqlite_*' AND lower(name) <> ? ORDER BY name",
|
|
127
|
+
(HISTORY_TABLE,), fetch=True,
|
|
128
|
+
)
|
|
129
|
+
for name, sql in rows:
|
|
130
|
+
tables.append(await _table(database, name, sql, datetime_columns))
|
|
131
|
+
return diff(expected, Schema(tuple(tables)), allow_drop_add=True)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Model declaration and persistence behavior."""
|
narabi/models/bulk.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Batch validated table rows into atomic INSERT and UPSERT statements."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from itertools import chain
|
|
6
|
+
|
|
7
|
+
from ..database import database_for, identifier
|
|
8
|
+
from .soft_delete import DELETED_AT
|
|
9
|
+
from .timestamps import encode_datetime, utc_now
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def physical_values(model, fields, database):
|
|
13
|
+
values = {}
|
|
14
|
+
for name, value in fields.items():
|
|
15
|
+
if mapping := model._record_value_fields.get(name):
|
|
16
|
+
values.update(mapping.unpack(value, database.backend))
|
|
17
|
+
else:
|
|
18
|
+
values[name] = encode_datetime(value, database.backend) if name in model._record_managed_fields else value
|
|
19
|
+
return values
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Upsert:
|
|
24
|
+
conflict: tuple[str, ...]
|
|
25
|
+
update: tuple[str, ...]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def upsert_columns(model, conflict, update):
|
|
29
|
+
def fields(value, label):
|
|
30
|
+
if isinstance(value, str):
|
|
31
|
+
value = (value,)
|
|
32
|
+
try:
|
|
33
|
+
names = tuple(value)
|
|
34
|
+
except TypeError as error:
|
|
35
|
+
raise TypeError(f"{label} must be a field name or iterable of field names") from error
|
|
36
|
+
if not names or any(not isinstance(name, str) for name in names):
|
|
37
|
+
raise ValueError(f"{label} requires one or more field names")
|
|
38
|
+
if len(names) != len(set(names)):
|
|
39
|
+
raise ValueError(f"{label} contains duplicate fields")
|
|
40
|
+
for name in names:
|
|
41
|
+
if name not in model._record_fields or name in model._record_managed_fields:
|
|
42
|
+
raise ValueError(f"Invalid {label} field: {name!r}")
|
|
43
|
+
return names
|
|
44
|
+
|
|
45
|
+
keys = fields(conflict, "conflict")
|
|
46
|
+
changes = fields(update, "update")
|
|
47
|
+
if model._record_key in changes:
|
|
48
|
+
raise ValueError("The primary key cannot be an update field")
|
|
49
|
+
if set(keys).intersection(changes):
|
|
50
|
+
raise ValueError("Update fields must be distinct from conflict fields")
|
|
51
|
+
|
|
52
|
+
def expand(names):
|
|
53
|
+
return tuple(
|
|
54
|
+
path for name in names
|
|
55
|
+
for path in (model._record_value_fields[name].paths if name in model._record_value_fields else (name,))
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
if "updated_at" in model._record_managed_fields:
|
|
59
|
+
changes += ("updated_at",)
|
|
60
|
+
return Upsert(expand(keys), expand(changes))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
async def bulk_write(model, rows, validate, *, db=None, upsert=None):
|
|
64
|
+
source = iter(rows)
|
|
65
|
+
sentinel = object()
|
|
66
|
+
first = next(source, sentinel)
|
|
67
|
+
if first is sentinel:
|
|
68
|
+
return 0
|
|
69
|
+
database = database_for(None, db)
|
|
70
|
+
columns = model._record_columns
|
|
71
|
+
automatic = model._record_automatic_key
|
|
72
|
+
managed = model._record_managed_fields
|
|
73
|
+
now = utc_now() if "updated_at" in managed else None
|
|
74
|
+
suffix = ""
|
|
75
|
+
insert_into = f"INSERT INTO {model._record_table}"
|
|
76
|
+
if upsert is not None:
|
|
77
|
+
target = ", ".join(identifier(columns[path]) for path in upsert.conflict)
|
|
78
|
+
updates = [identifier(columns[path]) for path in upsert.update]
|
|
79
|
+
assignments = ", ".join(f"{column} = excluded.{column}" for column in updates)
|
|
80
|
+
suffix = f" ON CONFLICT ({target}) DO UPDATE SET {assignments}"
|
|
81
|
+
insert_into += ' AS "_narabi_bulk_target"'
|
|
82
|
+
|
|
83
|
+
async def flush(shape, batch):
|
|
84
|
+
if not shape:
|
|
85
|
+
return await database.execute(f"{insert_into} DEFAULT VALUES")
|
|
86
|
+
names = ", ".join(identifier(columns[path]) for path in shape)
|
|
87
|
+
row_sql = "(" + ", ".join([database.placeholder] * len(shape)) + ")"
|
|
88
|
+
bindings = tuple(value for row in batch for value in row)
|
|
89
|
+
values_sql = ", ".join([row_sql] * len(batch))
|
|
90
|
+
return await database.execute(
|
|
91
|
+
f"{insert_into} ({names}) VALUES {values_sql}{suffix}", bindings,
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
affected = 0
|
|
95
|
+
shape = ()
|
|
96
|
+
batch = []
|
|
97
|
+
seen = set()
|
|
98
|
+
parameter_limit = 999 if database.backend == "sqlite" else 65535
|
|
99
|
+
async with database.transaction():
|
|
100
|
+
for row in chain((first,), source):
|
|
101
|
+
if not isinstance(row, Mapping):
|
|
102
|
+
raise TypeError("Bulk rows must be mappings of constructor arguments")
|
|
103
|
+
values = await validate(model(**row))
|
|
104
|
+
if automatic is not None and values[automatic] is None:
|
|
105
|
+
del values[automatic]
|
|
106
|
+
for name in managed:
|
|
107
|
+
values[name] = None if name == DELETED_AT else now
|
|
108
|
+
bound = physical_values(model, values, database)
|
|
109
|
+
if upsert is not None and all(path in bound for path in upsert.conflict):
|
|
110
|
+
key = tuple(bound[path] for path in upsert.conflict)
|
|
111
|
+
if key in seen:
|
|
112
|
+
raise ValueError("Duplicate input conflict key")
|
|
113
|
+
seen.add(key)
|
|
114
|
+
row_shape = tuple(bound)
|
|
115
|
+
capacity = min(500, max(1, parameter_limit // len(row_shape))) if row_shape else 1
|
|
116
|
+
if batch and (row_shape != shape or len(batch) >= capacity):
|
|
117
|
+
affected += await flush(shape, batch)
|
|
118
|
+
batch.clear()
|
|
119
|
+
shape = row_shape
|
|
120
|
+
batch.append(tuple(bound.values()))
|
|
121
|
+
if batch:
|
|
122
|
+
affected += await flush(shape, batch)
|
|
123
|
+
return affected
|