@akal/supaforge 0.0.35 → 0.0.36

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 (39) hide show
  1. package/README.md +4 -1
  2. package/dist/base-command.js +4 -4
  3. package/dist/{chunk-SM7HP6EP.js → chunk-5UHIWFQG.js} +69 -9
  4. package/dist/{chunk-O5ERC2SE.js → chunk-AL6INEFX.js} +3 -3
  5. package/dist/{chunk-4AGJRRBT.js → chunk-CAQ3QQFP.js} +70 -22
  6. package/dist/{chunk-5Q6LSLA3.js → chunk-CCB7ARZU.js} +6 -6
  7. package/dist/{chunk-YZM76W22.js → chunk-EWNZIRCD.js} +4 -4
  8. package/dist/{chunk-YWERIWFD.js → chunk-FD2JKEJA.js} +5 -5
  9. package/dist/{chunk-NEM5AEPQ.js → chunk-GGZ7YWBZ.js} +24 -15
  10. package/dist/{chunk-7N63OPFN.js → chunk-JX5L253P.js} +46 -16
  11. package/dist/{chunk-GQPGH6YR.js → chunk-KHXEES2M.js} +2 -2
  12. package/dist/{chunk-4M6OQLPO.js → chunk-KT7NMELZ.js} +77 -7
  13. package/dist/{chunk-44UVQJV2.js → chunk-M2564IGT.js} +22 -15
  14. package/dist/{chunk-H2D3YSKM.js → chunk-MRXIE55Y.js} +3 -3
  15. package/dist/{chunk-NX2KKUS7.js → chunk-MZPWRWBL.js} +7 -7
  16. package/dist/{chunk-XLZCX6R2.js → chunk-OXS42LJH.js} +4 -4
  17. package/dist/{chunk-HNJ6BNNZ.js → chunk-Q43MN6NE.js} +2 -2
  18. package/dist/{chunk-ZI435CAU.js → chunk-RQCXGO37.js} +2 -2
  19. package/dist/{chunk-KNXHLVF7.js → chunk-SQ52YBKK.js} +3 -2
  20. package/dist/{chunk-T7GMPGUO.js → chunk-YUJ2MHLM.js} +674 -22
  21. package/dist/{chunk-AGONS5JJ.js → chunk-Z2YUOA4W.js} +2 -2
  22. package/dist/commands/clone.js +8 -8
  23. package/dist/commands/diff.d.ts +1 -0
  24. package/dist/commands/diff.js +14 -15
  25. package/dist/commands/hukam.js +14 -15
  26. package/dist/commands/init.js +2 -2
  27. package/dist/commands/mcp.js +9 -10
  28. package/dist/commands/migrate/baseline.js +5 -5
  29. package/dist/commands/migrate/create.js +22 -13
  30. package/dist/commands/migrate/list.js +5 -5
  31. package/dist/commands/migrate/run.js +9 -9
  32. package/dist/commands/report.js +5 -5
  33. package/dist/commands/restore.js +14 -13
  34. package/dist/commands/snapshot.js +8 -8
  35. package/dist/commands/sync.js +14 -15
  36. package/dist/index.d.ts +17 -0
  37. package/dist/index.js +13 -14
  38. package/package.json +2 -2
  39. package/dist/chunk-WNTCZM2J.js +0 -468
@@ -7,18 +7,24 @@ import {
7
7
  globToRegExp,
8
8
  matchesGlob,
9
9
  parseFlagList
10
- } from "./chunk-AGONS5JJ.js";
10
+ } from "./chunk-Z2YUOA4W.js";
11
11
  import {
12
- newPgClient
13
- } from "./chunk-4M6OQLPO.js";
12
+ Check,
13
+ heldSnapshot,
14
+ newPgClient,
15
+ pgQuery,
16
+ quoteName,
17
+ snapshotsOff
18
+ } from "./chunk-KT7NMELZ.js";
14
19
  import {
15
20
  DBDIFF_EXEC_TIMEOUT_MS,
16
21
  DBDIFF_MAX_BUFFER,
17
22
  DiagnosticError,
23
+ SUPABASE_PLATFORM_SCHEMAS,
18
24
  errMsg,
19
25
  friendlyDbError,
20
26
  schemaDiffIgnores
21
- } from "./chunk-KNXHLVF7.js";
27
+ } from "./chunk-SQ52YBKK.js";
22
28
 
23
29
  // src/utils/table-filter.ts
24
30
  var parseTableList = parseFlagList;
@@ -122,6 +128,499 @@ function isComparisonCheck(name) {
122
128
  return CHECK_KIND[name] === "comparison";
123
129
  }
124
130
 
