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
narabi/database.py ADDED
@@ -0,0 +1,310 @@
1
+ from asyncio import Lock, Task, current_task
2
+ from contextlib import asynccontextmanager
3
+ from contextvars import ContextVar
4
+ from dataclasses import dataclass, field
5
+ from importlib import import_module
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Any, Awaitable, Callable
9
+ from uuid import uuid4
10
+
11
+
12
+ def identifier(name):
13
+ return '"' + name.replace('"', '""') + '"'
14
+
15
+
16
+ _Callback = Callable[[], Awaitable[None]]
17
+
18
+
19
+ @dataclass
20
+ class _Transaction:
21
+ database: "Database"
22
+ connection: Any
23
+ owner: Task | None
24
+ undo: list[Callable[[], None]] = field(default_factory=list)
25
+ completion: dict[object, tuple[_Callback | None, _Callback | None]] = field(default_factory=dict)
26
+ rollback_only: bool = False
27
+
28
+ async def finish(self, *, committed):
29
+ errors = []
30
+ for commit, rollback in self.completion.values():
31
+ callback = commit if committed else rollback
32
+ if callback is not None:
33
+ try:
34
+ await callback()
35
+ except Exception as error:
36
+ errors.append(error)
37
+ if len(errors) == 1:
38
+ raise errors[0]
39
+ if errors:
40
+ raise ExceptionGroup("Transaction completion hooks failed", errors)
41
+
42
+
43
+ _contextual_transaction = ContextVar("record_transaction", default=None)
44
+
45
+
46
+ def _owned_transaction(context):
47
+ transaction = context.get()
48
+ if transaction is None:
49
+ return None
50
+ try:
51
+ owner = current_task()
52
+ except RuntimeError:
53
+ return None
54
+ if transaction.owner is owner:
55
+ return transaction
56
+ return None
57
+
58
+
59
+ class _SQLParameters(tuple):
60
+ def __repr__(self):
61
+ return "<redacted SQL parameters>"
62
+
63
+
64
+ class _NamedSQLParameters(dict):
65
+ def __repr__(self):
66
+ return "<redacted SQL parameters>"
67
+
68
+
69
+ class MissingDriverError(RuntimeError):
70
+ """A configured database driver is missing from the installation."""
71
+
72
+
73
+ def _load_driver(module, extra):
74
+ try:
75
+ return import_module(module)
76
+ except ModuleNotFoundError as error:
77
+ if error.name != module:
78
+ raise
79
+ raise MissingDriverError(f"Install narabi-orm[{extra}] to use {module}") from error
80
+
81
+
82
+ @asynccontextmanager
83
+ async def _sqlite_connection(target, *, migration):
84
+ driver = _load_driver("aiosqlite", "sqlite")
85
+ async with driver.connect(target) as connection:
86
+ foreign_keys = "OFF" if migration else "ON"
87
+ async with connection.execute(f"PRAGMA foreign_keys = {foreign_keys}"):
88
+ pass
89
+ async with connection.execute("BEGIN IMMEDIATE" if migration else "BEGIN"):
90
+ pass
91
+ yield connection
92
+
93
+
94
+ @asynccontextmanager
95
+ async def _postgresql_connection(target, *, migration):
96
+ driver = _load_driver("psycopg", "postgres")
97
+ async with await driver.AsyncConnection.connect(target) as connection:
98
+ yield connection
99
+
100
+
101
+ _CONNECTIONS = {"sqlite": _sqlite_connection, "postgresql": _postgresql_connection}
102
+
103
+
104
+ class Database:
105
+ def __init__(self, backend, database, *, pool=False):
106
+ if type(pool) is not bool or (pool and backend != "postgresql"):
107
+ raise ValueError("pool must be a boolean and requires PostgreSQL when enabled")
108
+ if backend not in _CONNECTIONS:
109
+ raise ValueError(f"Unsupported backend: {backend}")
110
+ self._pool_enabled = pool
111
+ self._pool = None
112
+ self._pool_lock = Lock() if pool else None
113
+ self.backend = backend
114
+ self.database = database
115
+ self.placeholder = "?" if backend == "sqlite" else "%s"
116
+ self._sandbox_owner = None
117
+ self._active = ContextVar("record_connection", default=None)
118
+
119
+ @classmethod
120
+ def from_config(cls, path=None, *, profile=None):
121
+ from .project import Project
122
+
123
+ project = Project.load(path)
124
+ backend, target = project.database_settings(profile)
125
+ return cls(backend, target, pool=project.database_config(profile).get("pool", False))
126
+
127
+ async def open(self):
128
+ """Start the configured PostgreSQL pool and wait for a connection."""
129
+ if self._pool_lock is None:
130
+ return
131
+ async with self._pool_lock:
132
+ if self._pool is not None:
133
+ return
134
+ _load_driver("psycopg", "postgres")
135
+ driver = _load_driver("psycopg_pool", "postgres")
136
+ pool = driver.AsyncConnectionPool(self.database, open=False)
137
+ try:
138
+ await pool.open(wait=True)
139
+ except BaseException:
140
+ await pool.close()
141
+ raise
142
+ self._pool = pool
143
+
144
+ async def close(self):
145
+ """Close the PostgreSQL pool during application shutdown."""
146
+ if self._pool_lock is None:
147
+ return
148
+ async with self._pool_lock:
149
+ pool, self._pool = self._pool, None
150
+ if pool is not None:
151
+ await pool.close()
152
+
153
+ @asynccontextmanager
154
+ async def _connect(self, *, migration=False):
155
+ if self._pool_enabled:
156
+ if self._pool is None:
157
+ raise RuntimeError("Open the PostgreSQL pool before using the database")
158
+ manager = self._pool.connection()
159
+ else:
160
+ manager = _CONNECTIONS[self.backend](self.database, migration=migration)
161
+ async with manager as connection:
162
+ yield connection
163
+
164
+ @asynccontextmanager
165
+ async def transaction(self, *, _migration=False):
166
+ if self._sandbox_owner is not None and self._sandbox_owner is not current_task():
167
+ raise RuntimeError("Run sandbox database operations in the console task")
168
+ parent = _owned_transaction(self._active)
169
+ if parent is not None:
170
+ if _migration:
171
+ raise RuntimeError("Migration transactions must be outermost")
172
+ async with self._savepoint(parent):
173
+ yield self
174
+ return
175
+ transaction = None
176
+ committed = False
177
+ try:
178
+ connection_context = self._connect(migration=True) if _migration else self._connect()
179
+ async with connection_context as connection:
180
+ transaction = _Transaction(self, connection, current_task())
181
+ token = self._active.set(transaction)
182
+ contextual_token = _contextual_transaction.set(transaction)
183
+ try:
184
+ yield self
185
+ if transaction.rollback_only:
186
+ raise RuntimeError("Transaction cannot commit after a savepoint failure")
187
+ await connection.commit()
188
+ committed = True
189
+ except BaseException:
190
+ try:
191
+ await connection.rollback()
192
+ finally:
193
+ for restore in reversed(transaction.undo):
194
+ restore()
195
+ raise
196
+ finally:
197
+ _contextual_transaction.reset(contextual_token)
198
+ self._active.reset(token)
199
+ except BaseException as failure:
200
+ if transaction is not None:
201
+ try:
202
+ await transaction.finish(committed=committed)
203
+ except Exception as callback_error:
204
+ failure.add_note(f"Transaction completion hook failed: {callback_error!r}")
205
+ raise
206
+ else:
207
+ await transaction.finish(committed=True)
208
+
209
+ @asynccontextmanager
210
+ async def _savepoint(self, parent):
211
+ name = f"narabi_{uuid4().hex}"
212
+ child = _Transaction(self, parent.connection, parent.owner)
213
+ try:
214
+ await self.execute(f"SAVEPOINT {name}")
215
+ except BaseException:
216
+ parent.rollback_only = True
217
+ raise
218
+ token = self._active.set(child)
219
+ contextual_token = _contextual_transaction.set(child)
220
+ try:
221
+ try:
222
+ yield
223
+ if child.rollback_only:
224
+ raise RuntimeError("Transaction cannot commit after a savepoint failure")
225
+ await self.execute(f"RELEASE SAVEPOINT {name}")
226
+ finally:
227
+ _contextual_transaction.reset(contextual_token)
228
+ self._active.reset(token)
229
+ except BaseException as failure:
230
+ try:
231
+ await self.execute(f"ROLLBACK TO SAVEPOINT {name}")
232
+ await self.execute(f"RELEASE SAVEPOINT {name}")
233
+ except BaseException as cleanup_error:
234
+ parent.rollback_only = True
235
+ failure.add_note(f"Savepoint cleanup failed: {cleanup_error!r}")
236
+ for restore in reversed(child.undo):
237
+ restore()
238
+ try:
239
+ await child.finish(committed=False)
240
+ except Exception as callback_error:
241
+ failure.add_note(f"Transaction completion hook failed: {callback_error!r}")
242
+ raise
243
+ else:
244
+ parent.undo.extend(child.undo)
245
+ for key, callbacks in child.completion.items():
246
+ parent.completion.setdefault(key, callbacks)
247
+
248
+ @asynccontextmanager
249
+ async def _operation(self):
250
+ if _owned_transaction(self._active) is not None:
251
+ yield
252
+ else:
253
+ async with self.transaction():
254
+ yield
255
+
256
+ def _on_completion(self, key, *, commit=None, rollback=None):
257
+ transaction = _owned_transaction(self._active)
258
+ if transaction is None:
259
+ raise RuntimeError("Completion hooks require an active transaction")
260
+ transaction.completion.setdefault(key, (commit, rollback))
261
+
262
+ def _on_rollback(self, restore):
263
+ transaction = _owned_transaction(self._active)
264
+ if transaction is not None:
265
+ transaction.undo.append(restore)
266
+
267
+ async def execute(self, sql, params=(), *, fetch=False):
268
+ """Execute SQL with native placeholders and optionally return rows."""
269
+ transaction = _owned_transaction(self._active)
270
+ if transaction is None:
271
+ async with self.transaction():
272
+ return await self.execute(sql, params, fetch=fetch)
273
+ async with transaction.connection.cursor() as cursor:
274
+ if params:
275
+ binding = _NamedSQLParameters(params) if isinstance(params, dict) else _SQLParameters(params)
276
+ await cursor.execute(sql, binding)
277
+ else:
278
+ await cursor.execute(sql)
279
+ if fetch:
280
+ return await cursor.fetchall()
281
+ return cursor.rowcount
282
+
283
+
284
+ _default = None
285
+ _configured = {}
286
+
287
+
288
+ def use_database(database):
289
+ global _default
290
+ _default = database
291
+
292
+
293
+ def default_database():
294
+ transaction = _owned_transaction(_contextual_transaction)
295
+ if transaction is not None:
296
+ return transaction.database
297
+ if _default is not None:
298
+ return _default
299
+ key = (Path.cwd(), os.getenv("NARABI_ENV", "dev"))
300
+ if key not in _configured:
301
+ _configured[key] = Database.from_config()
302
+ return _configured[key]
303
+
304
+
305
+ def database_for(state, requested):
306
+ if state is None:
307
+ return requested if requested is not None else default_database()
308
+ if requested is not None and requested is not state.database:
309
+ raise ValueError("Record belongs to another database")
310
+ return state.database
@@ -0,0 +1,13 @@
1
+ """Field annotations and generated defaults for Narabi models."""
2
+
3
+ from .defaults import Factory, Now, UUID4, UUID7
4
+ from .markers import (
5
+ CLASSIFICATIONS, AutoIncrement, Field, Increment, Indexed, Length, Personal,
6
+ Primary, Private, Range, Ref, Sensitive, Unique, describe,
7
+ )
8
+
9
+ __all__ = [
10
+ "AutoIncrement", "Factory", "Field", "Increment", "Indexed", "Length", "Now",
11
+ "Personal", "Primary", "Private", "Range", "Ref", "Sensitive", "UUID4",
12
+ "UUID7", "Unique", "describe",
13
+ ]
@@ -0,0 +1,59 @@
1
+ """Application-side defaults evaluated for each new model instance."""
2
+
3
+ from dataclasses import dataclass
4
+ from datetime import UTC, datetime
5
+ from functools import partial
6
+ from secrets import randbits
7
+ from time import time_ns
8
+ from typing import Callable, ClassVar, get_origin
9
+ from uuid import UUID, uuid4
10
+
11
+ import attrs
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Factory:
16
+ """Call a zero-argument function when a field is omitted."""
17
+
18
+ function: Callable[[], object]
19
+
20
+
21
+ class Now(Factory):
22
+ """Generate a timezone-aware UTC timestamp."""
23
+
24
+ def __init__(self):
25
+ super().__init__(partial(datetime.now, UTC))
26
+
27
+
28
+ class UUID4(Factory):
29
+ """Generate a random UUID version 4."""
30
+
31
+ def __init__(self):
32
+ super().__init__(_uuid4_string)
33
+
34
+
35
+ def _uuid4_string() -> str:
36
+ return str(uuid4())
37
+
38
+
39
+ def _uuid7_string() -> str:
40
+ # RFC 9562 section 5.7. Use random data for both payload fields.
41
+ milliseconds = time_ns() // 1_000_000
42
+ timestamp_and_version = milliseconds << 80 | 7 << 76
43
+ random_a = randbits(12) << 64
44
+ variant_and_random_b = 0b10 << 62 | randbits(62)
45
+ return str(UUID(int=timestamp_and_version | random_a | variant_and_random_b))
46
+
47
+
48
+ class UUID7(Factory):
49
+ """Generate a UUID with a millisecond timestamp and a random payload."""
50
+
51
+ def __init__(self):
52
+ super().__init__(_uuid7_string)
53
+
54
+
55
+ def configure_defaults(cls, metadata):
56
+ for name in cls.__dict__.get("__annotations__", {}):
57
+ default = vars(cls).get(name)
58
+ if isinstance(default, Factory) and get_origin(metadata[name].type) is not ClassVar:
59
+ setattr(cls, name, attrs.field(factory=default.function, kw_only=True))
@@ -0,0 +1,74 @@
1
+ from dataclasses import dataclass, replace
2
+ from types import UnionType
3
+ from typing import Generic, TypeVar, Union, get_args, get_origin
4
+
5
+ T = TypeVar("T")
6
+
7
+
8
+ class Primary(Generic[T]):
9
+ """Mark the field used to find a record."""
10
+
11
+
12
+ class Increment:
13
+ """Let the database assign the ID when a record is saved."""
14
+
15
+
16
+ AutoIncrement = Increment
17
+
18
+
19
+ class Ref(Generic[T]):
20
+ """Reference a persistent model by its primary key."""
21
+
22
+
23
+ class Unique(Generic[T]):
24
+ """Mark a unique field for schema tooling."""
25
+
26
+
27
+ class Indexed(Generic[T]):
28
+ """Mark an indexed field for schema tooling."""
29
+
30
+
31
+ class Personal(Generic[T]):
32
+ """Mark identifying information."""
33
+
34
+
35
+ class Sensitive(Generic[T]):
36
+ """Mark sensitive information."""
37
+
38
+
39
+ class Private(Generic[T]):
40
+ """Omit this field from default serialization."""
41
+
42
+
43
+ CLASSIFICATIONS = (Personal, Sensitive, Private)
44
+
45
+
46
+ Minimum = TypeVar("Minimum")
47
+ Maximum = TypeVar("Maximum")
48
+
49
+
50
+ class Length(Generic[T, Minimum, Maximum]):
51
+ """Describe minimum and maximum lengths."""
52
+
53
+
54
+ class Range(Generic[T, Minimum, Maximum]):
55
+ """Describe minimum and maximum values."""
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class Field:
60
+ type: object
61
+ markers: tuple[tuple[object, ...], ...] = ()
62
+ nullable: bool = False
63
+
64
+
65
+ def describe(hint):
66
+ origin = get_origin(hint)
67
+ args = get_args(hint)
68
+ if origin in (Union, UnionType) and len(args) == 2 and type(None) in args:
69
+ inner = next(arg for arg in args if arg is not type(None))
70
+ return replace(describe(inner), nullable=True)
71
+ if origin in (Primary, Unique, Indexed, Length, Range, Ref, *CLASSIFICATIONS):
72
+ inner = describe(args[0])
73
+ return replace(inner, markers=((origin, *args[1:]), *inner.markers))
74
+ return Field(hint)
@@ -0,0 +1,22 @@
1
+ """Python migration declarations and offline schema replay."""
2
+
3
+ from .decorators import migrate, rollback, seed, transform, verify
4
+ from .diff import Change, diff
5
+ from .errors import MigrationError
6
+ from .executor import apply_migrations
7
+ from .generate import generate_migration
8
+ from .history import AppliedMigration, apply_pending, migration_history
9
+ from .models import schema_from_models
10
+ from .postgresql import postgresql_drift
11
+ from .preview import SQLPreview, preview_sql
12
+ from .replay import replay
13
+ from .reverse import rollback_migrations
14
+ from .schema import Schema
15
+ from .sqlite import sqlite_drift
16
+
17
+ __all__ = [
18
+ "AppliedMigration", "Change", "MigrationError", "SQLPreview", "Schema",
19
+ "apply_migrations", "apply_pending", "diff", "generate_migration", "migrate",
20
+ "migration_history", "postgresql_drift", "preview_sql", "replay", "rollback",
21
+ "rollback_migrations", "schema_from_models", "seed", "sqlite_drift", "transform", "verify",
22
+ ]
@@ -0,0 +1,30 @@
1
+ """Create an initial schema atomically in an empty database."""
2
+
3
+ from ..schema import schema_statements
4
+ from .errors import MigrationError
5
+ from .executor import _migration_transaction, _validate_edits
6
+
7
+
8
+ async def load_schema(database, schema, *, record_baseline=None):
9
+ schema.validate()
10
+ _validate_edits(schema, (), allow_destructive=False)
11
+ statements = schema_statements(
12
+ {"tables": [table._definition() for table in schema.tables]}, database.backend,
13
+ )
14
+ async with _migration_transaction(database):
15
+ if database.backend == "sqlite":
16
+ objects = await database.execute(
17
+ "SELECT 1 FROM sqlite_schema WHERE name NOT GLOB 'sqlite_*' LIMIT 1", fetch=True,
18
+ )
19
+ else:
20
+ objects = await database.execute(
21
+ "SELECT 1 FROM pg_depend AS d JOIN pg_namespace AS n ON d.refobjid = n.oid "
22
+ "WHERE d.refclassid = 'pg_namespace'::regclass AND n.nspname = current_schema() LIMIT 1",
23
+ fetch=True,
24
+ )
25
+ if objects:
26
+ raise MigrationError("Schema loading requires an empty target")
27
+ for statement in statements:
28
+ await database.execute(statement)
29
+ if record_baseline is not None:
30
+ await record_baseline(database)
@@ -0,0 +1,22 @@
1
+ """Classify async functions declared in Python migration modules."""
2
+
3
+ from inspect import iscoroutinefunction
4
+
5
+
6
+ def _step(kind):
7
+ def decorate(function):
8
+ if not iscoroutinefunction(function):
9
+ raise TypeError(f"@{kind} requires an async function")
10
+ if hasattr(function, "_record_migration_kind"):
11
+ raise TypeError(f"{function.__name__} already has a migration decorator")
12
+ function._record_migration_kind = kind
13
+ return function
14
+
15
+ return decorate
16
+
17
+
18
+ migrate = _step("migrate")
19
+ transform = _step("transform")
20
+ seed = _step("seed")
21
+ verify = _step("verify")
22
+ rollback = _step("rollback")
@@ -0,0 +1,96 @@
1
+ """Compare two schema snapshots without opening a database connection."""
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import dataclass, replace
5
+
6
+ from .schema import Column, Index, Schema, Table
7
+
8
+
9
+ SchemaValue = Table | Column | Index | str
10
+
11
+
12
+ @dataclass(frozen=True, slots=True)
13
+ class Change:
14
+ kind: str
15
+ table: str
16
+ before: SchemaValue | None = None
17
+ after: SchemaValue | None = None
18
+
19
+
20
+ def _indexes(table):
21
+ result = {}
22
+ for number, index in enumerate(table.indexes, 1):
23
+ name = index.name or f"{table.name}_idx_{number}"
24
+ result[name] = replace(index, name=name)
25
+ return result
26
+
27
+
28
+ def _compare(kind, table, before, after):
29
+ for key in sorted(before.keys() - after.keys()):
30
+ yield Change(f"drop_{kind}", table, before=before[key])
31
+ for key in sorted(after.keys() - before.keys()):
32
+ yield Change(f"add_{kind}", table, after=after[key])
33
+ for key in sorted(before.keys() & after.keys()):
34
+ if before[key] != after[key]:
35
+ yield Change(f"change_{kind}", table, before[key], after[key])
36
+
37
+
38
+ def diff(
39
+ previous: Schema,
40
+ desired: Schema,
41
+ *,
42
+ renames: Mapping[tuple[str, str], str] | None = None,
43
+ allow_drop_add: bool = False,
44
+ ) -> tuple[Change, ...]:
45
+ """Describe changes from previous to desired, with explicit column renames."""
46
+ previous.validate()
47
+ desired.validate()
48
+ renames = dict(renames or {})
49
+ before = {table.name: table for table in previous.tables}
50
+ after = {table.name: table for table in desired.tables}
51
+ common = before.keys() & after.keys()
52
+ rename_targets = set()
53
+ for (table, old), new in renames.items():
54
+ if table not in common:
55
+ raise ValueError(f"Cannot rename a column on {table!r}, which must exist in both schemas")
56
+ old_names = {column.name for column in before[table].columns}
57
+ new_names = {column.name for column in after[table].columns}
58
+ if old not in old_names - new_names or new not in new_names - old_names:
59
+ raise ValueError(f"Invalid column rename {table}.{old} to {new}")
60
+ if (table, new) in rename_targets:
61
+ raise ValueError(f"Duplicate column rename destination {table}.{new}")
62
+ rename_targets.add((table, new))
63
+
64
+ removed_tables = before.keys() - after.keys()
65
+ added_tables = after.keys() - before.keys()
66
+ if removed_tables and added_tables and not allow_drop_add:
67
+ raise ValueError("Tables were removed and added. Confirm intentional drops with allow_drop_add=True")
68
+ changes = [Change("drop_table", name, before=before[name]) for name in sorted(removed_tables)]
69
+ changes.extend(Change("add_table", name, after=after[name]) for name in sorted(added_tables))
70
+
71
+ for name in sorted(common):
72
+ old_columns = {}
73
+ for column in before[name].columns:
74
+ new_name = renames.get((name, column.name), column.name)
75
+ link = column.references
76
+ if link is not None:
77
+ link = replace(link, field=renames.get((link.table, link.field), link.field))
78
+ normalized = replace(column, name=new_name, references=link)
79
+ old_columns[new_name] = normalized
80
+ if new_name != column.name:
81
+ changes.append(Change("rename_column", name, column, normalized))
82
+ new_columns = {column.name: column for column in after[name].columns}
83
+ if old_columns.keys() - new_columns.keys() and new_columns.keys() - old_columns.keys() and not allow_drop_add:
84
+ raise ValueError(f"{name}: confirm column renames or pass allow_drop_add=True for intentional drops")
85
+ changes.extend(_compare("column", name, old_columns, new_columns))
86
+
87
+ old_indexes = {
88
+ key: replace(index, fields=tuple(renames.get((name, field), field) for field in index.fields))
89
+ for key, index in _indexes(before[name]).items()
90
+ }
91
+ changes.extend(_compare("index", name, old_indexes, _indexes(after[name])))
92
+ changes.extend(_compare(
93
+ "check", name, {check.strip(): check.strip() for check in before[name].checks},
94
+ {check.strip(): check.strip() for check in after[name].checks},
95
+ ))
96
+ return tuple(changes)