kd-migrate 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Robert Trad
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.4
2
+ Name: kd-migrate
3
+ Version: 0.1.0
4
+ Summary: Declarative PostgreSQL schema migrations: diff a live database against a schema.sql file and apply the changes
5
+ Keywords: postgresql,postgres,migration,schema,diff,database
6
+ Author: Robert Trad
7
+ Author-email: Robert Trad <roberttrad@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Database
20
+ Classifier: Topic :: Software Development :: Version Control
21
+ Requires-Dist: psycopg[binary]>=3.3,<4
22
+ Requires-Dist: results>=2.0.1789346060
23
+ Requires-Python: >=3.12
24
+ Project-URL: Homepage, https://github.com/rouppart/KD-Migrate
25
+ Project-URL: Source, https://github.com/rouppart/KD-Migrate
26
+ Project-URL: Issues, https://github.com/rouppart/KD-Migrate/issues
27
+ Description-Content-Type: text/markdown
28
+
29
+ # kd-migrate
30
+
31
+ Declarative schema migrations for PostgreSQL.
32
+
33
+ Write your whole schema as plain SQL in a `schema.sql` file. kd-migrate builds that schema in
34
+ a scratch database, compares it with your real database, and generates the `ALTER` / `CREATE`
35
+ / `DROP` statements needed to bring the real database in line. Then you choose whether to apply
36
+ them or save them to a file.
37
+
38
+ There are no migration files to write and no version table to maintain: `schema.sql` is
39
+ the source of truth.
40
+
41
+ The comparison is done by [results](https://pypi.org/project/results/).
42
+
43
+ ## Installation
44
+
45
+ ```bash
46
+ pip install kd-migrate
47
+ # or
48
+ uv tool install kd-migrate
49
+ ```
50
+
51
+ Requires Python 3.12+.
52
+
53
+ ## Quick start
54
+
55
+ 1. Create an empty **diff database**, which kd-migrate uses as a scratch area:
56
+
57
+ ```sql
58
+ CREATE DATABASE myapp_diff;
59
+ ```
60
+
61
+ > ⚠️ Every schema in the diff database except `public` is dropped each time kd-migrate
62
+ > runs. Never point `diffdb` at a database that holds data you care about.
63
+
64
+ 2. Write your schema in `schema.sql`, using named schemas rather than `public`:
65
+
66
+ ```sql
67
+ CREATE SCHEMA app;
68
+
69
+ CREATE TABLE app.customer (
70
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
71
+ name text NOT NULL,
72
+ email text UNIQUE
73
+ );
74
+ ```
75
+
76
+ The `public` schema of the diff database isn't cleared between runs, so objects created
77
+ there would still exist on the next run and `CREATE` would fail.
78
+
79
+ 3. Create a config file, for example `migrate.toml`, next to it:
80
+
81
+ ```toml
82
+ host = "localhost"
83
+ db = "myapp"
84
+ user = "postgres"
85
+ password = "secret"
86
+ diffdb = "myapp_diff"
87
+ ```
88
+
89
+ 4. Run it:
90
+
91
+ ```bash
92
+ kd-migrate migrate.toml
93
+ ```
94
+
95
+ kd-migrate prints the generated SQL and asks what to do:
96
+
97
+ ```
98
+ 1) Apply migration
99
+ 2) Write to migration.sql
100
+ 3) Cancel
101
+ ```
102
+
103
+ If the database already matches the schema, it prints `No migration needed.` and exits.
104
+
105
+ ## Configuration
106
+
107
+ The config file is TOML.
108
+
109
+ | Key | Required | Default | Description |
110
+ |----------------|----------|---------------------|----------------------------------------------------------------|
111
+ | `host` | yes | | Host of the database to migrate (`host` or `host:port`). |
112
+ | `db` | yes | | Name of the database to migrate. |
113
+ | `user` | yes | | User for the database to migrate. |
114
+ | `password` | yes | | Password for the database to migrate. |
115
+ | `diffdb` | yes | | Name of the scratch database the schema is built in. |
116
+ | `diffhost` | no | value of `host` | Host of the diff database. |
117
+ | `diffuser` | no | value of `user` | User for the diff database. |
118
+ | `diffpassword` | no | value of `password` | Password for the diff database. |
119
+ | `schema_sql` | no | `schema.sql` | Path to the schema file, relative to the config file's folder. |
120
+
121
+ Keep the config file out of version control if it contains real credentials.
122
+
123
+ ## Splitting the schema across files
124
+
125
+ `schema.sql` can include other files with psql's `\i` command. Relative paths are resolved
126
+ from the folder of the file doing the include, and includes can be nested:
127
+
128
+ ```sql
129
+ -- schema.sql
130
+ \i schemas/app.sql
131
+ \i schemas/billing.sql
132
+ ```
133
+
134
+ ## Options
135
+
136
+ ```
137
+ kd-migrate [-h] [--keep-fk-recreations] env_file
138
+ ```
139
+
140
+ - `env_file`: path to the TOML config file.
141
+ - `--keep-fk-recreations`: keep every foreign key drop and re-create statement that results
142
+ generates. By default, kd-migrate removes those statements for foreign keys that haven't
143
+ changed and can't be affected by the migration, such as when a column is only added to a
144
+ table. Foreign keys are still recreated when they need to be: the referenced key changed,
145
+ one of the tables is rebuilt, or the type, collation or enum of one of their columns changed.
146
+
147
+ ## Notes
148
+
149
+ - Review the generated SQL before applying it. Destructive statements such as
150
+ `DROP TABLE` and `DROP COLUMN` are included when the schema calls for them.
151
+ - "Write to migration.sql" writes the file to the current working directory.
152
+
153
+ ## License
154
+
155
+ [MIT](LICENSE)
@@ -0,0 +1,127 @@
1
+ # kd-migrate
2
+
3
+ Declarative schema migrations for PostgreSQL.
4
+
5
+ Write your whole schema as plain SQL in a `schema.sql` file. kd-migrate builds that schema in
6
+ a scratch database, compares it with your real database, and generates the `ALTER` / `CREATE`
7
+ / `DROP` statements needed to bring the real database in line. Then you choose whether to apply
8
+ them or save them to a file.
9
+
10
+ There are no migration files to write and no version table to maintain: `schema.sql` is
11
+ the source of truth.
12
+
13
+ The comparison is done by [results](https://pypi.org/project/results/).
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ pip install kd-migrate
19
+ # or
20
+ uv tool install kd-migrate
21
+ ```
22
+
23
+ Requires Python 3.12+.
24
+
25
+ ## Quick start
26
+
27
+ 1. Create an empty **diff database**, which kd-migrate uses as a scratch area:
28
+
29
+ ```sql
30
+ CREATE DATABASE myapp_diff;
31
+ ```
32
+
33
+ > ⚠️ Every schema in the diff database except `public` is dropped each time kd-migrate
34
+ > runs. Never point `diffdb` at a database that holds data you care about.
35
+
36
+ 2. Write your schema in `schema.sql`, using named schemas rather than `public`:
37
+
38
+ ```sql
39
+ CREATE SCHEMA app;
40
+
41
+ CREATE TABLE app.customer (
42
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
43
+ name text NOT NULL,
44
+ email text UNIQUE
45
+ );
46
+ ```
47
+
48
+ The `public` schema of the diff database isn't cleared between runs, so objects created
49
+ there would still exist on the next run and `CREATE` would fail.
50
+
51
+ 3. Create a config file, for example `migrate.toml`, next to it:
52
+
53
+ ```toml
54
+ host = "localhost"
55
+ db = "myapp"
56
+ user = "postgres"
57
+ password = "secret"
58
+ diffdb = "myapp_diff"
59
+ ```
60
+
61
+ 4. Run it:
62
+
63
+ ```bash
64
+ kd-migrate migrate.toml
65
+ ```
66
+
67
+ kd-migrate prints the generated SQL and asks what to do:
68
+
69
+ ```
70
+ 1) Apply migration
71
+ 2) Write to migration.sql
72
+ 3) Cancel
73
+ ```
74
+
75
+ If the database already matches the schema, it prints `No migration needed.` and exits.
76
+
77
+ ## Configuration
78
+
79
+ The config file is TOML.
80
+
81
+ | Key | Required | Default | Description |
82
+ |----------------|----------|---------------------|----------------------------------------------------------------|
83
+ | `host` | yes | | Host of the database to migrate (`host` or `host:port`). |
84
+ | `db` | yes | | Name of the database to migrate. |
85
+ | `user` | yes | | User for the database to migrate. |
86
+ | `password` | yes | | Password for the database to migrate. |
87
+ | `diffdb` | yes | | Name of the scratch database the schema is built in. |
88
+ | `diffhost` | no | value of `host` | Host of the diff database. |
89
+ | `diffuser` | no | value of `user` | User for the diff database. |
90
+ | `diffpassword` | no | value of `password` | Password for the diff database. |
91
+ | `schema_sql` | no | `schema.sql` | Path to the schema file, relative to the config file's folder. |
92
+
93
+ Keep the config file out of version control if it contains real credentials.
94
+
95
+ ## Splitting the schema across files
96
+
97
+ `schema.sql` can include other files with psql's `\i` command. Relative paths are resolved
98
+ from the folder of the file doing the include, and includes can be nested:
99
+
100
+ ```sql
101
+ -- schema.sql
102
+ \i schemas/app.sql
103
+ \i schemas/billing.sql
104
+ ```
105
+
106
+ ## Options
107
+
108
+ ```
109
+ kd-migrate [-h] [--keep-fk-recreations] env_file
110
+ ```
111
+
112
+ - `env_file`: path to the TOML config file.
113
+ - `--keep-fk-recreations`: keep every foreign key drop and re-create statement that results
114
+ generates. By default, kd-migrate removes those statements for foreign keys that haven't
115
+ changed and can't be affected by the migration, such as when a column is only added to a
116
+ table. Foreign keys are still recreated when they need to be: the referenced key changed,
117
+ one of the tables is rebuilt, or the type, collation or enum of one of their columns changed.
118
+
119
+ ## Notes
120
+
121
+ - Review the generated SQL before applying it. Destructive statements such as
122
+ `DROP TABLE` and `DROP COLUMN` are included when the schema calls for them.
123
+ - "Write to migration.sql" writes the file to the current working directory.
124
+
125
+ ## License
126
+
127
+ [MIT](LICENSE)
@@ -0,0 +1,58 @@
1
+ [project]
2
+ name = "kd-migrate"
3
+ version = "0.1.0"
4
+ description = "Declarative PostgreSQL schema migrations: diff a live database against a schema.sql file and apply the changes"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.12"
9
+ keywords = [
10
+ "postgresql",
11
+ "postgres",
12
+ "migration",
13
+ "schema",
14
+ "diff",
15
+ "database",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Environment :: Console",
20
+ "Intended Audience :: Developers",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3 :: Only",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Programming Language :: Python :: 3.14",
27
+ "Topic :: Database",
28
+ "Topic :: Software Development :: Version Control",
29
+ ]
30
+ dependencies = [
31
+ "psycopg[binary]>=3.3,<4",
32
+ "results>=2.0.1789346060",
33
+ ]
34
+
35
+ [[project.authors]]
36
+ name = "Robert Trad"
37
+ email = "roberttrad@gmail.com"
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/rouppart/KD-Migrate"
41
+ Source = "https://github.com/rouppart/KD-Migrate"
42
+ Issues = "https://github.com/rouppart/KD-Migrate/issues"
43
+
44
+ [project.scripts]
45
+ kd-migrate = "kd_migrate:main"
46
+
47
+ [build-system]
48
+ requires = ["uv_build>=0.13.12,<0.14.0"]
49
+ build-backend = "uv_build"
50
+
51
+ [dependency-groups]
52
+ dev = [
53
+ "ruff",
54
+ "ty",
55
+ ]
56
+
57
+ [tool.ruff]
58
+ line-length = 100
@@ -0,0 +1,50 @@
1
+ [project]
2
+ name = "kd-migrate"
3
+ version = "0.1.0"
4
+ description = "Declarative PostgreSQL schema migrations: diff a live database against a schema.sql file and apply the changes"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Robert Trad", email = "roberttrad@gmail.com" }
8
+ ]
9
+ license = "MIT"
10
+ license-files = ["LICENSE"]
11
+ requires-python = ">=3.12"
12
+ keywords = ["postgresql", "postgres", "migration", "schema", "diff", "database"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Environment :: Console",
16
+ "Intended Audience :: Developers",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Topic :: Database",
24
+ "Topic :: Software Development :: Version Control",
25
+ ]
26
+ dependencies = [
27
+ "psycopg[binary]>=3.3,<4",
28
+ "results>=2.0.1789346060",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/rouppart/KD-Migrate"
33
+ Source = "https://github.com/rouppart/KD-Migrate"
34
+ Issues = "https://github.com/rouppart/KD-Migrate/issues"
35
+
36
+ [project.scripts]
37
+ kd-migrate = "kd_migrate:main"
38
+
39
+ [build-system]
40
+ requires = ["uv_build>=0.13.12,<0.14.0"]
41
+ build-backend = "uv_build"
42
+
43
+ [dependency-groups]
44
+ dev = [
45
+ "ruff",
46
+ "ty",
47
+ ]
48
+
49
+ [tool.ruff]
50
+ line-length = 100
@@ -0,0 +1,3 @@
1
+ from kd_migrate.migrate import main
2
+
3
+ __all__ = ["main"]
@@ -0,0 +1,323 @@
1
+ import argparse
2
+ import sys
3
+ import tomllib
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from urllib.parse import quote
7
+
8
+ import psycopg
9
+ import results
10
+ from psycopg import sql
11
+ from results.dbdiff import Migration
12
+ from results.dbdiff.changes import Changes
13
+ from results.dbdiff.statements import Statements
14
+ from results.dbdiff.util import differences
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Config:
19
+ host: str
20
+ db: str
21
+ user: str
22
+ password: str
23
+ diffhost: str
24
+ diffdb: str
25
+ diffuser: str
26
+ diffpassword: str
27
+ schema_sql: Path
28
+
29
+
30
+ def load_config(env_file: Path) -> Config:
31
+ if not env_file.is_file():
32
+ raise FileNotFoundError(f"Env file not found: {env_file}")
33
+
34
+ data = tomllib.loads(env_file.read_text(encoding="utf-8"))
35
+
36
+ required_keys = ["host", "db", "user", "password", "diffdb"]
37
+ missing_keys = [key for key in required_keys if not data.get(key)]
38
+
39
+ if missing_keys:
40
+ missing = ", ".join(missing_keys)
41
+ raise ValueError(f"Missing required env key(s): {missing}")
42
+
43
+ return Config(
44
+ host=data["host"],
45
+ db=data["db"],
46
+ user=data["user"],
47
+ password=data["password"],
48
+ diffhost=data.get("diffhost", data["host"]),
49
+ diffdb=data["diffdb"],
50
+ diffuser=data.get("diffuser", data["user"]),
51
+ diffpassword=data.get("diffpassword", data["password"]),
52
+ schema_sql=resolve_relative_path(env_file, data.get("schema_sql", "schema.sql")),
53
+ )
54
+
55
+
56
+ def resolve_relative_path(env_file: Path, value: str) -> Path:
57
+ path = Path(value)
58
+
59
+ if path.is_absolute():
60
+ return path
61
+
62
+ return env_file.parent / path
63
+
64
+
65
+ def database_url(host: str, user: str, password: str, database_name: str) -> str:
66
+ return f"postgresql://{quote(user)}:{quote(password)}@{host}/{quote(database_name)}"
67
+
68
+
69
+ def source_url(config: Config) -> str:
70
+ return database_url(config.host, config.user, config.password, config.db)
71
+
72
+
73
+ def diff_url(config: Config) -> str:
74
+ return database_url(config.diffhost, config.diffuser, config.diffpassword, config.diffdb)
75
+
76
+
77
+ def execute_sql(connection_url: str, sql: str) -> None:
78
+ with psycopg.connect(connection_url, autocommit=True) as connection:
79
+ connection.execute(sql) # ty:ignore[no-matching-overload]
80
+
81
+
82
+ def drop_all_schemas(config: Config) -> None:
83
+ with psycopg.connect(diff_url(config), autocommit=True) as connection:
84
+ schema_names = connection.execute(
85
+ """
86
+ SELECT nspname
87
+ FROM pg_namespace
88
+ WHERE nspname <> 'public' AND nspname <> 'information_schema' AND nspname NOT LIKE 'pg_%'
89
+ """
90
+ ).fetchall()
91
+
92
+ if not schema_names:
93
+ return
94
+
95
+ drop_sql = sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(
96
+ sql.SQL(", ").join(sql.Identifier(schema_name) for (schema_name,) in schema_names)
97
+ )
98
+ connection.execute(drop_sql)
99
+
100
+
101
+ def build_diff_database(config: Config) -> None:
102
+ if not config.schema_sql.is_file():
103
+ raise FileNotFoundError(f"Schema SQL file not found: {config.schema_sql}")
104
+
105
+ schema_sql = load_sql_file(config.schema_sql)
106
+ execute_sql(diff_url(config), schema_sql)
107
+
108
+
109
+ def load_sql_file(path: Path, seen: set[Path] | None = None) -> str:
110
+ path = path.resolve()
111
+ seen = seen or set()
112
+
113
+ if path in seen:
114
+ raise ValueError(f"Recursive SQL include detected: {path}")
115
+
116
+ if not path.is_file():
117
+ raise FileNotFoundError(f"SQL file not found: {path}")
118
+
119
+ seen.add(path)
120
+ output: list[str] = []
121
+
122
+ for line in path.read_text(encoding="utf-8").splitlines():
123
+ stripped = line.strip()
124
+
125
+ if stripped.startswith(r"\i "):
126
+ include_path = Path(stripped[2:].strip())
127
+
128
+ if not include_path.is_absolute():
129
+ include_path = path.parent / include_path
130
+
131
+ output.append(load_sql_file(include_path, seen))
132
+ continue
133
+
134
+ output.append(line)
135
+
136
+ seen.remove(path)
137
+
138
+ return "\n".join(output) + "\n"
139
+
140
+
141
+ def generate_migration_script(config: Config, keep_fk_recreations: bool) -> str:
142
+ source_db = results.db(source_url(config))
143
+ target_db = results.db(diff_url(config))
144
+
145
+ # Same steps as results' schemadiff_as_statements, but keeping the Migration
146
+ # around so its inspected schemas can be used to filter the statements
147
+ migration = Migration(source_db, target_db)
148
+ migration.set_safety(False)
149
+ migration.add_all_changes_ordered()
150
+ statements = migration.statements
151
+
152
+ if not keep_fk_recreations:
153
+ redundant = redundant_fk_statements(migration.changes)
154
+ statements = Statements(s for s in statements if s not in redundant)
155
+
156
+ return statements.sql
157
+
158
+
159
+ def redundant_fk_statements(changes: Changes) -> set[str]:
160
+ """
161
+ Since results 2.0.1789346060, every unchanged foreign key on or referencing a
162
+ modified table is dropped and recreated, even when the table change cannot affect it
163
+ (e.g. adding a column). Return the drop/add/validate statements of those foreign
164
+ keys, except when a recreation is actually needed: the referenced key changed, either
165
+ table is rebuilt, or the type/collation/enum of one of the foreign key columns changed.
166
+ """
167
+ i_from = changes.i_from
168
+ i_target = changes.i_target
169
+
170
+ _, _, modified_tables, _ = differences(i_from.tables, i_target.tables)
171
+ rebuilt_tables = {
172
+ key
173
+ for key, table in modified_tables.items()
174
+ if not table.is_alterable or table.is_partitioned != i_from.tables[key].is_partitioned
175
+ }
176
+
177
+ key_changed_tables = set(rebuilt_tables)
178
+ _, removed_constraints, modified_constraints, _ = differences(
179
+ i_from.constraints, i_target.constraints
180
+ )
181
+ for constraint in (*removed_constraints.values(), *modified_constraints.values()):
182
+ if constraint.constraint_type in ("PRIMARY KEY", "UNIQUE"):
183
+ key_changed_tables.add(constraint.quoted_full_table_name)
184
+ _, removed_indexes, modified_indexes, _ = differences(i_from.indexes, i_target.indexes)
185
+ for index in (*removed_indexes.values(), *modified_indexes.values()):
186
+ if index.is_unique:
187
+ key_changed_tables.add(index.quoted_full_table_name)
188
+
189
+ def columns_changed(table_name: str, column_names: list[str]) -> bool:
190
+ # Only changes to a column's type, collation or enum can affect a foreign key.
191
+ # Nullability, default, comment, identity, etc. changes don't need a recreation.
192
+ if table_name not in modified_tables:
193
+ return False
194
+
195
+ from_columns = i_from.tables[table_name].columns
196
+ target_columns = i_target.tables[table_name].columns
197
+
198
+ for name in column_names:
199
+ before = from_columns.get(name)
200
+ after = target_columns.get(name)
201
+
202
+ if before is None or after is None:
203
+ return True
204
+
205
+ if (
206
+ before.dbtypestr != after.dbtypestr
207
+ or before.collation != after.collation
208
+ or before.enum != after.enum
209
+ ):
210
+ return True
211
+
212
+ return False
213
+
214
+ _, _, _, unmodified_constraints = differences(i_from.constraints, i_target.constraints)
215
+ redundant: set[str] = set()
216
+
217
+ for key, fk in unmodified_constraints.items():
218
+ if fk.constraint_type != "FOREIGN KEY":
219
+ continue
220
+
221
+ table = fk.quoted_full_table_name
222
+ foreign_table = fk.quoted_full_foreign_table_name
223
+
224
+ if table in key_changed_tables or foreign_table in key_changed_tables:
225
+ continue
226
+
227
+ if columns_changed(table, fk.fk_columns_local) or columns_changed(
228
+ foreign_table, fk.fk_columns_foreign
229
+ ):
230
+ continue
231
+
232
+ redundant.add(i_from.constraints[key].drop_statement)
233
+ redundant.update(fk.safer_create_statements)
234
+
235
+ return redundant
236
+
237
+
238
+ def ask_choice() -> str:
239
+ choices = {
240
+ "1": "apply",
241
+ "2": "write",
242
+ "3": "cancel",
243
+ }
244
+
245
+ while True:
246
+ print("1) Apply migration")
247
+ print("2) Write to migration.sql")
248
+ print("3) Cancel")
249
+
250
+ choice = input("#? ").strip()
251
+
252
+ if choice in choices:
253
+ return choices[choice]
254
+
255
+ print("Invalid choice.")
256
+
257
+
258
+ def run(config: Config, keep_fk_recreations: bool) -> int:
259
+ print("Clearing diff database")
260
+ drop_all_schemas(config)
261
+
262
+ print("Building diff database")
263
+ build_diff_database(config)
264
+
265
+ print()
266
+ print("Comparing")
267
+ print()
268
+
269
+ migration_script = generate_migration_script(config, keep_fk_recreations)
270
+
271
+ if not migration_script.strip():
272
+ print("No migration needed.")
273
+ return 0
274
+
275
+ print(migration_script)
276
+
277
+ print()
278
+ print("Migration script generated. What would you like to do?")
279
+
280
+ choice = ask_choice()
281
+
282
+ if choice == "apply":
283
+ execute_sql(source_url(config), migration_script)
284
+ print("Migration applied.")
285
+ return 0
286
+
287
+ if choice == "write":
288
+ migration_output = Path("migration.sql")
289
+ migration_output.write_text(f"{migration_script}\n", encoding="utf-8")
290
+ print(f"Migration written to {migration_output}.")
291
+ return 0
292
+
293
+ print("Canceled.")
294
+ return 0
295
+
296
+
297
+ def parse_args(argv: list[str]) -> argparse.Namespace:
298
+ parser = argparse.ArgumentParser(
299
+ description="Generate and optionally apply a database migration."
300
+ )
301
+ parser.add_argument("env_file", type=Path, help="Path to a TOML env file.")
302
+ parser.add_argument(
303
+ "--keep-fk-recreations",
304
+ action="store_true",
305
+ help="Keep the drop/add of unchanged foreign keys on modified tables.",
306
+ )
307
+
308
+ return parser.parse_args(argv)
309
+
310
+
311
+ def main(argv: list[str] | None = None) -> int:
312
+ args = parse_args(sys.argv[1:] if argv is None else argv)
313
+
314
+ try:
315
+ config = load_config(args.env_file.resolve())
316
+ return run(config, args.keep_fk_recreations)
317
+ except Exception as error: # noqa: BLE001 - top-level CLI guard
318
+ print(error, file=sys.stderr)
319
+ return 1
320
+
321
+
322
+ if __name__ == "__main__":
323
+ raise SystemExit(main())