@supabase/pg-delta 1.0.0-alpha.23 → 1.0.0-alpha.25

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 (66) hide show
  1. package/dist/core/catalog.model.d.ts +2 -2
  2. package/dist/core/catalog.model.js +26 -21
  3. package/dist/core/integrations/supabase.js +84 -0
  4. package/dist/core/objects/aggregate/changes/aggregate.privilege.js +21 -9
  5. package/dist/core/objects/foreign-data-wrapper/foreign-data-wrapper/changes/foreign-data-wrapper.alter.js +4 -1
  6. package/dist/core/objects/foreign-data-wrapper/foreign-data-wrapper/changes/foreign-data-wrapper.create.js +6 -3
  7. package/dist/core/objects/foreign-data-wrapper/foreign-data-wrapper/foreign-data-wrapper.model.d.ts +11 -0
  8. package/dist/core/objects/foreign-data-wrapper/foreign-data-wrapper/foreign-data-wrapper.model.js +11 -0
  9. package/dist/core/objects/foreign-data-wrapper/foreign-table/changes/foreign-table.alter.js +4 -1
  10. package/dist/core/objects/foreign-data-wrapper/foreign-table/changes/foreign-table.create.js +6 -3
  11. package/dist/core/objects/foreign-data-wrapper/foreign-table/foreign-table.model.d.ts +11 -0
  12. package/dist/core/objects/foreign-data-wrapper/foreign-table/foreign-table.model.js +11 -0
  13. package/dist/core/objects/foreign-data-wrapper/sensitive-options.d.ts +32 -0
  14. package/dist/core/objects/foreign-data-wrapper/sensitive-options.js +129 -0
  15. package/dist/core/objects/foreign-data-wrapper/server/changes/server.alter.js +4 -1
  16. package/dist/core/objects/foreign-data-wrapper/server/changes/server.create.js +6 -3
  17. package/dist/core/objects/foreign-data-wrapper/server/server.model.d.ts +10 -0
  18. package/dist/core/objects/foreign-data-wrapper/server/server.model.js +10 -0
  19. package/dist/core/objects/foreign-data-wrapper/user-mapping/changes/user-mapping.alter.js +4 -1
  20. package/dist/core/objects/foreign-data-wrapper/user-mapping/changes/user-mapping.create.js +6 -3
  21. package/dist/core/objects/foreign-data-wrapper/user-mapping/user-mapping.model.d.ts +10 -0
  22. package/dist/core/objects/foreign-data-wrapper/user-mapping/user-mapping.model.js +10 -0
  23. package/dist/core/objects/rls-policy/rls-policy.model.d.ts +2 -2
  24. package/dist/core/objects/table/table.model.js +7 -2
  25. package/dist/core/post-diff-normalization.d.ts +7 -0
  26. package/dist/core/post-diff-normalization.js +33 -4
  27. package/dist/core/sort/cycle-breakers.js +139 -17
  28. package/package.json +1 -1
  29. package/src/core/catalog.model.ts +36 -20
  30. package/src/core/integrations/supabase.test.ts +198 -0
  31. package/src/core/integrations/supabase.ts +84 -0
  32. package/src/core/objects/aggregate/changes/aggregate.privilege.test.ts +79 -0
  33. package/src/core/objects/aggregate/changes/aggregate.privilege.ts +22 -9
  34. package/src/core/objects/foreign-data-wrapper/foreign-data-wrapper/changes/foreign-data-wrapper.alter.test.ts +34 -4
  35. package/src/core/objects/foreign-data-wrapper/foreign-data-wrapper/changes/foreign-data-wrapper.alter.ts +5 -1
  36. package/src/core/objects/foreign-data-wrapper/foreign-data-wrapper/changes/foreign-data-wrapper.create.test.ts +34 -0
  37. package/src/core/objects/foreign-data-wrapper/foreign-data-wrapper/changes/foreign-data-wrapper.create.ts +7 -5
  38. package/src/core/objects/foreign-data-wrapper/foreign-data-wrapper/foreign-data-wrapper.model.ts +11 -0
  39. package/src/core/objects/foreign-data-wrapper/foreign-table/changes/foreign-table.alter.test.ts +25 -4
  40. package/src/core/objects/foreign-data-wrapper/foreign-table/changes/foreign-table.alter.ts +5 -1
  41. package/src/core/objects/foreign-data-wrapper/foreign-table/changes/foreign-table.create.test.ts +54 -0
  42. package/src/core/objects/foreign-data-wrapper/foreign-table/changes/foreign-table.create.ts +7 -5
  43. package/src/core/objects/foreign-data-wrapper/foreign-table/foreign-table.model.ts +11 -0
  44. package/src/core/objects/foreign-data-wrapper/sensitive-options.test.ts +98 -0
  45. package/src/core/objects/foreign-data-wrapper/sensitive-options.ts +133 -0
  46. package/src/core/objects/foreign-data-wrapper/server/changes/server.alter.test.ts +39 -4
  47. package/src/core/objects/foreign-data-wrapper/server/changes/server.alter.ts +5 -1
  48. package/src/core/objects/foreign-data-wrapper/server/changes/server.create.test.ts +36 -0
  49. package/src/core/objects/foreign-data-wrapper/server/changes/server.create.ts +7 -5
  50. package/src/core/objects/foreign-data-wrapper/server/server.model.ts +10 -0
  51. package/src/core/objects/foreign-data-wrapper/user-mapping/changes/user-mapping.alter.test.ts +39 -6
  52. package/src/core/objects/foreign-data-wrapper/user-mapping/changes/user-mapping.alter.ts +5 -1
  53. package/src/core/objects/foreign-data-wrapper/user-mapping/changes/user-mapping.create.test.ts +38 -2
  54. package/src/core/objects/foreign-data-wrapper/user-mapping/changes/user-mapping.create.ts +7 -5
  55. package/src/core/objects/foreign-data-wrapper/user-mapping/user-mapping.model.ts +10 -0
  56. package/src/core/objects/table/table.model.ts +7 -2
  57. package/src/core/plan/sql-format/format-off.test.ts +4 -4
  58. package/src/core/plan/sql-format/format-pretty-lower-leading.test.ts +4 -4
  59. package/src/core/plan/sql-format/format-pretty-narrow.test.ts +5 -4
  60. package/src/core/plan/sql-format/format-pretty-preserve.test.ts +4 -4
  61. package/src/core/plan/sql-format/format-pretty-upper.test.ts +4 -4
  62. package/src/core/post-diff-normalization.test.ts +123 -0
  63. package/src/core/post-diff-normalization.ts +40 -4
  64. package/src/core/sort/cycle-breakers.test.ts +236 -2
  65. package/src/core/sort/cycle-breakers.ts +184 -24
  66. package/src/core/sort/sort-changes.test.ts +317 -0
