@akal/supaforge 0.0.31 → 0.0.33

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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +29 -11
  3. package/dist/base-command.d.ts +1 -0
  4. package/dist/base-command.js +2 -2
  5. package/dist/{chunk-BHYLBKYD.js → chunk-2SELREHW.js} +5 -5
  6. package/dist/{chunk-5Z3SAIQS.js → chunk-3HGAV5CC.js} +97 -831
  7. package/dist/{chunk-XMYMIURR.js → chunk-4IVN7QVY.js} +119 -39
  8. package/dist/{chunk-NXRSAVRU.js → chunk-6LJERPUN.js} +28 -7
  9. package/dist/{chunk-4OU7KO5Y.js → chunk-6Q7MHFBM.js} +2 -2
  10. package/dist/{chunk-PARSNTBD.js → chunk-7NAZGZPV.js} +56 -25
  11. package/dist/{chunk-VOXZWQ3N.js → chunk-BUOWHE36.js} +372 -9
  12. package/dist/{chunk-TQJSQLWA.js → chunk-DMIWAJRB.js} +38 -10
  13. package/dist/{chunk-LQXF65MC.js → chunk-GEHPTPNZ.js} +3 -3
  14. package/dist/chunk-GZREXCQZ.js +207 -0
  15. package/dist/{chunk-YVDSR4GM.js → chunk-MIRLB5JM.js} +51 -23
  16. package/dist/{chunk-KIFJGON5.js → chunk-NTUASFQ3.js} +2 -2
  17. package/dist/{chunk-5QQBTLWO.js → chunk-ORQJVE57.js} +3 -3
  18. package/dist/{chunk-VMTBLHN2.js → chunk-SC2XHGIS.js} +2 -2
  19. package/dist/{chunk-X6V2GGDZ.js → chunk-SQPCWGQO.js} +388 -64
  20. package/dist/chunk-UWAVXC57.js +916 -0
  21. package/dist/commands/clone.js +10 -10
  22. package/dist/commands/diff.d.ts +16 -0
  23. package/dist/commands/diff.js +11 -12
  24. package/dist/commands/hukam.js +11 -12
  25. package/dist/commands/mcp.d.ts +1 -0
  26. package/dist/commands/mcp.js +18 -9
  27. package/dist/commands/migrate/baseline.js +3 -3
  28. package/dist/commands/migrate/create.js +5 -6
  29. package/dist/commands/migrate/list.js +4 -4
  30. package/dist/commands/migrate/run.js +5 -6
  31. package/dist/commands/report.js +3 -3
  32. package/dist/commands/restore.js +11 -13
  33. package/dist/commands/snapshot.js +6 -8
  34. package/dist/commands/sync.js +11 -12
  35. package/dist/index.d.ts +5 -0
  36. package/dist/index.js +16 -16
  37. package/package.json +10 -8
  38. package/bin/dev.js +0 -10
  39. package/dist/base-command.js.map +0 -1
  40. package/dist/chunk-4OU7KO5Y.js.map +0 -1
  41. package/dist/chunk-5QQBTLWO.js.map +0 -1
  42. package/dist/chunk-5Z3SAIQS.js.map +0 -1
  43. package/dist/chunk-6WAMNZLO.js.map +0 -1
  44. package/dist/chunk-BHYLBKYD.js.map +0 -1
  45. package/dist/chunk-BLKJWDTL.js.map +0 -1
  46. package/dist/chunk-DQQ5E563.js.map +0 -1
  47. package/dist/chunk-G2DIPIYU.js.map +0 -1
  48. package/dist/chunk-H5MJ5DFX.js +0 -16
  49. package/dist/chunk-H5MJ5DFX.js.map +0 -1
  50. package/dist/chunk-KIFJGON5.js.map +0 -1
  51. package/dist/chunk-LQXF65MC.js.map +0 -1
  52. package/dist/chunk-NXRSAVRU.js.map +0 -1
  53. package/dist/chunk-PARSNTBD.js.map +0 -1
  54. package/dist/chunk-RRMI5CZD.js +0 -376
  55. package/dist/chunk-RRMI5CZD.js.map +0 -1
  56. package/dist/chunk-SF3YA42C.js +0 -506
  57. package/dist/chunk-SF3YA42C.js.map +0 -1
  58. package/dist/chunk-TQJSQLWA.js.map +0 -1
  59. package/dist/chunk-VMTBLHN2.js.map +0 -1
  60. package/dist/chunk-VOXZWQ3N.js.map +0 -1
  61. package/dist/chunk-X6V2GGDZ.js.map +0 -1
  62. package/dist/chunk-XMYMIURR.js.map +0 -1
  63. package/dist/chunk-YVDSR4GM.js.map +0 -1
  64. package/dist/commands/clone.js.map +0 -1
  65. package/dist/commands/diff.js.map +0 -1
  66. package/dist/commands/help.js.map +0 -1
  67. package/dist/commands/hukam.js.map +0 -1
  68. package/dist/commands/init.js.map +0 -1
  69. package/dist/commands/mcp.js.map +0 -1
  70. package/dist/commands/migrate/baseline.js.map +0 -1
  71. package/dist/commands/migrate/create.js.map +0 -1
  72. package/dist/commands/migrate/list.js.map +0 -1
  73. package/dist/commands/migrate/run.js.map +0 -1
  74. package/dist/commands/report.js.map +0 -1
  75. package/dist/commands/restore.js.map +0 -1
  76. package/dist/commands/snapshot.js.map +0 -1
  77. package/dist/commands/sync.js.map +0 -1
  78. package/dist/help.js.map +0 -1
  79. package/dist/index.js.map +0 -1
