snake-orm 0.1.0b1__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.
- snake_orm-0.1.0b1.dist-info/METADATA +366 -0
- snake_orm-0.1.0b1.dist-info/RECORD +198 -0
- snake_orm-0.1.0b1.dist-info/WHEEL +4 -0
- snake_orm-0.1.0b1.dist-info/entry_points.txt +2 -0
- snake_orm-0.1.0b1.dist-info/licenses/LICENSE +21 -0
- snakeorm/__init__.py +214 -0
- snakeorm/advisor.py +109 -0
- snakeorm/cli/__init__.py +3 -0
- snakeorm/cli/app.py +992 -0
- snakeorm/cli/discovery.py +179 -0
- snakeorm/cli/hooks.py +86 -0
- snakeorm/compiler/__init__.py +3 -0
- snakeorm/compiler/compiler.py +330 -0
- snakeorm/connection.py +228 -0
- snakeorm/contrib/__init__.py +17 -0
- snakeorm/contrib/asgi.py +192 -0
- snakeorm/contrib/config.py +264 -0
- snakeorm/contrib/deliver.py +256 -0
- snakeorm/contrib/django.py +245 -0
- snakeorm/contrib/sidecar.py +44 -0
- snakeorm/contrib/wsgi.py +176 -0
- snakeorm/core/__init__.py +1 -0
- snakeorm/core/config.py +173 -0
- snakeorm/core/converters.py +172 -0
- snakeorm/core/exceptions.py +175 -0
- snakeorm/core/placement.py +15 -0
- snakeorm/core/sentinels.py +37 -0
- snakeorm/core/signals.py +114 -0
- snakeorm/debug/__init__.py +42 -0
- snakeorm/debug/assets/css/panel.css +616 -0
- snakeorm/debug/assets/css/snake_orm_app.css +293 -0
- snakeorm/debug/assets/img/icon.svg +5 -0
- snakeorm/debug/assets/js/history.js +425 -0
- snakeorm/debug/assets/js/language.js +283 -0
- snakeorm/debug/assets/js/panel.js +241 -0
- snakeorm/debug/assets/js/snake_orm_app.js +82 -0
- snakeorm/debug/assets/pages/cli.html +28 -0
- snakeorm/debug/assets/pages/config.html +34 -0
- snakeorm/debug/assets/pages/database_first.html +29 -0
- snakeorm/debug/assets/pages/help.html +21 -0
- snakeorm/debug/assets/pages/history.html +27 -0
- snakeorm/debug/capture.py +234 -0
- snakeorm/debug/channel.py +131 -0
- snakeorm/debug/collector.py +144 -0
- snakeorm/debug/config.py +149 -0
- snakeorm/debug/html.py +578 -0
- snakeorm/debug/matrix.py +60 -0
- snakeorm/debug/origin.py +42 -0
- snakeorm/debug/otel/__init__.py +68 -0
- snakeorm/debug/otel/context.py +43 -0
- snakeorm/debug/otel/exporter.py +277 -0
- snakeorm/debug/otel/payload.py +97 -0
- snakeorm/debug/otel/report.py +29 -0
- snakeorm/debug/otel/spans.py +393 -0
- snakeorm/debug/otel/summary.py +59 -0
- snakeorm/debug/record.py +54 -0
- snakeorm/debug/report.py +311 -0
- snakeorm/debug/testing.py +23 -0
- snakeorm/decorators/__init__.py +13 -0
- snakeorm/decorators/abstract.py +26 -0
- snakeorm/decorators/db_first.py +104 -0
- snakeorm/decorators/function.py +28 -0
- snakeorm/decorators/model.py +268 -0
- snakeorm/decorators/polymorphic.py +140 -0
- snakeorm/decorators/result.py +167 -0
- snakeorm/decorators/row.py +90 -0
- snakeorm/decorators/trigger.py +47 -0
- snakeorm/decorators/view.py +149 -0
- snakeorm/dialects/__init__.py +6 -0
- snakeorm/dialects/base.py +373 -0
- snakeorm/dialects/capabilities.py +571 -0
- snakeorm/dialects/literals.py +46 -0
- snakeorm/dialects/matrix.py +384 -0
- snakeorm/dialects/mysql.py +519 -0
- snakeorm/dialects/postgres.py +504 -0
- snakeorm/dialects/sqlite.py +417 -0
- snakeorm/drivers/__init__.py +18 -0
- snakeorm/drivers/asyncbase.py +73 -0
- snakeorm/drivers/asyncdecorators.py +244 -0
- snakeorm/drivers/asyncpool.py +228 -0
- snakeorm/drivers/asyncpsycopg.py +124 -0
- snakeorm/drivers/asyncpymysql.py +50 -0
- snakeorm/drivers/asyncsqlite.py +30 -0
- snakeorm/drivers/base.py +76 -0
- snakeorm/drivers/failures.py +181 -0
- snakeorm/drivers/logging.py +167 -0
- snakeorm/drivers/pool.py +352 -0
- snakeorm/drivers/psycopg.py +188 -0
- snakeorm/drivers/pymysql.py +176 -0
- snakeorm/drivers/savepoints.py +46 -0
- snakeorm/drivers/sqlite.py +170 -0
- snakeorm/drivers/threaded.py +143 -0
- snakeorm/drivers/timeout.py +87 -0
- snakeorm/dto/__init__.py +55 -0
- snakeorm/dto/read.py +231 -0
- snakeorm/dto/region.py +326 -0
- snakeorm/dto/resolve.py +354 -0
- snakeorm/dto/spec.py +201 -0
- snakeorm/expressions/__init__.py +88 -0
- snakeorm/expressions/conditional.py +178 -0
- snakeorm/expressions/expression.py +810 -0
- snakeorm/expressions/functions.py +71 -0
- snakeorm/expressions/keys.py +299 -0
- snakeorm/expressions/paths.py +43 -0
- snakeorm/expressions/scalar.py +293 -0
- snakeorm/expressions/window.py +248 -0
- snakeorm/fields/__init__.py +68 -0
- snakeorm/fields/check.py +79 -0
- snakeorm/fields/column.py +316 -0
- snakeorm/fields/enum.py +64 -0
- snakeorm/fields/index.py +46 -0
- snakeorm/fields/relationship.py +738 -0
- snakeorm/fields/typed.py +736 -0
- snakeorm/helpers/__init__.py +1 -0
- snakeorm/helpers/annotations.py +21 -0
- snakeorm/helpers/inheritance.py +41 -0
- snakeorm/helpers/pyliteral.py +52 -0
- snakeorm/helpers/pytype.py +50 -0
- snakeorm/introspection/__init__.py +13 -0
- snakeorm/introspection/base.py +30 -0
- snakeorm/introspection/drift.py +78 -0
- snakeorm/introspection/models.py +633 -0
- snakeorm/introspection/mysql.py +367 -0
- snakeorm/introspection/postgres.py +397 -0
- snakeorm/introspection/sqlite.py +217 -0
- snakeorm/introspection/unsupported.py +94 -0
- snakeorm/linker/__init__.py +3 -0
- snakeorm/linker/linker.py +521 -0
- snakeorm/metadata/__init__.py +41 -0
- snakeorm/metadata/check.py +37 -0
- snakeorm/metadata/column.py +201 -0
- snakeorm/metadata/enum_storage.py +33 -0
- snakeorm/metadata/fk_action.py +19 -0
- snakeorm/metadata/foreign_key.py +26 -0
- snakeorm/metadata/index.py +43 -0
- snakeorm/metadata/index_method.py +19 -0
- snakeorm/metadata/int_size.py +20 -0
- snakeorm/metadata/json_storage.py +21 -0
- snakeorm/metadata/polymorphic.py +30 -0
- snakeorm/metadata/primary_key.py +23 -0
- snakeorm/metadata/relationship.py +60 -0
- snakeorm/metadata/relationship_kind.py +43 -0
- snakeorm/metadata/routine.py +26 -0
- snakeorm/metadata/server_default.py +20 -0
- snakeorm/metadata/table.py +97 -0
- snakeorm/metadata/table_kind.py +23 -0
- snakeorm/metadata/trigger.py +62 -0
- snakeorm/metadata/type_params.py +348 -0
- snakeorm/migration/__init__.py +88 -0
- snakeorm/migration/asyncrunner.py +168 -0
- snakeorm/migration/autodetect.py +96 -0
- snakeorm/migration/ddl.py +1172 -0
- snakeorm/migration/diff.py +701 -0
- snakeorm/migration/loader.py +77 -0
- snakeorm/migration/operations.py +952 -0
- snakeorm/migration/planner.py +78 -0
- snakeorm/migration/realize.py +420 -0
- snakeorm/migration/renames.py +153 -0
- snakeorm/migration/render.py +1095 -0
- snakeorm/migration/runner.py +314 -0
- snakeorm/migration/squash.py +60 -0
- snakeorm/migration/state.py +107 -0
- snakeorm/model.py +162 -0
- snakeorm/py.typed +0 -0
- snakeorm/query/__init__.py +9 -0
- snakeorm/query/compound.py +288 -0
- snakeorm/query/join_kind.py +19 -0
- snakeorm/query/joined.py +143 -0
- snakeorm/query/query.py +1001 -0
- snakeorm/query/recursive.py +244 -0
- snakeorm/registry/__init__.py +5 -0
- snakeorm/registry/by_module.py +163 -0
- snakeorm/registry/registry.py +166 -0
- snakeorm/session/__init__.py +8 -0
- snakeorm/session/asyncsession.py +638 -0
- snakeorm/session/coercion.py +306 -0
- snakeorm/session/factory.py +29 -0
- snakeorm/session/guards.py +269 -0
- snakeorm/session/isolation.py +23 -0
- snakeorm/session/mapper.py +213 -0
- snakeorm/session/planning.py +815 -0
- snakeorm/session/retry.py +96 -0
- snakeorm/session/session.py +871 -0
- snakeorm/session/shared.py +355 -0
- snakeorm/sql/__init__.py +18 -0
- snakeorm/sql/adapt.py +104 -0
- snakeorm/sql/aggregate.py +232 -0
- snakeorm/sql/condition.py +359 -0
- snakeorm/sql/delete.py +46 -0
- snakeorm/sql/insert.py +149 -0
- snakeorm/sql/joins.py +158 -0
- snakeorm/sql/pk_subquery.py +54 -0
- snakeorm/sql/refs.py +19 -0
- snakeorm/sql/resolver.py +28 -0
- snakeorm/sql/select.py +175 -0
- snakeorm/sql/update.py +82 -0
- snakeorm/sql/value.py +552 -0
- snakeorm/times.py +276 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Migration apply order BY FK DEPENDENCY: the one creating a table goes BEFORE the one referencing
|
|
2
|
+
it.
|
|
3
|
+
|
|
4
|
+
The dependency is DERIVED from the FKs (the `target_table` serialised into the migration), NOT
|
|
5
|
+
declared by hand as in Django. It exists for PER-DOMAIN migrations (several directories, each
|
|
6
|
+
numbering from `0001`): all of them are loaded and ordered so that `accounts` (which creates `users`)
|
|
7
|
+
comes before `blog` (which references it), and so on. A reference to a table that no migration in the
|
|
8
|
+
set creates (it already exists) imposes no order.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from snakeorm.core.exceptions import SnakeMigrationError
|
|
14
|
+
from snakeorm.metadata import SnakeRelationshipKind
|
|
15
|
+
from snakeorm.migration.operations import CreateTable
|
|
16
|
+
from snakeorm.migration.runner import Migration
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _created(migration: Migration) -> set[str]:
|
|
20
|
+
"""Tables this migration CREATES."""
|
|
21
|
+
return {op.table.name for op in migration.operations if isinstance(op, CreateTable)}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _referenced(migration: Migration) -> set[str]:
|
|
25
|
+
"""Tables the FKs of this migration REFERENCE (by `target_table`, without the schema).
|
|
26
|
+
|
|
27
|
+
Only TO_ONE counts: it is this table that CARRIES the FK, so it depends on the target. A TO_MANY is
|
|
28
|
+
the INVERSE relation (the FK lives in the other table), so it imposes NO dependency here — counting
|
|
29
|
+
it would introduce cycles (accounts.User.posts <-> blog.Post.author).
|
|
30
|
+
"""
|
|
31
|
+
refs: set[str] = set()
|
|
32
|
+
for op in migration.operations:
|
|
33
|
+
if isinstance(op, CreateTable):
|
|
34
|
+
for relationship in op.table.relationships:
|
|
35
|
+
if (
|
|
36
|
+
relationship.kind is SnakeRelationshipKind.TO_ONE
|
|
37
|
+
and relationship.target_table
|
|
38
|
+
):
|
|
39
|
+
refs.add(relationship.target_table.rpartition(".")[2])
|
|
40
|
+
return refs
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def dependency_order(migrations: list[Migration]) -> list[Migration]:
|
|
44
|
+
"""Orders migrations so each one comes AFTER those creating the tables it references.
|
|
45
|
+
|
|
46
|
+
DFS with cycle detection; stable output (it starts in version order). References to tables that no
|
|
47
|
+
migration in the set creates (already existing ones) impose no order.
|
|
48
|
+
"""
|
|
49
|
+
creator: dict[str, Migration] = {}
|
|
50
|
+
for migration in migrations:
|
|
51
|
+
for table in _created(migration):
|
|
52
|
+
creator[table] = migration
|
|
53
|
+
|
|
54
|
+
ordered: list[Migration] = []
|
|
55
|
+
visited: set[str] = set()
|
|
56
|
+
visiting: set[str] = set()
|
|
57
|
+
|
|
58
|
+
def visit(migration: Migration) -> None:
|
|
59
|
+
if migration.version in visited:
|
|
60
|
+
return
|
|
61
|
+
if migration.version in visiting:
|
|
62
|
+
raise SnakeMigrationError(
|
|
63
|
+
f"Dependency cycle among migrations: '{migration.version}' depends (through an "
|
|
64
|
+
f"FK, directly or indirectly) on itself. Review the cross-domain relationships."
|
|
65
|
+
)
|
|
66
|
+
visiting.add(migration.version)
|
|
67
|
+
created = _created(migration)
|
|
68
|
+
for ref in sorted(_referenced(migration)):
|
|
69
|
+
target = creator.get(ref)
|
|
70
|
+
if target is not None and ref not in created:
|
|
71
|
+
visit(target)
|
|
72
|
+
visiting.discard(migration.version)
|
|
73
|
+
visited.add(migration.version)
|
|
74
|
+
ordered.append(migration)
|
|
75
|
+
|
|
76
|
+
for migration in sorted(migrations, key=lambda m: m.version):
|
|
77
|
+
visit(migration)
|
|
78
|
+
return ordered
|
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
"""Landing an (engine-agnostic) migration plan on a concrete engine.
|
|
2
|
+
|
|
3
|
+
The mismatch between what the plan asks for and the SHAPE each engine accepts is resolved HERE, in
|
|
4
|
+
one single place (not with an `if dialect...` inside every `up_sql`). The oldest translation is
|
|
5
|
+
SQLite's FKs (`supports_add_constraint=False`): if the table is born in this plan, its FK already
|
|
6
|
+
travelled inside the `CREATE TABLE` and the `AddForeignKey` is redundant; if it already existed,
|
|
7
|
+
SQLite cannot add it and that is SAID out loud (a green plan that leaves the database without the
|
|
8
|
+
declared integrity is worse than one that refuses).
|
|
9
|
+
|
|
10
|
+
There are two kinds of gate, and mixing them is what this file keeps apart:
|
|
11
|
+
|
|
12
|
+
- `_guard_capability` reads a TABLE of operation -> capability. It can only say "always": the
|
|
13
|
+
operation needs the capability whatever it carries.
|
|
14
|
+
- `_guard_partial_index` is CONDITIONAL — the same `CreateIndex` is fine or refused depending on the
|
|
15
|
+
index inside it, so it cannot be a row in that table without refusing every index on MySQL. The
|
|
16
|
+
sentence above applies twice over: a partial UNIQUE silently widened into a full one is a green
|
|
17
|
+
plan that leaves the database enforcing a rule the model never declared.
|
|
18
|
+
- `_guard_dropped_fk_column` is conditional on the PLAN, which is one step further out: the same
|
|
19
|
+
`DropColumn` is fine or refused depending on whether an earlier operation already took the
|
|
20
|
+
foreign key out of the way. Nothing about the operation on its own can answer that.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from collections.abc import Sequence
|
|
26
|
+
|
|
27
|
+
from snakeorm.dialects import SnakeDialect
|
|
28
|
+
from snakeorm.dialects.capabilities import Cap, Nope
|
|
29
|
+
from snakeorm.core.exceptions import SnakeMigrationError
|
|
30
|
+
from snakeorm.migration.ddl import foreign_key_name, inlined_foreign_keys
|
|
31
|
+
from snakeorm.metadata import (
|
|
32
|
+
SnakeIndexInfo,
|
|
33
|
+
SnakeRelationshipInfo,
|
|
34
|
+
SnakeRelationshipKind,
|
|
35
|
+
SnakeTableInfo,
|
|
36
|
+
)
|
|
37
|
+
from snakeorm.migration.operations import (
|
|
38
|
+
AddCheck,
|
|
39
|
+
AddForeignKey,
|
|
40
|
+
AlterColumn,
|
|
41
|
+
AlterFunction,
|
|
42
|
+
AlterTableComment,
|
|
43
|
+
AlterView,
|
|
44
|
+
CreateFunction,
|
|
45
|
+
CreateIndex,
|
|
46
|
+
CreateSchema,
|
|
47
|
+
CreateTable,
|
|
48
|
+
CreateView,
|
|
49
|
+
DropCheck,
|
|
50
|
+
DropColumn,
|
|
51
|
+
DropForeignKey,
|
|
52
|
+
DropFunction,
|
|
53
|
+
DropSchema,
|
|
54
|
+
DropTable,
|
|
55
|
+
DropView,
|
|
56
|
+
RebuildTable,
|
|
57
|
+
SnakeMigrationOperation,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def realize(
|
|
62
|
+
operations: Sequence[SnakeMigrationOperation], dialect: SnakeDialect
|
|
63
|
+
) -> list[SnakeMigrationOperation]:
|
|
64
|
+
"""Returns the plan exactly as it must be applied on this engine.
|
|
65
|
+
|
|
66
|
+
With `supports_add_constraint` it returns the SAME plan untouched. It serves both directions: the
|
|
67
|
+
`CreateTable`/`DropTable` pair covers them (if the table is born or dies here, its FK goes with
|
|
68
|
+
it).
|
|
69
|
+
"""
|
|
70
|
+
created = {
|
|
71
|
+
operation.table.name
|
|
72
|
+
for operation in operations
|
|
73
|
+
if isinstance(operation, CreateTable | DropTable)
|
|
74
|
+
}
|
|
75
|
+
plan: list[SnakeMigrationOperation] = []
|
|
76
|
+
# Grows AS THE PLAN IS WALKED, and that is the point: a `DropForeignKey` only clears the way for
|
|
77
|
+
# a `DropColumn` that comes AFTER it. A set built up front would accept the two in the wrong
|
|
78
|
+
# order, which is precisely the order the server refuses.
|
|
79
|
+
keys_already_dropped: set[tuple[str, str]] = set()
|
|
80
|
+
for operation in operations:
|
|
81
|
+
_guard_capability(operation, dialect)
|
|
82
|
+
_guard_partial_index(operation, dialect)
|
|
83
|
+
_guard_dropped_fk_column(operation, dialect, keys_already_dropped)
|
|
84
|
+
if isinstance(operation, DropForeignKey):
|
|
85
|
+
keys_already_dropped.update(
|
|
86
|
+
_held_columns(operation.table, operation.relationship)
|
|
87
|
+
)
|
|
88
|
+
if isinstance(operation, RebuildTable):
|
|
89
|
+
# A rebuild that leaves a key behind has REMOVED it, as surely as a `DropForeignKey`
|
|
90
|
+
# would have. Not counting it here would refuse a plan that is correct — the guard's
|
|
91
|
+
# whole job is telling "the key is still standing" from "somebody already took it out",
|
|
92
|
+
# and a rebuild is the other way of taking it out on the engine that has no other.
|
|
93
|
+
keys_already_dropped.update(_keys_removed_by(operation))
|
|
94
|
+
if not dialect.supports_replace_view and isinstance(operation, AlterView):
|
|
95
|
+
# Without `CREATE OR REPLACE VIEW`, altering a view means dropping and creating it. The
|
|
96
|
+
# plan is rewritten here (not in the emitter, which knows nothing about engines).
|
|
97
|
+
plan.extend((DropView(operation.old), CreateView(operation.new)))
|
|
98
|
+
continue
|
|
99
|
+
if dialect.supports_add_constraint or not isinstance(
|
|
100
|
+
operation, AddForeignKey | DropForeignKey
|
|
101
|
+
):
|
|
102
|
+
plan.append(operation)
|
|
103
|
+
continue
|
|
104
|
+
if operation.table.name not in created:
|
|
105
|
+
carries = (
|
|
106
|
+
"carries" if isinstance(operation, AddForeignKey) else "leaves out"
|
|
107
|
+
)
|
|
108
|
+
raise SnakeMigrationError(
|
|
109
|
+
f"The foreign key '{operation.relationship.name}' of table "
|
|
110
|
+
f"'{operation.table.name}' cannot be applied: this engine does not know how to "
|
|
111
|
+
f"add constraints to an existing table (`ALTER TABLE ... ADD CONSTRAINT`), so the "
|
|
112
|
+
f"table has to be remade around the key. The ORM owns that operation: a "
|
|
113
|
+
f"`RebuildTable` creates the new table with the right constraints inside, copies "
|
|
114
|
+
f"the rows, drops the old one and renames — and the autodetected migration writes "
|
|
115
|
+
f"one by itself when the constraints are the table's ONLY change. Reaching this "
|
|
116
|
+
f"`{type(operation).__name__}` means the plan was written by hand, or the same "
|
|
117
|
+
f"migration also moves a column, an index or the table comment: split those into "
|
|
118
|
+
f"their own migration, or replace this operation with a `RebuildTable` whose "
|
|
119
|
+
f"`after` {carries} '{operation.relationship.name}'."
|
|
120
|
+
)
|
|
121
|
+
if operation.relationship not in inlined_foreign_keys(operation.table, dialect):
|
|
122
|
+
raise SnakeMigrationError(
|
|
123
|
+
f"The foreign key '{operation.relationship.name}' of table "
|
|
124
|
+
f"'{operation.table.name}' has no resolved target (`target_table` is empty), so it "
|
|
125
|
+
f"could not be written inside the `CREATE TABLE` and this engine does not accept "
|
|
126
|
+
f"adding it afterwards. Check that `snake_link()` ran before the migration was "
|
|
127
|
+
f"generated."
|
|
128
|
+
)
|
|
129
|
+
return plan
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# Operation -> (the capability enabling it, the reason if the engine lacks it). It is a TABLE and not
|
|
133
|
+
# a chain of `if`s so it can be read at a glance and checked that every plan capability appears here
|
|
134
|
+
# (otherwise it stays declared but unread, as `supports_add_constraint` was for months).
|
|
135
|
+
#
|
|
136
|
+
# The capability goes in as a member of `Cap` and NOT as the flag's name in a string, which is how it
|
|
137
|
+
# used to be. With the string, `getattr(dialect, flag)` resolved at run time: renaming or moving a
|
|
138
|
+
# flag broke nothing at compile time, and this table went on asking about something that no longer
|
|
139
|
+
# existed. `AlterColumn` came to be the only place `supports_alter_column` was read, and it was here,
|
|
140
|
+
# inside a string.
|
|
141
|
+
_REQUIREMENTS: tuple[tuple[type, Cap, str], ...] = (
|
|
142
|
+
(
|
|
143
|
+
CreateSchema,
|
|
144
|
+
Cap.SCHEMAS,
|
|
145
|
+
# It names TWO edits, and the second is the one that unblocks anything. The advice used to
|
|
146
|
+
# stop at "drop the `schema=` from the models", which does not move what is being refused:
|
|
147
|
+
# the `CreateSchema` in front of the runner comes out of a migration FILE, already written
|
|
148
|
+
# and sitting on disk. Editing the models only changes what the NEXT autodetect emits, so
|
|
149
|
+
# the reader follows the instruction, runs the migration again and meets the same sentence.
|
|
150
|
+
"this engine has no named schemas (SQLite's are ATTACHED databases, a different thing). "
|
|
151
|
+
"Drop the `schema=` from the models this connection serves AND regenerate the migration "
|
|
152
|
+
"that carries this `CreateSchema`: editing the models only changes what the next "
|
|
153
|
+
"autodetect writes, and the file the runner is holding is still on disk.",
|
|
154
|
+
),
|
|
155
|
+
(
|
|
156
|
+
DropSchema,
|
|
157
|
+
Cap.SCHEMAS,
|
|
158
|
+
# The same two edits as its twin above, and it used to give neither. "There is none to drop"
|
|
159
|
+
# is a true fact about the engine and no answer at all to the person holding the file: their
|
|
160
|
+
# migration still carries the operation, and reading that the schema was never there does
|
|
161
|
+
# not tell them what to do about the line in front of them.
|
|
162
|
+
"this engine has no named schemas, so there is none to drop. Drop the `schema=` from the "
|
|
163
|
+
"models this connection serves AND regenerate the migration that carries this "
|
|
164
|
+
"`DropSchema`: editing the models only changes what the next autodetect writes, and the "
|
|
165
|
+
"file the runner is holding is still on disk.",
|
|
166
|
+
),
|
|
167
|
+
(
|
|
168
|
+
AlterColumn,
|
|
169
|
+
Cap.ALTER_COLUMN,
|
|
170
|
+
# The one entry that really does end at `RunSQL`, and it says so on purpose now that its
|
|
171
|
+
# neighbours point at `RebuildTable`: that operation refuses a pair of snapshots disagreeing
|
|
172
|
+
# about a column (its `__post_init__` names the fields), because SQLite would apply the
|
|
173
|
+
# difference and Postgres would not. So there is no ORM-owned door here, and sending the
|
|
174
|
+
# reader to try one would cost them a run to find out.
|
|
175
|
+
"this engine does not know how to alter an existing column. On SQLite the table has to be "
|
|
176
|
+
"rebuilt (create the new one, copy the rows, drop the old one and rename), and this is the "
|
|
177
|
+
"one case the ORM does NOT do for you: `RebuildTable` only carries constraints and refuses "
|
|
178
|
+
"a pair that disagrees about a column, so do it with an explicit `RunSQL`.",
|
|
179
|
+
),
|
|
180
|
+
(
|
|
181
|
+
AddCheck,
|
|
182
|
+
Cap.CHECK_CONSTRAINT_DDL,
|
|
183
|
+
# It EXPLAINS, like its `DropCheck` twin below, and it points at the door the ORM OWNS:
|
|
184
|
+
# `RebuildTable` is an operation this module imports, and `diff_schema` collapses a pure
|
|
185
|
+
# constraint change into one. A refusal that names a closed door costs the reader a run.
|
|
186
|
+
"this engine does not know how to add a constraint to an existing table: a CHECK can only "
|
|
187
|
+
"travel inside the `CREATE TABLE`, so putting one on a table that is already there takes "
|
|
188
|
+
"rebuilding the whole table (create the new one with the CHECK inside, copy the rows, drop "
|
|
189
|
+
"the old one and rename). The ORM owns that: it is `RebuildTable`, and the autodetected "
|
|
190
|
+
"migration writes one whenever the constraints are the table's ONLY change. Reaching this "
|
|
191
|
+
"`AddCheck` means it was written by hand, or the same migration also moves a column, "
|
|
192
|
+
"an index or the table comment: split those into their own migration, or replace this "
|
|
193
|
+
"operation with the `RebuildTable`.",
|
|
194
|
+
),
|
|
195
|
+
(
|
|
196
|
+
DropCheck,
|
|
197
|
+
Cap.CHECK_CONSTRAINT_DDL,
|
|
198
|
+
"this engine does not know how to drop a constraint from an existing table: it would take "
|
|
199
|
+
"rebuilding the whole table, which is what `RebuildTable` does and what the autodetected "
|
|
200
|
+
"migration emits when the constraints are the table's ONLY change.",
|
|
201
|
+
),
|
|
202
|
+
# Both used to ask about `supports_schemas`, which is not the same thing: an engine can store
|
|
203
|
+
# functions and have no schemas. It coincided across all three engines, so it worked and nobody
|
|
204
|
+
# saw it; the catalogue exposed it by demanding STORED_FUNCTIONS have a reader of its own.
|
|
205
|
+
(
|
|
206
|
+
CreateFunction,
|
|
207
|
+
Cap.STORED_FUNCTIONS,
|
|
208
|
+
"this engine has no stored functions for a migration to create. The body of a "
|
|
209
|
+
"`snake_function` is written in its engine's dialect, so it was never portable.",
|
|
210
|
+
),
|
|
211
|
+
(
|
|
212
|
+
DropFunction,
|
|
213
|
+
Cap.STORED_FUNCTIONS,
|
|
214
|
+
"this engine has no stored functions for a migration to drop.",
|
|
215
|
+
),
|
|
216
|
+
# The THIRD member of the family, and it was missing while its two brothers were here. A plan
|
|
217
|
+
# that alters a function was accepted on engines with no stored functions at all, and the driver
|
|
218
|
+
# was what explained it — at apply time, on somebody's deploy.
|
|
219
|
+
(
|
|
220
|
+
AlterFunction,
|
|
221
|
+
Cap.STORED_FUNCTIONS,
|
|
222
|
+
"this engine has no stored functions for a migration to alter.",
|
|
223
|
+
),
|
|
224
|
+
# The reason used to name MySQL as one of the engines that cannot, and it was FALSE: measured,
|
|
225
|
+
# MariaDB stores the comment and `ALTER TABLE t COMMENT = 'x'` replaces it. The dialect had
|
|
226
|
+
# confused "it spells it differently" with "it cannot", so this refusal was firing on an engine
|
|
227
|
+
# that does the job — with a sentence, "there is no comment to change", that was not true of it.
|
|
228
|
+
# Only the engine the sentence was always true about is left.
|
|
229
|
+
(
|
|
230
|
+
AlterTableComment,
|
|
231
|
+
Cap.COMMENTS,
|
|
232
|
+
"this engine stores no comment at all, so there is no comment to change. It is not a "
|
|
233
|
+
"question of spelling: MySQL writes it as a clause instead of a statement and the dialect "
|
|
234
|
+
"translates that, but SQLite has nowhere to put one.",
|
|
235
|
+
),
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
_INDEX_CREATORS: tuple[type, ...] = (CreateIndex, CreateTable)
|
|
240
|
+
"""The operations that put an index INTO the database. Two, and the second is the easy one to miss.
|
|
241
|
+
|
|
242
|
+
`CreateIndex` carries one explicitly; `CreateTable` emits the whole table's indexes inline, and that
|
|
243
|
+
is the path a first migration takes — and the one the demos' bootstrap takes. A guard that only knew
|
|
244
|
+
about `CreateIndex` would report itself green over the case that actually breaks.
|
|
245
|
+
|
|
246
|
+
It is a tuple and not an `isinstance` chain buried inside the function so that
|
|
247
|
+
`test_the_guard_sees_every_operation_that_creates_an_index` can compare it against the operations
|
|
248
|
+
that really emit a `CREATE INDEX`, read out of their own source. This guard is CONDITIONAL —it
|
|
249
|
+
depends on the index carried, not on the operation's type— so it cannot live in `_REQUIREMENTS`, and
|
|
250
|
+
`test_every_operation_declares_its_capability` cannot see it. Something had to.
|
|
251
|
+
"""
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _created_indexes(
|
|
255
|
+
operation: SnakeMigrationOperation,
|
|
256
|
+
) -> tuple[tuple[SnakeTableInfo, SnakeIndexInfo], ...]:
|
|
257
|
+
"""Every (table, index) pair this operation would create, whichever shape it carries them in."""
|
|
258
|
+
if isinstance(operation, CreateIndex):
|
|
259
|
+
return ((operation.table, operation.index),)
|
|
260
|
+
if isinstance(operation, CreateTable):
|
|
261
|
+
return tuple((operation.table, index) for index in operation.table.indexes)
|
|
262
|
+
return ()
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _guard_partial_index(
|
|
266
|
+
operation: SnakeMigrationOperation, dialect: SnakeDialect
|
|
267
|
+
) -> None:
|
|
268
|
+
"""Stops a partial UNIQUE index where the engine has no partial indexes, and lets a search one by.
|
|
269
|
+
|
|
270
|
+
ONE capability, TWO behaviours, because they are not the same decision:
|
|
271
|
+
|
|
272
|
+
- A SEARCH partial index is an OPTIMISATION. Emitting it over the whole table finds the same
|
|
273
|
+
rows and stores the same bytes; what it costs is space and a little write time. That is a
|
|
274
|
+
degradation of exactly the kind this catalogue exists to declare, `emit_create_index` performs
|
|
275
|
+
it by dropping the `WHERE`, and the session announces the reason once.
|
|
276
|
+
- A partial UNIQUE index is INTEGRITY. Widening `UNIQUE(email) WHERE deleted_at IS NULL` into
|
|
277
|
+
`UNIQUE(email)` forbids rows the domain allows — re-registering a soft-deleted address stops
|
|
278
|
+
working — and dropping the uniqueness instead leaves the database without a rule the model
|
|
279
|
+
declares. No warning repairs either, so it stops here.
|
|
280
|
+
|
|
281
|
+
`Cap` does not tell the two apart and should not: it describes the ENGINE, which has exactly one
|
|
282
|
+
gap. What tells them apart is the index's own `unique`, already in the metadata.
|
|
283
|
+
"""
|
|
284
|
+
if dialect.capabilities.can(Cap.PARTIAL_INDEXES):
|
|
285
|
+
return
|
|
286
|
+
for table, index in _created_indexes(operation):
|
|
287
|
+
if index.where is None or not index.unique:
|
|
288
|
+
continue
|
|
289
|
+
raise SnakeMigrationError(
|
|
290
|
+
f"The partial UNIQUE index '{index.resolved_name(table.name)}' of table "
|
|
291
|
+
f"'{table.name}' cannot be applied: this engine has no partial indexes, so there is no "
|
|
292
|
+
f"way to say 'unique only among these rows'. It is NOT degraded to a full UNIQUE the "
|
|
293
|
+
f"way a search index is: that would forbid duplicates the domain allows, which is a "
|
|
294
|
+
f"different schema and not a slower one. Either drop the `unique=True` (leaving the "
|
|
295
|
+
f"index as a search one, which this engine does support), or express the rule with a "
|
|
296
|
+
f"generated column plus a plain UNIQUE over it in a `RunSQL`."
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _held_columns(
|
|
301
|
+
table: SnakeTableInfo, relationship: SnakeRelationshipInfo
|
|
302
|
+
) -> set[tuple[str, str]]:
|
|
303
|
+
"""The `(table, column)` pairs this to-one foreign key HOLDS on the near side.
|
|
304
|
+
|
|
305
|
+
The near side and not the far one: what an engine refuses to drop is the column the constraint
|
|
306
|
+
is declared ON. Compound keys hold several, which is why it is a set and not one name — the
|
|
307
|
+
project's rule that a simple and a compound key share one structure lands here too.
|
|
308
|
+
"""
|
|
309
|
+
return {(table.name, local) for local, _ in relationship.foreign_key.pairs}
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _keys_removed_by(operation: RebuildTable) -> set[tuple[str, str]]:
|
|
313
|
+
"""The `(table, column)` pairs whose foreign key the rebuild leaves behind.
|
|
314
|
+
|
|
315
|
+
Compared by relation NAME, which is what `foreign_key_name` derives the constraint's name from:
|
|
316
|
+
the same key with another shape is still the same constraint, and the rebuild replaces it rather
|
|
317
|
+
than removing it.
|
|
318
|
+
"""
|
|
319
|
+
surviving = {
|
|
320
|
+
relationship.name
|
|
321
|
+
for relationship in operation.after.relationships
|
|
322
|
+
if relationship.kind is SnakeRelationshipKind.TO_ONE
|
|
323
|
+
}
|
|
324
|
+
removed: set[tuple[str, str]] = set()
|
|
325
|
+
for relationship in operation.before.relationships:
|
|
326
|
+
if relationship.kind is not SnakeRelationshipKind.TO_ONE:
|
|
327
|
+
continue
|
|
328
|
+
if relationship.name in surviving:
|
|
329
|
+
continue
|
|
330
|
+
removed.update(_held_columns(operation.before, relationship))
|
|
331
|
+
return removed
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _guard_dropped_fk_column(
|
|
335
|
+
operation: SnakeMigrationOperation,
|
|
336
|
+
dialect: SnakeDialect,
|
|
337
|
+
keys_already_dropped: set[tuple[str, str]],
|
|
338
|
+
) -> None:
|
|
339
|
+
"""Stops a `DropColumn` over a column whose foreign key is still standing, where it must.
|
|
340
|
+
|
|
341
|
+
MEASURED on the three engines, with the same statement over the same shape:
|
|
342
|
+
|
|
343
|
+
- PostgreSQL takes it and the constraint falls with the column, so nothing is guarded here.
|
|
344
|
+
- MySQL/MariaDB answer error 1553: InnoDB will not lose the index the key sits on. The way out
|
|
345
|
+
is a `DropForeignKey` one operation earlier, which the ORM's own diff already emits.
|
|
346
|
+
- SQLite answers "unknown column ... in foreign key definition", and it has no `DROP
|
|
347
|
+
CONSTRAINT` to put in front, so the way out there is a `RebuildTable` that leaves the key
|
|
348
|
+
behind — which the loop above already counts as having removed it.
|
|
349
|
+
|
|
350
|
+
SO THE ADVICE IS PER ENGINE: telling a SQLite reader to put a `DropForeignKey` first sends them
|
|
351
|
+
to an operation this very module refuses a few lines up, for lack of `Cap.ADD_CONSTRAINT`.
|
|
352
|
+
|
|
353
|
+
It is NOT translated into an invented `DropForeignKey`. The reverse of dropping a key is adding
|
|
354
|
+
it back, and that needs the target table — which this operation does not carry and must not be
|
|
355
|
+
made to guess; a synthesised key would apply green and leave the rollback writing a constraint
|
|
356
|
+
pointing nowhere. So the plan stops and names what is missing, in the ORM's own vocabulary.
|
|
357
|
+
|
|
358
|
+
The guard reads the operation's OWN table: after the diff has run, the relation is gone from the
|
|
359
|
+
desired table and the plan already carries the `DropForeignKey`, so it says nothing. What it
|
|
360
|
+
catches is the plan written by hand — or generated somewhere the key was lost — which is the
|
|
361
|
+
only place a naked drop can still reach a server.
|
|
362
|
+
"""
|
|
363
|
+
if not isinstance(operation, DropColumn):
|
|
364
|
+
return
|
|
365
|
+
# `isinstance(..., Nope)` and not `not can(...)`: the two ask the same question, and this one
|
|
366
|
+
# also narrows the answer to the branch that HAS a `reason`, which the MySQL message quotes.
|
|
367
|
+
# Asking with `can()` would leave the reason reachable only through a cast.
|
|
368
|
+
#
|
|
369
|
+
# Only the MySQL branch quotes it, and that is deliberate rather than an oversight: SQLite's
|
|
370
|
+
# reason ends by sending the reader to a hand-written `RunSQL`, which is the sentence this pass
|
|
371
|
+
# exists to stop repeating. Quoting it under an answer that names `RebuildTable` would put the
|
|
372
|
+
# two doors in one paragraph and make the reader pick. The reason itself is worth fixing where
|
|
373
|
+
# it lives, in `dialects/sqlite.py`; until then this branch says the limit in its own words.
|
|
374
|
+
support = dialect.capabilities.support_for(Cap.DROP_COLUMN_CASCADES_FK)
|
|
375
|
+
if not isinstance(support, Nope):
|
|
376
|
+
return
|
|
377
|
+
for relationship in operation.table.relationships:
|
|
378
|
+
if relationship.kind is not SnakeRelationshipKind.TO_ONE:
|
|
379
|
+
continue
|
|
380
|
+
held = _held_columns(operation.table, relationship)
|
|
381
|
+
if (operation.table.name, operation.column.name) not in held:
|
|
382
|
+
continue
|
|
383
|
+
if held <= keys_already_dropped:
|
|
384
|
+
continue
|
|
385
|
+
name = foreign_key_name(operation.table, relationship)
|
|
386
|
+
if dialect.capabilities.can(Cap.ADD_CONSTRAINT):
|
|
387
|
+
raise SnakeMigrationError(
|
|
388
|
+
f"The column '{operation.column.name}' of table '{operation.table.name}' cannot "
|
|
389
|
+
f"be dropped: the foreign key '{name}' still holds it, and this engine refuses to "
|
|
390
|
+
f"drop a column while its key is standing — {support.reason}. "
|
|
391
|
+
f"Put a `DropForeignKey` for '{relationship.name}' BEFORE this `DropColumn`: that "
|
|
392
|
+
f"is what the autodetected migration does, and it is also what makes the rollback "
|
|
393
|
+
f"able to put the key back."
|
|
394
|
+
)
|
|
395
|
+
raise SnakeMigrationError(
|
|
396
|
+
f"The column '{operation.column.name}' of table '{operation.table.name}' cannot be "
|
|
397
|
+
f"dropped: the foreign key '{name}' still holds it, and this engine refuses to drop a "
|
|
398
|
+
f"column that a foreign key names. A `DropForeignKey` in front does NOT open this "
|
|
399
|
+
f"door — the same engine has no `ALTER TABLE ... DROP CONSTRAINT`, so that operation "
|
|
400
|
+
f"is refused too, and the plan would stop in both of its halves. What works here is "
|
|
401
|
+
f"remaking the table around the key: put a `RebuildTable` whose `after` no longer "
|
|
402
|
+
f"carries '{relationship.name}' BEFORE this `DropColumn`, and the column comes free "
|
|
403
|
+
f"with its rows intact."
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _guard_capability(
|
|
408
|
+
operation: SnakeMigrationOperation, dialect: SnakeDialect
|
|
409
|
+
) -> None:
|
|
410
|
+
"""Stops at the PLAN whatever the engine cannot do, saying what it is and what the way out is.
|
|
411
|
+
|
|
412
|
+
It fails at GENERATION time (before deploying), not with a cryptic `syntax error` from the engine.
|
|
413
|
+
It does NOT translate on its own initiative: rebuilding a table to simulate an `ALTER COLUMN` puts
|
|
414
|
+
data at risk, and that is the user's call.
|
|
415
|
+
"""
|
|
416
|
+
for kind, cap, reason in _REQUIREMENTS:
|
|
417
|
+
if isinstance(operation, kind) and not dialect.capabilities.can(cap):
|
|
418
|
+
raise SnakeMigrationError(
|
|
419
|
+
f"The operation {type(operation).__name__} cannot be applied: {reason}"
|
|
420
|
+
)
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""What the generator FLAGS for the person in front of it. It suggests; it does not decide.
|
|
2
|
+
|
|
3
|
+
The file is named after the first of them and now holds three, which is worth saying rather than
|
|
4
|
+
leaving for the next reader to discover: possible column renames, narrowing type changes, and a
|
|
5
|
+
destructive operation under standing views. They belong together because they share one rule —
|
|
6
|
+
each one is emitted at GENERATION time, when there is somebody there to read it, and none of them
|
|
7
|
+
edits the plan. A heuristic that decides on its own will, the day it gets it wrong, move data into
|
|
8
|
+
the wrong column in silence.
|
|
9
|
+
|
|
10
|
+
A rename reaches the diff as `DropColumn` + `AddColumn` (correct but catastrophic: it deletes the
|
|
11
|
+
data). The diff is not corrected here, it is only flagged so a human can write a `RenameColumn`.
|
|
12
|
+
That is also why it stays quiet in the face of AMBIGUITY (several candidates of the same type).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from collections.abc import Sequence
|
|
18
|
+
|
|
19
|
+
from snakeorm.dialects import PostgresDialect
|
|
20
|
+
from snakeorm.metadata import SnakeTableInfo
|
|
21
|
+
from snakeorm.migration.ddl import sql_type_of
|
|
22
|
+
from snakeorm.migration.operations import (
|
|
23
|
+
AddColumn,
|
|
24
|
+
AlterColumn,
|
|
25
|
+
DropColumn,
|
|
26
|
+
DropTable,
|
|
27
|
+
RebuildTable,
|
|
28
|
+
SnakeMigrationOperation,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
# (table, old name, new name)
|
|
32
|
+
RenameSuggestion = tuple[str, str, str]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def rename_suggestions(
|
|
36
|
+
operations: Sequence[SnakeMigrationOperation],
|
|
37
|
+
) -> list[RenameSuggestion]:
|
|
38
|
+
"""(drop, add) pairs of the SAME type and table that are probably a rename.
|
|
39
|
+
|
|
40
|
+
A suggestion only comes out when the pairing is UNAMBIGUOUS: exactly one dropped column and one
|
|
41
|
+
added column of that type in that table. With more candidates, silence.
|
|
42
|
+
"""
|
|
43
|
+
dropped: dict[tuple[str, type], list[str]] = {}
|
|
44
|
+
added: dict[tuple[str, type], list[str]] = {}
|
|
45
|
+
|
|
46
|
+
for operation in operations:
|
|
47
|
+
if isinstance(operation, DropColumn):
|
|
48
|
+
key = (operation.table.name, operation.column.python_type)
|
|
49
|
+
dropped.setdefault(key, []).append(operation.column.name)
|
|
50
|
+
elif isinstance(operation, AddColumn):
|
|
51
|
+
key = (operation.table.name, operation.column.python_type)
|
|
52
|
+
added.setdefault(key, []).append(operation.column.name)
|
|
53
|
+
|
|
54
|
+
suggestions: list[RenameSuggestion] = []
|
|
55
|
+
for key, old_names in sorted(dropped.items(), key=lambda item: item[0][0]):
|
|
56
|
+
new_names = added.get(key, [])
|
|
57
|
+
if len(old_names) != 1 or len(new_names) != 1:
|
|
58
|
+
continue # ambiguous (or no counterpart): nothing is guessed
|
|
59
|
+
suggestions.append((key[0], old_names[0], new_names[0]))
|
|
60
|
+
return suggestions
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def format_rename_hint(suggestions: Sequence[RenameSuggestion]) -> str:
|
|
64
|
+
"""Message for the CLI with the suspected renames, or an empty string if there are none."""
|
|
65
|
+
if not suggestions:
|
|
66
|
+
return ""
|
|
67
|
+
lines = [
|
|
68
|
+
"Warning: this could be a RENAME, and as it stands it DELETES the old column's data.",
|
|
69
|
+
]
|
|
70
|
+
lines.extend(
|
|
71
|
+
f" - {table}: did you rename '{old}' to '{new}'? Replace its DropColumn + AddColumn "
|
|
72
|
+
f'with RenameColumn({table}, old_name="{old}", new_name="{new}").'
|
|
73
|
+
for table, old, new in suggestions
|
|
74
|
+
)
|
|
75
|
+
return "\n".join(lines)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def narrowing_warnings(operations: Sequence[SnakeMigrationOperation]) -> list[str]:
|
|
79
|
+
"""Type changes that NARROW the column and may not fit the existing rows.
|
|
80
|
+
|
|
81
|
+
Narrowing a `NUMERIC(12,2)` to `NUMERIC(10,2)` makes `migrate` fail if some row does not fit;
|
|
82
|
+
warning at GENERATION time beats finding out during the deploy. It only points, it does not
|
|
83
|
+
block: narrowing is usually intentional and safe.
|
|
84
|
+
"""
|
|
85
|
+
dialect = PostgresDialect()
|
|
86
|
+
warnings_: list[str] = []
|
|
87
|
+
for operation in operations:
|
|
88
|
+
if not isinstance(operation, AlterColumn):
|
|
89
|
+
continue
|
|
90
|
+
if (operation.old.precision or 0) <= (operation.new.precision or 0):
|
|
91
|
+
continue # not a narrowing: same width or wider
|
|
92
|
+
warnings_.append(
|
|
93
|
+
f"{operation.table.name}.{operation.new.name} narrows "
|
|
94
|
+
f"{sql_type_of(operation.old, dialect)} -> {sql_type_of(operation.new, dialect)}. "
|
|
95
|
+
f"Rows that do not fit will make the migrate fail. Check the data before applying it."
|
|
96
|
+
)
|
|
97
|
+
return warnings_
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def format_narrowing_hint(warnings_: Sequence[str]) -> str:
|
|
101
|
+
"""Message for the CLI with the detected narrowings, or an empty string if there are none."""
|
|
102
|
+
if not warnings_:
|
|
103
|
+
return ""
|
|
104
|
+
return "\n".join(f"Warning: {warning}" for warning in warnings_)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def standing_view_warning(
|
|
108
|
+
operations: Sequence[SnakeMigrationOperation],
|
|
109
|
+
state_tables: Sequence[SnakeTableInfo],
|
|
110
|
+
) -> str:
|
|
111
|
+
"""A plan that DESTROYS a table while views stand, stated as two facts and a question.
|
|
112
|
+
|
|
113
|
+
THE CONDITION IS DOUBLE, and that is what keeps it from becoming background noise. It takes a
|
|
114
|
+
destructive operation over a table — `RebuildTable` or `DropTable` — AND at least one view in
|
|
115
|
+
the replayed state. A migration that only adds a column says nothing even in a schema full of
|
|
116
|
+
views, and a migration that drops ten tables says nothing in a schema with no view.
|
|
117
|
+
|
|
118
|
+
THE TWO DESTRUCTIONS FAIL DIFFERENTLY, which is why both are in. A `RebuildTable` ends, on the
|
|
119
|
+
engine that cannot alter a constraint in place, in a `RENAME` that REPARSES the whole schema: a
|
|
120
|
+
view that reads the table makes it fail and the migration rolls back — loud, and at deploy time.
|
|
121
|
+
A `DropTable` is worse: SQLite resolves a view lazily, so the drop goes through and leaves the
|
|
122
|
+
view DANGLING. Nothing reports that until somebody queries it or the next rename reparses.
|
|
123
|
+
|
|
124
|
+
WHAT IT MAY NOT SAY IS WHICH VIEW READS WHICH TABLE, because it does not know. `depends_on` is
|
|
125
|
+
view->view only, `SnakeTableInfo` has no field naming the tables a view reads, and a view
|
|
126
|
+
declared with `sql=` is raw text. So the message states the two sets, says out loud that the
|
|
127
|
+
pairing is the reader's to make, and names what to write if it is real.
|
|
128
|
+
|
|
129
|
+
Returns an empty string when there is nothing to say.
|
|
130
|
+
"""
|
|
131
|
+
rebuilt = sorted(
|
|
132
|
+
{op.after.name for op in operations if isinstance(op, RebuildTable)}
|
|
133
|
+
)
|
|
134
|
+
dropped = sorted({op.table.name for op in operations if isinstance(op, DropTable)})
|
|
135
|
+
views = sorted({table.name for table in state_tables if table.is_view})
|
|
136
|
+
if not views or not (rebuilt or dropped):
|
|
137
|
+
return ""
|
|
138
|
+
destroyed: list[str] = []
|
|
139
|
+
if rebuilt:
|
|
140
|
+
destroyed.append(f"rebuilds {', '.join(rebuilt)}")
|
|
141
|
+
if dropped:
|
|
142
|
+
destroyed.append(f"drops {', '.join(dropped)}")
|
|
143
|
+
return (
|
|
144
|
+
f"This migration {' and '.join(destroyed)}, and the schema has these views standing: "
|
|
145
|
+
f"{', '.join(views)}. SnakeORM cannot tell you which of those views read those tables: "
|
|
146
|
+
f"nothing in the metadata says it — `depends_on` names other views only, and a view "
|
|
147
|
+
f"declared with `sql=` is raw text — so that pairing is yours to make. Read the view "
|
|
148
|
+
f"definitions. If one of them does read one of those tables, put a DropView of it BEFORE "
|
|
149
|
+
f"the operation and a CreateView of it AFTER, in this same file: a rebuild ends in a "
|
|
150
|
+
f"RENAME that reparses the whole schema and the migration will fail halfway, and a dropped "
|
|
151
|
+
f"table leaves the view standing but broken, which nothing reports until somebody queries "
|
|
152
|
+
f"it."
|
|
153
|
+
)
|