@supabase/pg-delta 1.0.0-alpha.24 → 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 (58) 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/package.json +1 -1
  26. package/src/core/catalog.model.ts +36 -20
  27. package/src/core/integrations/supabase.test.ts +198 -0
  28. package/src/core/integrations/supabase.ts +84 -0
  29. package/src/core/objects/aggregate/changes/aggregate.privilege.test.ts +79 -0
  30. package/src/core/objects/aggregate/changes/aggregate.privilege.ts +22 -9
  31. package/src/core/objects/foreign-data-wrapper/foreign-data-wrapper/changes/foreign-data-wrapper.alter.test.ts +34 -4
  32. package/src/core/objects/foreign-data-wrapper/foreign-data-wrapper/changes/foreign-data-wrapper.alter.ts +5 -1
  33. package/src/core/objects/foreign-data-wrapper/foreign-data-wrapper/changes/foreign-data-wrapper.create.test.ts +34 -0
  34. package/src/core/objects/foreign-data-wrapper/foreign-data-wrapper/changes/foreign-data-wrapper.create.ts +7 -5
  35. package/src/core/objects/foreign-data-wrapper/foreign-data-wrapper/foreign-data-wrapper.model.ts +11 -0
  36. package/src/core/objects/foreign-data-wrapper/foreign-table/changes/foreign-table.alter.test.ts +25 -4
  37. package/src/core/objects/foreign-data-wrapper/foreign-table/changes/foreign-table.alter.ts +5 -1
  38. package/src/core/objects/foreign-data-wrapper/foreign-table/changes/foreign-table.create.test.ts +54 -0
  39. package/src/core/objects/foreign-data-wrapper/foreign-table/changes/foreign-table.create.ts +7 -5
  40. package/src/core/objects/foreign-data-wrapper/foreign-table/foreign-table.model.ts +11 -0
  41. package/src/core/objects/foreign-data-wrapper/sensitive-options.test.ts +98 -0
  42. package/src/core/objects/foreign-data-wrapper/sensitive-options.ts +133 -0
  43. package/src/core/objects/foreign-data-wrapper/server/changes/server.alter.test.ts +39 -4
  44. package/src/core/objects/foreign-data-wrapper/server/changes/server.alter.ts +5 -1
  45. package/src/core/objects/foreign-data-wrapper/server/changes/server.create.test.ts +36 -0
  46. package/src/core/objects/foreign-data-wrapper/server/changes/server.create.ts +7 -5
  47. package/src/core/objects/foreign-data-wrapper/server/server.model.ts +10 -0
  48. package/src/core/objects/foreign-data-wrapper/user-mapping/changes/user-mapping.alter.test.ts +39 -6
  49. package/src/core/objects/foreign-data-wrapper/user-mapping/changes/user-mapping.alter.ts +5 -1
  50. package/src/core/objects/foreign-data-wrapper/user-mapping/changes/user-mapping.create.test.ts +38 -2
  51. package/src/core/objects/foreign-data-wrapper/user-mapping/changes/user-mapping.create.ts +7 -5
  52. package/src/core/objects/foreign-data-wrapper/user-mapping/user-mapping.model.ts +10 -0
  53. package/src/core/objects/table/table.model.ts +7 -2
  54. package/src/core/plan/sql-format/format-off.test.ts +4 -4
  55. package/src/core/plan/sql-format/format-pretty-lower-leading.test.ts +4 -4
  56. package/src/core/plan/sql-format/format-pretty-narrow.test.ts +5 -4
  57. package/src/core/plan/sql-format/format-pretty-preserve.test.ts +4 -4
  58. package/src/core/plan/sql-format/format-pretty-upper.test.ts +4 -4