@@ -1,43 +1,50 @@
1
1
  import {
2
2
  sanitizeForReport
3
- } from "./chunk-4OU7KO5Y.js";
3
+ } from "./chunk-6Q7MHFBM.js";
4
4
  import {
5
5
  coverage,
6
6
  formatSkips,
7
7
  renderDetailed,
8
8
  renderSummary
9
- } from "./chunk-LQXF65MC.js";
9
+ } from "./chunk-GEHPTPNZ.js";
10
10
  import {
11
- CHECK_META,
12
- CHECK_NAMES,
13
11
  createDefaultRegistry,
14
- describeTableFilter,
15
- isFiltered,
16
- planWork,
17
- promote,
18
- resolveTableFilter,
19
12
  scan,
20
13
  summarizeByKind
21
- } from "./chunk-5Z3SAIQS.js";
14
+ } from "./chunk-3HGAV5CC.js";
22
15
  import {
23
16
  comparedSchemas,
24
17
  proofScope,
25
18
  proveConvergence,
26
19
  residualHeldBack
27
- } from "./chunk-TQJSQLWA.js";
20
+ } from "./chunk-DMIWAJRB.js";
21
+ import {
22
+ CHECK_META,
23
+ CHECK_NAMES,
24
+ describeTableFilter,
25
+ isFiltered,
26
+ planWork,
27
+ promote,
28
+ resolveTableFilter
29
+ } from "./chunk-UWAVXC57.js";
28
30
  import {
29
31
  renderTip
30
32
  } from "./chunk-BLKJWDTL.js";
31
33
  import {
32
34
  BaseCommand
33
- } from "./chunk-SF3YA42C.js";
35
+ } from "./chunk-GZREXCQZ.js";
34
36
  import {
35
37
  isCloneDatabase,
36
38
  sourceLooksLikeCloneOf
37
- } from "./chunk-5QQBTLWO.js";
39
+ } from "./chunk-ORQJVE57.js";
38
40
  import {
39
41
  parseFlagList
40
42
  } from "./chunk-DQQ5E563.js";
