@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
@@ -1,4 +1,5 @@
1
1
  import { quoteLiteral } from "../../../base.change.js";
2
+ import { redactOptionValue } from "../../sensitive-options.js";
2
3
  import { AlterUserMappingChange } from "./user-mapping.base.js";
3
4
  /**
4
5
  * ALTER USER MAPPING ... OPTIONS ( ADD | SET | DROP ... )
@@ -22,7 +23,9 @@ export class AlterUserMappingSetOptions extends AlterUserMappingChange {
22
23
  optionParts.push(`DROP ${opt.option}`);
23
24
  }
24
25
  else {
25
- const value = opt.value !== undefined ? quoteLiteral(opt.value) : "''";
26
+ const value = opt.value !== undefined
27
+ ? quoteLiteral(redactOptionValue(opt.option, opt.value))
28
+ : "''";
26
29
  optionParts.push(`${opt.action} ${opt.option} ${value}`);
27
30
  }
28
31
  }
@@ -1,5 +1,6 @@
1
1
  import { quoteLiteral } from "../../../base.change.js";
2
2
  import { stableId } from "../../../utils.js";
3
+ import { redactOptionValue } from "../../sensitive-options.js";
3
4
  import { CreateUserMappingChange } from "./user-mapping.base.js";
4
5
  /**
5
6
  * Create a user mapping.
@@ -39,9 +40,11 @@ export class CreateUserMapping extends CreateUserMappingChange {
39
40
  if (this.userMapping.options && this.userMapping.options.length > 0) {
40
41
  const optionPairs = [];
41
42
  for (let i = 0; i < this.userMapping.options.length; i += 2) {
42
- if (i + 1 < this.userMapping.options.length) {
43
- optionPairs.push(`${this.userMapping.options[i]} ${quoteLiteral(this.userMapping.options[i + 1])}`);
44
- }
43
+ const key = this.userMapping.options[i];
44
+ const value = this.userMapping.options[i + 1];
45
+ if (key === undefined || value === undefined)
46
+ continue;
47
+ optionPairs.push(`${key} ${quoteLiteral(redactOptionValue(key, value))}`);
45
48
  }
46
49
  if (optionPairs.length > 0) {
47
50
  parts.push(`OPTIONS (${optionPairs.join(", ")})`);
@@ -32,5 +32,15 @@ export declare class UserMapping extends BasePgModel {
32
32
  options: string[] | null;
33
33
  };
34
34
  }
35
+ /**
36
+ * Extract `pg_user_mapping` rows into `UserMapping` models.
37
+ *
38
+ * The returned models carry option values **verbatim** from
39
+ * `pg_user_mapping.umoptions`, which means cleartext secrets like
40
+ * `password` are present in memory. Always route through
41
+ * `extractCatalog` (which calls `normalizeCatalog`) before emitting
42
+ * options to any output channel — see CLI-1467 and
43
+ * `packages/pg-delta/src/core/objects/foreign-data-wrapper/sensitive-options.ts`.
44
+ */
35
45
  export declare function extractUserMappings(pool: Pool): Promise<UserMapping[]>;
36
46
  export {};
@@ -44,6 +44,16 @@ export class UserMapping extends BasePgModel {
44
44
  };
45
45
  }
46
46
  }