@@ -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,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supabase/pg-delta",
3
- "version": "1.0.0-alpha.24",
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,
@@ -0,0 +1,198 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { Change } from "../change.types.ts";
3
+ import { evaluatePattern } from "./filter/dsl.ts";
4
+ import { supabase } from "./supabase.ts";
5
+
6
+ if (!supabase.filter) {
7
+ throw new Error("supabase integration is missing a filter");
8
+ }
9
+ const filter = supabase.filter;
10
+
11
+ /**
12
+ * Build a synthetic FDW change shaped like what `flattenChange` consumes.
13
+ * The change carries a `foreignDataWrapper` model whose `handler`/`validator`
14
+ * are schema-qualified function references (the form
15
+ * `extractForeignDataWrappers` produces).
16
+ */
17
+ function fdwChange(
18
+ operation: "create" | "alter" | "drop",
19
+ fdw: {
20
+ name: string;
21
+ owner: string;
22
+ handler: string | null;
23
+ validator: string | null;
24
+ },
25
+ ): Change {
26
+ return {
27
+ objectType: "foreign_data_wrapper",
28
+ operation,
29
+ scope: "object",
30
+ foreignDataWrapper: fdw,
31
+ requires: [],
32
+ creates: [],
33
+ drops: [],
34
+ } as unknown as Change;
35
+ }
36
+
37
+ /**
38
+ * Synthetic FDW privilege change. The three concrete privilege classes
39
+ * (`GrantForeignDataWrapperPrivileges`, `RevokeForeignDataWrapperPrivileges`,
40
+ * `RevokeGrantOptionForeignDataWrapperPrivileges`) all extend
41
+ * `AlterForeignDataWrapperChange`, so their `operation` is `"alter"` in
42
+ * production. The filter rule we exercise here keys off `scope` only,
43
+ * but pinning `operation: "alter"` keeps the synthetic shape honest.
44
+ */
45
+ function fdwPrivilegeChange(fdw: { name: string; owner: string }): Change {
46
+ return {
47
+ objectType: "foreign_data_wrapper",
48
+ operation: "alter",
49
+ scope: "privilege",
50
+ foreignDataWrapper: { ...fdw, handler: null, validator: null },
51
+ grantee: "postgres",
52
+ requires: [],
53
+ creates: [],
54
+ drops: [],
55
+ } as unknown as Change;
56
+ }
57
+
58
+ function serverPrivilegeChange(server: {
59
+ name: string;
60
+ owner: string;
61
+ }): Change {
62
+ return {
63
+ objectType: "server",
64
+ operation: "alter",
65
+ scope: "privilege",
66
+ server,
67
+ grantee: "postgres",
68
+ requires: [],
69
+ creates: [],
70
+ drops: [],
71
+ } as unknown as Change;
72
+ }
73
+
74
+ describe("supabase integration filter — foreign data wrappers", () => {
75
+ // Regression for CLI-1470. Wasm-based foreign data wrappers on Supabase
76
+ // (e.g. `clerk`, `clerk_oauth`) are provisioned at project creation by
77
+ // `supabase_admin` and their handler/validator live in `extensions.*`.
78
+ // pg-delta must not emit `CREATE/DROP/ALTER FOREIGN DATA WRAPPER` for
79
+ // them, even when the FDW owner has been rewritten away from
80
+ // `supabase_admin` (e.g. after a dump/restore).
81
+ test("suppresses CREATE for FDW with handler in extensions schema", () => {
82
+ const change = fdwChange("create", {
83
+ name: "clerk",
84
+ owner: "postgres",
85
+ handler: "extensions.wasm_fdw_handler",
86
+ validator: "extensions.wasm_fdw_validator",
87
+ });
88
+ expect(evaluatePattern(filter, change)).toBe(false);
89
+ });
90
+
91
+ test("suppresses DROP for FDW with handler in extensions schema", () => {
92
+ const change = fdwChange("drop", {
93
+ name: "clerk_oauth",
94
+ owner: "postgres",
95
+ handler: "extensions.wasm_fdw_handler",
96
+ validator: "extensions.wasm_fdw_validator",
97
+ });
98
+ expect(evaluatePattern(filter, change)).toBe(false);
99
+ });
100
+
101
+ test("suppresses ALTER for FDW with handler in extensions schema", () => {
102
+ const change = fdwChange("alter", {
103
+ name: "clerk",
104
+ owner: "postgres",
105
+ handler: "extensions.wasm_fdw_handler",
106
+ validator: "extensions.wasm_fdw_validator",
107
+ });
108
+ expect(evaluatePattern(filter, change)).toBe(false);
109
+ });
110
+
111
+ test("suppresses FDW when only the validator lives in extensions", () => {
112
+ const change = fdwChange("create", {
113
+ name: "partial_wasm",
114
+ owner: "postgres",
115
+ handler: null,
116
+ validator: "extensions.wasm_fdw_validator",
117
+ });
118
+ expect(evaluatePattern(filter, change)).toBe(false);
119
+ });
120
+
121
+ test("preserves user FDW whose handler lives outside extensions", () => {
122
+ const change = fdwChange("create", {
123
+ name: "user_fdw",
124
+ owner: "postgres",
125
+ handler: "public.my_fdw_handler",
126
+ validator: "public.my_fdw_validator",
127
+ });
128
+ expect(evaluatePattern(filter, change)).toBe(true);
129
+ });
130
+
131
+ test("preserves user FDW with no handler/validator", () => {
132
+ const change = fdwChange("create", {
133
+ name: "user_fdw_bare",
134
+ owner: "postgres",
135
+ handler: null,
136
+ validator: null,
137
+ });
138
+ expect(evaluatePattern(filter, change)).toBe(true);
139
+ });
140
+ });
141
+
142
+ describe("supabase integration filter — foreign data wrapper / server ACLs", () => {
143
+ // Regression for CLI-1469. `GRANT`/`REVOKE ... ON FOREIGN DATA WRAPPER`
144
+ // require superuser. On Supabase Cloud `postgres` has the elevated
145
+ // rights to make them work; the local Docker image does not, so
146
+ // `supabase db reset` aborts with `permission denied for foreign-data
147
+ // wrapper`. FDW ACL is platform-managed, not user-declarative state —
148
+ // suppress regardless of owner because `pg_dump` rewrites OWNER TO
149
+ // away from `supabase_admin`.
150
+ test("suppresses FDW ACL when owner=supabase_admin (existing */owner rule)", () => {
151
+ const change = fdwPrivilegeChange({
152
+ name: "dblink_fdw",
153
+ owner: "supabase_admin",
154
+ });
155
+ expect(evaluatePattern(filter, change)).toBe(false);
156
+ });
157
+
158
+ test("suppresses FDW ACL when owner=postgres (post-restore)", () => {
159
+ const change = fdwPrivilegeChange({
160
+ name: "dblink_fdw",
161
+ owner: "postgres",
162
+ });
163
+ expect(evaluatePattern(filter, change)).toBe(false);
164
+ });
165
+
166
+ // FOREIGN SERVER ACL is owner-scoped, not blanket-suppressed:
167
+ // server GRANT/REVOKE does not require superuser, so a user-owned
168
+ // server's ACL must roundtrip. The pre-existing `*/owner` rule
169
+ // already drops platform-managed servers (owner ∈ system roles).
170
+ test("suppresses server ACL when owner=supabase_admin (existing */owner rule)", () => {
171
+ const change = serverPrivilegeChange({
172
+ name: "platform_server",
173
+ owner: "supabase_admin",
174
+ });
175
+ expect(evaluatePattern(filter, change)).toBe(false);
176
+ });
177
+
178
+ test("preserves server ACL when owner=postgres", () => {
179
+ const change = serverPrivilegeChange({
180
+ name: "user_dblink_server",
181
+ owner: "postgres",
182
+ });
183
+ expect(evaluatePattern(filter, change)).toBe(true);
184
+ });
185
+
186
+ // Non-privilege FDW changes whose handler/validator aren't in
187
+ // `extensions.*` should still pass through (a user FDW is plain DDL,
188
+ // not the platform-managed flavor).
189
+ test("preserves non-privilege FDW changes for user wrappers", () => {
190
+ const change = fdwChange("create", {
191
+ name: "user_fdw",
192
+ owner: "postgres",
193
+ handler: "public.my_fdw_handler",
194
+ validator: null,
195
+ });
196
+ expect(evaluatePattern(filter, change)).toBe(true);
197
+ });
198
+ });
@@ -99,6 +99,34 @@ export const supabase: IntegrationDSL = {
99
99
  operation: "drop",
100
100
  scope: "object",
101
101
  },
