@supabase/pg-delta 1.0.0-alpha.16 → 1.0.0-alpha.18

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.
@@ -32,6 +32,25 @@ export function expandReplaceDependencies({ changes, mainCatalog, branchCatalog,
32
32
  replaceRoots.add(id);
33
33
  }
34
34
  }
35
+ // Procedure stableIds are signature-qualified
36
+ // (`procedure:schema.name(argtypes)`), so a function whose parameter types
37
+ // change has different ids in `createdIds` and `droppedIds` and would not
38
+ // appear in the intersection above. Treat any dropped procedure whose
39
+ // `(schema, name)` matches a created procedure as a replace root so
40
+ // dependents referencing the old signature via pg_depend get promoted to
41
+ // DROP+CREATE.
42
+ const createdProcedureNames = new Set();
43
+ for (const id of createdIds) {
44
+ const key = parseProcedureSchemaName(id);
45
+ if (key)
46
+ createdProcedureNames.add(key);
47
+ }
48
+ for (const id of droppedIds) {
49
+ const key = parseProcedureSchemaName(id);
50
+ if (key && createdProcedureNames.has(key)) {
51
+ replaceRoots.add(id);
52
+ }
53
+ }
35
54
  if (replaceRoots.size === 0) {
36
55
  return {
37
56
  changes,
@@ -149,6 +168,14 @@ function isOwnedSequenceColumnDependency(referencedId, dependentId, mainCatalog,
149
168
  return (dependentId ===
150
169
  stableId.column(sequence.owned_by_schema, sequence.owned_by_table, sequence.owned_by_column));
151
170
  }
171
+ function parseProcedureSchemaName(stableId) {
172
+ if (!stableId.startsWith("procedure:"))
173
+ return null;
174
+ const paren = stableId.indexOf("(");
175
+ if (paren === -1)
176
+ return null;
177
+ return stableId.slice("procedure:".length, paren);
178
+ }
152
179
  function normalizeDependentId(dependentId) {
153
180
  let id = dependentId;
154
181
  while (id.startsWith("comment:")) {
@@ -17,8 +17,7 @@ import { GrantProcedurePrivileges, RevokeGrantOptionProcedurePrivileges, RevokeP
17
17
  export function diffProcedures(ctx, main, branch) {
18
18
  const { created, dropped, altered } = diffObjects(main, branch);
19
19
  const changes = [];
20
- for (const procedureId of created) {
21
- const proc = branch[procedureId];
20
+ const appendCreateProcedureChanges = (proc) => {
22
21
  changes.push(new CreateProcedure({ procedure: proc }));
23
22
  // OWNER: If the procedure should be owned by someone other than the current user,
24
23
  // emit ALTER FUNCTION/PROCEDURE ... OWNER TO after creation
@@ -53,6 +52,9 @@ export function diffProcedures(ctx, main, branch) {
53
52
  Revoke: RevokeProcedurePrivileges,
54
53
  RevokeGrantOption: RevokeGrantOptionProcedurePrivileges,
55
54
  }, ctx.version));
55
+ };
56
+ for (const procedureId of created) {
57
+ appendCreateProcedureChanges(branch[procedureId]);
56
58
  }
57
59
  for (const procedureId of dropped) {
58
60
  changes.push(new DropProcedure({ procedure: main[procedureId] }));
@@ -60,22 +62,18 @@ export function diffProcedures(ctx, main, branch) {
60
62
  for (const procedureId of altered) {
61
63
  const mainProcedure = main[procedureId];
62
64
  const branchProcedure = branch[procedureId];
63
- // Check if non-alterable properties have changed
64
- // These require dropping and recreating the procedure
65
- const NON_ALTERABLE_FIELDS = [
65
+ // Fields that are part of the function's identity/signature. PostgreSQL
66
+ // rejects `CREATE OR REPLACE FUNCTION` for any of these changes with
67
+ // errors such as:
68
+ // - cannot change return type of existing function
69
+ // - cannot change name of input parameter "..."
70
+ // - cannot change whether a procedure has output parameters
71
+ // - cannot remove parameter defaults from existing function
72
+ // These require `DROP FUNCTION` followed by `CREATE FUNCTION`.
73
+ const SIGNATURE_BREAKING_FIELDS = [
66
74
  "kind",
67
75
  "return_type",
68
76
  "return_type_schema",
69
- "language",
70
- // The following properties are alterable in SQL, but our generator may choose
71
- // to replace on changes not covered by explicit ALTER actions. Keep them out here
72
- // to allow ALTER for those we implement below.
73
- // security_definer,
74
- // volatility,
75
- // parallel_safety,
76
- // is_strict,
77
- // leakproof,
78
- // Returns-set is part of the signature and not alterable
79
77
  "returns_set",
80
78
  "argument_count",
81
79
  "argument_default_count",
@@ -84,20 +82,35 @@ export function diffProcedures(ctx, main, branch) {
84
82
  "all_argument_types",
85
83
  "argument_modes",
86
84
  "argument_defaults",
85
+ ];
86
+ // Fields where `CREATE OR REPLACE` is sufficient - body replacement only.
87
+ // Other fields (security_definer, volatility, parallel_safety, is_strict,
88
+ // leakproof, config) are alterable via dedicated ALTER actions below.
89
+ const OR_REPLACEABLE_NON_ALTERABLE_FIELDS = [
90
+ "language",
87
91
  "source_code",
88
92
  "binary_path",
89
93
  "sql_body",
90
- // config is alterable via SET/RESET
91
94
  ];
92
- const nonAlterablePropsChanged = hasNonAlterableChanges(mainProcedure, branchProcedure, NON_ALTERABLE_FIELDS, {
95
+ const signatureChanged = hasNonAlterableChanges(mainProcedure, branchProcedure, SIGNATURE_BREAKING_FIELDS, {
93
96
  argument_names: deepEqual,
94
97
  argument_types: deepEqual,
95
98
  all_argument_types: deepEqual,
96
99
  argument_modes: deepEqual,
97
- config: deepEqual,
98
100
  });
99
- if (nonAlterablePropsChanged) {
100
- // Replace the entire procedure
101
+ const nonAlterablePropsChanged = signatureChanged ||
102
+ hasNonAlterableChanges(mainProcedure, branchProcedure, OR_REPLACEABLE_NON_ALTERABLE_FIELDS);
103
+ if (signatureChanged) {
104
+ // PostgreSQL cannot change an existing function's signature via
105
+ // `CREATE OR REPLACE`. Drop the old signature, then recreate.
106
+ // `expandReplaceDependencies` will cascade the replacement to dependent
107
+ // objects (views, triggers, column defaults) via pg_depend edges.
108
+ changes.push(new DropProcedure({ procedure: mainProcedure }));
109
+ appendCreateProcedureChanges(branchProcedure);
110
+ }
111
+ else if (nonAlterablePropsChanged) {
112
+ // Body-only non-alterable change - `CREATE OR REPLACE` preserves the
113
+ // function OID and keeps dependent objects attached.
101
114
  changes.push(new CreateProcedure({ procedure: branchProcedure, orReplace: true }));
102
115
  if (mainProcedure.comment !== branchProcedure.comment) {
103
116
  if (branchProcedure.comment === null) {
@@ -66,6 +66,7 @@ function createAlterConstraintChange(mainTable, branchTable) {
66
66
  mainC.validated !== branchC.validated ||
67
67
  mainC.is_local !== branchC.is_local ||
68
68
  mainC.no_inherit !== branchC.no_inherit ||
69
+ mainC.is_temporal !== branchC.is_temporal ||
69
70
  JSON.stringify(mainC.key_columns) !==
70
71
  JSON.stringify(branchC.key_columns) ||
71
72
  JSON.stringify(mainC.foreign_key_columns) !==
@@ -23,6 +23,7 @@ declare const tableConstraintPropsSchema: z.ZodObject<{
23
23
  validated: z.ZodBoolean;
24
24
  is_local: z.ZodBoolean;
25
25
  no_inherit: z.ZodBoolean;
26
+ is_temporal: z.ZodBoolean;
26
27
  is_partition_clone: z.ZodBoolean;
27
28
  parent_constraint_schema: z.ZodNullable<z.ZodString>;
28
29
  parent_constraint_name: z.ZodNullable<z.ZodString>;
@@ -125,6 +126,7 @@ declare const tablePropsSchema: z.ZodObject<{
125
126
  validated: z.ZodBoolean;
126
127
  is_local: z.ZodBoolean;
127
128
  no_inherit: z.ZodBoolean;
129
+ is_temporal: z.ZodBoolean;
128
130
  is_partition_clone: z.ZodBoolean;
129
131
  parent_constraint_schema: z.ZodNullable<z.ZodString>;
130
132
  parent_constraint_name: z.ZodNullable<z.ZodString>;
@@ -239,6 +241,7 @@ export declare class Table extends BasePgModel implements TableLikeObject {
239
241
  validated: boolean;
240
242
  is_local: boolean;
241
243
  no_inherit: boolean;
244
+ is_temporal: boolean;
242
245
  is_partition_clone: boolean;
243
246
  parent_constraint_schema: string | null;
244
247
  parent_constraint_name: string | null;
@@ -300,6 +303,7 @@ export declare class Table extends BasePgModel implements TableLikeObject {
300
303
  validated: boolean;
301
304
  is_local: boolean;
302
305
  no_inherit: boolean;
306
+ is_temporal: boolean;
303
307
  is_partition_clone: boolean;
304
308
  parent_constraint_schema: string | null;
305
309
  parent_constraint_name: string | null;
@@ -42,6 +42,7 @@ const tableConstraintPropsSchema = z.object({
42
42
  validated: z.boolean(),
43
43
  is_local: z.boolean(),
44
44
  no_inherit: z.boolean(),
45
+ is_temporal: z.boolean(),
45
46
  is_partition_clone: z.boolean(),
46
47
  parent_constraint_schema: z.string().nullable(),
47
48
  parent_constraint_name: z.string().nullable(),
@@ -253,6 +254,7 @@ select
253
254
  'validated', c.convalidated,
254
255
  'is_local', c.conislocal,
255
256
  'no_inherit', c.connoinherit,
257
+ 'is_temporal', coalesce((to_jsonb(c)->>'conperiod')::boolean, false),
256
258
 
257
259
  -- NEW: propagated-to-partition tagging (PG15+)
258
260
  'is_partition_clone', (c.conparentid <> 0::oid),
@@ -44,6 +44,11 @@ export function diffTriggers(main, branch, branchIndexableObjects) {
44
44
  if (mainTrigger.is_partition_clone || branchTrigger.is_partition_clone) {
45
45
  continue;
46
46
  }
47
+ // Note: column_numbers is excluded because it contains pg_trigger.tgattr
48
+ // attnums that differ between databases when physical column layouts
49
+ // diverge but logical (named) columns match. The definition field
50
+ // (pg_get_triggerdef) already captures the UPDATE OF column list by name,
51
+ // so we compare by definition instead.
47
52
  const NON_ALTERABLE_FIELDS = [
48
53
  "function_schema",
49
54
  "function_name",
@@ -53,14 +58,14 @@ export function diffTriggers(main, branch, branchIndexableObjects) {
53
58
  "deferrable",
54
59
  "initially_deferred",
55
60
  "argument_count",
56
- "column_numbers",
57
61
  "arguments",
58
62
  "when_condition",
59
63
  "old_table",
60
64
  "new_table",
61
65
  "owner",
66
+ "definition", // Compare by definition instead of column_numbers (tgattr)
62
67
  ];
63
- const shouldReplace = hasNonAlterableChanges(mainTrigger, branchTrigger, NON_ALTERABLE_FIELDS, { column_numbers: deepEqual, arguments: deepEqual });
68
+ const shouldReplace = hasNonAlterableChanges(mainTrigger, branchTrigger, NON_ALTERABLE_FIELDS, { arguments: deepEqual });
64
69
  if (shouldReplace) {
65
70
  const tableStableId = stableId.table(branchTrigger.schema, branchTrigger.table_name);
66
71
  changes.push(new ReplaceTrigger({
@@ -83,7 +83,6 @@ export declare class Trigger extends BasePgModel {
83
83
  deferrable: boolean;
84
84
  initially_deferred: boolean;
85
85
  argument_count: number;
86
- column_numbers: number[] | null;
87
86
  arguments: string[];
88
87
  when_condition: string | null;
89
88
  old_table: string | null;
@@ -94,6 +93,7 @@ export declare class Trigger extends BasePgModel {
94
93
  parent_table_name: string | null;
95
94
  is_on_partitioned_table: boolean;
96
95
  owner: string;
96
+ definition: string;
97
97
  comment: string | null;
98
98
  };
99
99
  }
@@ -120,7 +120,10 @@ export class Trigger extends BasePgModel {
120
120
  deferrable: this.deferrable,
121
121
  initially_deferred: this.initially_deferred,
122
122
  argument_count: this.argument_count,
123
- column_numbers: this.column_numbers,
123
+ // column_numbers excluded: contains pg_trigger.tgattr attnums that differ
124
+ // between databases when physical column layouts diverge but logical
125
+ // (named) columns match. The definition field (pg_get_triggerdef) captures
126
+ // the UPDATE OF column list by name, so we compare by definition instead.
124
127
  arguments: this.arguments,
125
128
  when_condition: this.when_condition,
126
129
  old_table: this.old_table,
@@ -131,6 +134,7 @@ export class Trigger extends BasePgModel {
131
134
  parent_table_name: this.parent_table_name,
132
135
  is_on_partitioned_table: this.is_on_partitioned_table,
133
136
  owner: this.owner,
137
+ definition: this.definition,
134
138
  comment: this.comment,
135
139
  };
136
140
  }
@@ -294,6 +294,7 @@ const pkConstraint = {
294
294
  validated: true,
295
295
  is_local: true,
296
296
  no_inherit: false,
297
+ is_temporal: false,
297
298
  is_partition_clone: false,
298
299
  parent_constraint_schema: null,
299
300
  parent_constraint_name: null,
@@ -324,6 +325,7 @@ const uniqueConstraint = {
324
325
  validated: true,
325
326
  is_local: true,
326
327
  no_inherit: false,
328
+ is_temporal: false,
327
329
  is_partition_clone: false,
328
330
  parent_constraint_schema: null,
329
331
  parent_constraint_name: null,
@@ -353,6 +355,7 @@ const fkConstraint = {
353
355
  validated: true,
354
356
  is_local: true,
355
357
  no_inherit: false,
358
+ is_temporal: false,
356
359
  is_partition_clone: false,
357
360
  parent_constraint_schema: null,
358
361
  parent_constraint_name: null,
@@ -382,6 +385,7 @@ const checkConstraint = {
382
385
  validated: true,
383
386
  is_local: true,
384
387
  no_inherit: true,
388
+ is_temporal: false,
385
389
  is_partition_clone: false,
386
390
  parent_constraint_schema: null,
387
391
  parent_constraint_name: null,
@@ -8,6 +8,13 @@ import type { Change } from "./change.types.ts";
8
8
  * - If replace expansion added `DropTable(T)+CreateTable(T)`, targeted
9
9
  * `AlterTableDropColumn(T.*)` / `AlterTableDropConstraint(T.*)` changes are
10
10
  * redundant and create an unbreakable drop-phase cycle, so we elide them.
11
+ * - When the same `DropTable+CreateTable` pair is present, the expansion
12
+ * also emits one `AlterTableAddConstraint` / `AlterTableValidateConstraint`
13
+ * / `CreateCommentOnConstraint` per branch constraint, which may collide
14
+ * with the same change already emitted by `diffTables()` (for example on a
15
+ * shape flip or a new constraint). We dedupe these keeping only the last
16
+ * occurrence so the expansion's emission survives and the diffTables
17
+ * duplicate is removed.
11
18
  * - If two dropped tables reference each other via FK, we insert dedicated
12
19
  * `AlterTableDropConstraint` changes and teach the paired `DropTable`
13
20
  * changes not to claim those FK stable IDs.
@@ -1,4 +1,5 @@
1
- import { AlterTableDropColumn, AlterTableDropConstraint, } from "./objects/table/changes/table.alter.js";
1
+ import { AlterTableAddConstraint, AlterTableDropColumn, AlterTableDropConstraint, AlterTableValidateConstraint, } from "./objects/table/changes/table.alter.js";
2
+ import { CreateCommentOnConstraint } from "./objects/table/changes/table.comment.js";
2
3
  import { DropTable } from "./objects/table/changes/table.drop.js";
3
4
  import { stableId } from "./objects/utils.js";
4
5
  function constraintStableId(table, constraintName) {
@@ -33,6 +34,63 @@ function isSupersededByTableReplacement(change, replacedTableIds) {
33
34
  }
34
35
  return replacedTableIds.has(change.table.stableId);
35
36
  }
37
+ /**
38
+ * Drop earlier duplicates of `AlterTableAddConstraint` /
39
+ * `AlterTableValidateConstraint` / `CreateCommentOnConstraint` targeting
40
+ * replaced tables, keeping only the last occurrence of each
41
+ * `(changeType, table.stableId, constraint.name)`.
42
+ *
43
+ * When `expandReplaceDependencies()` promotes a table to a full
44
+ * `DropTable + CreateTable` pair, it also emits one
45
+ * `AlterTableAddConstraint` (plus optional `VALIDATE CONSTRAINT` /
46
+ * `COMMENT ON CONSTRAINT`) per branch constraint. If `diffTables()` already
47
+ * emitted the same change for a shape flip or a new constraint on that
48
+ * table, the plan ends up with two identical `ALTER TABLE ... ADD
49
+ * CONSTRAINT ...` statements and PostgreSQL fails at apply time with
50
+ * `constraint "..." for relation "..." already exists`. Because
51
+ * `expandReplaceDependencies()` appends its additions after the original
52
+ * `diffTables()` output, the last occurrence is the expansion's emission —
53
+ * keeping it preserves correctness while removing the duplicate.
54
+ */
55
+ function dropReplacedTableDuplicateConstraintChanges(changes, replacedTableIds) {
56
+ if (replacedTableIds.size === 0)
57
+ return changes;
58
+ const keyFor = (change) => {
59
+ if (!(change instanceof AlterTableAddConstraint) &&
60
+ !(change instanceof AlterTableValidateConstraint) &&
61
+ !(change instanceof CreateCommentOnConstraint)) {
62
+ return null;
63
+ }
64
+ if (!replacedTableIds.has(change.table.stableId))
65
+ return null;
66
+ const tag = change instanceof AlterTableAddConstraint
67
+ ? "add"
68
+ : change instanceof AlterTableValidateConstraint
69
+ ? "validate"
70
+ : "comment";
71
+ return `${tag}:${constraintStableId(change.table, change.constraint.name)}`;
72
+ };
73
+ const seen = new Set();
74
+ const reversedKept = [];
75
+ let mutated = false;
76
+ // Walk backwards: the first encounter of each key corresponds to its LAST
77
+ // occurrence in the original order. `expandReplaceDependencies()` appends
78
+ // additions after the original changes, so "last wins" keeps the
79
+ // expansion's emission and drops the earlier diffTables duplicate.
80
+ for (let i = changes.length - 1; i >= 0; i--) {
81
+ const change = changes[i];
82
+ const key = keyFor(change);
83
+ if (key !== null) {
84
+ if (seen.has(key)) {
85
+ mutated = true;
86
+ continue;
87
+ }
88
+ seen.add(key);
89
+ }
90
+ reversedKept.push(change);
91
+ }
92
+ return mutated ? reversedKept.reverse() : changes;
93
+ }
36
94
  function collectExplicitConstraintDropIds(changes) {
37
95
  const explicitConstraintDropIds = new Set();
38
96
  for (const change of changes) {
@@ -59,6 +117,13 @@ function hasSameEntries(left, right) {
59
117
  * - If replace expansion added `DropTable(T)+CreateTable(T)`, targeted
60
118
  * `AlterTableDropColumn(T.*)` / `AlterTableDropConstraint(T.*)` changes are
61
119
  * redundant and create an unbreakable drop-phase cycle, so we elide them.
120
+ * - When the same `DropTable+CreateTable` pair is present, the expansion
121
+ * also emits one `AlterTableAddConstraint` / `AlterTableValidateConstraint`
122
+ * / `CreateCommentOnConstraint` per branch constraint, which may collide
123
+ * with the same change already emitted by `diffTables()` (for example on a
124
+ * shape flip or a new constraint). We dedupe these keeping only the last
125
+ * occurrence so the expansion's emission survives and the diffTables
126
+ * duplicate is removed.
62
127
  * - If two dropped tables reference each other via FK, we insert dedicated
63
128
  * `AlterTableDropConstraint` changes and teach the paired `DropTable`
64
129
  * changes not to claim those FK stable IDs.
@@ -67,9 +132,10 @@ function hasSameEntries(left, right) {
67
132
  * in the corresponding `diff*` function instead of this pass.
68
133
  */
69
134
  export function normalizePostDiffCycles({ changes, mainCatalog, replacedTableIds = new Set(), }) {
135
+ const dedupedChanges = dropReplacedTableDuplicateConstraintChanges(changes, replacedTableIds);
70
136
  const structurallyNormalizedChanges = replacedTableIds.size === 0
71
- ? changes
72
- : changes.filter((change) => !isSupersededByTableReplacement(change, replacedTableIds));
137
+ ? dedupedChanges
138
+ : dedupedChanges.filter((change) => !isSupersededByTableReplacement(change, replacedTableIds));
73
139
  const dropTableChanges = structurallyNormalizedChanges.filter((change) => change instanceof DropTable);
74
140
  if (dropTableChanges.length < 2) {
75
141
  return structurallyNormalizedChanges;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supabase/pg-delta",
3
- "version": "1.0.0-alpha.16",
3
+ "version": "1.0.0-alpha.18",
4
4
  "description": "PostgreSQL migrations made easy",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -3,6 +3,9 @@ import { Catalog, createEmptyCatalog } from "./catalog.model.ts";
3
3
  import type { Change } from "./change.types.ts";
4
4
  import { expandReplaceDependencies } from "./expand-replace-dependencies.ts";
5
5
  import { DefaultPrivilegeState } from "./objects/base.default-privileges.ts";
6
+ import { CreateProcedure } from "./objects/procedure/changes/procedure.create.ts";
7
+ import { DropProcedure } from "./objects/procedure/changes/procedure.drop.ts";
8
+ import { Procedure } from "./objects/procedure/procedure.model.ts";
6
9
  import { CreateSequence } from "./objects/sequence/changes/sequence.create.ts";
7
10
  import { DropSequence } from "./objects/sequence/changes/sequence.drop.ts";
8
11
  import { diffSequences } from "./objects/sequence/sequence.diff.ts";
@@ -22,6 +25,9 @@ import { Table } from "./objects/table/table.model.ts";
22
25
  import { CreateEnum } from "./objects/type/enum/changes/enum.create.ts";
23
26
  import { DropEnum } from "./objects/type/enum/changes/enum.drop.ts";
24
27
  import { Enum } from "./objects/type/enum/enum.model.ts";
28
+ import { CreateView } from "./objects/view/changes/view.create.ts";
29
+ import { DropView } from "./objects/view/changes/view.drop.ts";
30
+ import { View } from "./objects/view/view.model.ts";
25
31
 
26
32
  function mockChange(overrides: {
27
33
  creates?: string[];
@@ -330,6 +336,7 @@ describe("expandReplaceDependencies", () => {
330
336
  validated: true,
331
337
  is_local: true,
332
338
  no_inherit: false,
339
+ is_temporal: false,
333
340
  is_partition_clone: false,
334
341
  parent_constraint_schema: null,
335
342
  parent_constraint_name: null,
@@ -431,4 +438,115 @@ describe("expandReplaceDependencies", () => {
431
438
  expect(expanded.changes).toContain(preExistingGrant);
432
439
  expect(expanded.replacedTableIds.has("table:public.parents")).toBe(false);
433
440
  });
441
+
442
+ test("promotes dependent view when a procedure's parameter types change", async () => {
443
+ // Procedure stableIds are signature-qualified, so a parameter-type change
444
+ // produces different stableIds in `createdIds` and `droppedIds`. The
445
+ // expander must still treat the (schema, name)-matched pair as a replace
446
+ // root so a dependent view is promoted from `CREATE OR REPLACE VIEW` to
447
+ // `DROP VIEW` + `CREATE VIEW` (otherwise `DROP FUNCTION` fails with
448
+ // "cannot drop function because other objects depend on it").
449
+ const baseline = await createEmptyCatalog(170000, "postgres");
450
+ const procedureBase = {
451
+ schema: "public",
452
+ name: "format_id",
453
+ kind: "f" as const,
454
+ return_type: "text",
455
+ return_type_schema: "pg_catalog",
456
+ language: "sql",
457
+ security_definer: false,
458
+ volatility: "i" as const,
459
+ parallel_safety: "u" as const,
460
+ execution_cost: 100,
461
+ result_rows: 0,
462
+ is_strict: false,
463
+ leakproof: false,
464
+ returns_set: false,
465
+ argument_count: 1,
466
+ argument_default_count: 0,
467
+ argument_names: ["id"],
468
+ all_argument_types: null,
469
+ argument_modes: null,
470
+ argument_defaults: null,
471
+ source_code: "SELECT 'id:' || id::text",
472
+ binary_path: null,
473
+ sql_body: null,
474
+ config: null,
475
+ owner: "postgres",
476
+ comment: null,
477
+ privileges: [],
478
+ };
479
+ const mainProcedure = new Procedure({
480
+ ...procedureBase,
481
+ argument_types: ["int4"],
482
+ definition: "CREATE FUNCTION public.format_id(id integer) ...",
483
+ });
484
+ const branchProcedure = new Procedure({
485
+ ...procedureBase,
486
+ argument_types: ["int8"],
487
+ definition: "CREATE FUNCTION public.format_id(id bigint) ...",
488
+ });
489
+ const viewBase = {
490
+ schema: "public",
491
+ name: "items_formatted",
492
+ row_security: false,
493
+ force_row_security: false,
494
+ has_indexes: false,
495
+ has_rules: false,
496
+ has_triggers: false,
497
+ has_subclasses: false,
498
+ is_populated: true,
499
+ replica_identity: "d" as const,
500
+ is_partition: false,
501
+ options: null,
502
+ partition_bound: null,
503
+ owner: "postgres",
504
+ comment: null,
505
+ columns: [],
506
+ privileges: [],
507
+ };
508
+ const mainView = new View({
509
+ ...viewBase,
510
+ definition: "SELECT public.format_id(id) FROM public.items",
511
+ });
512
+ const branchView = new View({
513
+ ...viewBase,
514
+ definition: "SELECT public.format_id(id::bigint) FROM public.items",
515
+ });
516
+
517
+ const changes: Change[] = [
518
+ new DropProcedure({ procedure: mainProcedure }),
519
+ new CreateProcedure({ procedure: branchProcedure }),
520
+ // view.diff emits this because pg_get_viewdef text differs after the
521
+ // underlying function signature changes.
522
+ new CreateView({ view: branchView, orReplace: true }),
523
+ ];
524
+
525
+ const mainCatalog = new Catalog({
526
+ ...baseline,
527
+ procedures: { [mainProcedure.stableId]: mainProcedure },
528
+ views: { [mainView.stableId]: mainView },
529
+ depends: [
530
+ {
531
+ dependent_stable_id: mainView.stableId,
532
+ referenced_stable_id: mainProcedure.stableId,
533
+ deptype: "n",
534
+ },
535
+ ],
536
+ });
537
+ const branchCatalog = new Catalog({
538
+ ...baseline,
539
+ procedures: { [branchProcedure.stableId]: branchProcedure },
540
+ views: { [branchView.stableId]: branchView },
541
+ depends: [],
542
+ });
543
+
544
+ const expanded = expandReplaceDependencies({
545
+ changes,
546
+ mainCatalog,
547
+ branchCatalog,
548
+ });
549
+
550
+ expect(expanded.changes.some((c) => c instanceof DropView)).toBe(true);
551
+ });
434
552
  });
@@ -102,6 +102,25 @@ export function expandReplaceDependencies({
102
102
  }
103
103
  }
104
104
 
105
+ // Procedure stableIds are signature-qualified
106
+ // (`procedure:schema.name(argtypes)`), so a function whose parameter types
107
+ // change has different ids in `createdIds` and `droppedIds` and would not
108
+ // appear in the intersection above. Treat any dropped procedure whose
109
+ // `(schema, name)` matches a created procedure as a replace root so
110
+ // dependents referencing the old signature via pg_depend get promoted to
111
+ // DROP+CREATE.
112
+ const createdProcedureNames = new Set<string>();
113
+ for (const id of createdIds) {
114
+ const key = parseProcedureSchemaName(id);
115
+ if (key) createdProcedureNames.add(key);
116
+ }
117
+ for (const id of droppedIds) {
118
+ const key = parseProcedureSchemaName(id);
119
+ if (key && createdProcedureNames.has(key)) {
120
+ replaceRoots.add(id);
121
+ }
122
+ }
123
+
105
124
  if (replaceRoots.size === 0) {
106
125
  return {
107
126
  changes,
@@ -259,6 +278,13 @@ function isOwnedSequenceColumnDependency(
259
278
  );
260
279
  }
261
280
 
281
+ function parseProcedureSchemaName(stableId: string): string | null {
282
+ if (!stableId.startsWith("procedure:")) return null;
283
+ const paren = stableId.indexOf("(");
284
+ if (paren === -1) return null;
285
+ return stableId.slice("procedure:".length, paren);
286
+ }
287
+
262
288
  function normalizeDependentId(dependentId: string): string | null {
263
289
  let id = dependentId;
264
290