43
+ import {
44
+ Preflight,
45
+ describeFailure,
46
+ redactUrls
47
+ } from "./chunk-SQPCWGQO.js";
41
48
  import {
42
49
  CLONE_SKIP_FLAGS,
43
50
  DEFAULT_IGNORE_SCHEMAS,
@@ -127,7 +134,7 @@ function describeCheckOutcome(status, issueCount, skipReason) {
127
134
  if (status === "skipped") {
128
135
  return { glyph: dim("\u25CB"), text: dim(`skipped \u2014 ${skipReason ?? "no reason given"}`) };
129
136
  }
130
- return { glyph: ok("\u2713"), text: `${issueCount} issues` };
137
+ return { glyph: ok("\u2713"), text: `${issueCount} ${issueCount === 1 ? "issue" : "issues"}` };
131
138
  }
132
139
  var APPLY_ONLY_FLAGS = [
133
140
  { flag: "prove", shapesThePlan: false },
@@ -320,12 +327,7 @@ ${warn(`${result.errors.length} error(s):`)}`);
320
327
  this.log(`
321
328
  ${dim(describeTableFilter(tableFilter))}`);
322
329
  }
323
- if (!flags.json && !flags.ci) {
324
- const sourceEnv = config.environments[config.source];
325
- const targetEnv = config.environments[config.target];
326
- const pre = this.createPreflight("Diff preflight checks").addDatabase("Source", config.source, sourceEnv.dbUrl).addDatabase("Target", config.target, targetEnv.dbUrl);
327
- await this.runPreflight(pre, "Diff");
328
- }
330
+ await this.preflightBothDatabases(config, flags);
329
331
  const makeProgress = () => {
330
332
  if (flags.json || flags.ci) return void 0;
331
333
  process.stdout.write("\n Scanning...\n");
@@ -361,12 +363,18 @@ ${warn(`${result.errors.length} error(s):`)}`);
361
363
  durationMs: c.durationMs,
362
364
  ...c.error ? { error: sanitizeForReport(c.error) } : {}
363
365
  })));
366
+ const unchecked = scanResult.checks.filter((c) => c.status === "error").map((c) => ({ check: c.check, error: sanitizeForReport(c.error ?? "check failed") }));
364
367
  if (scanResult.summary.total === 0) {
365
368
  if (flags.json) {
366
369
  const empty = { applied: [], skipped: [], errors: [] };
367
- this.json(empty);
370
+ this.json(unchecked.length ? { ...empty, unchecked } : empty);
371
+ if (unchecked.length) this.exit(1);
368
372
  return;
369
373
  }
374
+ if (unchecked.length) {
375
+ this.reportUnchecked(unchecked);
376
+ this.exit(1);
377
+ }
370
378
  this.log(`${ok("No drift detected.")} Nothing to apply. \u2713`);
371
379
  this.log(renderTip({ command: "diff", apply: true, driftTotal: 0 }));
372
380
  return;
@@ -394,6 +402,7 @@ ${warn(`${result.errors.length} error(s):`)}`);
394
402
  sourceUrl: sourceEnv.dbUrl,
395
403
  targetUrl: targetEnv.dbUrl,
396
404
  migrationSql,
405
+ fixes: replay,
397
406
  // Every schema the schema diff compares, not `public` alone: a
398
407
  // migration dropping a schema the source lacks runs against it.
399
408
  schemas: await comparedSchemas(
@@ -405,25 +414,22 @@ ${warn(`${result.errors.length} error(s):`)}`);
405
414
  // target already lacks elsewhere is not this migration's to fix.
406
415
  checks: scanResult.checks.map((c) => c.check)
407
416
  });
408
- if (proof.skipped) {
409
- this.log(` ${warn("Convergence not proven")}: ${proof.skipped}`);
410
- this.log(` ${dim("Continuing \u2014 re-run without --prove to silence this.")}
417
+ const heldBack = [...heldBackSql(scanResult, planned), ...(proof.notApplied ?? []).map((n) => n.sql)];
418
+ if (proof.notApplied?.length) {
419
+ this.log(` ${dim(`Left out, as the apply will leave them \u2014 this server can't hold them: ${proof.notApplied.map((n) => n.issueId).join(", ")}`)}`);
420
+ }
421
+ if (proof.skipped && replay.length === 0) {
422
+ this.log(` ${dim(`Nothing to prove: ${proof.skipped}.`)}
411
423
  `);
412
- } else if (!proof.converged && residualHeldBack(proof.residual, heldBackSql(scanResult, planned)).unexplained.length === 0) {
424
+ } else if (proof.skipped) {
425
+ this.refuseUnproven(`Not proven: ${proof.skipped}`, [], flags.json);
426
+ } else if (!proof.converged && residualHeldBack(proof.residual, heldBack).unexplained.length === 0) {
413
427
  this.log(` ${ok("Converged")}, apart from what is held back and stays on the target:`);
414
428
  for (const line of proof.residual.slice(0, 15)) this.log(` ${dim(line)}`);
415
429
  this.log("");
416
430
  } else if (!proof.converged) {
417
- this.log(` ${warn("Migration does not reproduce the source.")} Nothing was applied.
418
- `);
419
- const { unexplained } = residualHeldBack(proof.residual, heldBackSql(scanResult, planned));
420
- for (const line of unexplained.slice(0, 15)) this.log(` ${line}`);
421
- if (unexplained.length > 15) {
422
- this.log(` ${dim(`\u2026and ${unexplained.length - 15} more`)}`);
423
- }
424
- this.log(`
425
- ${dim("These objects would still differ after applying.")}`);
426
- this.exit(1);
431
+ const { unexplained } = residualHeldBack(proof.residual, heldBack);
432
+ this.refuseUnproven("Migration does not reproduce the source.", unexplained, flags.json);
427
433
  } else {
428
434
  if (proof.outOfScope?.length) {
429
435
  this.log(` ${ok("Converged")} on what this run compares. Outside it, and already different before:`);
@@ -448,11 +454,13 @@ ${warn(`${result.errors.length} error(s):`)}`);
448
454
  transactional: !flags["no-transaction"]
449
455
  });