102
+ // Include user-attached triggers on tables in Supabase-managed schemas.
103
+ //
104
+ // Triggers live in the schema of the table they fire on, so a user
105
+ // trigger on `auth.users` reports `trigger/schema = auth` and is
106
+ // otherwise indistinguishable from Supabase's own triggers via the
107
+ // schema-level deny list. Triggers also have no real owner — pg-delta
108
+ // surfaces the parent table's owner as `trigger/owner`, which for
109
+ // `auth.users` and `storage.objects` is always a Supabase system role,
110
+ // so the owner-level deny list catches them too.
111
+ //
112
+ // The trigger function, however, is genuinely user-owned: a customer
113
+ // who wants to run code on an auth event creates a function in
114
+ // `public` (or any non-managed schema) and points the trigger at it.
115
+ // Supabase's own auth/storage triggers either come from extensions
116
+ // (already filtered out at extract time via `pg_depend`) or call
117
+ // functions inside the same managed schema, so `function_schema`
118
+ // outside the managed list is a reliable user-defined marker.
119
+ {
120
+ and: [
121
+ { objectType: "trigger" },
122
+ { "trigger/schema": [...SUPABASE_SYSTEM_SCHEMAS] },
123
+ {
124
+ not: {
125
+ "trigger/function_schema": [...SUPABASE_SYSTEM_SCHEMAS],
126
+ },
127
+ },
128
+ ],
129
+ },
102
130
  // Exclude system objects
