asqueel-migration 0.2.2__tar.gz → 0.2.3__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.
Files changed (94) hide show
  1. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/CHANGELOG.md +10 -0
  2. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/PKG-INFO +1 -1
  3. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/RELEASING.md +6 -1
  4. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/docs/capabilities.md +3 -2
  5. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/docs/known_limits.md +5 -4
  6. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/__init__.py +1 -1
  7. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/readers/sqlite_reader.py +101 -1
  8. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/writers/sqlite_writer.py +7 -2
  9. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_sqlite_contracts.py +85 -3
  10. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_sqlite_writer.py +28 -2
  11. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/.gitignore +0 -0
  12. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/LICENSE +0 -0
  13. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/NOTICE +0 -0
  14. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/README.md +0 -0
  15. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/assets/branding/asqueel-migration-inverse.svg +0 -0
  16. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/assets/branding/asqueel-migration-primary.svg +0 -0
  17. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/assets/branding/asqueel-monogram.svg +0 -0
  18. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/docs/_static/brand.css +0 -0
  19. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/docs/conf.py +0 -0
  20. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/docs/index.rst +0 -0
  21. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/docs/legacy_test_alignment.md +0 -0
  22. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/docs/maintenance.md +0 -0
  23. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/docs/producer_guide.md +0 -0
  24. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/pyproject.toml +0 -0
  25. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/scripts/check_distribution.py +0 -0
  26. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/_sql.py +0 -0
  27. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/adapters/__init__.py +0 -0
  28. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/adapters/mssql_adapter.py +0 -0
  29. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/adapters/mysql_adapter.py +0 -0
  30. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/adapters/pg_adapter.py +0 -0
  31. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/adapters/sqlite_adapter.py +0 -0
  32. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/cli.py +0 -0
  33. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/command_builder.py +0 -0
  34. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/database.py +0 -0
  35. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/diff_engine.py +0 -0
  36. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/editor_service.py +0 -0
  37. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/exceptions.py +0 -0
  38. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/executor.py +0 -0
  39. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/json_producer.py +0 -0
  40. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/migrator.py +0 -0
  41. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/py.typed +0 -0
  42. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/readers/__init__.py +0 -0
  43. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/readers/base_reader.py +0 -0
  44. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/readers/mssql_reader.py +0 -0
  45. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/readers/mysql_reader.py +0 -0
  46. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/readers/pg_reader.py +0 -0
  47. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/schemas/sql_model-1.0.xsd +0 -0
  48. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/schemas/structure-1.0.json +0 -0
  49. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/service.py +0 -0
  50. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/structures.py +0 -0
  51. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/validation.py +0 -0
  52. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/writers/__init__.py +0 -0
  53. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/writers/base_writer.py +0 -0
  54. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/writers/mssql_writer.py +0 -0
  55. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/writers/mysql_writer.py +0 -0
  56. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/writers/pg_writer.py +0 -0
  57. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/src/asqueel_migration/xml_producer.py +0 -0
  58. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/__init__.py +0 -0
  59. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/conftest.py +0 -0
  60. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/support/__init__.py +0 -0
  61. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/support/migration_base.py +0 -0
  62. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/support/mssql_database.py +0 -0
  63. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/support/mysql_database.py +0 -0
  64. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/support/orm_producer.py +0 -0
  65. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/support/pg_database.py +0 -0
  66. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/support/sqlite_database.py +0 -0
  67. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/support/sqltools.py +0 -0
  68. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_capabilities.py +0 -0
  69. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_cli.py +0 -0
  70. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_connection_error.py +0 -0
  71. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_editor_service.py +0 -0
  72. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_editor_service_contracts.py +0 -0
  73. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_execution_atomicity.py +0 -0
  74. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_executor_column_order.py +0 -0
  75. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_identifier_quoting.py +0 -0
  76. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_index_roundtrip.py +0 -0
  77. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_json_producer.py +0 -0
  78. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_legacy_unique_removal.py +0 -0
  79. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_migration_modes_pg.py +0 -0
  80. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_migration_mssql.py +0 -0
  81. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_migration_mysql.py +0 -0
  82. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_migration_pg.py +0 -0
  83. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_migration_sqlite.py +0 -0
  84. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_mssql_writer.py +0 -0
  85. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_mysql_writer.py +0 -0
  86. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_pg_adapter.py +0 -0
  87. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_regressions.py +0 -0
  88. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_serial4.py +0 -0
  89. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_service.py +0 -0
  90. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_size_normalization.py +0 -0
  91. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_todo_features.py +0 -0
  92. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_validation.py +0 -0
  93. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_wave0_pg.py +0 -0
  94. {asqueel_migration-0.2.2 → asqueel_migration-0.2.3}/tests/test_xml_producer.py +0 -0
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.3 — 2026-10-18
4
+
5
+ - Create SQLite foreign keys with `DEFERRABLE` / `INITIALLY DEFERRED` on new
6
+ tables, following the PostgreSQL writer: `initially_deferred` applies only
7
+ together with `deferrable`. A self-referencing deferred FK lets a child row be
8
+ inserted before its parent inside one transaction.
9
+ - Read SQLite FK deferral from the stored `CREATE TABLE` text, in table-constraint
10
+ and column-constraint form, so a deferred FK converges on the next plan.
11
+ Changing the deferral of an existing FK remains a gated table rebuild.
12
+
3
13
  ## 0.2.2 — 2026-10-15