47
+ /**
48
+ * Extract `pg_user_mapping` rows into `UserMapping` models.
49
+ *
50
+ * The returned models carry option values **verbatim** from
51
+ * `pg_user_mapping.umoptions`, which means cleartext secrets like
52
+ * `password` are present in memory. Always route through
53
+ * `extractCatalog` (which calls `normalizeCatalog`) before emitting
54
+ * options to any output channel — see CLI-1467 and
55
+ * `packages/pg-delta/src/core/objects/foreign-data-wrapper/sensitive-options.ts`.
56
+ */
47
57
  export async function extractUserMappings(pool) {
48
58
  const { rows: mappingRows } = await pool.query(sql `
49
59
  select
@@ -3,9 +3,9 @@ import z from "zod";
3
3
  import { BasePgModel } from "../base.model.ts";
4
4
  declare const rlsPolicyReferencedRelationSchema: z.ZodObject<{
5
5
  kind: z.ZodEnum<{
6
+ table: "table";
6
7
  foreign_table: "foreign_table";
7
8
  materialized_view: "materialized_view";
8
- table: "table";
9
9
  view: "view";
10
10
  }>;
11
11
  schema: z.ZodString;
@@ -37,9 +37,9 @@ declare const rlsPolicyPropsSchema: z.ZodObject<{
37
37
  comment: z.ZodNullable<z.ZodString>;
38
38
  referenced_relations: z.ZodArray<z.ZodObject<{
39
39
  kind: z.ZodEnum<{
40
+ table: "table";
40
41
  foreign_table: "foreign_table";
41
42
  materialized_view: "materialized_view";
42
- table: "table";
43
43
  view: "view";
44
44
  }>;
45
45
  schema: z.ZodString;
@@ -292,8 +292,13 @@ select
292
292
  'no_inherit', c.connoinherit,
293
293
  'is_temporal', coalesce((to_jsonb(c)->>'conperiod')::boolean, false),
294
294
 
295
- -- NEW: propagated-to-partition tagging (PG15+)
296
- 'is_partition_clone', (c.conparentid <> 0::oid),
295
+ -- Inherited from a parent (partition or classical inheritance).
296
+ -- coninhcount > 0 is the canonical signal across every constraint
297
+ -- kind. We previously used conparentid <> 0, but PostgreSQL only
298
+ -- populates conparentid for PK / UNIQUE / FK on partitions; CHECK
299
+ -- constraints on partitions always have conparentid = 0 and were
300
+ -- being re-emitted on every child, failing apply with 42710.
301
+ 'is_partition_clone', (c.coninhcount > 0),
297
302
  'parent_constraint_schema', case when c.conparentid <> 0::oid then pc.connamespace::regnamespace::text end,
298
303
  'parent_constraint_name', case when c.conparentid <> 0::oid then quote_ident(pc.conname) end,
299
304
  'parent_table_schema', case when c.conparentid <> 0::oid then pc_rel.relnamespace::regnamespace::text end,
@@ -15,6 +15,13 @@ import type { Table } from "./objects/table/table.model.ts";
15
15
  * `DropTable(T) + CreateTable(T)` pair. Without this, the apply phase
16
16
  * would try to drop a column that no longer exists in the freshly
17
17
  * recreated table.
18
+ * - Prunes `DropSequence(S)` changes when `S` is `OWNED BY` a column on a
19
+ * table promoted to `DropTable + CreateTable` by the expander. The
20
+ * `DROP TABLE` cascade drops the sequence at apply time; emitting an
21
+ * explicit `DROP SEQUENCE` in the same drop phase both duplicates the
22
+ * cascade and forms an unbreakable `DropSequence ↔ DropTable` cycle on
23
+ * the bidirectional pg_depend edges between the sequence and the
24
+ * owning column.
18
25
  * - Dedupes duplicate `AlterTableAddConstraint` /
19
26
  * `AlterTableValidateConstraint` / `CreateCommentOnConstraint` changes
20
27
  * produced when `diffTables()` and `expandReplaceDependencies()` both
@@ -1,5 +1,6 @@
1
1
  import { CreateIndex } from "./objects/index/changes/index.create.js";
2
2
  import { DropIndex } from "./objects/index/changes/index.drop.js";
3
+ import { DropSequence } from "./objects/sequence/changes/sequence.drop.js";
3
4
  import { AlterTableAddConstraint, AlterTableDropColumn, AlterTableDropConstraint, AlterTableSetReplicaIdentity, AlterTableValidateConstraint, } from "./objects/table/changes/table.alter.js";
4
5
  import { CreateCommentOnConstraint } from "./objects/table/changes/table.comment.js";
5
6
  import { stableId } from "./objects/utils.js";
@@ -7,11 +8,32 @@ function constraintStableId(table, constraintName) {
7
8
  return stableId.constraint(table.schema, table.name, constraintName);
8
9
  }
9
10
  function isSupersededByTableReplacement(change, replacedTableIds) {
10
- if (!(change instanceof AlterTableDropColumn) &&
11
- !(change instanceof AlterTableDropConstraint)) {
12
- return false;
11
+ if (change instanceof AlterTableDropColumn ||
12
+ change instanceof AlterTableDropConstraint) {
13
+ return replacedTableIds.has(change.table.stableId);
13
14
  }
14
- return replacedTableIds.has(change.table.stableId);
15
+ // `DropSequence(S)` is superseded when S is OWNED BY a column on a table
16
+ // that `expandReplaceDependencies` has promoted to `DropTable + CreateTable`
17
+ // in the same plan. PostgreSQL cascade-drops the OWNED BY sequence as part
18
+ // of the DROP TABLE, so the explicit DROP SEQUENCE is redundant and — more
19
+ // importantly — closes an unbreakable `DropSequence ↔ DropTable` cycle in
20
+ // the drop phase via the bidirectional pg_depend edges between the
21
+ // sequence and its owning column (`column → sequence` for the DEFAULT
22
+ // nextval reference, `sequence → column` for the OWNED BY auto-dependency).
23
+ // The alpha.15 short-circuit in `diffSequences.dropped` only suppresses
24
+ // `DropSequence` when the owning table itself is gone from `branchTables`;
25
+ // here the table survives in branch and the replacement is added later by
26
+ // the expander, so this whole-plan rewrite has to happen post-diff.
27
+ if (change instanceof DropSequence) {
28
+ if (!change.sequence.owned_by_schema ||
29
+ !change.sequence.owned_by_table ||
30
+ !change.sequence.owned_by_column) {
31
+ return false;
32
+ }
33
+ const ownedByTableId = stableId.table(change.sequence.owned_by_schema, change.sequence.owned_by_table);
34
+ return replacedTableIds.has(ownedByTableId);
35
+ }
36
+ return false;
15
37
  }
16
38
  /**
17
39
  * Drop earlier duplicates of `AlterTableAddConstraint` /
@@ -179,6 +201,13 @@ function restoreReplicaIdentityAfterIndexReplace(changes, branchTables) {
179
201
  * `DropTable(T) + CreateTable(T)` pair. Without this, the apply phase
180
202
  * would try to drop a column that no longer exists in the freshly
181
203
  * recreated table.
204
+ * - Prunes `DropSequence(S)` changes when `S` is `OWNED BY` a column on a
205
+ * table promoted to `DropTable + CreateTable` by the expander. The
206
+ * `DROP TABLE` cascade drops the sequence at apply time; emitting an
207
+ * explicit `DROP SEQUENCE` in the same drop phase both duplicates the
208
+ * cascade and forms an unbreakable `DropSequence ↔ DropTable` cycle on
209
+ * the bidirectional pg_depend edges between the sequence and the
210
+ * owning column.
182
211
  * - Dedupes duplicate `AlterTableAddConstraint` /
183
212
  * `AlterTableValidateConstraint` / `CreateCommentOnConstraint` changes
184
213
  * produced when `diffTables()` and `expandReplaceDependencies()` both
@@ -66,6 +66,32 @@ export function tryBreakCycleByChangeInjection(cycleNodeIndexes, phaseChanges) {
66
66
  const pubColBroken = tryBreakPublicationColumnCycle(cycleNodeIndexes, phaseChanges);
67
67
  if (pubColBroken)
68
68
  return pubColBroken;
69
+ // ─── Branch C: Publication ↔ dropped FK chain ↔ constraint drop ──────
70
+ // Triggered when publication membership is being removed for tables in
71
+ // the same drop phase as a FK chain, and the chain ends at a separately
72
+ // emitted `AlterTableDropConstraint` on a table that is also being
73
+ // removed from the publication.
74
+ //
75
+ // Example (4-change cycle):
76
+ // AlterPublicationDropTables(p, [labs, posts, post_attachments])
77
+ // DropTable(post_attachments)
78
+ // DropTable(posts)
79
+ // AlterTableDropConstraint(labs.unique_lab_id)
80
+ //
81
+ // Cycle:
82
+ // publication:p → table:post_attachments
83
+ // post_attachments.post_id_fkey → column:posts.id
84
+ // posts.lab_id_fkey → constraint:labs.unique_lab_id
85
+ // constraint:labs.unique_lab_id → table:labs
86
+ //
87
+ // Fix: inject explicit FK drops for the FK constraints claimed by the
88
+ // DropTables in the cycle, including FKs that point at the terminal
89
+ // dropped constraint. The publication and terminal constraint changes
90
+ // stay unchanged; only the intermediate FK ownership is reassigned from
91
+ // DropTable to dedicated AlterTableDropConstraint changes.
92
+ const pubFkConstraintBroken = tryBreakPublicationFkConstraintDropCycle(cycleNodeIndexes, phaseChanges);
93
+ if (pubFkConstraintBroken)
94
+ return pubFkConstraintBroken;
69
95
  // No known pattern. Returning null lets sortPhaseChanges throw the
70
96
  // formatted CycleError with full diagnostic — better a clear bug
71
97
  // report than silently shipping a broken plan.
@@ -90,6 +116,19 @@ function tryBreakFkCycle(cycleNodeIndexes, phaseChanges) {
90
116
  cycleDropTables.push(change);
91
117
  }
92
118
  const cycleTableIds = new Set(cycleDropTables.map((change) => change.table.stableId));
119
+ return injectFkConstraintDropsForDropTables({
120
+ phaseChanges,
121
+ dropTables: cycleDropTables,
122
+ shouldInject: (fk, tableId) => isCrossCycleFkConstraint(fk, tableId, cycleTableIds),
123
+ });
124
+ }
125
+ /**
126
+ * Shared FK-drop injection used by Branch A and Branch C. The caller owns
127
+ * the cycle-specific matcher; this helper only handles the mechanical
128
+ * rewrite: add dedicated `AlterTableDropConstraint` changes and rebuild
129
+ * affected `DropTable`s with updated `externallyDroppedConstraints`.
130
+ */
131
+ function injectFkConstraintDropsForDropTables({ phaseChanges, dropTables, shouldInject, }) {
93
132
  // For each DropTable in the cycle, find every FK whose referenced table
94
133
  // is also in the cycle. Each such FK becomes one injected
95
134
  // `AlterTableDropConstraint` and one entry on the source table's
@@ -100,11 +139,13 @@ function tryBreakFkCycle(cycleNodeIndexes, phaseChanges) {
100
139
  const injectedDropsByTableId = new Map();
101
140
  const updatedExternalsByTableId = new Map();
102
141
  let didMutate = false;
103
- for (const dropTable of cycleDropTables) {
142
+ for (const dropTable of dropTables) {
104
143
  const tableId = dropTable.table.stableId;
105
144
  const existingExternals = new Set(dropTable.externallyDroppedConstraints);
106
145
  let tableMutated = false;
107
- for (const fk of iterCrossCycleFkConstraints(dropTable.table.constraints, tableId, cycleTableIds)) {
146
+ for (const fk of iterFkConstraints(dropTable.table.constraints)) {
147
+ if (!shouldInject(fk, tableId))
148
+ continue;
108
149
  // Skip if a same-table `AlterTableDropConstraint` is already in the
109
150
  // change list — could happen if a previous breaker iteration
110
151
  // injected one, or the diff layer emitted one explicitly.
@@ -159,31 +200,37 @@ function tryBreakFkCycle(cycleNodeIndexes, phaseChanges) {
159
200
  return rewritten;
160
201
  }
161
202
  /**
162
- * Yield FK constraints on `constraints` whose referenced table is also a
163
- * member of the cycle (i.e. an FK strictly between two cycle DropTables).
203
+ * Yield FK constraints on `constraints`.
164
204
  *
165
- * Self-referencing FKs are skipped they create a self-loop in the
166
- * dependency graph which the existing sort-phase handler resolves on its
167
- * own; injecting an `AlterTableDropConstraint` for a self-FK would just
168
- * add noise.
205
+ * Partition clones are skipped because PostgreSQL drops them when the
206
+ * parent constraint is dropped.
169
207
  */
170
- function* iterCrossCycleFkConstraints(constraints, ownTableId, cycleTableIds) {
208
+ function* iterFkConstraints(constraints) {
171
209
  for (const constraint of constraints) {
172
210
  if (constraint.constraint_type !== "f")
173
211
  continue;
174
212
  if (constraint.is_partition_clone)
175
213
  continue;
176
- if (!constraint.foreign_key_schema || !constraint.foreign_key_table) {
177
- continue;
178
- }
179
- const referencedId = stableId.table(constraint.foreign_key_schema, constraint.foreign_key_table);
180
- if (referencedId === ownTableId)
181
- continue;
182
- if (!cycleTableIds.has(referencedId))
183
- continue;
184
214
  yield constraint;
185
215
  }
186
216
  }
217
+ /**
218
+ * True when `constraint` references another DropTable in the cycle.
219
+ *
220
+ * Self-referencing FKs are skipped — they create a self-loop in the
221
+ * dependency graph which the existing sort-phase handler resolves on its
222
+ * own; injecting an `AlterTableDropConstraint` for a self-FK would just
223
+ * add noise.
224
+ */
225
+ function isCrossCycleFkConstraint(constraint, ownTableId, cycleTableIds) {
226
+ if (!constraint.foreign_key_schema || !constraint.foreign_key_table) {
227
+ return false;
228
+ }
229
+ const referencedId = stableId.table(constraint.foreign_key_schema, constraint.foreign_key_table);
230
+ if (referencedId === ownTableId)
231
+ return false;
232
+ return cycleTableIds.has(referencedId);
233
+ }
187
234
  /**
188
235
  * True iff `phaseChanges` already contains an explicit
189
236
  * `AlterTableDropConstraint(table, constraint)` for the given pair —
@@ -267,3 +314,78 @@ function tryBreakPublicationColumnCycle(cycleNodeIndexes, phaseChanges) {
267
314
  });
268
315
  return rewritten;
269
316
  }
317
+ /**
318
+ * Branch C worker — break a publication membership removal cycle where
319
+ * dropped tables form a FK chain ending at a separately dropped referenced
320
+ * constraint.
321
+ */
322
+ function tryBreakPublicationFkConstraintDropCycle(cycleNodeIndexes, phaseChanges) {
323
+ let pubChange = null;
324
+ let terminalConstraintDrop = null;
325
+ const dropTables = [];
326
+ for (const nodeIndex of cycleNodeIndexes) {
327
+ const change = phaseChanges[nodeIndex];
328
+ if (change instanceof AlterPublicationDropTables) {
329
+ if (pubChange !== null)
330
+ return null;
331
+ pubChange = change;
332
+ }
333
+ else if (change instanceof AlterTableDropConstraint) {
334
+ if (terminalConstraintDrop !== null)
335
+ return null;
336
+ terminalConstraintDrop = change;
337
+ }
338
+ else if (change instanceof DropTable) {
339
+ dropTables.push(change);
340
+ }
341
+ else {
342
+ return null;
343
+ }
344
+ }
345
+ if (pubChange === null ||
346
+ terminalConstraintDrop === null ||
347
+ dropTables.length === 0) {
348
+ return null;
349
+ }
350
+ const publicationTableIds = new Set(pubChange.tables.map((table) => stableId.table(table.schema, table.name)));
351
+ if (!publicationTableIds.has(terminalConstraintDrop.table.stableId)) {
352
+ return null;
353
+ }
354
+ for (const dropTable of dropTables) {
355
+ if (!publicationTableIds.has(dropTable.table.stableId))
356
+ return null;
357
+ }
358
+ const cycleDropTableIds = new Set(dropTables.map((change) => change.table.stableId));
359
+ let hasFkToTerminalConstraint = false;
360
+ for (const dropTable of dropTables) {
361
+ for (const fk of iterFkConstraints(dropTable.table.constraints)) {
362
+ if (fkReferencesConstraint(fk, terminalConstraintDrop)) {
363
+ hasFkToTerminalConstraint = true;
364
+ break;
365
+ }
366
+ }
367
+ if (hasFkToTerminalConstraint)
368
+ break;
369
+ }
370
+ if (!hasFkToTerminalConstraint)
371
+ return null;
372
+ return injectFkConstraintDropsForDropTables({
373
+ phaseChanges,
374
+ dropTables,
375
+ shouldInject: (fk, tableId) => isCrossCycleFkConstraint(fk, tableId, cycleDropTableIds) ||
376
+ fkReferencesConstraint(fk, terminalConstraintDrop),
377
+ });
378
+ }
379
+ function fkReferencesConstraint(fk, constraintDrop) {
380
+ if (fk.foreign_key_schema !== constraintDrop.table.schema ||
381
+ fk.foreign_key_table !== constraintDrop.table.name ||
382
+ fk.foreign_key_columns === null) {
383
+ return false;
384
+ }
385
+ return sameOrderedStrings(fk.foreign_key_columns, constraintDrop.constraint.key_columns);
386
+ }
387
+ function sameOrderedStrings(left, right) {
388
+ if (left.length !== right.length)
389
+ return false;
390
+ return left.every((value, index) => value === right[index]);
391
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supabase/pg-delta",
3
- "version": "1.0.0-alpha.23",
3
+ "version": "1.0.0-alpha.25",
4
4
  "description": "PostgreSQL migrations made easy",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -22,12 +22,13 @@ import {
22
22
  } from "./objects/extension/extension.model.ts";
23
23
  import {
24
24
  extractForeignDataWrappers,
25
- type ForeignDataWrapper,
25
+ ForeignDataWrapper,
26
26
  } from "./objects/foreign-data-wrapper/foreign-data-wrapper/foreign-data-wrapper.model.ts";
27
27
  import {
28
28
  extractForeignTables,
29
- type ForeignTable,
29
+ ForeignTable,
30
30
  } from "./objects/foreign-data-wrapper/foreign-table/foreign-table.model.ts";
31
+ import { redactSensitiveOptionPairs } from "./objects/foreign-data-wrapper/sensitive-options.ts";
31
32
  import {
32
33
  extractServers,
33
34
  Server,
@@ -421,29 +422,56 @@ function listToRecord<T extends BasePgModel>(list: T[]) {
421
422
  }
422
423
 
423
424
  function normalizeCatalog(catalog: Catalog): Catalog {
425
+ const foreignDataWrappers = mapRecord(
426
+ catalog.foreignDataWrappers,
427
+ (fdw) =>
428
+ new ForeignDataWrapper({
429
+ name: fdw.name,
430
+ owner: fdw.owner,
431
+ handler: fdw.handler,
432
+ validator: fdw.validator,
433
+ options: redactSensitiveOptionPairs(fdw.options),
434
+ comment: fdw.comment,
435
+ privileges: fdw.privileges,
436
+ }),
437
+ );
438
+
424
439
  const servers = mapRecord(catalog.servers, (server) => {
425
- const maskedOptions = maskOptions(server.options);
426
440
  return new Server({
427
441
  name: server.name,
428
442
  owner: server.owner,
429
443
  foreign_data_wrapper: server.foreign_data_wrapper,
430
444
  type: server.type,
431
445
  version: server.version,
432
- options: maskedOptions,
446
+ options: redactSensitiveOptionPairs(server.options),
433
447
  comment: server.comment,
434
448
  privileges: server.privileges,
435
449
  });
436
450
  });
437
451
 
438
452
  const userMappings = mapRecord(catalog.userMappings, (mapping) => {
439
- const maskedOptions = maskOptions(mapping.options);
440
453
  return new UserMapping({
441
454
  user: mapping.user,
442
455
  server: mapping.server,
443
- options: maskedOptions,
456
+ options: redactSensitiveOptionPairs(mapping.options),
444
457
  });
445
458
  });
446
459
 
460
+ const foreignTables = mapRecord(
461
+ catalog.foreignTables,
462
+ (foreignTable) =>
463
+ new ForeignTable({
464
+ schema: foreignTable.schema,
465
+ name: foreignTable.name,
466
+ owner: foreignTable.owner,
467
+ server: foreignTable.server,
468
+ columns: foreignTable.columns,
469
+ options: redactSensitiveOptionPairs(foreignTable.options),
470
+ comment: foreignTable.comment,
471
+ privileges: foreignTable.privileges,
472
+ }),
473
+ );
474
+
447
475
  const subscriptions = mapRecord(catalog.subscriptions, (subscription) => {
448
476
  return new Subscription({
449
477
  name: subscription.name,
@@ -490,10 +518,10 @@ function normalizeCatalog(catalog: Catalog): Catalog {
490
518
  rules: catalog.rules,
491
519
  ranges: catalog.ranges,
492
520
  views: catalog.views,
493
- foreignDataWrappers: catalog.foreignDataWrappers,
521
+ foreignDataWrappers,
494
522
  servers,
495
523
  userMappings,
496
- foreignTables: catalog.foreignTables,
524
+ foreignTables,
497
525
  depends: catalog.depends,
498
526
  indexableObjects: catalog.indexableObjects,
499
527
  version: catalog.version,
@@ -501,18 +529,6 @@ function normalizeCatalog(catalog: Catalog): Catalog {
501
529
  });
502
530
  }
503
531
 
504
- function maskOptions(options: string[] | null): string[] | null {
505
- if (!options || options.length === 0) return options;
506
- const masked: string[] = [];
507
- for (let i = 0; i < options.length; i += 2) {
508
- const key = options[i];
509
- const value = options[i + 1];
510
- if (key === undefined || value === undefined) continue;
511
- masked.push(key, `__OPTION_${key.toUpperCase()}__`);
512
- }
513
- return masked.length > 0 ? masked : null;
514
- }
515
-
516
532
  function mapRecord<TValue, TResult>(
517
533
  record: Record<string, TValue>,
518
534
  mapper: (value: TValue) => TResult,