103
131
  {
104
132
  not: {
@@ -131,6 +159,62 @@ export const supabase: IntegrationDSL = {
131
159
  },
132
160
  ],
133
161
  },
162
+ // Platform-managed foreign data wrapper ACL.
163
+ // `GRANT`/`REVOKE ... ON FOREIGN DATA WRAPPER` requires
164
+ // superuser. On Supabase Cloud `postgres` has the elevated
165
+ // rights to make this work, but the local Docker image does
166
+ // not, so `supabase db reset` aborts with
167
+ // `permission denied for foreign-data wrapper`. The
168
+ // `*/owner` rule above already covers wrappers owned by
169
+ // `supabase_admin`, but `pg_dump` rewrites OWNER TO clauses
170
+ // to whoever the dump runs under, so after a restore the
171
+ // FDW typically ends up owned by `postgres` and slips past
172
+ // the owner gate. A non-superuser `postgres` still can't
173
+ // grant on a FDW (this is true regardless of who owns the
174
+ // wrapper locally), so the ACL diff is not user-replayable.
175
+ // We don't apply the same blanket rule to `FOREIGN SERVER`:
176
+ // server GRANT/REVOKE doesn't require superuser, and
177
+ // user-created servers (e.g. a `dblink` server pointing to
178
+ // a peer DB) carry legitimate user ACL that should
179
+ // roundtrip — the existing `*/owner` rule already drops
180
+ // platform-managed servers.
181
+ {
182
+ and: [
183
+ { objectType: "foreign_data_wrapper" },
184
+ { scope: "privilege" },
185
+ ],
186
+ },
187
+ // Platform-managed foreign data wrappers — Wasm-based FDWs
188
+ // (e.g. `clerk`, `clerk_oauth`) whose handler/validator live in
189
+ // the `extensions` schema. `CREATE FOREIGN DATA WRAPPER`
190
+ // requires superuser, and Supabase Cloud provisions these via
191
+ // `supabase_admin` at project creation; replaying the DDL
192
+ // against a local image fails because the local environment
193
+ // has no equivalent pre-step. We can't rely on the FDW owner
194
+ // alone — after a dump/restore the owner is often rewritten
195
+ // away from `supabase_admin` — so match on the function
196
+ // reference instead.
197
+ {
198
+ and: [
199
+ { objectType: "foreign_data_wrapper" },
200
+ {
201
+ or: [
202
+ {
203
+ "foreign_data_wrapper/handler": {
204
+ op: "regex",
205
+ value: "^extensions\\.",
206
+ },
207
+ },
208
+ {
209
+ "foreign_data_wrapper/validator": {
210
+ op: "regex",
211
+ value: "^extensions\\.",
212
+ },
213
+ },
214
+ ],
215
+ },
216
+ ],
217
+ },
134
218
  ],