4
14
 
5
15
  - Remove column UNIQUE using the actual constraint and index names from the
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: asqueel-migration
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Database schema migration engine - compares desired structure with actual database and generates SQL commands
5
5
  Project-URL: Homepage, https://github.com/asqueel-org/asqueel-migration
6
6
  Project-URL: Documentation, https://github.com/asqueel-org/asqueel-migration/tree/main/docs
@@ -1,7 +1,7 @@
1
1
  # Release Asqueel Migration
2
2
 
3
3
  Distribution: `asqueel-migration`. Python package: `asqueel_migration`.
4
- Repository: `asqueel-org/asqueel-migration`. Release version: `0.2.2`.
4
+ Repository: `asqueel-org/asqueel-migration`. Release version: `0.2.3`.
5
5
  The single version source is `src/asqueel_migration/__init__.py`; Hatch reads it
6
6
  for both wheel and source archive. See [CHANGELOG.md](CHANGELOG.md).
7
7
  The retained historical tags `v0.1.0` and `v0.1.1`
@@ -44,6 +44,11 @@ For PostgreSQL regressions, use the disposable server selected by
44
44
  `GNR_TEST_PG_HOST`, `GNR_TEST_PG_PORT`, `GNR_TEST_PG_USER` and
45
45
  `GNR_TEST_PG_PASSWORD`, or the existing `testing.postgresql` fixture.
46
46
 
47
+ For 0.2.3, the SQLite deferred foreign key tests in
48
+ `tests/test_sqlite_contracts.py` and `tests/test_sqlite_writer.py` must pass
49
+ against the installed wheel. Asqueel raises its pin to `>=0.2.3` only after
50
+ 0.2.3 is available from PyPI.
51
+
47
52
  For 0.2.2, `tests/test_legacy_unique_removal.py` must pass against the installed
48
53
  wheel: real constraint/index names, schema-qualified index removal, preserved
49
54
  ordinary indexes, explicit unique indexes, convergence and accepted duplicates.
@@ -52,8 +52,9 @@ See [serial widths and conversion limits](known_limits.md).
52
52
 
53
53
  Foreign keys are inline in `CREATE TABLE`, enforced on connections opened by
54
54
  this library, and read through `PRAGMA foreign_key_list`. UPDATE/DELETE actions
