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.
Files changed (56) hide show
  1. narabi/__init__.py +27 -0
  2. narabi/__main__.py +5 -0
  3. narabi/cli.py +338 -0
  4. narabi/console.py +102 -0
  5. narabi/database.py +310 -0
  6. narabi/fields/__init__.py +13 -0
  7. narabi/fields/defaults.py +59 -0
  8. narabi/fields/markers.py +74 -0
  9. narabi/migrations/__init__.py +22 -0
  10. narabi/migrations/bootstrap.py +30 -0
  11. narabi/migrations/decorators.py +22 -0
  12. narabi/migrations/diff.py +96 -0
  13. narabi/migrations/dsl.py +255 -0
  14. narabi/migrations/errors.py +5 -0
  15. narabi/migrations/executor.py +299 -0
  16. narabi/migrations/generate.py +149 -0
  17. narabi/migrations/historical.py +158 -0
  18. narabi/migrations/history.py +160 -0
  19. narabi/migrations/models.py +57 -0
  20. narabi/migrations/postgres_executor.py +239 -0
  21. narabi/migrations/postgresql.py +268 -0
  22. narabi/migrations/preview.py +150 -0
  23. narabi/migrations/replay.py +40 -0
  24. narabi/migrations/reverse.py +127 -0
  25. narabi/migrations/schema.py +169 -0
  26. narabi/migrations/snapshot.py +52 -0
  27. narabi/migrations/sqlite.py +131 -0
  28. narabi/models/__init__.py +1 -0
  29. narabi/models/bulk.py +123 -0
  30. narabi/models/core.py +440 -0
  31. narabi/models/inflection.py +37 -0
  32. narabi/models/lifecycle.py +125 -0
  33. narabi/models/privacy.py +19 -0
  34. narabi/models/serialization.py +145 -0
  35. narabi/models/soft_delete.py +59 -0
  36. narabi/models/timestamps.py +47 -0
  37. narabi/models/validation.py +149 -0
  38. narabi/models/values.py +167 -0
  39. narabi/project.py +108 -0
  40. narabi/py.typed +0 -0
  41. narabi/pytest.py +11 -0
  42. narabi/query/__init__.py +7 -0
  43. narabi/query/expressions.py +180 -0
  44. narabi/query/relation.py +562 -0
  45. narabi/query/scopes.py +36 -0
  46. narabi/relations/__init__.py +6 -0
  47. narabi/relations/prefetch.py +66 -0
  48. narabi/relations/references.py +196 -0
  49. narabi/relations/relationships.py +185 -0
  50. narabi/schema.py +132 -0
  51. narabi/stubs.py +275 -0
  52. narabi_orm-0.1.0.dist-info/METADATA +104 -0
  53. narabi_orm-0.1.0.dist-info/RECORD +56 -0
  54. narabi_orm-0.1.0.dist-info/WHEEL +4 -0
  55. narabi_orm-0.1.0.dist-info/entry_points.txt +2 -0
  56. narabi_orm-0.1.0.dist-info/licenses/LICENSE +29 -0