135
219
  },
136
220
  },
@@ -92,6 +92,85 @@ describe("aggregate.privilege", () => {
92
92
  );
93
93
  });
94
94
 
95
+ // Regression for CLI-1471: ordered-set / hypothetical-set / variadic
96
+ // aggregates have `identity_arguments` that include `ORDER BY` or
97
+ // `VARIADIC` keywords. Those keywords are rejected by
98
+ // `GRANT ... ON FUNCTION (...)` (only positional argument types are
99
+ // accepted there), so the serializer must drop back to the
100
+ // `proargtypes`-derived `argument_types` list.
101
+ test("grant on ordered-set aggregate emits proargtypes signature", async () => {
102
+ const aggregate = new Aggregate({
103
+ ...base,
104
+ name: "os_last",
105
+ aggkind: "o",
106
+ identity_arguments: "anyelement ORDER BY anyelement",
107
+ argument_types: ["anyelement", "anyelement"],
108
+ return_type: "anyelement",
109
+ transition_function: "public.os_last_sfunc(anyelement,anyelement)",
110
+ state_data_type: "anyelement",
111
+ argument_count: 2,
112
+ });
113
+ const change = new GrantAggregatePrivileges({
114
+ aggregate,
115
+ grantee: "role_exec",
116
+ privileges: [{ privilege: "EXECUTE", grantable: false }],
117
+ version: 170000,
118
+ });
119
+ await assertValidSql(change.serialize());
120
+ expect(change.serialize()).toBe(
121
+ "GRANT ALL ON FUNCTION public.os_last(anyelement, anyelement) TO role_exec",
122
+ );
123
+ });
124
+
125
+ test("revoke on hypothetical-set aggregate emits proargtypes signature", async () => {
126
+ const aggregate = new Aggregate({
127
+ ...base,
128
+ name: "hyp_rank",
129
+ aggkind: "h",
130
+ identity_arguments: 'VARIADIC "any" ORDER BY VARIADIC "any"',
131
+ argument_types: ['"any"'],
132
+ return_type: "bigint",
133
+ transition_function:
134
+ 'pg_catalog.ordered_set_transition_multi(internal,"any")',
135
+ state_data_type: "internal",
136
+ argument_count: 1,
137
+ });
138
+ const change = new RevokeAggregatePrivileges({
139
+ aggregate,
140
+ grantee: "role_old",
141
+ privileges: [{ privilege: "EXECUTE", grantable: false }],
142
+ version: 170000,
143
+ });
144
+ await assertValidSql(change.serialize());
145
+ expect(change.serialize()).toBe(
146
+ 'REVOKE ALL ON FUNCTION public.hyp_rank("any") FROM role_old',
147
+ );
148
+ });
149
+
150
+ test("revoke grant option on ordered-set aggregate emits proargtypes signature", async () => {
151
+ const aggregate = new Aggregate({
152
+ ...base,
153
+ name: "os_last",
154
+ aggkind: "o",
155
+ identity_arguments: "anyelement ORDER BY anyelement",
156
+ argument_types: ["anyelement", "anyelement"],
157
+ return_type: "anyelement",
158
+ transition_function: "public.os_last_sfunc(anyelement,anyelement)",
159
+ state_data_type: "anyelement",
160
+ argument_count: 2,
161
+ });
162
+ const change = new RevokeGrantOptionAggregatePrivileges({
163
+ aggregate,
164
+ grantee: "role_with_option",
165
+ privilegeNames: ["EXECUTE"],
166
+ version: 170000,
167
+ });
168
+ await assertValidSql(change.serialize());
169
+ expect(change.serialize()).toBe(
170
+ "REVOKE GRANT OPTION FOR ALL ON FUNCTION public.os_last(anyelement, anyelement) FROM role_with_option",
171
+ );
172
+ });
173
+
95
174
  test("revoke privileges and grant option", async () => {
96
175
  const aggregate = new Aggregate(base);
97
176
  const revoke = new RevokeAggregatePrivileges({
@@ -12,6 +12,25 @@ export type AggregatePrivilege =
12
12
  | RevokeAggregatePrivileges
13
13
  | RevokeGrantOptionAggregatePrivileges;
14
14
 
15
+ /**
16
+ * Build the signature `<schema>.<name>(<argtypes>)` for use inside
17
+ * `GRANT`/`REVOKE ... ON FUNCTION (...)`.
18
+ *
19
+ * The aggregate's `identityArguments` (from
20
+ * `pg_get_function_identity_arguments`) embeds `ORDER BY` for ordered-set
21
+ * and hypothetical-set aggregates (`aggkind` of `o`/`h`) and `VARIADIC`
22
+ * for variadic aggregates — both of which the GRANT parser rejects with
23
+ * a syntax error. PostgreSQL resolves the aggregate from the positional
24
+ * argument types alone, so use `argument_types` here regardless of
25
+ * `aggkind`. Other aggregate DDL (`ALTER AGGREGATE`, `COMMENT ON
26
+ * AGGREGATE`, `SECURITY LABEL ON AGGREGATE`, `DROP AGGREGATE`) accepts
27
+ * the identity form and keeps using it.
28
+ */
29
+ function aggregateGrantSignature(aggregate: Aggregate): string {
30
+ const args = (aggregate.argument_types ?? []).join(", ");
31
+ return `${aggregate.schema}.${aggregate.name}(${args})`;
32
+ }
33
+
15
34
  export class GrantAggregatePrivileges extends AlterAggregateChange {
16
35
  public readonly aggregate: Aggregate;
17
36
  public readonly grantee: string;
@@ -52,9 +71,7 @@ export class GrantAggregatePrivileges extends AlterAggregateChange {
52
71
  const kindPrefix = getObjectKindPrefix("FUNCTION");
53
72
  const list = this.privileges.map((p) => p.privilege);
54
73
  const privSql = formatObjectPrivilegeList("FUNCTION", list, this.version);
55
- const aggregateName = `${this.aggregate.schema}.${this.aggregate.name}`;
56
- const signature = this.aggregate.identityArguments;
57
- const qualified = `${aggregateName}(${signature})`;
74
+ const qualified = aggregateGrantSignature(this.aggregate);
58
75
  return `GRANT ${privSql} ${kindPrefix} ${qualified} TO ${this.grantee}${withGrant}`;
59
76
  }
60
77
  }
@@ -97,9 +114,7 @@ export class RevokeAggregatePrivileges extends AlterAggregateChange {
97
114
  const kindPrefix = getObjectKindPrefix("FUNCTION");
98
115
  const list = this.privileges.map((p) => p.privilege);
99
116
  const privSql = formatObjectPrivilegeList("FUNCTION", list, this.version);
100
- const aggregateName = `${this.aggregate.schema}.${this.aggregate.name}`;
101
- const signature = this.aggregate.identityArguments;
102
- const qualified = `${aggregateName}(${signature})`;
117
+ const qualified = aggregateGrantSignature(this.aggregate);
103
118
  return `REVOKE ${privSql} ${kindPrefix} ${qualified} FROM ${this.grantee}`;
104
119
  }
105
120
  }
@@ -139,9 +154,7 @@ export class RevokeGrantOptionAggregatePrivileges extends AlterAggregateChange {
139
154
  this.privilegeNames,
140
155
  this.version,
141
156
  );
142
- const aggregateName = `${this.aggregate.schema}.${this.aggregate.name}`;
143
- const signature = this.aggregate.identityArguments;
144
- const qualified = `${aggregateName}(${signature})`;
157
+ const qualified = aggregateGrantSignature(this.aggregate);
145
158
  return `REVOKE GRANT OPTION FOR ${privSql} ${kindPrefix} ${qualified} FROM ${this.grantee}`;
146
159
  }
147
160
  }