55
- and composite references round-trip. Cross-attached-file foreign keys and
56
- requested deferral options are rejected by reviewed apply. Constraint names are
55
+ and composite references round-trip. Cross-attached-file foreign keys
56
+ are rejected by reviewed apply. `DEFERRABLE` and `INITIALLY DEFERRED` are
57
+ created with the table and read back from the stored `CREATE TABLE` text. Constraint names are
57
58
  not recovered by SQLite PRAGMAs; use the default `ignore_constraint_name=True`.
58
59
  No automatic table rebuild is implemented. `TIMESTAMP` maps to `DH` without
59
60
  rewriting a legacy column. Use dtype `I` for SQLite integer primary keys.
@@ -34,13 +34,14 @@ finds residual changes. Replan and review before retrying after a failure.
34
34
 
35
35
  New tables can declare same-schema foreign keys and composite UNIQUE constraints
36
36
  in the development branch. Additions or changes to those constraints on existing
37
- tables require a table rebuild, which the engine does not implement. CHECK,
38
- foreign key deferral and cross-file foreign keys remain unsupported. Do not
37
+ tables require a table rebuild, which the engine does not implement; this
38
+ includes changing the deferral of an existing foreign key. CHECK and cross-file
39
+ foreign keys remain unsupported. Do not
39
40
  suppress skipped-operation errors to create an unconstrained schema.
40
41
 
41
42
  SQLite PRAGMAs do not expose FK names or deferral clauses. The reader represents
42
- FK columns, target and actions, with structural names; it does not prove the
43
- absence of an existing deferred constraint. Standalone unique indexes also have
43
+ FK columns, target and actions, with structural names, and recovers deferral
44
+ from the stored `CREATE TABLE` text. Standalone unique indexes also have
44
45
  limited introspection fidelity; prefer declared UNIQUE constraints for uniqueness.
45
46
  Declared type mapping is not a full SQLite affinity equivalence system. Legacy
46
47
  `TIMESTAMP` is recognized as `DH`; this does not imply arbitrary type aliases are