131
+ // src/checks/roles.ts
132
+ var PLATFORM_ROLES = [
133
+ "postgres",
134
+ "supabase_admin",
135
+ "authenticator",
136
+ "supabase_auth_admin",
137
+ "supabase_storage_admin",
138
+ "dashboard_user",
139
+ "pgbouncer",
140
+ "supavisor",
141
+ // Created by Supabase's own images for Edge Functions, Realtime, read
142
+ // replicas and logical replication. Diffing a project against plain
143
+ // PostgreSQL offered to create all four on the target.
144
+ "supabase_functions_admin",
145
+ "supabase_realtime_admin",
146
+ "supabase_read_only_user",
147
+ "supabase_replication_admin"
148
+ ];
149
+ var API_ROLES = ["anon", "authenticated", "service_role"];
150
+ var quoted = (names2) => names2.map((n) => `'${n.replace(/'/g, "''")}'`).join(", ");
151
+ var ROLES_SQL = `
152
+ SELECT
153
+ rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb,
154
+ rolcanlogin, rolreplication, rolbypassrls, rolconnlimit,
155
+ rolvaliduntil::text AS rolvaliduntil
156
+ FROM pg_roles
157
+ WHERE NOT (rolname LIKE 'pg_%')
158
+ AND rolname NOT IN (${quoted([...PLATFORM_ROLES, ...API_ROLES])})
159
+ AND rolname <> current_user
160
+ ORDER BY rolname
161
+ `;
162
+ function grantSchemaFilter(ignoreSchemas) {
163
+ const excluded = [.../* @__PURE__ */ new Set([...SUPABASE_PLATFORM_SCHEMAS, ...ignoreSchemas])];
164
+ return `NOT IN (${quoted(excluded)})`;
165
+ }
166
+ var grantsSql = (ignoreSchemas) => `
167
+ SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
168
+ n.nspname AS table_schema, c.relname AS table_name,
169
+ a.privilege_type, a.is_grantable,
170
+ CASE c.relkind WHEN 'S' THEN 'sequence' ELSE 'table' END AS object_kind
171
+ FROM pg_class c
172
+ JOIN pg_namespace n ON n.oid = c.relnamespace
173
+ CROSS JOIN LATERAL aclexplode(c.relacl) a
174
+ WHERE c.relacl IS NOT NULL
175
+ AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')
176
+ AND a.grantee <> c.relowner
177
+ AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
178
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
179
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
180
+ ORDER BY 1, 2, 3, 4
181
+ `;
182
+ var schemaGrantsSql = (ignoreSchemas) => `
183
+ SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
184
+ n.nspname AS table_schema, '' AS table_name,
185
+ a.privilege_type, a.is_grantable, 'schema' AS object_kind
186
+ FROM pg_namespace n
187
+ CROSS JOIN LATERAL aclexplode(n.nspacl) a
188
+ WHERE n.nspacl IS NOT NULL
189
+ AND a.grantee <> n.nspowner
190
+ AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
191
+ AND n.nspname NOT LIKE 'pg\\_%' AND n.nspname <> 'information_schema'
192
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_namespace'::regclass AND d.objid = n.oid AND d.deptype = 'e')
193
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
194
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
195
+ ORDER BY 1, 2, 4
196
+ `;
197
+ var schemasSql = (ignoreSchemas) => `
198
+ SELECT nspname AS table_schema, '' AS table_name, 'schema' AS object_kind
199
+ FROM pg_namespace
200
+ WHERE nspname ${grantSchemaFilter(ignoreSchemas)}
201
+ `;
202
+ var columnGrantsSql = (ignoreSchemas) => `
203
+ SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
204
+ n.nspname AS table_schema, c.relname AS table_name, att.attname AS column_name,
205
+ a.privilege_type, a.is_grantable
206
+ FROM pg_attribute att
207
+ JOIN pg_class c ON c.oid = att.attrelid
208
+ JOIN pg_namespace n ON n.oid = c.relnamespace
209
+ CROSS JOIN LATERAL aclexplode(att.attacl) a
210
+ WHERE att.attacl IS NOT NULL AND att.attnum > 0 AND NOT att.attisdropped
211
+ AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
212
+ AND a.grantee <> c.relowner
213
+ AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
214
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
215
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
216
+ ORDER BY 1, 2, 3, 4, 5
217
+ `;
218
+ var functionGrantsSql = (ignoreSchemas) => `
219
+ SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
220
+ n.nspname AS table_schema, p.proname AS table_name,
221
+ pg_get_function_identity_arguments(p.oid) AS args,
222
+ CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END AS object_kind,
223
+ a.privilege_type, a.is_grantable
224
+ FROM pg_proc p
225
+ JOIN pg_namespace n ON n.oid = p.pronamespace
226
+ CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) a
227
+ WHERE a.grantee <> p.proowner
228
+ AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
229
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')
230
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
231
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
232
+ ORDER BY 1, 2, 3, 4, 6
233
+ `;
234
+ var routinesSql = (ignoreSchemas) => `
235
+ SELECT n.nspname AS table_schema, p.proname AS table_name,
236
+ pg_get_function_identity_arguments(p.oid) AS args,
237
+ CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END AS object_kind
238
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
239
+ WHERE n.nspname ${grantSchemaFilter(ignoreSchemas)}
240
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')
241
+ `;
242
+ var relationsSql = (ignoreSchemas) => `
243
+ SELECT n.nspname AS table_schema, c.relname AS table_name,
244
+ CASE c.relkind WHEN 'S' THEN 'sequence' ELSE 'table' END AS object_kind
245
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
246
+ WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')
247
+ AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
248
+ `;
249
+ var DEFAULT_GRANTS_SQL = `
250
+ SELECT CASE d.defaclobjtype WHEN 'S' THEN 'sequence' WHEN 'f' THEN 'function' ELSE 'table' END AS object_kind,
251
+ n.nspname AS table_schema,
252
+ CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
253
+ a.privilege_type, a.is_grantable
254
+ FROM pg_default_acl d
255
+ LEFT JOIN pg_namespace n ON n.oid = d.defaclnamespace
256
+ CROSS JOIN LATERAL aclexplode(d.defaclacl) a
257
+ WHERE d.defaclobjtype IN ('r', 'S', 'f') AND d.defaclrole = current_user::regrole::oid
258
+ AND a.grantee <> d.defaclrole
259
+ UNION ALL
260
+ SELECT 'function', NULL, 'PUBLIC', 'EXECUTE', false
261
+ WHERE NOT EXISTS (
262
+ SELECT 1 FROM pg_default_acl d
263
+ WHERE d.defaclobjtype = 'f' AND d.defaclnamespace = 0 AND d.defaclrole = current_user::regrole::oid)
264
+ `;
265
+ function objectKey(o) {
266
+ if (o.object_kind === "schema") return `schema:${o.table_schema}`;
267
+ const routine = o.object_kind === "function" || o.object_kind === "procedure";
268
+ return `${routine ? "routine" : o.object_kind ?? "table"}:${o.table_schema}.${o.table_name}${routine ? `(${o.args ?? ""})` : ""}`;
269
+ }
270
+ function defaultKind(kind) {
271
+ return kind === "procedure" ? "function" : kind ?? "table";
272
+ }
273
+ function grantedByDefault(relations, defaults) {
274
+ const present = new Set(relations.map(objectKey));
275
+ const granted = new Set(defaults.map((d) => `${defaultKind(d.object_kind)}|${d.table_schema ?? "*"}|${d.grantee}|${d.privilege_type}|${Boolean(d.is_grantable)}`));
276
+ return (g) => !g.column_name && !present.has(objectKey(g)) && [g.table_schema, "*"].some((schema) => granted.has(`${defaultKind(g.object_kind)}|${schema}|${g.grantee}|${g.privilege_type}|${Boolean(g.is_grantable)}`));
277
+ }
278
+ function defaultGrantsToRevoke(sourceRelations, targetRelations, defaults, sourceGrants) {
279
+ const present = new Set(targetRelations.map(objectKey));
280
+ const held = new Set(sourceGrants.filter((g) => !g.column_name).map((g) => `${objectKey(g)}|${g.grantee}|${g.privilege_type}`));
281
+ const issues = [];
282
+ for (const rel of sourceRelations) {
283
+ if (present.has(objectKey(rel))) continue;
284
+ const name = `${rel.table_schema}.${rel.table_name}`;
285
+ const extra = /* @__PURE__ */ new Map();
286
+ for (const d of defaults) {
287
+ if (defaultKind(d.object_kind) !== defaultKind(rel.object_kind)) continue;
288
+ if (d.table_schema !== null && d.table_schema !== rel.table_schema) continue;
289
+ if (held.has(`${objectKey(rel)}|${d.grantee}|${d.privilege_type}`)) continue;
290
+ extra.set(d.grantee, (extra.get(d.grantee) ?? /* @__PURE__ */ new Set()).add(d.privilege_type));
291
+ }
292
+ for (const [grantee, privileges] of [...extra].sort(([a], [b]) => a.localeCompare(b))) {
293
+ const gs = [...privileges].sort().map((privilege_type) => ({
294
+ grantee,
295
+ table_schema: rel.table_schema,
296
+ table_name: rel.table_name,
297
+ privilege_type,
298
+ is_grantable: false,
299
+ ...rel.object_kind && rel.object_kind !== "table" ? { object_kind: rel.object_kind } : {},
300
+ ...rel.args !== void 0 ? { args: rel.args } : {}
301
+ }));
302
+ const routine = rel.object_kind === "function" || rel.object_kind === "procedure";
303
+ issues.push({
304
+ // Tables keep the id they have always had; others say what they are.
305
+ id: `roles-grant-default-${grantee}.${name}${routine ? `(${rel.args ?? ""})` : ""}`,
306
+ check: "roles",
307
+ severity: extraGrantSeverity(grantee),
308
+ title: `Default grants to take back: ${describeGroup(gs)}`,
309
+ description: `Creating ${describeObject(gs[0])} on the target gives ${grantee} what its default privileges grant. The source does not grant "${describeGroup(gs)}", so it is revoked once it exists.`,
310
+ targetValue: gs,
311
+ sql: {
312
+ up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(grantee)};`,
313
+ down: `GRANT ${groupTarget(gs)} TO ${granteeSql(grantee)};`
314
+ }
315
+ });
316
+ }
317
+ }
318
+ return issues;
319
+ }
320
+ var OPEN_GRANTEES = /* @__PURE__ */ new Set(["anon", "authenticated", "PUBLIC"]);
321
+ function extraGrantSeverity(grantee) {
322
+ return OPEN_GRANTEES.has(grantee) ? "critical" : "warning";
323
+ }
324
+ var RolesCheck = class extends Check {
325
+ /**
326
+ * `explicit`: report a grant the source has even where the target's
327
+ * default privileges would make it. A migration file is replayed on
328
+ * databases whose defaults differ — Supabase stopped granting the Data API
329
+ * roles on new tables in `public` — so it must say every grant itself.
330
+ */
331
+ constructor(queryFn = pgQuery, options = {}) {
332
+ super();
333
+ this.queryFn = queryFn;
334
+ this.options = options;
335
+ }
336
+ name = "roles";
337
+ async scan(ctx) {
338
+ const ignore = ctx.config.ignoreSchemas ?? [];
339
+ const version = async (url) => Number((await this.queryFn(url, `SELECT current_setting('server_version_num') AS v`))[0]?.v ?? 0);
340
+ const [
341
+ sourceRoles,
342
+ targetRoles,
343
+ sourceGrants,
344
+ targetGrants,
345
+ sourceColumns,
346
+ targetColumns,
347
+ sourceVersion,
348
+ targetVersion,
349
+ sourceRelations,
350
+ targetRelations,
351
+ targetDefaults,
352
+ sourceRoutineGrants,
353
+ targetRoutineGrants,
354
+ sourceRoutines,
355
+ targetRoutines,
356
+ sourceSchemaGrants,
357
+ targetSchemaGrants,
358
+ sourceSchemas
359
+ ] = await Promise.all([
360
+ this.queryFn(ctx.source.dbUrl, ROLES_SQL),
361
+ this.queryFn(ctx.target.dbUrl, ROLES_SQL),
362
+ this.queryFn(ctx.source.dbUrl, grantsSql(ignore)),
363
+ this.queryFn(ctx.target.dbUrl, grantsSql(ignore)),
364
+ this.queryFn(ctx.source.dbUrl, columnGrantsSql(ignore)),
365
+ this.queryFn(ctx.target.dbUrl, columnGrantsSql(ignore)),
366
+ version(ctx.source.dbUrl),
367
+ version(ctx.target.dbUrl),
368
+ this.queryFn(ctx.source.dbUrl, relationsSql(ignore)),
369
+ this.queryFn(ctx.target.dbUrl, relationsSql(ignore)),
370
+ this.queryFn(ctx.target.dbUrl, DEFAULT_GRANTS_SQL),
371
+ this.queryFn(ctx.source.dbUrl, functionGrantsSql(ignore)),
372
+ this.queryFn(ctx.target.dbUrl, functionGrantsSql(ignore)),
373
+ this.queryFn(ctx.source.dbUrl, routinesSql(ignore)),
374
+ this.queryFn(ctx.target.dbUrl, routinesSql(ignore)),
375
+ this.queryFn(ctx.source.dbUrl, schemaGrantsSql(ignore)),
376
+ this.queryFn(ctx.target.dbUrl, schemaGrantsSql(ignore)),
377
+ this.queryFn(ctx.source.dbUrl, schemasSql(ignore))
378
+ ]);
379
+ const sourceObjects = [...sourceRelations ?? [], ...sourceRoutines ?? [], ...sourceSchemas ?? []];
380
+ const targetObjects = [...targetRelations ?? [], ...targetRoutines ?? []];
381
+ const sourceAll = [...sourceGrants ?? [], ...sourceRoutineGrants ?? [], ...sourceSchemaGrants ?? []];
382
+ const inSource = new Set(sourceObjects.map(objectKey));
383
+ const targetAll = [...targetGrants ?? [], ...targetRoutineGrants ?? [], ...targetSchemaGrants ?? []].filter((g) => !g.object_kind || g.object_kind === "table" || inSource.has(objectKey(g)));
384
+ const comparable = comparablePrivileges(sourceVersion, targetVersion);
385
+ const byDefault = this.options.explicit ? () => false : grantedByDefault(targetObjects, targetDefaults ?? []);
386
+ return [
387
+ ...diffRoles(sourceRoles, targetRoles),
388
+ ...diffGrants(
389
+ [...sourceAll, ...sourceColumns ?? []].filter((g) => comparable(g) && !byDefault(g)),
390
+ [...targetAll, ...targetColumns ?? []].filter(comparable),
391
+ absentOn(targetRoles, sourceRoles)
392
+ ),
393
+ ...defaultGrantsToRevoke(
394
+ sourceObjects,
395
+ targetObjects,
396
+ (targetDefaults ?? []).filter((d) => comparable(d)),
397
+ sourceAll
398
+ )
399
+ ];
400
+ }
401
+ };
402
+ function absentOn(target, source) {
403
+ const present = new Set((target ?? []).map((r) => r.rolname));
404
+ return new Set((source ?? []).map((r) => r.rolname).filter((name) => !present.has(name)));
405
+ }
406
+ function roleAttrs(r) {
407
+ const attrs = [];
408
+ if (r.rolsuper) attrs.push("SUPERUSER");
409
+ if (r.rolinherit) attrs.push("INHERIT");
410
+ if (r.rolcreaterole) attrs.push("CREATEROLE");
411
+ if (r.rolcreatedb) attrs.push("CREATEDB");
412
+ if (r.rolcanlogin) attrs.push("LOGIN");
413
+ if (r.rolreplication) attrs.push("REPLICATION");
414
+ if (r.rolbypassrls) attrs.push("BYPASSRLS");
415
+ if (r.rolconnlimit >= 0) attrs.push(`CONNECTION LIMIT ${r.rolconnlimit}`);
416
+ if (r.rolvaliduntil) attrs.push(`VALID UNTIL '${r.rolvaliduntil}'`);
417
+ return attrs.length > 0 ? attrs.join(" ") : "NOLOGIN";
418
+ }
419
+ function rolesEqual(a, b) {
420
+ return a.rolsuper === b.rolsuper && a.rolinherit === b.rolinherit && a.rolcreaterole === b.rolcreaterole && a.rolcreatedb === b.rolcreatedb && a.rolcanlogin === b.rolcanlogin && a.rolreplication === b.rolreplication && a.rolbypassrls === b.rolbypassrls && a.rolconnlimit === b.rolconnlimit && a.rolvaliduntil === b.rolvaliduntil;
421
+ }
422
+ function diffRoles(source, target) {
423
+ const issues = [];
424
+ const sourceMap = new Map(source.map((r) => [r.rolname, r]));
425
+ const targetMap = new Map(target.map((r) => [r.rolname, r]));
426
+ for (const [name, sr] of sourceMap) {
427
+ if (!targetMap.has(name)) {
428
+ issues.push({
429
+ id: `roles-missing-${name}`,
430
+ check: "roles",
431
+ severity: "critical",
432
+ title: `Missing role: ${name}`,
433
+ description: `Role "${name}" exists in source but is missing from target. Any RLS policies or grants referencing this role will be silently ineffective.`,
434
+ sourceValue: sr,
435
+ sql: {
436
+ up: `CREATE ROLE ${quoteName(name)} ${roleAttrs(sr)};`,
437
+ down: `DROP ROLE IF EXISTS ${quoteName(name)};`
438
+ }
439
+ });
440
+ }
441
+ }
442
+ for (const [name, tr] of targetMap) {
443
+ if (!sourceMap.has(name)) {
444
+ issues.push({
445
+ id: `roles-extra-${name}`,
446
+ check: "roles",
447
+ severity: "warning",
448
+ title: `Extra role: ${name}`,
449
+ description: `Role "${name}" exists in target but not in source.`,
450
+ targetValue: tr,
451
+ sql: {
452
+ up: `DROP ROLE IF EXISTS ${quoteName(name)};`,
453
+ down: `CREATE ROLE ${quoteName(name)} ${roleAttrs(tr)};`
454
+ }
455
+ });
456
+ }
457
+ }
458
+ for (const [name, sr] of sourceMap) {
459
+ const tr = targetMap.get(name);
460
+ if (tr && !rolesEqual(sr, tr)) {
461
+ issues.push({
462
+ id: `roles-modified-${name}`,
463
+ check: "roles",
464
+ severity: "warning",
465
+ title: `Modified role: ${name}`,
466
+ description: `Role "${name}" has different attributes between source and target.`,
467
+ sourceValue: sr,
468
+ targetValue: tr,
469
+ sql: {
470
+ up: `ALTER ROLE ${quoteName(name)} ${roleAttrs(sr)};`,
471
+ down: `ALTER ROLE ${quoteName(name)} ${roleAttrs(tr)};`
472
+ }
473
+ });
474
+ }
475
+ }
476
+ return issues;
477
+ }
478
+ function grantKey(g) {
479
+ const column = g.column_name ? `.${g.column_name}` : "";
480
+ const routine = g.object_kind === "function" || g.object_kind === "procedure";
481
+ return `${g.grantee}.${g.table_schema}.${g.table_name}${routine ? `(${g.args ?? ""})` : ""}${column}.${g.privilege_type}`;
482
+ }
483
+ function objectSql(g) {
484
+ const name = `${quoteName(g.table_schema)}.${quoteName(g.table_name)}`;
485
+ switch (g.object_kind) {
486
+ case "schema":
487
+ return `SCHEMA ${quoteName(g.table_schema)}`;
488
+ case "sequence":
489
+ return `SEQUENCE ${name}`;
490
+ case "function":
491
+ return `FUNCTION ${name}(${g.args ?? ""})`;
492
+ case "procedure":
493
+ return `PROCEDURE ${name}(${g.args ?? ""})`;
494
+ default:
495
+ return name;
496
+ }
497
+ }
498
+ function describeObject(g) {
499
+ const name = `${g.table_schema}.${g.table_name}`;
500
+ switch (g.object_kind) {
501
+ case "schema":
502
+ return `schema ${g.table_schema}`;
503
+ case "sequence":
504
+ return `sequence ${name}`;
505
+ case "function":
506
+ return `function ${name}(${g.args ?? ""})`;
507
+ case "procedure":
508
+ return `procedure ${name}(${g.args ?? ""})`;
509
+ default:
510
+ return name;
511
+ }
512
+ }
513
+ function granteeSql(grantee) {
514
+ return grantee === "PUBLIC" ? "PUBLIC" : `"${grantee.replace(/"/g, '""')}"`;
515
+ }
516
+ function grantTarget(g) {
517
+ const column = g.column_name ? ` ("${g.column_name.replace(/"/g, '""')}")` : "";
518
+ return `${g.privilege_type}${column} ON ${objectSql(g)}`;
519
+ }
520
+ function describeGrant(g) {
521
+ const column = g.column_name ? `(${g.column_name}) ` : "";
522
+ return `${g.privilege_type} ${column}ON ${describeObject(g)} TO ${g.grantee}`;
523
+ }
524
+ var grantSql = (g, withOption = g.is_grantable) => `GRANT ${grantTarget(g)} TO ${granteeSql(g.grantee)}${withOption ? " WITH GRANT OPTION" : ""};`;
525
+ function comparablePrivileges(sourceVersion, targetVersion) {
526
+ const both = Math.min(sourceVersion || Infinity, targetVersion || Infinity);
527
+ const acrossFifteen = Boolean(sourceVersion && targetVersion) && sourceVersion < 15e4 !== targetVersion < 15e4;
528
+ return (g) => (g.privilege_type !== "MAINTAIN" || both >= 17e4) && !(acrossFifteen && g.object_kind === "schema" && g.table_schema === "public" && g.grantee === "PUBLIC" && g.privilege_type === "CREATE");
529
+ }
530
+ function grouped(grants) {
531
+ const groups = /* @__PURE__ */ new Map();
532
+ for (const g of grants) {
533
+ const key = `${grantKey(g).replace(/\.[^.]+$/, "")}.${Boolean(g.is_grantable)}`;
534
+ groups.set(key, [...groups.get(key) ?? [], g]);
535
+ }
536
+ return [...groups.values()];
537
+ }
538
+ function groupTarget(gs) {
539
+ const column = gs[0].column_name ? ` ("${gs[0].column_name.replace(/"/g, '""')}")` : "";
540
+ return `${gs.map((g) => `${g.privilege_type}${column}`).join(", ")} ON ${objectSql(gs[0])}`;
541
+ }
542
+ function describeGroup(gs) {
543
+ const column = gs[0].column_name ? `(${gs[0].column_name}) ` : "";
544
+ return `${gs.map((g) => g.privilege_type).join(", ")} ${column}ON ${describeObject(gs[0])} TO ${gs[0].grantee}`;
545
+ }
546
+ var groupKey = (gs) => grantKey(gs[0]).replace(/\.[^.]+$/, "");
547
+ function grantsToMissingRoles(grants) {
548
+ const byRole = /* @__PURE__ */ new Map();
549
+ for (const g of grants) byRole.set(g.grantee, [...byRole.get(g.grantee) ?? [], g]);
550
+ return [...byRole].map(([role, gs]) => {
551
+ const groups = grouped(gs);
552
+ const objects = new Set(gs.map((g) => describeObject(g))).size;
553
+ const what = `${gs.length} privilege${gs.length === 1 ? "" : "s"} on ${objects} object${objects === 1 ? "" : "s"}`;
554
+ return {
555
+ id: `roles-grant-missing-role-${role}`,
556
+ check: "roles",
557
+ severity: "warning",
558
+ title: `Missing grants: ${what} to ${role}, a role the target does not have`,
559
+ description: `The source grants ${what} to "${role}", which the target lacks. They can only be applied once the role exists (see "Missing role"); on a target that is not meant to have it, skip the roles check.`,
560
+ sourceValue: gs,
561
+ sql: {
562
+ up: groups.map((g) => `GRANT ${groupTarget(g)} TO ${granteeSql(role)}${g[0].is_grantable ? " WITH GRANT OPTION" : ""};`).join("\n"),
563
+ down: groups.map((g) => `REVOKE ${groupTarget(g)} FROM ${granteeSql(role)};`).reverse().join("\n")
564
+ }
565
+ };
566
+ });
567
+ }
568
+ function diffGrants(source, target, missingRoles = /* @__PURE__ */ new Set()) {
569
+ const issues = [];
570
+ const sourceMap = new Map(source.map((g) => [grantKey(g), g]));
571
+ const targetMap = new Map(target.map((g) => [grantKey(g), g]));
572
+ const missing = [...sourceMap].filter(([key]) => !targetMap.has(key)).map(([, g]) => g);
573
+ issues.push(...grantsToMissingRoles(missing.filter((g) => missingRoles.has(g.grantee))));
574
+ for (const gs of grouped(missing.filter((g) => !missingRoles.has(g.grantee)))) {
575
+ const plural = gs.length > 1 ? "s" : "";
576
+ issues.push({
577
+ id: `roles-grant-missing-${groupKey(gs)}`,
578
+ check: "roles",
579
+ severity: "warning",
580
+ title: `Missing grant${plural}: ${describeGroup(gs)}`,
581
+ description: `Grant${plural} "${describeGroup(gs)}" ${gs.length > 1 ? "are" : "is"} missing from target.`,
582
+ sourceValue: gs.length > 1 ? gs : gs[0],
583
+ sql: {
584
+ up: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? " WITH GRANT OPTION" : ""};`,
585
+ down: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`
586
+ }
587
+ });
588
+ }
589
+ for (const [key, sg] of sourceMap) {
590
+ const tg = targetMap.get(key);
591
+ if (tg && Boolean(sg.is_grantable) !== Boolean(tg.is_grantable)) {
592
+ const revokeOption = `REVOKE GRANT OPTION FOR ${grantTarget(sg)} FROM ${granteeSql(sg.grantee)};`;
593
+ issues.push({
594
+ id: `roles-grant-option-${key}`,
595
+ check: "roles",
596
+ severity: "warning",
597
+ title: `Grant option differs: ${describeGrant(sg)}`,
598
+ description: `"${describeGrant(sg)}" is held ${sg.is_grantable ? "with" : "without"} the grant option in source and ${tg.is_grantable ? "with" : "without"} it in target.`,
599
+ sourceValue: sg,
600
+ targetValue: tg,
601
+ sql: sg.is_grantable ? { up: grantSql(sg, true), down: revokeOption } : { up: revokeOption, down: grantSql(tg, true) }
602
+ });
603
+ }
604
+ }
605
+ const extra = [...targetMap].filter(([key]) => !sourceMap.has(key)).map(([, g]) => g);
606
+ for (const gs of grouped(extra)) {
607
+ const plural = gs.length > 1 ? "s" : "";
608
+ issues.push({
609
+ id: `roles-grant-extra-${groupKey(gs)}`,
610
+ check: "roles",
611
+ severity: extraGrantSeverity(gs[0].grantee),
612
+ title: `Extra grant${plural}: ${describeGroup(gs)}`,
613
+ description: `Grant${plural} "${describeGroup(gs)}" exist${gs.length > 1 ? "" : "s"} in target but not in source.`,
614
+ targetValue: gs.length > 1 ? gs : gs[0],
615
+ sql: {
616
+ up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`,
617
+ down: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? " WITH GRANT OPTION" : ""};`
618
+ }
619
+ });
620
+ }
621
+ return issues;
622
+ }
623
+
125
624
  // src/dbdiff.ts
126
625
  import { execFile } from "child_process";
127
626
  import { createRequire } from "module";
@@ -253,7 +752,7 @@ var unquote = (part) => {
253
752
  const p = part.trim();
254
753
  return p.startsWith('"') ? p.slice(1, -1).replace(/""/g, '"') : p;
255
754
  };
256
- var objectKey = (schema, table, name) => `${(schema || "public").toLowerCase()}.${(table ?? "").toLowerCase()}.${(name ?? "").toLowerCase()}`;
755
+ var objectKey2 = (schema, table, name) => `${(schema || "public").toLowerCase()}.${(table ?? "").toLowerCase()}.${(name ?? "").toLowerCase()}`;
257
756
  function schemaQualified(identifier) {
258
757
  const parts = identifier.match(new RegExp(NAME_PART, "g")) ?? [identifier];
259
758
  const fold = (part) => unquote(part).toLowerCase();
@@ -301,7 +800,7 @@ var NOT_A_TABLE = /* @__PURE__ */ new Set([
301
800
  function createdPolicies(sql) {
302
801
  const tree = parseStatements(sql);
303
802
  if (tree) {
304
- return tree.filter((s) => s.kind === "CreatePolicyStmt").map(({ node }) => objectKey(node.table?.schemaname, node.table?.relname, node.policy_name));
803
+ return tree.filter((s) => s.kind === "CreatePolicyStmt").map(({ node }) => objectKey2(node.table?.schemaname, node.table?.relname, node.policy_name));
305
804
  }
306
805
  const out = [];
307
806
  const re = new RegExp(String.raw`CREATE\s+POLICY\s+(${NAME_PART})\s+ON\s+(${IDENT})`, "gi");
@@ -313,7 +812,7 @@ function createdPolicies(sql) {
313
812
  function droppedPolicies(sql) {
314
813
  const tree = parseStatements(sql);
315
814
  if (tree) {
316
- return tree.filter((s) => s.kind === "DropStmt" && s.node.removeType === "OBJECT_POLICY").flatMap(({ node }) => node.objects.map((o) => (o.List?.items ?? []).map((i) => i.String?.sval)).map((parts) => objectKey(parts.at(-3), parts.at(-2), parts.at(-1))));
815
+ return tree.filter((s) => s.kind === "DropStmt" && s.node.removeType === "OBJECT_POLICY").flatMap(({ node }) => node.objects.map((o) => (o.List?.items ?? []).map((i) => i.String?.sval)).map((parts) => objectKey2(parts.at(-3), parts.at(-2), parts.at(-1))));
317
816
  }
318
817
  const out = [];
319
818
  const re = new RegExp(String.raw`DROP\s+POLICY\s+(?:IF\s+EXISTS\s+)?(${NAME_PART})\s+ON\s+(${IDENT})`, "gi");
@@ -466,7 +965,10 @@ function policyOnlyKeys(sql) {
466
965
  return [.../* @__PURE__ */ new Set([...createdPolicies(sql), ...droppedPolicies(sql)])];
467
966
  }
468
967
  function rolesOf({ kind, node }) {
469
- const specs = kind === "GrantStmt" && node.is_grant ? node.grantees ?? [] : kind === "GrantRoleStmt" && node.is_grant ? node.grantee_roles ?? [] : kind === "CreatePolicyStmt" || kind === "AlterPolicyStmt" ? node.roles ?? [] : [];
968
+ const specs = kind === "GrantStmt" && node.is_grant ? node.grantees ?? [] : kind === "GrantRoleStmt" && node.is_grant ? node.grantee_roles ?? [] : kind === "CreatePolicyStmt" || kind === "AlterPolicyStmt" ? node.roles ?? [] : kind === "AlterDefaultPrivilegesStmt" ? [
969
+ ...(node.options ?? []).filter((o) => o.DefElem?.defname === "roles").flatMap((o) => o.DefElem.arg?.List?.items ?? []),
970
+ ...node.action?.is_grant ? node.action.grantees ?? [] : []
971
+ ] : [];
470
972
  return specs.map((spec) => spec.RoleSpec).filter((role) => role?.roletype === "ROLESPEC_CSTRING" && typeof role.rolename === "string").map((role) => role.rolename).filter((name) => !name.startsWith("pg_"));
471
973
  }
472
974
  var ROLE_KEYWORDS = /* @__PURE__ */ new Set(["public", "current_user", "current_role", "session_user"]);
@@ -567,6 +1069,15 @@ var DBDIFF_NOISE_LINE = /^\s*[ℹ✔✓⚠⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]/u;
567
1069
  function stripDbDiffNoise(text) {
568
1070
  return text.split("\n").filter((line) => line.trim() !== "" && !DBDIFF_NOISE_LINE.test(line)).join("\n").trim();
569
1071
  }
1072
+ function snapshotArgs(sourceUrl, targetUrl) {
1073
+ if (snapshotsOff()) return ["--no-snapshot"];
1074
+ const source = heldSnapshot(sourceUrl);
1075
+ const target = heldSnapshot(targetUrl);
1076
+ return [
1077
+ ...source ? [`--source-snapshot=${source}`] : [],
1078
+ ...target ? [`--target-snapshot=${target}`] : []
1079
+ ];
1080
+ }
570
1081
  function buildDbDiffArgs(options, outputFile) {
571
1082
  const args = [
572
1083
  "diff",
@@ -579,6 +1090,9 @@ function buildDbDiffArgs(options, outputFile) {
579
1090
  // public interface and did nothing.
580
1091
  `--include=${options.include}`,
581
1092
  "--nocomments",
1093
+ // The instant the scan reads each side as of, so the schema and data
1094
+ // diffs see what every other check does; or none, under --no-snapshot.
1095
+ ...snapshotArgs(options.sourceUrl, options.targetUrl),
582
1096
  // @dbdiff/cli >= 3.0.0-rc.3 refuses to emit a migration containing
583
1097
  // DROP TABLE or DROP COLUMN unless this is passed, exiting non-zero and
584
1098
  // writing no output file. SupaForge is a *detection* tool: an extra table
@@ -867,8 +1381,14 @@ function unfoldedIssues(result, check, ignoreSchemas, ignoredSchemaTables) {
867
1381
  };
868
1382
  });
869
1383
  }
1384
+ function platformDefaultPrivileges(sql) {
1385
+ const role = /^\s*ALTER\s+DEFAULT\s+PRIVILEGES\s+FOR\s+ROLE\s+("(?:[^"]|"")+"|[\w$]+)/i.exec(sql)?.[1];
1386
+ if (!role) return false;
1387
+ const name = role.startsWith('"') ? role.slice(1, -1).replace(/""/g, '"') : role.toLowerCase();
1388
+ return name !== "postgres" && PLATFORM_ROLES.includes(name);
1389
+ }
870
1390
  function issuesFromUnits(upUnits, downUnits, check, ignoreSchemas, ignoredSchemaTables) {
871
- const pairs = pairUnits(upUnits, downUnits).filter(({ up, down }) => !(ignoreSchemas?.length && isCrossSchemaFkUnit(up, down, ignoreSchemas, ignoredSchemaTables)));
1391
+ const pairs = pairUnits(upUnits, downUnits).filter(({ up, down }) => !(ignoreSchemas?.length && isCrossSchemaFkUnit(up, down, ignoreSchemas, ignoredSchemaTables)) && !platformDefaultPrivileges(up.sql));
872
1392
  return pairs.map(({ up, down }, i) => {
873
1393
  const upSql = up.sql;
874
1394
  const downSql = down?.sql ?? "";
@@ -1489,6 +2009,32 @@ function extractRoutineArgs(sql) {
1489
2009
  }
1490
2010
  return "";
1491
2011
  }
2012
+ function rolesAddressed(sql) {
2013
+ const names2 = (specs = []) => specs.map((s) => s.RoleSpec).filter((r) => r?.roletype === "ROLESPEC_CSTRING" && typeof r.rolename === "string" && !r.rolename.startsWith("pg_")).map((r) => r.rolename);
2014
+ return (parseStatements(sql) ?? []).flatMap(({ kind, node }) => kind === "GrantStmt" ? names2(node.grantees) : kind === "CreatePolicyStmt" || kind === "AlterPolicyStmt" ? names2(node.roles) : kind === "AlterDefaultPrivilegesStmt" ? [...names2(node.action?.grantees), ...names2((node.options ?? []).filter((o) => o.DefElem?.defname === "roles").flatMap((o) => o.DefElem.arg?.List?.items ?? []))] : []);
2015
+ }
2016
+ function withoutAbsentRoles(issues, targetRoles) {
2017
+ const absentIn = (sql) => rolesAddressed(sql).filter((r) => !targetRoles.has(r));
2018
+ return issues.map((issue) => {
2019
+ if (!issue.sql) return issue;
2020
+ const missing = /* @__PURE__ */ new Set();
2021
+ const keep = (sql) => splitStatements(sql).filter((statement) => {
2022
+ const absent = absentIn(statement);
2023
+ absent.forEach((r) => missing.add(r));
2024
+ return absent.length === 0;
2025
+ });
2026
+ const up = keep(issue.sql.up);
2027
+ if (missing.size === 0) return issue;
2028
+ const down = keep(issue.sql.down ?? "");
2029
+ const roles = [...missing].sort().join(", ") + (missing.size > 1 ? ", roles" : ", a role");
2030
+ if (up.length === 0) return { ...issue, manualOnly: `it names ${roles} the target does not have` };
2031
+ return {
2032
+ ...issue,
2033
+ description: `${issue.description} What it grants to ${roles} the target does not have is left out.`,
2034
+ sql: { up: up.join("\n"), down: down.join("\n") }
2035
+ };
2036
+ });
2037
+ }
1492
2038
 
1493
2039
  // src/pg-errors.ts
1494
2040
  var ABSENT_ON_TARGET = /* @__PURE__ */ new Set(["42P01", "42883", "3F000", "42704"]);
@@ -1498,6 +2044,61 @@ function sqlState(err) {
1498
2044
  const code = err?.code;
1499
2045
  return typeof code === "string" ? code : void 0;
1500
2046
  }
2047
+ var OLDER_SERVER = /* @__PURE__ */ new Set(["42601", "0A000", "22023"]);
2048
+
2049
+ // src/lock-budget.ts
2050
+ var INDEXED = /* @__PURE__ */ new Set(["CONSTR_PRIMARY", "CONSTR_UNIQUE", "CONSTR_EXCLUSION"]);
2051
+ function estimateLocks(statements) {
2052
+ const relations = /* @__PURE__ */ new Set();
2053
+ let made = 0;
2054
+ for (const sql of statements) {
2055
+ const parsed = parseStatements(sql);
2056
+ if (!parsed) {
2057
+ made += 1;
2058
+ continue;
2059
+ }
2060
+ for (const { kind, node } of parsed) {
2061
+ if (kind === "CreateStmt") made += 2;
2062
+ if (kind === "IndexStmt") made += 1;
2063
+ walk(node, (key, value) => {
2064
+ if (typeof value.relname === "string") relations.add(`${value.schemaname ?? ""}.${value.relname}`.toLowerCase());
2065
+ if (key === "Constraint" && (INDEXED.has(value.contype) || value.contype === "CONSTR_IDENTITY")) made += 1;
2066
+ });
2067
+ }
2068
+ }
2069
+ return relations.size + made;
2070
+ }
2071
+ function walk(node, visit) {
2072
+ if (Array.isArray(node)) {
2073
+ for (const item of node) walk(item, visit);
2074
+ } else if (node && typeof node === "object") {
2075
+ for (const [key, value] of Object.entries(node)) {
2076
+ if (value && typeof value === "object" && !Array.isArray(value)) visit(key, value);
2077
+ walk(value, visit);
2078
+ }
2079
+ }
2080
+ }
2081
+ async function readLockBudget(client) {
2082
+ try {
2083
+ const { rows: [row] } = await client.query(`
2084
+ SELECT current_setting('max_locks_per_transaction')::bigint
2085
+ * (current_setting('max_connections')::bigint
2086
+ + coalesce(current_setting('autovacuum_worker_slots', true), current_setting('autovacuum_max_workers'))::bigint + 1
2087
+ + current_setting('max_worker_processes')::bigint
2088
+ + current_setting('max_wal_senders')::bigint
2089
+ + current_setting('max_prepared_transactions')::bigint) AS capacity,
2090
+ (SELECT count(*) FROM pg_locks WHERE NOT fastpath) AS in_use`);
2091
+ return { capacity: Number(row.capacity), inUse: Number(row.in_use) };
2092
+ } catch {
2093
+ return void 0;
2094
+ }
2095
+ }
2096
+ function lockBudgetWarning(needed, budget, what) {
2097
+ if (!budget) return void 0;
2098
+ const free = budget.capacity - budget.inUse - Math.ceil(budget.capacity / 10);
2099
+ if (needed <= free) return void 0;
2100
+ return `${what} takes about ${needed} locks in one transaction, and the target has room for about ${Math.max(free, 0)} (max_locks_per_transaction for each connection slot, less what other sessions hold). It may fail with "out of shared memory" and roll back. Raising max_locks_per_transaction on the target (a restart) makes room; --no-transaction commits as it goes instead.`;
2101
+ }
1501
2102
 
1502
2103
  // src/promote.ts
1503
2104
  function outOfScopeReason(sql, filter) {
@@ -1676,22 +2277,39 @@ function dropDuplicateObjectFixes(statements, skipped) {
1676
2277
  }
1677
2278
  return kept;
1678
2279
  }
1679
- async function executeSql(dbUrl, statements, result, transactional) {
2280
+ async function executeSql(dbUrl, statements, result, transactional, sourceMajor) {
1680
2281
  if (statements.length === 0) return;
1681
2282
  const client = newPgClient(dbUrl);
1682
2283
  await client.connect();
1683
2284
  try {
1684
- if (transactional) await runInTransaction(client, statements, result);
2285
+ const olderTarget = sourceMajor !== void 0 && await majorOf(client) < sourceMajor;
2286
+ if (transactional) await runInTransaction(client, statements, result, olderTarget);
1685
2287
  else await runIndependently(client, statements, result);
1686
2288
  } finally {
1687
2289
  await client.end();
1688
2290
  }
1689
2291
  }
1690
- async function runLikeApply(dbUrl, statements) {
2292
+ async function runLikeApply(dbUrl, statements, sourceMajor) {
1691
2293
  const result = { applied: [], skipped: [], errors: [] };
1692
- await executeSql(dbUrl, statements, result, true);
2294
+ await executeSql(dbUrl, statements, result, true, sourceMajor);
1693
2295
  return result;
1694
2296
  }
2297
+ async function majorOf(client) {
2298
+ const { rows: [row] } = await client.query(`SELECT current_setting('server_version_num') AS v`);
2299
+ return Math.floor(Number(row?.v ?? 0) / 1e4);
2300
+ }
2301
+ async function serverMajor(dbUrl) {
2302
+ const client = newPgClient(dbUrl);
2303
+ try {
2304
+ await client.connect();
2305
+ return await majorOf(client);
2306
+ } catch {
2307
+ return void 0;
2308
+ } finally {
2309
+ await client.end().catch(() => {
2310
+ });
2311
+ }
2312
+ }
1695
2313
  async function runIndependently(client, statements, result) {
1696
2314
  for (const stmt of statements) {
1697
2315
  try {
@@ -1706,16 +2324,21 @@ function isEnumValueAddition(sql) {
1706
2324
  const statements = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
1707
2325
  return statements.length > 0 && statements.every((s) => /^\s*ALTER\s+TYPE\s+\S+\s+ADD\s+VALUE\b/i.test(sqlSkeleton(s)));
1708
2326
  }
1709
- async function runInTransaction(client, statements, result) {
2327
+ async function runInTransaction(client, statements, result, olderTarget = false) {
1710
2328
  const additions = statements.filter((s) => isEnumValueAddition(s.sql));
1711
2329
  const rest = statements.filter((s) => !isEnumValueAddition(s.sql));
1712
- if (additions.length > 0 && !await runBatch(client, additions, result)) return;
1713
- await runBatch(client, rest, result);
2330
+ const warning = lockBudgetWarning(estimateLocks(rest.map((s) => s.sql)), await readLockBudget(client), "This apply");
2331
+ if (warning) result.warnings = [...result.warnings ?? [], warning];
2332
+ if (additions.length > 0 && !await runBatch(client, additions, result, olderTarget)) return;
2333
+ await runBatch(client, rest, result, olderTarget);
1714
2334
  }
1715
- function unmetDependency(sql, err) {
2335
+ function unmetDependency(sql, err, olderTarget = false) {
1716
2336
  const code = sqlState(err);
1717
2337
  if (!code) return void 0;
1718
- if (/^\s*CREATE\s+EXTENSION\b/i.test(sqlSkeleton(sql))) {
2338
+ if (olderTarget && OLDER_SERVER.has(code)) {
2339
+ return "the target's PostgreSQL is older than the source's and does not support it";
2340
+ }
2341
+ if (/(?:^|;)\s*CREATE\s+EXTENSION\b/i.test(sqlSkeleton(sql))) {
1719
2342
  return EXTENSION_UNAVAILABLE.has(code) ? "this server does not ship it" : void 0;
1720
2343
  }
1721
2344
  if (ABSENT_ON_TARGET.has(code) || code === UNDEFINED_COLUMN) {
@@ -1723,7 +2346,18 @@ function unmetDependency(sql, err) {
1723
2346
  }
1724
2347
  return void 0;
1725
2348
  }
1726
- async function runBatch(client, statements, result) {
2349
+ function revokesFromAbsent(sql) {
2350
+ const statements = parseStatements(sql);
2351
+ if (!statements?.length) return false;
2352
+ const targets = /* @__PURE__ */ new Set();
2353
+ for (const { kind, node } of statements) {
2354
+ if (kind !== "GrantStmt" || node.is_grant || node.targtype !== "ACL_TARGET_OBJECT") return false;
2355
+ if ((node.objects ?? []).length !== 1) return false;
2356
+ targets.add(JSON.stringify([node.objtype, node.objects[0]], (key, value) => key === "location" ? void 0 : value));
2357
+ }
2358
+ return targets.size === 1;
2359
+ }
2360
+ async function runBatch(client, statements, result, olderTarget = false) {
1727
2361
  if (statements.length === 0) return true;
1728
2362
  const done = [];
1729
2363
  await client.query("BEGIN");
@@ -1738,7 +2372,7 @@ async function runBatch(client, statements, result) {
1738
2372
  await client.query("RELEASE SAVEPOINT sf_fix");
1739
2373
  done.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
1740
2374
  } catch (err) {
1741
- const why = unmetDependency(stmt.sql, err);
2375
+ const why = unmetDependency(stmt.sql, err, olderTarget);
1742
2376
  if (why && await client.query("ROLLBACK TO SAVEPOINT sf_fix").then(() => true, () => false)) {
1743
2377
  unmet.push({ stmt, err, why });
1744
2378
  continue;
@@ -1753,6 +2387,11 @@ async function runBatch(client, statements, result) {
1753
2387
  if (unmet.length === pending.length) break;
1754
2388
  pending = unmet.map((u) => u.stmt);
1755
2389
  }
2390
+ const gone = unmet.filter((u) => revokesFromAbsent(u.stmt.sql));
2391
+ unmet = unmet.filter((u) => !gone.includes(u));
2392
+ for (const { stmt } of gone) {
2393
+ done.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql, note: "nothing to revoke: the object is not on the target" });
2394
+ }
1756
2395
  await client.query("COMMIT");
1757
2396
  result.applied.push(...done);
1758
2397
  for (const { stmt, err, why } of unmet) {
@@ -1815,7 +2454,13 @@ async function promote(options) {
1815
2454
  }
1816
2455
  return result;
1817
2456
  }
1818
- await executeSql(dbUrl, sqlStatements, result, transactional);
2457
+ await executeSql(
2458
+ dbUrl,
2459
+ sqlStatements,
2460
+ result,
2461
+ transactional,
2462
+ options.sourceUrl ? await serverMajor(options.sourceUrl) : void 0
2463
+ );
1819
2464
  if (result.rolledBack) {
1820
2465
  for (const act of apiActions) {
1821
2466
  result.skipped.push({
@@ -1844,15 +2489,22 @@ export {
1844
2489
  CHECK_NAMES,
1845
2490
  CHECK_META,
1846
2491
  isComparisonCheck,
2492
+ PLATFORM_ROLES,
2493
+ RolesCheck,
1847
2494
  runDbDiff,
1848
2495
  isDestructiveSql,
1849
2496
  destructiveReason,
1850
2497
  sqlToIssues,
1851
2498
  schemaNotices,
2499
+ withoutAbsentRoles,
1852
2500
  ABSENT_ON_TARGET,
1853
2501
  EXTENSION_UNAVAILABLE,
2502
+ OLDER_SERVER,
2503
+ estimateLocks,
2504
+ readLockBudget,
2505
+ lockBudgetWarning,
1854
2506
  planWork,
1855
2507
  runLikeApply,
1856
2508
  promote
1857
2509
  };
1858
- //# sourceMappingURL=chunk-T7GMPGUO.js.map
2510
+ //# sourceMappingURL=chunk-YUJ2MHLM.js.map