@@ -0,0 +1,149 @@
1
+ """Generate editable Python migrations from a structural diff."""
2
+
3
+ from collections.abc import Iterable
4
+ from itertools import groupby
5
+
6
+ from .diff import Change
7
+ from .schema import Column, Index, Table
8
+
9
+
10
+ _TYPES = {"integer": "int", "text": "str", "boolean": "bool", "real": "float", "datetime": "datetime"}
11
+ _PHASES = {
12
+ "drop_check": 0,
13
+ "drop_index": 0,
14
+ "change_index": 0,
15
+ "rename_column": 1,
16
+ "add_table": 2,
17
+ "drop_column": 3,
18
+ "change_column": 3,
19
+ "add_column": 3,
20
+ "add_index": 4,
21
+ "add_check": 4,
22
+ "drop_table": 5,
23
+ }
24
+
25
+
26
+ def ordered_changes(changes):
27
+ changes = tuple(changes)
28
+ for change in changes:
29
+ if change.kind not in _PHASES:
30
+ raise ValueError(f"Unsupported migration change {change.kind!r}")
31
+ added_indexes = (
32
+ Change("add_index", change.table, after=change.after)
33
+ for change in changes if change.kind == "change_index"
34
+ )
35
+ return sorted((*changes, *added_indexes), key=lambda change: (_PHASES[change.kind], change.table))
36
+
37
+
38
+ def destructive(change: Change) -> bool:
39
+ if change.kind in ("drop_table", "drop_column"):
40
+ return True
41
+ if change.kind == "change_column":
42
+ return change.before.kind != change.after.kind
43
+ return False
44
+
45
+
46
+ def _annotation(column: Column, *, markers: bool) -> str:
47
+ annotation = _TYPES[column.kind]
48
+ if markers and column.unique:
49
+ annotation = f"Unique[{annotation}]"
50
+ if markers and column.primary:
51
+ annotation = f"Primary[{annotation}]"
52
+ return f"{annotation} | None" if column.nullable else annotation
53
+
54
+
55
+ def _reference(column: Column):
56
+ link = column.references
57
+ return None if link is None else (link.table, link.field)
58
+
59
+
60
+ def _add_column(column: Column) -> str:
61
+ args = [repr(column.name), _annotation(column, markers=True)]
62
+ if column.auto_increment:
63
+ args.append("auto_increment=True")
64
+ if column.references is not None:
65
+ args.append(f"references={_reference(column)!r}")
66
+ return f"table.add({', '.join(args)})"
67
+
68
+
69
+ def _change_column(before: Column, after: Column) -> str:
70
+ args = [repr(after.name), _annotation(after, markers=False)]
71
+ for name in ("primary", "unique", "auto_increment"):
72
+ if getattr(before, name) != getattr(after, name):
73
+ args.append(f"{name}={getattr(after, name)!r}")
74
+ if before.references != after.references:
75
+ args.append(f"references={_reference(after)!r}")
76
+ return f"table.change({', '.join(args)})"
77
+
78
+
79
+ def _add_index(index: Index) -> str:
80
+ args = [repr(field) for field in index.fields]
81
+ if index.name is not None:
82
+ args.append(f"name={index.name!r}")
83
+ if index.unique:
84
+ args.append("unique=True")
85
+ return f"table.index({', '.join(args)})"
86
+
87
+
88
+ def _create_table(table: Table):
89
+ return [
90
+ *map(_add_column, table.columns),
91
+ *map(_add_index, table.indexes),
92
+ *(f"table.check({check!r})" for check in table.checks),
93
+ ]
94
+
95
+
96
+ def _operation(change: Change) -> str:
97
+ old, new = change.before, change.after
98
+ match change.kind:
99
+ case "drop_column":
100
+ return f"table.remove({old.name!r})"
101
+ case "add_column":
102
+ return _add_column(new)
103
+ case "rename_column":
104
+ return f"table.rename({old.name!r}, to={new.name!r})"
105
+ case "change_column":
106
+ return _change_column(old, new)
107
+ case "drop_index" | "change_index":
108
+ return f"table.drop_index({old.name!r})"
109
+ case "add_index":
110
+ return _add_index(new)
111
+ case "drop_check":
112
+ return f"table.drop_check({old!r})"
113
+ case "add_check":
114
+ return f"table.check({new!r})"
115
+ raise ValueError(f"Unsupported table edit {change.kind!r}")
116
+
117
+
118
+ def generate_migration(changes: Iterable[Change]) -> str:
119
+ """Render Python source for a structural migration. The caller owns the file."""
120
+ ordered = ordered_changes(changes)
121
+ body = []
122
+ for (_, name), group in groupby(ordered, key=lambda change: (_PHASES[change.kind], change.table)):
123
+ edits = list(group)
124
+ first = edits[0]
125
+ if first.kind == "drop_table":
126
+ body.extend([" # Destructive: drops the table and its data.", f" query.drop({name!r})"])
127
+ continue
128
+ if first.kind == "add_table":
129
+ method, operations = "create", _create_table(first.after)
130
+ else:
131
+ method, operations = "table", []
132
+ for change in edits:
133
+ if destructive(change):
134
+ operations.append("# Destructive: review data before applying this change.")
135
+ operations.append(_operation(change))
136
+ body.append(f" async with query.{method}({name!r}) as table:")
137
+ body.extend(f" {operation}" for operation in operations)
138
+ source = [
139
+ "from datetime import datetime",
140
+ "",
141
+ "from narabi import Primary, Unique, migrate",
142
+ "",
143
+ "",
144
+ "@migrate",
145
+ "async def change_schema(query):",
146
+ ' """Apply the reviewed structural changes."""',
147
+ *(body or [" pass"]),
148
+ ]
149
+ return "\n".join(source) + "\n"
@@ -0,0 +1,158 @@
1
+ """Queries over the tables and columns visible at a migration step."""
2
+
3
+ from dataclasses import dataclass, replace
4
+
5
+ from ..database import Database, _Transaction, _owned_transaction, identifier
6
+ from ..models.timestamps import decode_datetime, encode_datetime
7
+ from .errors import MigrationError
8
+ from .schema import Schema, Table
9
+
10
+
11
+ @dataclass(slots=True)
12
+ class _Step:
13
+ database: Database
14
+ transaction: _Transaction
15
+ readonly: bool
16
+ closed: bool = False
17
+
18
+ async def execute(self, sql, parameters, *, fetch=False):
19
+ if _owned_transaction(self.database._active) is not self.transaction:
20
+ raise MigrationError("Historical queries require their active migration transaction")
21
+ if self.closed:
22
+ raise MigrationError("This historical migration step has ended")
23
+ return await self.database.execute(sql, parameters, fetch=fetch)
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class HistoricalRelation:
28
+ _step: _Step
29
+ _table: Table
30
+ _filters: tuple[tuple[str, object], ...] = ()
31
+
32
+ def _parameters(self, values: dict[str, object]) -> tuple[object, ...]:
33
+ columns = {column.name: column for column in self._table.columns}
34
+ result = []
35
+ for name, value in values.items():
36
+ if name not in columns:
37
+ raise MigrationError(f"Unknown historical column {self._table.name}.{name}")
38
+ if columns[name].kind == "datetime":
39
+ value = encode_datetime(value, self._step.database.backend)
40
+ result.append(value)
41
+ return tuple(result)
42
+
43
+ def _where_sql(self) -> tuple[str, tuple[object, ...]]:
44
+ clauses, parameters = [], []
45
+ for name, value in self._filters:
46
+ if value is None:
47
+ clauses.append(f"{identifier(name)} IS NULL")
48
+ else:
49
+ clauses.append(f"{identifier(name)} = {self._step.database.placeholder}")
50
+ parameters.append(value)
51
+ where = " WHERE " + " AND ".join(clauses) if clauses else ""
52
+ return where, tuple(parameters)
53
+
54
+ @property
55
+ def _columns_sql(self) -> str:
56
+ return ", ".join(identifier(column.name) for column in self._table.columns)
57
+
58
+ def _row(self, values) -> dict[str, object]:
59
+ result = {}
60
+ for column, value in zip(self._table.columns, values, strict=True):
61
+ if value is not None:
62
+ if column.kind == "datetime":
63
+ value = decode_datetime(value)
64
+ elif column.kind == "boolean":
65
+ value = bool(value)
66
+ result[column.name] = value
67
+ return result
68
+
69
+ def _require_write(self) -> None:
70
+ if self._step.readonly:
71
+ raise MigrationError("Verification queries are read-only")
72
+
73
+ def where(self, **values: object) -> "HistoricalRelation":
74
+ encoded = self._parameters(values)
75
+ return replace(self, _filters=self._filters + tuple(zip(values, encoded)))
76
+
77
+ async def all(self) -> list[dict[str, object]]:
78
+ where, params = self._where_sql()
79
+ order = next((identifier(column.name) for column in self._table.columns if column.primary), None)
80
+ order_sql = f" ORDER BY {order}" if order is not None else ""
81
+ rows = await self._step.execute(
82
+ f"SELECT {self._columns_sql} FROM {identifier(self._table.name)}{where}{order_sql}",
83
+ params, fetch=True,
84
+ )
85
+ return [self._row(row) for row in rows]
86
+
87
+ def __await__(self):
88
+ return self.all().__await__()
89
+
90
+ @property
91
+ def exists(self):
92
+ return self._exists()
93
+
94
+ async def _exists(self) -> bool:
95
+ where, params = self._where_sql()
96
+ rows = await self._step.execute(
97
+ f"SELECT 1 FROM {identifier(self._table.name)}{where} LIMIT 1", params, fetch=True,
98
+ )
99
+ return bool(rows)
100
+
101
+ async def create(self, **values: object) -> dict[str, object]:
102
+ self._require_write()
103
+ if self._filters:
104
+ raise MigrationError("Create rows on a historical table without filters")
105
+ params = self._parameters(values)
106
+ if values:
107
+ fields = ", ".join(map(identifier, values))
108
+ placeholders = ", ".join([self._step.database.placeholder] * len(values))
109
+ inputs = f"({fields}) VALUES ({placeholders})"
110
+ else:
111
+ inputs = "DEFAULT VALUES"
112
+ rows = await self._step.execute(
113
+ f"INSERT INTO {identifier(self._table.name)} {inputs} RETURNING {self._columns_sql}",
114
+ params, fetch=True,
115
+ )
116
+ return self._row(rows[0])
117
+
118
+ async def update(self, **values: object) -> int:
119
+ self._require_write()
120
+ if not values:
121
+ return 0
122
+ params = self._parameters(values)
123
+ fields = ", ".join(f"{identifier(name)} = {self._step.database.placeholder}" for name in values)
124
+ where, filters = self._where_sql()
125
+ return await self._step.execute(
126
+ f"UPDATE {identifier(self._table.name)} SET {fields}{where}", params + filters,
127
+ )
128
+
129
+ async def delete(self) -> int:
130
+ self._require_write()
131
+ where, params = self._where_sql()
132
+ return await self._step.execute(f"DELETE FROM {identifier(self._table.name)}{where}", params)
133
+
134
+
135
+ class HistoricalQuery:
136
+ """Resolve data operations against a historical schema snapshot."""
137
+
138
+ def __init__(self, database: Database, schema: Schema, *, readonly: bool = False):
139
+ transaction = _owned_transaction(database._active)
140
+ if transaction is None:
141
+ raise MigrationError("Historical queries require an active migration transaction")
142
+ self._step = _Step(database, transaction, readonly)
143
+ self._schema = schema
144
+
145
+ def close(self) -> None:
146
+ self._step.closed = True
147
+
148
+ def table(self, name: str) -> HistoricalRelation:
149
+ try:
150
+ table = self._schema.table(name)
151
+ except KeyError:
152
+ raise MigrationError(f"Unknown historical table {name!r}") from None
153
+ return HistoricalRelation(self._step, table)
154
+
155
+ def __getattr__(self, name: str) -> HistoricalRelation:
156
+ if name.startswith("_"):
157
+ raise AttributeError(name)
158
+ return self.table(name)
@@ -0,0 +1,160 @@
1
+ """File checksums and durable migration history."""
2
+
3
+ from contextlib import contextmanager
4
+ from dataclasses import dataclass
5
+ from datetime import datetime
6
+ from hashlib import sha256
7
+ from pathlib import Path
8
+ import sys
9
+ from types import ModuleType
10
+ from uuid import uuid4
11
+
12
+ from ..database import Database, identifier
13
+ from ..models.timestamps import decode_datetime, utc_now
14
+ from .errors import MigrationError
15
+ from .executor import _execute, _migration_transaction, _prepare, _require_backend
16
+ from .schema import Schema
17
+ from .sqlite import HISTORY_TABLE
18
+
19
+
20
+ _TABLE = identifier(HISTORY_TABLE)
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class AppliedMigration:
25
+ position: int
26
+ name: str
27
+ checksum: str
28
+ applied_at: datetime
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class _Source:
33
+ path: Path
34
+ name: str
35
+ content: bytes
36
+ checksum: str
37
+
38
+
39
+ def _sources(paths):
40
+ result = []
41
+ names = set()
42
+ for value in paths:
43
+ path = Path(value)
44
+ if path.suffix != ".py" or not path.stem:
45
+ raise ValueError(f"Expected a Python migration file, got {path}")
46
+ if path.stem in names:
47
+ raise ValueError(f"Duplicate migration name {path.stem!r}")
48
+ names.add(path.stem)
49
+ content = path.read_bytes()
50
+ result.append(_Source(path, path.stem, content, sha256(content).hexdigest()))
51
+ return result
52
+
53
+
54
+ @contextmanager
55
+ def _load(sources):
56
+ modules = []
57
+ try:
58
+ for source in sources:
59
+ module = ModuleType(f"_narabi_migration_{uuid4().hex}")
60
+ module.__file__ = str(source.path)
61
+ modules.append(module)
62
+ sys.modules[module.__name__] = module
63
+ exec(compile(source.content, str(source.path), "exec", dont_inherit=True), vars(module))
64
+ yield modules
65
+ finally:
66
+ for module in modules:
67
+ if sys.modules.get(module.__name__) is module:
68
+ del sys.modules[module.__name__]
69
+
70
+
71
+ async def _read(database):
72
+ if database.backend == "postgresql":
73
+ sql = (
74
+ "SELECT 1 FROM information_schema.tables WHERE table_schema = current_schema() "
75
+ "AND table_type = 'BASE TABLE' AND table_name = %s"
76
+ )
77
+ else:
78
+ sql = "SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?"
79
+ exists = await database.execute(sql, (HISTORY_TABLE,), fetch=True)
80
+ if not exists:
81
+ return ()
82
+ rows = await database.execute(
83
+ f"SELECT position, name, checksum, applied_at FROM {_TABLE} WHERE position <> 0 ORDER BY position", fetch=True,
84
+ )
85
+ return tuple(
86
+ AppliedMigration(number, name, checksum, decode_datetime(applied_at))
87
+ for number, name, checksum, applied_at in rows
88
+ )
89
+
90
+
91
+ def _verify(history, sources):
92
+ source_names = {source.name for source in sources}
93
+ for position, entry in enumerate(history, 1):
94
+ if entry.position != position:
95
+ raise MigrationError("Migration history has a gap in its applied positions")
96
+ if entry.name not in source_names:
97
+ raise MigrationError(f"Missing applied migration {entry.name!r}")
98
+ source = sources[position - 1]
99
+ if entry.name != source.name:
100
+ raise MigrationError(f"Migration history is out of order at {entry.name!r}")
101
+ if entry.checksum != source.checksum:
102
+ raise MigrationError(f"Checksum mismatch for applied migration {entry.name!r}")
103
+
104
+
105
+ async def migration_history(database: Database) -> tuple[AppliedMigration, ...]:
106
+ """Return recorded migrations in apply order."""
107
+ _require_backend(database)
108
+ async with database._operation():
109
+ return await _read(database)
110
+
111
+
112
+ async def _ensure_history(database):
113
+ await database.execute(
114
+ f"CREATE TABLE IF NOT EXISTS {_TABLE} ("
115
+ "position INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, "
116
+ "checksum TEXT NOT NULL, applied_at TEXT NOT NULL)"
117
+ )
118
+
119
+
120
+ async def apply_pending(
121
+ database: Database, *paths: str | Path, allow_destructive: bool = False,
122
+ ) -> Schema:
123
+ """Apply an ordered list of migration files using durable migration history."""
124
+ _require_backend(database)
125
+ sources = _sources(paths)
126
+ async with _migration_transaction(database):
127
+ await _ensure_history(database)
128
+ applied = await _read(database)
129
+ _verify(applied, sources)
130
+ boundary = len(applied)
131
+ with _load(sources) as modules:
132
+ plan = await _prepare(
133
+ modules[boundary:], modules[:boundary], allow_destructive=allow_destructive,
134
+ )
135
+ await _execute(database, *plan)
136
+ applied_at = utc_now().isoformat()
137
+ placeholders = ", ".join([database.placeholder] * 4)
138
+ for number, source in enumerate(sources[boundary:], boundary + 1):
139
+ await database.execute(
140
+ f"INSERT INTO {_TABLE} (position, name, checksum, applied_at) VALUES ({placeholders})",
141
+ (number, source.name, source.checksum, applied_at),
142
+ )
143
+ return plan[1]
144
+
145
+
146
+ async def pending_plan(database: Database, *paths: str | Path):
147
+ """Verify applied checksums and preview pending actions without executing them."""
148
+ from .executor import _drift
149
+
150
+ _require_backend(database)
151
+ sources = _sources(paths)
152
+ async with database._operation():
153
+ applied = await _read(database)
154
+ _verify(applied, sources)
155
+ boundary = len(applied)
156
+ with _load(sources) as modules:
157
+ existing, _, actions = await _prepare(
158
+ modules[boundary:], modules[:boundary], allow_destructive=True,
159
+ )
160
+ return applied, actions, await _drift(database, existing)
@@ -0,0 +1,57 @@
1
+ """Read desired schema from the table models supplied by an application."""
2
+
3
+ from ..fields import Indexed, Unique
4
+ from .schema import COLUMN_KINDS, Column, Index, Reference, Schema, Table
5
+
6
+
7
+ def schema_from_models(*models: type) -> Schema:
8
+ """Describe the columns and indexes declared by a set of @table models."""
9
+ tables = []
10
+ for model in models:
11
+ if not isinstance(model, type) or "_record_key" not in vars(model):
12
+ raise TypeError("schema_from_models() expects @table models")
13
+ columns = []
14
+ indexes = []
15
+ checks = []
16
+ for name in model._record_fields:
17
+ field = model._record_metadata[name]
18
+ mapping = model._record_value_fields.get(name)
19
+ if mapping is not None:
20
+ physical = tuple(model._record_columns[path] for path in mapping.paths)
21
+ unique = (Unique,) in field.markers
22
+ for column, component in zip(physical, mapping.type._value_components.values()):
23
+ columns.append(Column(
24
+ column, COLUMN_KINDS[component.type], nullable=mapping.nullable,
25
+ unique=unique and len(physical) == 1,
26
+ ))
27
+ if len(physical) > 1 and mapping.nullable:
28
+ checks.append(mapping.null_check(model._record_columns))
29
+ if (Indexed,) in field.markers or (unique and len(physical) > 1):
30
+ indexes.append(Index(physical, unique=unique and len(physical) > 1))
31
+ continue
32
+ column = model._record_columns[name]
33
+ reference = model._record_references.get(name)
34
+ annotation = field.type
35
+ link = None
36
+ if reference is not None:
37
+ target = reference.target()
38
+ target_key = target._record_key
39
+ annotation = target._record_metadata[target_key].type
40
+ link = Reference(target._record_table_name, target._record_columns[target_key])
41
+ kind = COLUMN_KINDS.get(annotation)
42
+ if kind is None:
43
+ raise TypeError(f"{model.__qualname__}.{name}: unsupported schema type {annotation!r}")
44
+ nullable = field.nullable
45
+ if name in model._record_managed_fields:
46
+ nullable = name == "deleted_at"
47
+ columns.append(Column(
48
+ column, kind, primary=name == model._record_key,
49
+ nullable=nullable, unique=(Unique,) in field.markers,
50
+ auto_increment=name == model._record_automatic_key, references=link,
51
+ ))
52
+ if (Indexed,) in field.markers:
53
+ indexes.append(Index((column,)))
54
+ tables.append(Table(model._record_table_name, tuple(columns), tuple(indexes), tuple(checks)))
55
+ schema = Schema(tuple(tables))
56
+ schema.validate()
57
+ return schema