@@ -57,7 +57,7 @@ from asqueel_migration.structures import (
57
57
  from asqueel_migration.validation import StructureValidator
58
58
  from asqueel_migration.xml_producer import XmlStructureProducer, struct_to_xml
59
59
 
60
- __version__ = "0.2.2"
60
+ __version__ = "0.2.3"
61
61
 
62
62
  __all__ = [
63
63
  "FORMAT_VERSION",
@@ -33,6 +33,7 @@ v1 limitations
33
33
  back as dtype ``I`` (not ``serial``): migrations targeting SQLite must
34
34
  declare integer PKs as ``I``.
35
35
  - Foreign keys are read from PRAGMAs, which omit names and deferral options.
36
+ Deferral options are recovered from the stored CREATE TABLE text.
36
37
  - CHECK constraints are not introspected.
37
38
  """
38
39
 
@@ -201,6 +202,7 @@ class SqliteReader(BaseReader):
201
202
  f'PRAGMA {self.quote_identifier(schema_name)}.foreign_key_list({self.quote_identifier(table_name)})'
202
203
  ):
203
204
  groups[row[0]].append(row)
205
+ deferral = self._fk_deferral(schema_name, table_name) if groups else {}
204
206
  for fk_id, rows in groups.items():
205
207
  rows.sort(key=lambda row: row[1])
206
208
  _, _, target, _, _, on_update, on_delete, _ = rows[0]
@@ -211,16 +213,114 @@ class SqliteReader(BaseReader):
211
213
  pk = {}
212
214
  self._fetch_primary_key(schema_name, target, pk)
213
215
  related_columns = pk.get('PRIMARY KEY', {}).get('columns', [])
216
+ columns = [row[3] for row in rows]
217
+ deferrable, initially_deferred = deferral.get(
218
+ tuple(name.lower() for name in columns), (False, False)
219
+ )
214
220
  table_constraints['FOREIGN KEY'][fk_id] = {
215
221
  'constraint_type': 'FOREIGN KEY',
216
- 'columns': [row[3] for row in rows],
222
+ 'columns': columns,
217
223
  'related_schema': schema_name,
218
224
  'related_table': target,
219
225
  'related_columns': related_columns,
220
226
  'on_update': on_update,
221
227
  'on_delete': on_delete,
228
+ 'deferrable': deferrable,
229
+ 'initially_deferred': initially_deferred,
222
230
  }
223
231
 
232
+ def _fk_deferral(self, schema_name, table_name):
233
+ """Return the deferral options of a table's foreign keys.
234
+
235
+ SQLite stores the CREATE TABLE text verbatim and the PRAGMAs omit
236
+ deferral, so each top-level definition of the table body holding a
237
+ ``REFERENCES`` clause is parsed. Both the table-constraint form
238
+ (``FOREIGN KEY (cols) REFERENCES ...``) and the column-constraint
239
+ form (``col type REFERENCES ...``) are recognized.
240
+
241
+ Returns:
242
+ dict: ``{(local columns, lower-cased): (deferrable,
243
+ initially_deferred)}``.
244
+ """
245
+ row = self._fetch(
246
+ f'SELECT sql FROM {self.quote_identifier(schema_name)}.sqlite_master '
247
+ 'WHERE type=\'table\' AND name=?',
248
+ (table_name,),
249
+ )
250
+ result = {}
251
+ for text, masked in self._table_body_items(row[0][0]):
252
+ references = re.search(r'\bREFERENCES\b', masked, re.IGNORECASE)
253
+ if not references:
254
+ continue
255
+ head = re.match(
256
+ r'\s*(?:CONSTRAINT\s+\S+\s+)?FOREIGN\s+KEY\s*\(([^)]*)\)',
257
+ masked, re.IGNORECASE,
258
+ )
259
+ if head:
260
+ columns = text[head.start(1):head.end(1)].split(',')
261
+ else:
262
+ columns = [text.split(None, 1)[0]]
263
+ clause = re.search(
264
+ r'(NOT\s+)?DEFERRABLE(?:\s+INITIALLY\s+(DEFERRED|IMMEDIATE))?',
265
+ masked[references.end():], re.IGNORECASE,
266
+ )
267
+ deferrable = bool(clause) and not clause.group(1)
268
+ initially_deferred = deferrable and (clause.group(2) or '').upper() == 'DEFERRED'
269
+ key = tuple(self._unquote(column).lower() for column in columns)
270
+ result[key] = (deferrable, initially_deferred)
271
+ return result
272
+
273
+ @staticmethod
274
+ def _table_body_items(create_sql):
275
+ """Split a CREATE TABLE body into its top-level definitions.
276
+
277
+ Returns a list of ``(text, masked)`` pairs: ``masked`` has the same
278
+ length as ``text`` with quoted content blanked, so keyword searches
279
+ never match inside identifiers or string literals.
280
+ """
281
+ closers = {'"': '"', "'": "'", '`': '`', '[': ']'}
282
+ masked = []
283
+ index = 0
284
+ while index < len(create_sql):
285
+ char = create_sql[index]
286
+ if char in closers:
287
+ end = create_sql.find(closers[char], index + 1)
288
+ while closers[char] != ']' and end + 1 < len(create_sql) and create_sql[end + 1] == char:
289
+ end = create_sql.find(char, end + 2)
290
+ masked.append(char + '_' * (end - index - 1) + closers[char])
291
+ index = end + 1
292
+ continue
293
+ masked.append(char)
294
+ index += 1
295
+ masked = ''.join(masked)
296
+ start = masked.index('(') + 1
297
+ items = []
298
+ depth = 0
299
+ item_start = start
300
+ for position in range(start, len(masked)):
301
+ char = masked[position]
302
+ if char == '(':
303
+ depth += 1
304
+ elif char == ')' and depth:
305
+ depth -= 1
306
+ elif char in ',)' and not depth:
307
+ items.append((create_sql[item_start:position], masked[item_start:position]))
308
+ item_start = position + 1
309
+ if char == ')':
310
+ break
311
+ return items
312
+
313
+ @staticmethod
314
+ def _unquote(identifier):
315
+ """Return an identifier without its SQLite quoting."""
316
+ identifier = identifier.strip()
317
+ if identifier[:1] in '"`' and identifier[-1:] == identifier[:1]:
318
+ quote = identifier[0]
319
+ return identifier[1:-1].replace(quote * 2, quote)
320
+ if identifier[:1] == '[' and identifier[-1:] == ']':
321
+ return identifier[1:-1]
322
+ return identifier
323
+
224
324
  def _fetch_primary_key(self, schema_name, table_name, table_constraints):
225
325
  pk_columns = []
226
326
  for row in self._fetch(
@@ -65,6 +65,7 @@ class SqliteWriter(BaseWriter):
65
65
  # Represent FKs and UNIQUE, but gate ALTER ADD/DROP separately.
66
66
  CAPABILITIES = frozenset({
67
67
  'index_where', 'foreign_keys', 'inline_foreign_keys', 'unique_constraints',
68
+ 'fk_deferrable',
68
69
  })
69
70
 
70
71
  def column_sql_type(self, dtype, size=None):
@@ -229,8 +230,6 @@ class SqliteWriter(BaseWriter):
229
230
  def foreign_key_sql(self, fk_name, columns, related_table, related_schema,
230
231
  related_columns, on_delete=None, on_update=None,
231
232
  deferrable=False, initially_deferred=False):
232
- if deferrable or initially_deferred:
233
- self._unsupported('deferrable foreign keys')
234
233
  q = self.quote_identifier
235
234
  local = ', '.join(q(col) for col in columns)
236
235
  remote = ', '.join(q(col) for col in related_columns)
@@ -240,6 +239,12 @@ class SqliteWriter(BaseWriter):
240
239
  for clause, action in (('DELETE', on_delete), ('UPDATE', on_update)):
241
240
  if action:
242
241
  sql += f' ON {clause} {action}'
242
+ # Same rule as the PostgreSQL writer: INITIALLY DEFERRED only
243
+ # together with DEFERRABLE.
244
+ if deferrable:
245
+ sql += ' DEFERRABLE'
246
+ if initially_deferred:
247
+ sql += ' INITIALLY DEFERRED'
243
248
  return sql
244
249
 
245
250
  def execute(self, sql, auto_commit=False, manager=False):
@@ -148,7 +148,7 @@ def test_existing_table_constraint_additions_refused(tmp_path, kind):
148
148
  db.closeConnection()
149
149
 
150
150
 
151
- @pytest.mark.parametrize('change', ['cross_schema', 'deferrable', 'check'])
151
+ @pytest.mark.parametrize('change', ['cross_schema', 'check'])
152
152
  def test_unsupported_features_refused_before_creation(tmp_path, change):
153
153
  path = tmp_path / 'base.db'
154
154
  db = SqliteDatabase({'dbname': str(path)}, application_schemas=['main'])
@@ -159,8 +159,6 @@ def test_unsupported_features_refused_before_creation(tmp_path, change):
159
159
  relation['related_schema'] = 'elsewhere'
160
160
  desired['root']['schemas'].update(model('elsewhere')['root']['schemas'])
161
161
  db = SqliteDatabase({'dbname': str(path)}, application_schemas=['main', 'elsewhere'])
162
- elif change == 'deferrable':
163
- relation['deferrable'] = True
164
162
  else:
165
163
  constraint = next(iter(table['constraints'].values()))['attributes']
166
164
  constraint.pop('columns')
@@ -171,6 +169,90 @@ def test_unsupported_features_refused_before_creation(tmp_path, change):
171
169
  assert not path.exists()
172
170
 
173
171
 
172
+ def hierarchy(**deferral):
173
+ return JsonStructureProducer({'db': 'logical', 'schemas': [{'name': 'main', 'tables': [{
174
+ 'name': 'nodes', 'pkey': 'id', 'columns': [
175
+ {'name': 'id', 'dtype': 'T'}, {'name': 'parent_id', 'dtype': 'T'},
176
+ ],
177
+ 'relations': [{
178
+ 'columns': ['parent_id'], 'related_schema': 'main', 'related_table': 'nodes',
179
+ 'related_columns': ['id'], 'on_delete': 'CASCADE', **deferral,
180
+ }],
181
+ }]}]}).get_json_struct()
182
+
183
+
184
+ def test_deferred_self_reference_allows_child_before_parent(tmp_path):
185
+ path = tmp_path / 'base.db'
186
+ desired = hierarchy(deferrable=True, initially_deferred=True)
187
+ db = SqliteDatabase({'dbname': str(path)}, application_schemas=['main'])
188
+ try:
189
+ plan = apply(db, desired)
190
+ assert 'ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED' in plan['sql']
191
+ db.closeConnection()
192
+ assert plan_migration(db, desired)['empty']
193
+ finally:
194
+ db.closeConnection()
195
+ with sqlite3.connect(path, isolation_level=None) as conn:
196
+ conn.execute('PRAGMA foreign_keys = ON')
197
+ conn.execute('BEGIN')
198
+ conn.execute("INSERT INTO nodes VALUES ('child', 'root')")
199
+ conn.execute("INSERT INTO nodes VALUES ('root', NULL)")
200
+ conn.execute('COMMIT')
201
+ assert conn.execute('SELECT id, parent_id FROM nodes ORDER BY id').fetchall() == [
202
+ ('child', 'root'), ('root', None),
203
+ ]
204
+ conn.execute('BEGIN')
205
+ conn.execute("INSERT INTO nodes VALUES ('orphan', 'missing')")
206
+ with pytest.raises(sqlite3.IntegrityError, match='FOREIGN KEY'):
207
+ conn.execute('COMMIT')
208
+ conn.execute('ROLLBACK')
209
+ assert conn.execute("SELECT id FROM nodes WHERE id='orphan'").fetchall() == []
210
+
211
+
212
+ def test_immediate_self_reference_rejects_child_before_parent(tmp_path):
213
+ path = tmp_path / 'base.db'
214
+ db = SqliteDatabase({'dbname': str(path)}, application_schemas=['main'])
215
+ try:
216
+ assert 'DEFERRABLE' not in apply(db, hierarchy())['sql']
217
+ finally:
218
+ db.closeConnection()
219
+ with sqlite3.connect(path, isolation_level=None) as conn:
220
+ conn.execute('PRAGMA foreign_keys = ON')
221
+ conn.execute('BEGIN')
222
+ with pytest.raises(sqlite3.IntegrityError, match='FOREIGN KEY'):
223
+ conn.execute("INSERT INTO nodes VALUES ('child', 'root')")
224
+ conn.execute('ROLLBACK')
225
+
226
+
227
+ @pytest.mark.parametrize('declared, deferral', [
228
+ ('DEFERRABLE INITIALLY DEFERRED', {'deferrable': True, 'initially_deferred': True}),
229
+ ('deferrable', {'deferrable': True}),
230
+ ('DEFERRABLE INITIALLY IMMEDIATE', {'deferrable': True}),
231
+ ('NOT DEFERRABLE INITIALLY DEFERRED', {}),
232
+ ('', {}),
233
+ ])
234
+ @pytest.mark.parametrize('form', ['table', 'column'])
235
+ def test_introspect_legacy_fk_deferral(tmp_path, declared, deferral, form):
236
+ path = tmp_path / 'base.db'
237
+ references = f'REFERENCES "nodes" ("id") ON DELETE CASCADE {declared}'
238
+ if form == 'table':
239
+ body = f'"id" TEXT PRIMARY KEY, "parent_id" TEXT, CONSTRAINT "x" FOREIGN KEY ("parent_id") {references}'
240
+ else:
241
+ body = f'"id" TEXT PRIMARY KEY, "parent_id" TEXT {references}'
242
+ with sqlite3.connect(path) as conn:
243
+ conn.execute(f'CREATE TABLE "nodes" ({body})')
244
+ db = SqliteDatabase({'dbname': str(path)}, application_schemas=['main'])
245
+ try:
246
+ assert apply(db, hierarchy(**deferral))['empty']
247
+ if deferral.get('initially_deferred'):
248
+ # Dropping the deferral is a FK rebuild, gated on SQLite.
249
+ skipped = plan_migration(db, hierarchy())['skipped_changes']
250
+ assert skipped
251
+ assert all(change['capability'] == 'drop_constraint' for change in skipped)
252
+ finally:
253
+ db.closeConnection()
254
+
255
+
174
256
  def test_skipped_changes_are_structured_repeatable_and_keep_warnings(tmp_path):
175
257
  db = SqliteDatabase({'dbname': str(tmp_path / 'base.db')}, application_schemas=['main'])
176
258
  try:
@@ -2,7 +2,7 @@
2
2
 
3
3
  Exact-SQL oracles for the declared-type map, column/add-column fragments,
4
4
  one-per-fragment ALTER TABLE assembly, CREATE INDEX variants and the
5
- qualified table name; plus the explicit errors of the unsupported DDL
5
+ qualified table name, foreign keys with deferral options; plus the explicit errors of the unsupported DDL
6
6
  methods.
7
7
  """
8
8
 
@@ -115,6 +115,33 @@ class TestConstraintSql:
115
115
  ) == 'CONSTRAINT "cst_c" CHECK (rating >= 0)'
116
116
 
117
117
 
118
+ class TestForeignKeySql:
119
+ def test_plain(self, writer):
120
+ assert writer.foreign_key_sql('fk', ['a'], 'other', 'alfa', ['id']) == (
121
+ 'CONSTRAINT "fk" FOREIGN KEY ("a") REFERENCES "other" ("id")'
122
+ )
123
+
124
+ def test_actions_then_deferral(self, writer):
125
+ assert writer.foreign_key_sql(
126
+ 'fk', ['a'], 'other', 'alfa', ['id'], on_delete='CASCADE',
127
+ on_update='CASCADE', deferrable=True, initially_deferred=True,
128
+ ) == (
129
+ 'CONSTRAINT "fk" FOREIGN KEY ("a") REFERENCES "other" ("id")'
130
+ ' ON DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED'
131
+ )
132
+
133
+ def test_deferrable_only(self, writer):
134
+ assert writer.foreign_key_sql(
135
+ 'fk', ['a'], 'other', 'alfa', ['id'], deferrable=True
136
+ ) == 'CONSTRAINT "fk" FOREIGN KEY ("a") REFERENCES "other" ("id") DEFERRABLE'
137
+
138
+ def test_initially_deferred_requires_deferrable(self, writer):
139
+ # Same rule as the PostgreSQL writer.
140
+ assert writer.foreign_key_sql(
141
+ 'fk', ['a'], 'other', 'alfa', ['id'], initially_deferred=True
142
+ ) == 'CONSTRAINT "fk" FOREIGN KEY ("a") REFERENCES "other" ("id")'
143
+
144
+
118
145
  class TestUnsupportedRaise:
119
146
  @pytest.mark.parametrize('call', [
120
147
  lambda w: w.create_db_sql('db'),
@@ -129,7 +156,6 @@ class TestUnsupportedRaise:
129
156
  lambda w: w.create_extension_sql('unaccent'),
130
157
  lambda w: w.comment_on_column_sql('alfa', 'doc', 'c', 'x'),
131
158
  lambda w: w.comment_on_table_sql('alfa', 'doc', 'x'),
132
- lambda w: w.foreign_key_sql('fk', ['a'], 'other', 'alfa', ['id'], deferrable=True),
133
159
  lambda w: w.execute('SELECT 1'),
134
160
  ])
135
161
  def test_raises_sql_migration_error(self, writer, call):