@@ -62,7 +62,9 @@ function fkConstraint(props: {
62
62
  fkColumn: string;
63
63
  targetSchema: string;
64
64
  targetTable: string;
65
+ targetColumn?: string;
65
66
  }) {
67
+ const targetColumn = props.targetColumn ?? "id";
66
68
  return {
67
69
  name: props.name,
68
70
  constraint_type: "f" as const,
@@ -78,7 +80,7 @@ function fkConstraint(props: {
78
80
  parent_table_schema: null,
79
81
  parent_table_name: null,
80
82
  key_columns: [props.fkColumn],
81
- foreign_key_columns: ["id"],
83
+ foreign_key_columns: [targetColumn],
82
84
  foreign_key_table: props.targetTable,
83
85
  foreign_key_schema: props.targetSchema,
84
86
  foreign_key_table_is_partition: false,
@@ -91,7 +93,41 @@ function fkConstraint(props: {
91
93
  match_type: "s" as const,
92
94
  check_expression: null,
93
95
  owner: "postgres",
94
- definition: `FOREIGN KEY (${props.fkColumn}) REFERENCES ${props.targetSchema}.${props.targetTable}(id)`,
96
+ definition: `FOREIGN KEY (${props.fkColumn}) REFERENCES ${props.targetSchema}.${props.targetTable}(${targetColumn})`,
97
+ comment: null,
98
+ };
99
+ }
100
+
101
+ function uniqueConstraint(name: string, column: string) {
102
+ return {
103
+ name,
104
+ constraint_type: "u" as const,
105
+ deferrable: false,
106
+ initially_deferred: false,
107
+ validated: true,
108
+ is_local: true,
109
+ no_inherit: false,
110
+ is_temporal: false,
111
+ is_partition_clone: false,
112
+ parent_constraint_schema: null,
113
+ parent_constraint_name: null,
114
+ parent_table_schema: null,
115
+ parent_table_name: null,
116
+ key_columns: [column],
117
+ foreign_key_columns: null,
118
+ foreign_key_table: null,
119
+ foreign_key_schema: null,
120
+ foreign_key_table_is_partition: null,
121
+ foreign_key_parent_schema: null,
122
+ foreign_key_parent_table: null,
123
+ foreign_key_effective_schema: null,
124
+ foreign_key_effective_table: null,
125
+ on_update: null,
126
+ on_delete: null,
127
+ match_type: null,
128
+ check_expression: null,
129
+ owner: "postgres",
130
+ definition: `UNIQUE (${column})`,
95
131
  comment: null,
96
132
  };
97
133
  }
@@ -448,6 +484,204 @@ describe("tryBreakCycleByChangeInjection", () => {
448
484
  expect(broken).toBeNull();
449
485
  });
450
486
 
487
+ test("publication FK-chain constraint-drop 3-cycle: injects terminal FK drop", () => {
488
+ // Schema:
489
+ // publication p includes labs and posts
490
+ // posts.lab_id REFERENCES labs(id)
491
+ // Diff drops posts and drops labs.unique_lab_id while also removing both
492
+ // tables from the publication. The FK edge from posts to the terminal
493
+ // constraint drop forms:
494
+ // AlterPublicationDropTables → DropTable(posts)
495
+ // DropTable(posts) → AlterTableDropConstraint(labs.unique_lab_id)
496
+ // AlterTableDropConstraint(labs.unique_lab_id) → AlterPublicationDropTables
497
+ const tableLabs = new Table({
498
+ ...baseTableProps,
499
+ name: "labs",
500
+ columns: [{ ...integerColumn("id", 1), not_null: true }],
501
+ constraints: [uniqueConstraint("unique_lab_id", "id")],
502
+ });
503
+ const tablePosts = new Table({
504
+ ...baseTableProps,
505
+ name: "posts",
506
+ columns: [
507
+ { ...integerColumn("id", 1), not_null: true },
508
+ integerColumn("lab_id", 2),
509
+ ],
510
+ constraints: [
511
+ fkConstraint({
512
+ name: "posts_lab_id_fkey",
513
+ fkColumn: "lab_id",
514
+ targetSchema: "public",
515
+ targetTable: "labs",
516
+ }),
517
+ ],
518
+ });
519
+ const publication = new Publication({
520
+ name: "p",
521
+ owner: "postgres",
522
+ comment: null,
523
+ all_tables: false,
524
+ publish_insert: true,
525
+ publish_update: true,
526
+ publish_delete: true,
527
+ publish_truncate: true,
528
+ publish_via_partition_root: false,
529
+ tables: [
530
+ { schema: "public", name: "labs", columns: null, row_filter: null },
531
+ { schema: "public", name: "posts", columns: null, row_filter: null },
532
+ ],
533
+ schemas: [],
534
+ });
535
+
536
+ const terminalDrop = new AlterTableDropConstraint({
537
+ table: tableLabs,
538
+ constraint: tableLabs.constraints[0],
539
+ });
540
+ const changes: Change[] = [
541
+ new AlterPublicationDropTables({
542
+ publication,
543
+ tables: publication.tables,
544
+ }),
545
+ new DropTable({ table: tablePosts }),
546
+ terminalDrop,
547
+ ];
548
+
549
+ const broken = tryBreakCycleByChangeInjection([0, 1, 2], changes);
550
+ if (broken === null) throw new Error("expected breaker to fire");
551
+
552
+ const injectedDrops = broken.filter(
553
+ (change): change is AlterTableDropConstraint =>
554
+ change instanceof AlterTableDropConstraint &&
555
+ change.table.stableId === tablePosts.stableId,
556
+ );
557
+ expect(injectedDrops).toHaveLength(1);
558
+ expect(injectedDrops[0].constraint.name).toBe("posts_lab_id_fkey");
559
+
560
+ const rewrittenPostsDrop = broken.find(
561
+ (change): change is DropTable =>
562
+ change instanceof DropTable &&
563
+ change.table.stableId === tablePosts.stableId,
564
+ );
565
+ if (!rewrittenPostsDrop) throw new Error("missing rewritten DropTable");
566
+ expect(
567
+ rewrittenPostsDrop.externallyDroppedConstraints.has("posts_lab_id_fkey"),
568
+ ).toBe(true);
569
+ expect(broken).toContain(terminalDrop);
570
+ });
571
+
572
+ test("publication FK-chain constraint-drop 4-cycle: injects FK drops along the dropped-table chain", () => {
573
+ // Schema:
574
+ // publication p includes labs, posts, and post_attachments
575
+ // post_attachments.post_id REFERENCES posts(id)
576
+ // posts.lab_id REFERENCES labs(id)
577
+ // Diff drops post_attachments and posts, drops labs.unique_lab_id,
578
+ // and removes all three tables from the publication.
579
+ const tableLabs = new Table({
580
+ ...baseTableProps,
581
+ name: "labs",
582
+ columns: [{ ...integerColumn("id", 1), not_null: true }],
583
+ constraints: [uniqueConstraint("unique_lab_id", "id")],
584
+ });
585
+ const tablePosts = new Table({
586
+ ...baseTableProps,
587
+ name: "posts",
588
+ columns: [
589
+ { ...integerColumn("id", 1), not_null: true },
590
+ integerColumn("lab_id", 2),
591
+ ],
592
+ constraints: [
593
+ fkConstraint({
594
+ name: "posts_lab_id_fkey",
595
+ fkColumn: "lab_id",
596
+ targetSchema: "public",
597
+ targetTable: "labs",
598
+ }),
599
+ ],
600
+ });
601
+ const tablePostAttachments = new Table({
602
+ ...baseTableProps,
603
+ name: "post_attachments",
604
+ columns: [
605
+ { ...integerColumn("id", 1), not_null: true },
606
+ integerColumn("post_id", 2),
607
+ ],
608
+ constraints: [
609
+ fkConstraint({
610
+ name: "post_attachments_post_id_fkey",
611
+ fkColumn: "post_id",
612
+ targetSchema: "public",
613
+ targetTable: "posts",
614
+ }),
615
+ ],
616
+ });
617
+ const publication = new Publication({
618
+ name: "p",
619
+ owner: "postgres",
620
+ comment: null,
621
+ all_tables: false,
622
+ publish_insert: true,
623
+ publish_update: true,
624
+ publish_delete: true,
625
+ publish_truncate: true,
626
+ publish_via_partition_root: false,
627
+ tables: [
628
+ { schema: "public", name: "labs", columns: null, row_filter: null },
629
+ {
630
+ schema: "public",
631
+ name: "post_attachments",
632
+ columns: null,
633
+ row_filter: null,
634
+ },
635
+ { schema: "public", name: "posts", columns: null, row_filter: null },
636
+ ],
637
+ schemas: [],
638
+ });
639
+
640
+ const terminalDrop = new AlterTableDropConstraint({
641
+ table: tableLabs,
642
+ constraint: tableLabs.constraints[0],
643
+ });
644
+ const changes: Change[] = [
645
+ new AlterPublicationDropTables({
646
+ publication,
647
+ tables: publication.tables,
648
+ }),
649
+ new DropTable({ table: tablePostAttachments }),
650
+ new DropTable({ table: tablePosts }),
651
+ terminalDrop,
652
+ ];
653
+
654
+ const broken = tryBreakCycleByChangeInjection([0, 1, 2, 3], changes);
655
+ if (broken === null) throw new Error("expected breaker to fire");
656
+
657
+ const injectedDropNames = broken
658
+ .filter(
659
+ (change): change is AlterTableDropConstraint =>
660
+ change instanceof AlterTableDropConstraint && change !== terminalDrop,
661
+ )
662
+ .map((change) => change.constraint.name)
663
+ .sort();
664
+ expect(injectedDropNames).toEqual([
665
+ "post_attachments_post_id_fkey",
666
+ "posts_lab_id_fkey",
667
+ ]);
668
+
669
+ for (const [tableId, constraintName] of [
670
+ [tablePostAttachments.stableId, "post_attachments_post_id_fkey"],
671
+ [tablePosts.stableId, "posts_lab_id_fkey"],
672
+ ] as const) {
673
+ const rewrittenDrop = broken.find(
674
+ (change): change is DropTable =>
675
+ change instanceof DropTable && change.table.stableId === tableId,
676
+ );
677
+ if (!rewrittenDrop) throw new Error(`missing DropTable for ${tableId}`);
678
+ expect(
679
+ rewrittenDrop.externallyDroppedConstraints.has(constraintName),
680
+ ).toBe(true);
681
+ }
682
+ expect(broken).toContain(terminalDrop);
683
+ });
684
+
451
685
  test("returns null for a cycle with no recognised pattern (e.g. publication-only)", () => {
452
686
  // Cycle of `AlterPublicationSetOwner` changes — neither FK nor
453
687
  // publication-column shape. Breaker must bail so the formatted
@@ -78,6 +78,35 @@ export function tryBreakCycleByChangeInjection(
78
78
  );
79
79
  if (pubColBroken) return pubColBroken;
80
80
 
81
+ // ─── Branch C: Publication ↔ dropped FK chain ↔ constraint drop ──────
82
+ // Triggered when publication membership is being removed for tables in
83
+ // the same drop phase as a FK chain, and the chain ends at a separately
84
+ // emitted `AlterTableDropConstraint` on a table that is also being
85
+ // removed from the publication.
86
+ //
87
+ // Example (4-change cycle):
88
+ // AlterPublicationDropTables(p, [labs, posts, post_attachments])
89
+ // DropTable(post_attachments)
90
+ // DropTable(posts)
91
+ // AlterTableDropConstraint(labs.unique_lab_id)
92
+ //
93
+ // Cycle:
94
+ // publication:p → table:post_attachments
95
+ // post_attachments.post_id_fkey → column:posts.id
96
+ // posts.lab_id_fkey → constraint:labs.unique_lab_id
97
+ // constraint:labs.unique_lab_id → table:labs
98
+ //
99
+ // Fix: inject explicit FK drops for the FK constraints claimed by the
100
+ // DropTables in the cycle, including FKs that point at the terminal
101
+ // dropped constraint. The publication and terminal constraint changes
102
+ // stay unchanged; only the intermediate FK ownership is reassigned from
103
+ // DropTable to dedicated AlterTableDropConstraint changes.
104
+ const pubFkConstraintBroken = tryBreakPublicationFkConstraintDropCycle(
105
+ cycleNodeIndexes,
106
+ phaseChanges,
107
+ );
108
+ if (pubFkConstraintBroken) return pubFkConstraintBroken;
109
+
81
110
  // No known pattern. Returning null lets sortPhaseChanges throw the
82
111
  // formatted CycleError with full diagnostic — better a clear bug
83
112
  // report than silently shipping a broken plan.
@@ -109,6 +138,34 @@ function tryBreakFkCycle(
109
138
  cycleDropTables.map((change) => change.table.stableId),
110
139
  );
111
140
 
141
+ return injectFkConstraintDropsForDropTables({
142
+ phaseChanges,
143
+ dropTables: cycleDropTables,
144
+ shouldInject: (fk, tableId) =>
145
+ isCrossCycleFkConstraint(fk, tableId, cycleTableIds),
146
+ });
147
+ }
148
+
149
+ type FkConstraintPredicate = (
150
+ fk: TableConstraintProps,
151
+ tableId: string,
152
+ ) => boolean;
153
+
154
+ /**
155
+ * Shared FK-drop injection used by Branch A and Branch C. The caller owns
156
+ * the cycle-specific matcher; this helper only handles the mechanical
157
+ * rewrite: add dedicated `AlterTableDropConstraint` changes and rebuild
158
+ * affected `DropTable`s with updated `externallyDroppedConstraints`.
159
+ */
160
+ function injectFkConstraintDropsForDropTables({
161
+ phaseChanges,
162
+ dropTables,
163
+ shouldInject,
164
+ }: {
165
+ phaseChanges: readonly Change[];
166
+ dropTables: readonly DropTable[];
167
+ shouldInject: FkConstraintPredicate;
168
+ }): Change[] | null {
112
169
  // For each DropTable in the cycle, find every FK whose referenced table
113
170
  // is also in the cycle. Each such FK becomes one injected
114
171
  // `AlterTableDropConstraint` and one entry on the source table's
@@ -120,16 +177,14 @@ function tryBreakFkCycle(
120
177
  const updatedExternalsByTableId = new Map<string, Set<string>>();
121
178
  let didMutate = false;
122
179
 
123
- for (const dropTable of cycleDropTables) {
180
+ for (const dropTable of dropTables) {
124
181
  const tableId = dropTable.table.stableId;
125
182
  const existingExternals = new Set(dropTable.externallyDroppedConstraints);
126
183
  let tableMutated = false;
127
184
 
128
- for (const fk of iterCrossCycleFkConstraints(
129
- dropTable.table.constraints,
130
- tableId,
131
- cycleTableIds,
132
- )) {
185
+ for (const fk of iterFkConstraints(dropTable.table.constraints)) {
186
+ if (!shouldInject(fk, tableId)) continue;
187
+
133
188
  // Skip if a same-table `AlterTableDropConstraint` is already in the
134
189
  // change list — could happen if a previous breaker iteration
135
190
  // injected one, or the diff layer emitted one explicitly.
@@ -187,35 +242,45 @@ function tryBreakFkCycle(
187
242
  }
188
243
 
189
244
  /**
190
- * Yield FK constraints on `constraints` whose referenced table is also a
191
- * member of the cycle (i.e. an FK strictly between two cycle DropTables).
245
+ * Yield FK constraints on `constraints`.
192
246
  *
193
- * Self-referencing FKs are skipped they create a self-loop in the
194
- * dependency graph which the existing sort-phase handler resolves on its
195
- * own; injecting an `AlterTableDropConstraint` for a self-FK would just
196
- * add noise.
247
+ * Partition clones are skipped because PostgreSQL drops them when the
248
+ * parent constraint is dropped.
197
249
  */
198
- function* iterCrossCycleFkConstraints(
250
+ function* iterFkConstraints(
199
251
  constraints: readonly TableConstraintProps[],
200
- ownTableId: string,
201
- cycleTableIds: ReadonlySet<string>,
202
252
  ): Iterable<TableConstraintProps> {
203
253
  for (const constraint of constraints) {
204
254
  if (constraint.constraint_type !== "f") continue;
205
255
  if (constraint.is_partition_clone) continue;
206
- if (!constraint.foreign_key_schema || !constraint.foreign_key_table) {
207
- continue;
208
- }
209
- const referencedId = stableId.table(
210
- constraint.foreign_key_schema,
211
- constraint.foreign_key_table,
212
- );
213
- if (referencedId === ownTableId) continue;
214
- if (!cycleTableIds.has(referencedId)) continue;
215
256
  yield constraint;
216
257
  }
217
258
  }
218
259
 
260
+ /**
261
+ * True when `constraint` references another DropTable in the cycle.
262
+ *
263
+ * Self-referencing FKs are skipped — they create a self-loop in the
264
+ * dependency graph which the existing sort-phase handler resolves on its
265
+ * own; injecting an `AlterTableDropConstraint` for a self-FK would just
266
+ * add noise.
267
+ */
268
+ function isCrossCycleFkConstraint(
269
+ constraint: TableConstraintProps,
270
+ ownTableId: string,
271
+ cycleTableIds: ReadonlySet<string>,
272
+ ): boolean {
273
+ if (!constraint.foreign_key_schema || !constraint.foreign_key_table) {
274
+ return false;
275
+ }
276
+ const referencedId = stableId.table(
277
+ constraint.foreign_key_schema,
278
+ constraint.foreign_key_table,
279
+ );
280
+ if (referencedId === ownTableId) return false;
281
+ return cycleTableIds.has(referencedId);
282
+ }
283
+
219
284
  /**
220
285
  * True iff `phaseChanges` already contains an explicit
221
286
  * `AlterTableDropConstraint(table, constraint)` for the given pair —
@@ -309,3 +374,98 @@ function tryBreakPublicationColumnCycle(
309
374
  });
310
375
  return rewritten;
311
376
  }
377
+
378
+ /**
379
+ * Branch C worker — break a publication membership removal cycle where
380
+ * dropped tables form a FK chain ending at a separately dropped referenced
381
+ * constraint.
382
+ */
383
+ function tryBreakPublicationFkConstraintDropCycle(
384
+ cycleNodeIndexes: readonly number[],
385
+ phaseChanges: readonly Change[],
386
+ ): Change[] | null {
387
+ let pubChange: AlterPublicationDropTables | null = null;
388
+ let terminalConstraintDrop: AlterTableDropConstraint | null = null;
389
+ const dropTables: DropTable[] = [];
390
+
391
+ for (const nodeIndex of cycleNodeIndexes) {
392
+ const change = phaseChanges[nodeIndex];
393
+ if (change instanceof AlterPublicationDropTables) {
394
+ if (pubChange !== null) return null;
395
+ pubChange = change;
396
+ } else if (change instanceof AlterTableDropConstraint) {
397
+ if (terminalConstraintDrop !== null) return null;
398
+ terminalConstraintDrop = change;
399
+ } else if (change instanceof DropTable) {
400
+ dropTables.push(change);
401
+ } else {
402
+ return null;
403
+ }
404
+ }
405
+
406
+ if (
407
+ pubChange === null ||
408
+ terminalConstraintDrop === null ||
409
+ dropTables.length === 0
410
+ ) {
411
+ return null;
412
+ }
413
+
414
+ const publicationTableIds = new Set<string>(
415
+ pubChange.tables.map((table) => stableId.table(table.schema, table.name)),
416
+ );
417
+ if (!publicationTableIds.has(terminalConstraintDrop.table.stableId)) {
418
+ return null;
419
+ }
420
+
421
+ for (const dropTable of dropTables) {
422
+ if (!publicationTableIds.has(dropTable.table.stableId)) return null;
423
+ }
424
+
425
+ const cycleDropTableIds = new Set(
426
+ dropTables.map((change) => change.table.stableId),
427
+ );
428
+ let hasFkToTerminalConstraint = false;
429
+
430
+ for (const dropTable of dropTables) {
431
+ for (const fk of iterFkConstraints(dropTable.table.constraints)) {
432
+ if (fkReferencesConstraint(fk, terminalConstraintDrop)) {
433
+ hasFkToTerminalConstraint = true;
434
+ break;
435
+ }
436
+ }
437
+ if (hasFkToTerminalConstraint) break;
438
+ }
439
+ if (!hasFkToTerminalConstraint) return null;
440
+
441
+ return injectFkConstraintDropsForDropTables({
442
+ phaseChanges,
443
+ dropTables,
444
+ shouldInject: (fk, tableId) =>
445
+ isCrossCycleFkConstraint(fk, tableId, cycleDropTableIds) ||
446
+ fkReferencesConstraint(fk, terminalConstraintDrop),
447
+ });
448
+ }
449
+
450
+ function fkReferencesConstraint(
451
+ fk: TableConstraintProps,
452
+ constraintDrop: AlterTableDropConstraint,
453
+ ): boolean {
454
+ if (
455
+ fk.foreign_key_schema !== constraintDrop.table.schema ||
456
+ fk.foreign_key_table !== constraintDrop.table.name ||
457
+ fk.foreign_key_columns === null
458
+ ) {
459
+ return false;
460
+ }
461
+
462
+ return sameOrderedStrings(
463
+ fk.foreign_key_columns,
464
+ constraintDrop.constraint.key_columns,
465
+ );
466
+ }
467
+
468
+ function sameOrderedStrings(left: readonly string[], right: readonly string[]) {
469
+ if (left.length !== right.length) return false;
470
+ return left.every((value, index) => value === right[index]);
471
+ }