450
456
  if (flags.json) {
451
- this.json(result2);
457
+ this.json(unchecked.length ? { ...result2, unchecked } : result2);
458
+ if (result2.errors.length > 0 || unchecked.length > 0) this.exit(1);
452
459
  return;
453
460
  }
454
461
  this.renderApplyResult(result2, dryRun);
455
- if (result2.errors.length > 0) {
462
+ if (unchecked.length > 0) this.reportUnchecked(unchecked);
463
+ if (result2.errors.length > 0 || unchecked.length > 0) {
456
464
  this.exit(1);
457
465
  }
458
466
  this.log(renderTip({
@@ -535,18 +543,90 @@ ${warn(`${result.errors.length} error(s):`)}`);
535
543
  `
536
544
  );
537
545
  }
538
- if (drift.critical > 0 || flags["fail-on-posture"] && posture.critical > 0) {
546
+ if (drift.critical > 0 || flags["fail-on-posture"] && posture.critical > 0 || erroredChecks.length > 0) {
547
+ this.exit(1);
548
+ }
549
+ }
550
+ /**
551
+ * Stop before applying anything: the proof could not run, or ran and found
552
+ * the migration would not reproduce the source. Under --json the reason is
553
+ * the output, rather than nothing at all.
554
+ */
555
+ refuseUnproven(reason, residual, json) {
556
+ if (json) {
557
+ this.json({ proved: false, reason, residual, applied: [], skipped: [], errors: [] });
558
+ this.exit(1);
559
+ }
560
+ this.log(` ${warn(/[.!?]$/.test(reason) ? reason : `${reason}.`)} Nothing was applied.
561
+ `);
562
+ for (const line of residual.slice(0, 15)) this.log(` ${line}`);
563
+ if (residual.length > 15) this.log(` ${dim(`\u2026and ${residual.length - 15} more`)}`);
564
+ if (residual.length > 0) this.log(`
565
+ ${dim("These objects would still differ after applying.")}`);
566
+ else this.log(` ${dim("Re-run without --prove to apply without the proof.")}`);
567
+ this.exit(1);
568
+ }
569
+ /** Name the checks that failed, whose drift this run neither saw nor applied. */
570
+ reportUnchecked(unchecked) {
571
+ this.log(`
572
+ ${warn(`${unchecked.length} check(s) could not run, so nothing of theirs was applied:`)}`);
573
+ for (const u of unchecked) this.log(` ${u.check}: ${u.error}`);
574
+ this.log("");
575
+ }
576
+ /**
577
+ * Abort before scanning when either database can't be reached.
578
+ *
579
+ * Text mode prints the preflight as before. Under --json the report goes to
580
+ * stdout as JSON; under --ci it becomes an error annotation, with exit 2
581
+ * (couldn't run) as the CI contract says.
582
+ */
583
+ async preflightBothDatabases(config, flags) {
584
+ const quiet = Boolean(flags.json || flags.ci);
585
+ const pre = new Preflight("Diff preflight checks", quiet ? () => void 0 : (m) => this.log(m)).addDatabase("Source", config.source, config.environments[config.source].dbUrl).addDatabase("Target", config.target, config.environments[config.target].dbUrl);
586
+ const report = await pre.run();
587
+ if (report.passed) return;
588
+ const failures = report.checks.filter((c) => !c.passed).map((c) => `${c.label} not reachable: ${redactUrls(describeFailure(c.error))}`);
589
+ const message = `Diff aborted \u2014 ${failures.join("; ")}`;
590
+ if (flags.ci) {
591
+ process.stderr.write(`::error title=Diff aborted::${failures.join("; ")}
592
+ `);
593
+ process.stdout.write(JSON.stringify({
594
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
595
+ error: message,
596
+ score: null,
597
+ postureScore: null,
598
+ summary: { total: 0, critical: 0, warning: 0, info: 0 },
599
+ errors: failures.map((f) => ({ check: "preflight", message: f })),
600
+ skipped: [],
601
+ coverage: { compared: 0, total: 0 },
602
+ criticalIssues: [],
603
+ warningIssues: [],
604
+ preflight: report.checks.map(stripError)
605
+ }, null, 2) + "\n");
606
+ this.exit(2);
607
+ }
608
+ if (flags.json) {
609
+ this.json({ error: message, preflight: report.checks.map(stripError) });
539
610
  this.exit(1);
540
611
  }
612
+ this.error("Diff aborted \u2014 fix the issues above first.", { exit: 1 });
541
613
  }
542
614
  };
543
615
  function heldBackSql(scanResult, planned) {
544
616
  const skipped = new Set(planned.skipped.map((s) => s.issueId));
545
617
  return scanResult.checks.flatMap((c) => c.issues).filter((i) => skipped.has(i.id) && i.sql?.up).map((i) => i.sql.up);
546
618
  }
619
+ function stripError(c) {
620
+ return {
621
+ label: c.label,
622
+ passed: c.passed,
623
+ ...c.detail ? { detail: c.detail } : {},
624
+ ...c.error ? { error: redactUrls(describeFailure(c.error)) } : {}
625
+ };
626
+ }
547
627
 
548
628
  export {
549
629
  inertApplyFlags,
550
630
  Diff
551
631
  };
552
- //# sourceMappingURL=chunk-XMYMIURR.js.map
632
+ //# sourceMappingURL=chunk-4IVN7QVY.js.map
@@ -1,15 +1,22 @@
1
1
  import {
2
2
  backup
3
- } from "./chunk-KIFJGON5.js";
3
+ } from "./chunk-NTUASFQ3.js";
4
4
  import {
5
- CHECK_NAMES,
6
5
  createDefaultRegistry,
7
- promote,
8
6
  scan
9
- } from "./chunk-5Z3SAIQS.js";
7
+ } from "./chunk-3HGAV5CC.js";
8
+ import {
9
+ CHECK_NAMES,
10
+ promote
11
+ } from "./chunk-UWAVXC57.js";
10
12
  import {
11
13
  captureSnapshot
12
- } from "./chunk-YVDSR4GM.js";
14
+ } from "./chunk-MIRLB5JM.js";
15
+ import {
16
+ checkConnection,
17
+ describeFailure,
18
+ redactUrls
19
+ } from "./chunk-SQPCWGQO.js";
13
20
  import {
14
21
  resolveConfig,
15
22
  validateConfig
@@ -157,6 +164,15 @@ ${errors.join("\n")}` }], isError: true };
157
164
  if (errors.length > 0) {
158
165
  return { content: [{ type: "text", text: `Config errors:
159
166
  ${errors.join("\n")}` }], isError: true };
167
+ }
168
+ const unreachable = [];
169
+ for (const [label, name] of [["Source", config.source], ["Target", config.target]]) {
170
+ const conn = await checkConnection(config.environments[name].dbUrl);
171
+ if (!conn.reachable) unreachable.push(`${label} (${name}) not reachable: ${redactUrls(describeFailure(conn.error))}`);
172
+ }
173
+ if (unreachable.length > 0) {
174
+ return { content: [{ type: "text", text: `Nothing compared or applied.
175
+ ${unreachable.join("\n")}` }], isError: true };
160
176
  }
161
177
  const registry = createDefaultRegistry();
162
178
  const scanResult = await scan(registry, {
@@ -171,7 +187,12 @@ ${errors.join("\n")}` }], isError: true };
171
187
  checks,
172
188
  dryRun
173
189
  });
174
- return { content: [{ type: "text", text: JSON.stringify(promoteResult, null, 2) }] };
190
+ const unchecked = scanResult.checks.filter((c) => c.status === "error").map((c) => ({ check: c.check, error: c.error ?? "check failed" }));
191
+ const body = unchecked.length ? { ...promoteResult, unchecked } : promoteResult;
192
+ return {
193
+ content: [{ type: "text", text: JSON.stringify(body, null, 2) }],
194
+ ...unchecked.length || promoteResult.errors.length ? { isError: true } : {}
195
+ };
175
196
  } catch (err) {
176
197
  const msg = err instanceof Error ? err.message : String(err);
177
198
  return { content: [{ type: "text", text: `Error: ${msg}` }], isError: true };
@@ -475,4 +496,4 @@ export {
475
496
  clearLastScanResult,
476
497
  createServer
477
498
  };
478
- //# sourceMappingURL=chunk-NXRSAVRU.js.map
499
+ //# sourceMappingURL=chunk-6LJERPUN.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  redactUrls
3
- } from "./chunk-X6V2GGDZ.js";
3
+ } from "./chunk-SQPCWGQO.js";
4
4
 
5
5
  // src/utils/sanitize.ts
6
6
  function sanitizeForReport(text) {
@@ -10,4 +10,4 @@ function sanitizeForReport(text) {
10
10
  export {
11
11
  sanitizeForReport
12
12
  };
13
- //# sourceMappingURL=chunk-4OU7KO5Y.js.map
13
+ //# sourceMappingURL=chunk-6Q7MHFBM.js.map
@@ -1,23 +1,24 @@
1
1
  import {
2
2
  loadMigrations
3
- } from "./chunk-KIFJGON5.js";
3
+ } from "./chunk-NTUASFQ3.js";
4
4
  import {
5
5
  ensureMigrationsTable,
6
6
  getAppliedVersions
7
- } from "./chunk-VMTBLHN2.js";
7
+ } from "./chunk-SC2XHGIS.js";
8
8
  import {
9
9
  dropUnsupportedSetStatements,
10
10
  knownParameters
11
- } from "./chunk-TQJSQLWA.js";
11
+ } from "./chunk-DMIWAJRB.js";
12
12
  import {
13
13
  ABSENT_ON_TARGET,
14
- EXTENSION_UNAVAILABLE
15
- } from "./chunk-H5MJ5DFX.js";
14
+ EXTENSION_UNAVAILABLE,
15
+ PLATFORM_ROLES
16
+ } from "./chunk-UWAVXC57.js";
16
17
  import {
17
18
  rolesNamedBy,
18
19
  sqlSkeleton,
19
20
  statementSubject
20
- } from "./chunk-RRMI5CZD.js";
21
+ } from "./chunk-BUOWHE36.js";
21
22
  import {
22
23
  isCommentOnly,
23
24
  isPsqlMetaCommand,
@@ -26,7 +27,7 @@ import {
26
27
  } from "./chunk-G2DIPIYU.js";
27
28
  import {
28
29
  loadSnapshot
29
- } from "./chunk-YVDSR4GM.js";
30
+ } from "./chunk-MIRLB5JM.js";
30
31
  import {
31
32
  errMsg,
32
33
  pgClientConfig,
@@ -34,7 +35,7 @@ import {
34
35
  quoteIdent,
35
36
  quoteLiteral,
36
37
  quoteName
37
- } from "./chunk-X6V2GGDZ.js";
38
+ } from "./chunk-SQPCWGQO.js";
38
39
  import {
39
40
  DEFAULT_IGNORE_SCHEMAS,
40
41
  MIGRATIONS_TABLE,
@@ -323,17 +324,32 @@ async function recreateExternalDependents(client, dependents) {
323
324
  async function resetRelationGrants(client, schemas) {
324
325
  if (schemas.length === 0) return 0;
325
326
  const { rows } = await client.query(`
326
- SELECT format('REVOKE ALL ON %s FROM %s', c.oid::regclass,
327
- string_agg(DISTINCT CASE WHEN a.grantee = 0 THEN 'PUBLIC'
328
- ELSE quote_ident(pg_get_userbyid(a.grantee)) END, ', ')) AS statement
329
- FROM pg_class c
330
- JOIN pg_namespace n ON n.oid = c.relnamespace
331
- CROSS JOIN LATERAL aclexplode(c.relacl) a
332
- WHERE n.nspname = ANY($1)
333
- AND c.relkind IN ('r', 'p', 'v', 'f')
334
- AND a.grantee <> c.relowner
335
- GROUP BY c.oid
336
- `, [schemas]);
327
+ WITH acl AS (
328
+ SELECT CASE c.relkind WHEN 'S' THEN 'SEQUENCE ' ELSE '' END || c.oid::regclass::text AS object, a.grantee
329
+ FROM pg_class c
330
+ JOIN pg_namespace n ON n.oid = c.relnamespace
331
+ CROSS JOIN LATERAL aclexplode(c.relacl) a
332
+ WHERE n.nspname = ANY($1)
333
+ AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')
334
+ AND a.grantee <> c.relowner
335
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e')
336
+ UNION ALL
337
+ SELECT CASE p.prokind WHEN 'p' THEN 'PROCEDURE ' ELSE 'FUNCTION ' END || p.oid::regprocedure::text, a.grantee
338
+ FROM pg_proc p
339
+ JOIN pg_namespace n ON n.oid = p.pronamespace
340
+ CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) a
341
+ WHERE n.nspname = ANY($1)
342
+ AND a.grantee <> p.proowner
343
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')
344
+ )
345
+ SELECT format('REVOKE ALL ON %s FROM %s', object,
346
+ string_agg(DISTINCT CASE WHEN grantee = 0 THEN 'PUBLIC'
347
+ ELSE quote_ident(pg_get_userbyid(grantee)) END, ', ')) AS statement
348
+ FROM acl
349
+ WHERE grantee = 0
350
+ OR (pg_get_userbyid(grantee) <> ALL ($2::text[]) AND pg_get_userbyid(grantee) NOT LIKE 'pg\\_%')
351
+ GROUP BY object
352
+ `, [schemas, PLATFORM_ROLES]);
337
353
  for (const { statement } of rows) await client.query(statement);
338
354
  return rows.length;
339
355
  }
@@ -365,6 +381,7 @@ async function restoreFromSnapshot(options) {
365
381
  const transactional = !options.noTransaction;
366
382
  if (transactional) await client.query("BEGIN");
367
383
  const missing = /* @__PURE__ */ new Set();
384
+ const leftOut = /* @__PURE__ */ new Map();
368
385
  const createdBySchemaLayer = /* @__PURE__ */ new Set();
369
386
  let external = [];
370
387
  const { rows: [{ search_path: sessionSearchPath }] } = await client.query("SHOW search_path");
@@ -443,7 +460,7 @@ async function restoreFromSnapshot(options) {
443
460
  }
444
461
  }
445
462
  for (const sql of statements) {
446
- await applyStatement(client, sql, transactional, result, missing);
463
+ await applyStatement(client, sql, transactional, result, missing, leftOut);
447
464
  }
448
465
  } catch (err) {
449
466
  if (err instanceof RestoreAborted) throw err;
@@ -730,7 +747,7 @@ function mentionedPlatformSchema(sql, targetSchemas) {
730
747
  return SUPABASE_ONLY_SCHEMAS.find((schema) => !targetSchemas.has(schema) && new RegExp(String.raw`(?:"${schema}"|\b${schema})\s*\.`, "i").test(skeleton));
731
748
  }
732
749
  var ATTACHMENT = new RegExp(String.raw`^\s*(?:` + String.raw`GRANT|REVOKE|COMMENT\s+ON|SELECT|ALTER\s+PUBLICATION|ALTER\s+DEFAULT\s+PRIVILEGES|` + String.raw`ALTER\s+POLICY|ALTER\s+TABLE\s+(?:ONLY\s+)?\S+\s+ADD\s+CONSTRAINT\b[\s\S]*\bFOREIGN\s+KEY|` + String.raw`CREATE\s+(?:OR\s+REPLACE\s+)?(?:POLICY|(?:CONSTRAINT\s+)?TRIGGER|VIEW|MATERIALIZED\s+VIEW|RULE)` + String.raw`)\b`, "i");
733
- function tolerableFailure(sql, err, targetSchemas, missing = /* @__PURE__ */ new Set()) {
750
+ function tolerableFailure(sql, err, targetSchemas, missing = /* @__PURE__ */ new Set(), leftOut = /* @__PURE__ */ new Map()) {
734
751
  const code = err?.code;
735
752
  if (!code) return void 0;
736
753
  const skeleton = sqlSkeleton(sql);
@@ -747,16 +764,28 @@ function tolerableFailure(sql, err, targetSchemas, missing = /* @__PURE__ */ new
747
764
  }
748
765
  if (missing.size > 0) {
749
766
  const message = errMsg(err);
767
+ const absent = /^(?:relation|type|function) "([^"]+)" does not exist/i.exec(message)?.[1];
768
+ const key = absent && (absent.includes(".") ? absent : `public.${absent}`);
769
+ const cause = key ? leftOut.get(key) ?? leftOut.get(key.toLowerCase()) : void 0;
770
+ if (cause) return `${message}, as ${key} was left out: ${cause}`;
750
771
  const named = [...missing].filter((what) => {
751
772
  const name = /^the (.+) (?:extension|schema)$/.exec(what)?.[1];
752
- return name !== void 0 && new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i").test(message);
773
+ const word = name !== void 0 && new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
774
+ return word !== false && (word.test(message) || word.test(sqlSkeleton(sql)));
753
775
  });
754
776
  return `${message}, as this target lacks ${(named.length > 0 ? named : [...missing]).join(", ")}`;
755
777
  }
756
778
  return void 0;
757
779
  }
758
780
  var ROUTINE = /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:FUNCTION|PROCEDURE)\b/i;
759
- async function applyStatement(client, sql, transactional, result, missing) {
781
+ var CREATED = /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:(?:UNLOGGED|TEMP|TEMPORARY)\s+)?(?:TABLE|VIEW|MATERIALIZED\s+VIEW|TYPE|DOMAIN|SEQUENCE|FUNCTION|PROCEDURE)\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:("[^"]+"|[\w$]+)\s*\.\s*)?("[^"]+"|[\w$]+)/i;
782
+ function createdObjects(sql) {
783
+ const m = CREATED.exec(sqlSkeleton(sql));
784
+ if (!m) return [];
785
+ const bare = (n) => n.replace(/^"|"$/g, "");
786
+ return [`${m[1] ? bare(m[1]) : "public"}.${bare(m[2])}`];
787
+ }
788
+ async function applyStatement(client, sql, transactional, result, missing, leftOut = /* @__PURE__ */ new Map()) {
760
789
  if (transactional) await client.query("SAVEPOINT sf_restore_statement");
761
790
  try {
762
791
  const needed = extensionTargetSchema(sql);
@@ -769,9 +798,11 @@ async function applyStatement(client, sql, transactional, result, missing) {
769
798
  if (transactional) await client.query("ROLLBACK TO SAVEPOINT sf_restore_statement");
770
799
  const { rows } = await client.query("SELECT nspname FROM pg_namespace");
771
800
  const targetSchemas = new Set(rows.map((r) => r.nspname));
772
- const tolerated = tolerableFailure(sql, err, targetSchemas, missing);
801
+ const tolerated = tolerableFailure(sql, err, targetSchemas, missing, leftOut);
773
802
  if (tolerated) {
774
803
  result.skipped.push({ type: "sql", label: summarizeStatement(sql), reason: tolerated });
804
+ const cause = /(this target lacks .+)$/.exec(tolerated)?.[1] ?? tolerated;
805
+ for (const name of createdObjects(sql)) leftOut.set(name, cause);
775
806
  const extension = /^\s*CREATE\s+EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?("[^"]+"|[\w$-]+)/i.exec(sqlSkeleton(sql));
776
807
  const schema = mentionedPlatformSchema(sql, targetSchemas);
777
808
  if (extension) missing.add(`the ${extension[1].replace(/"/g, "")} extension`);
@@ -834,4 +865,4 @@ export {
834
865
  previewMigrationRestore,
835
866
  summarizeStatement
836
867
  };
837
- //# sourceMappingURL=chunk-PARSNTBD.js.map
868
+ //# sourceMappingURL=chunk-7NAZGZPV.js.map