@akal/supaforge 0.0.45 → 0.0.47

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 (31) hide show
  1. package/dist/base-command.js +1 -1
  2. package/dist/{chunk-KTATU64Y.js → chunk-2XMRTAFX.js} +108 -17
  3. package/dist/{chunk-ZLNP3DUB.js → chunk-3SEVACCT.js} +9 -6
  4. package/dist/{chunk-KPU6G6BO.js → chunk-4TBYWXUK.js} +6 -8
  5. package/dist/{chunk-JVZYVZUH.js → chunk-CRUFF6K5.js} +5 -7
  6. package/dist/{chunk-4RD66RHF.js → chunk-CUGDLO2L.js} +10 -12
  7. package/dist/{chunk-EMRM4RIV.js → chunk-EB6PCOIL.js} +2 -2
  8. package/dist/{chunk-DUTPOR7P.js → chunk-EGXQ37PA.js} +37 -14
  9. package/dist/{chunk-R4FSOTB6.js → chunk-KBZUTGGF.js} +7 -7
  10. package/dist/{chunk-CKH6J7DI.js → chunk-TU5UIODX.js} +7 -5
  11. package/dist/{chunk-HGCTVCLV.js → chunk-UUDXVYEI.js} +7 -7
  12. package/dist/{chunk-YABERWV7.js → chunk-WNZCOYOK.js} +176 -46
  13. package/dist/{chunk-J64XMOXU.js → chunk-XTSFAUXI.js} +5 -5
  14. package/dist/{chunk-UPWUXQ24.js → chunk-YQLVRHJA.js} +2 -2
  15. package/dist/{chunk-USIOUMYL.js → chunk-YYS4FJ23.js} +141 -2
  16. package/dist/commands/clone.d.ts +14 -1
  17. package/dist/commands/clone.js +15 -5
  18. package/dist/commands/diff.js +8 -9
  19. package/dist/commands/hukam.js +8 -9
  20. package/dist/commands/mcp.js +7 -8
  21. package/dist/commands/migrate/baseline.js +1 -1
  22. package/dist/commands/migrate/create.js +6 -7
  23. package/dist/commands/migrate/list.js +1 -1
  24. package/dist/commands/migrate/run.js +5 -6
  25. package/dist/commands/report.js +1 -1
  26. package/dist/commands/restore.js +6 -7
  27. package/dist/commands/snapshot.js +4 -5
  28. package/dist/commands/sync.js +8 -9
  29. package/dist/index.js +11 -12
  30. package/package.json +2 -2
  31. package/dist/chunk-WK5YTINL.js +0 -121
@@ -1,17 +1,16 @@
1
- import {
2
- isCommentOnly,
3
- splitSqlStatements
4
- } from "./chunk-WK5YTINL.js";
5
1
  import {
6
2
  dbdiffPgToolsEnv,
7
3
  describeMissingPgDump,
8
4
  escapeRegex,
9
5
  getServerMajorVersion,
10
6
  globToRegExp,
7
+ isCommentOnly,
11
8
  matchesGlob,
12
9
  parseFlagList,
13
- resolvePgDumpPath
14
- } from "./chunk-USIOUMYL.js";
10
+ pgToolConnection,
11
+ resolvePgDumpPath,
12
+ splitSqlStatements
13
+ } from "./chunk-YYS4FJ23.js";
15
14
  import {
16
15
  Check,
17
16
  heldSnapshot,
@@ -1011,37 +1010,113 @@ function withoutDropStatements(sql) {
1011
1010
  if (!/\bDROP\b/i.test(sql)) return sql;
1012
1011
  return splitSqlStatements(sql).filter((s) => !/^\s*DROP\b/i.test(sqlSkeleton(s))).join("\n");
1013
1012
  }
1014
- function nextReady(remaining, nodes, done) {
1015
- const ready = remaining.filter((i) => isSatisfied(nodes[i].after, done));
1016
- const first = (from, key) => from.reduce((best, i) => best === void 0 || key(nodes[i]) < key(nodes[best]) ? i : best, void 0);
1017
- const head = first(ready.filter((i) => nodes[i].rank !== void 0), (n) => n.rank);
1018
- const free = first(ready.filter((i) => nodes[i].rank === void 0), (n) => n.phase);
1019
- if (head === void 0 || free === void 0) return head ?? free ?? remaining[0];
1020
- const sequence = Math.min(...remaining.filter((i) => nodes[i].rank !== void 0 && !DROP_PHASES.has(nodes[i].phase)).map((i) => nodes[i].phase));
1021
- return nodes[free].phase < sequence ? free : head;
1022
- }
1023
- function isSatisfied(after, done) {
1024
- for (const dep of after) {
1025
- if (!done.has(dep)) return false;
1013
+ function orderNodes(nodes) {
1014
+ const n = nodes.length;
1015
+ const waiting = new Array(n);
1016
+ const dependents = Array.from({ length: n }, () => []);
1017
+ for (let i = 0; i < n; i++) {
1018
+ waiting[i] = nodes[i].after.size;
1019
+ for (const dep of nodes[i].after) dependents[dep].push(i);
1020
+ }
1021
+ const ranked = new MinHeap((a, b) => nodes[a].rank - nodes[b].rank || a - b);
1022
+ const free = new MinHeap((a, b) => nodes[a].phase - nodes[b].phase || a - b);
1023
+ const enqueue = (i) => (nodes[i].rank !== void 0 ? ranked : free).push(i);
1024
+ const sequenceLeft = /* @__PURE__ */ new Map();
1025
+ for (const node of nodes) {
1026
+ if (node.rank !== void 0 && !DROP_PHASES.has(node.phase)) {
1027
+ sequenceLeft.set(node.phase, (sequenceLeft.get(node.phase) ?? 0) + 1);
1028
+ }
1029
+ }
1030
+ const earliestInSequence = () => {
1031
+ let min = Infinity;
1032
+ for (const [phase, count] of sequenceLeft) if (count > 0 && phase < min) min = phase;
1033
+ return min;
1034
+ };
1035
+ const done = new Array(n).fill(false);
1036
+ for (let i = 0; i < n; i++) if (waiting[i] === 0) enqueue(i);
1037
+ let lowest = 0;
1038
+ const order = [];
1039
+ const peek = (heap) => {
1040
+ while (heap.size > 0 && done[heap.peek()]) heap.pop();
1041
+ return heap.size > 0 ? heap.peek() : void 0;
1042
+ };
1043
+ while (order.length < n) {
1044
+ const head = peek(ranked);
1045
+ const other = peek(free);
1046
+ let next;
1047
+ if (head === void 0 || other === void 0) {
1048
+ if (head !== void 0 || other !== void 0) {
1049
+ next = head ?? other;
1050
+ } else {
1051
+ while (done[lowest]) lowest++;
1052
+ next = lowest;
1053
+ }
1054
+ } else {
1055
+ next = nodes[other].phase < earliestInSequence() ? other : head;
1056
+ }
1057
+ done[next] = true;
1058
+ order.push(next);
1059
+ const node = nodes[next];
1060
+ if (node.rank !== void 0 && !DROP_PHASES.has(node.phase)) {
1061
+ sequenceLeft.set(node.phase, sequenceLeft.get(node.phase) - 1);
1062
+ }
1063
+ for (const d of dependents[next]) {
1064
+ if (--waiting[d] === 0 && !done[d]) enqueue(d);
1065
+ }
1066
+ }
1067
+ return order;
1068
+ }
1069
+ var MinHeap = class {
1070
+ constructor(compare) {
1071
+ this.compare = compare;
1072
+ }
1073
+ compare;
1074
+ items = [];
1075
+ get size() {
1076
+ return this.items.length;
1077
+ }
1078
+ peek() {
1079
+ return this.items[0];
1080
+ }
1081
+ push(item) {
1082
+ const items = this.items;
1083
+ items.push(item);
1084
+ let i = items.length - 1;
1085
+ while (i > 0) {
1086
+ const parent = i - 1 >> 1;
1087
+ if (this.compare(items[i], items[parent]) >= 0) break;
1088
+ [items[i], items[parent]] = [items[parent], items[i]];
1089
+ i = parent;
1090
+ }
1091
+ }
1092
+ pop() {
1093
+ const items = this.items;
1094
+ const top = items[0];
1095
+ const last = items.pop();
1096
+ if (items.length > 0) {
1097
+ items[0] = last;
1098
+ let i = 0;
1099
+ for (; ; ) {
1100
+ const l = 2 * i + 1;
1101
+ const r = l + 1;
1102
+ let m = i;
1103
+ if (l < items.length && this.compare(items[l], items[m]) < 0) m = l;
1104
+ if (r < items.length && this.compare(items[r], items[m]) < 0) m = r;
1105
+ if (m === i) break;
1106
+ [items[i], items[m]] = [items[m], items[i]];
1107
+ i = m;
1108
+ }
1109
+ }
1110
+ return top;
1026
1111
  }
1027
- return true;
1028
- }
1112
+ };
1029
1113
  function orderStatements(items, sqlOf, rankOf = () => void 0) {
1030
1114
  if (items.length < 2) return [...items];
1031
1115
  const texts = items.map(sqlOf);
1032
1116
  const provides = texts.map(providedNames);
1033
1117
  const nodes = texts.map((sql, i) => ({ phase: statementPhase(sql), rank: rankOf(items[i]), after: /* @__PURE__ */ new Set() }));
1034
1118
  linkDependencies(nodes, texts, provides);
1035
- const done = /* @__PURE__ */ new Set();
1036
- let remaining = texts.map((_, i) => i);
1037
- const ordered = [];
1038
- while (remaining.length > 0) {
1039
- const next = nextReady(remaining, nodes, done);
1040
- ordered.push(items[next]);
1041
- done.add(next);
1042
- remaining = remaining.filter((i) => i !== next);
1043
- }
1044
- return ordered;
1119
+ return orderNodes(nodes).map((i) => items[i]);
1045
1120
  }
1046
1121
  function splitQualified(identifier) {
1047
1122
  const parts = identifier.match(/"[^"]+"|[\w$]+/g) ?? [];
@@ -1214,8 +1289,9 @@ function snapshotArgs(sourceUrl, targetUrl) {
1214
1289
  function buildDbDiffArgs(options, outputFile) {
1215
1290
  const args = [
1216
1291
  "diff",
1217
- `--server1-url=${options.sourceUrl}`,
1218
- `--server2-url=${options.targetUrl}`,
1292
+ // A process's arguments are readable by every user on the machine; its
1293
+ // environment only by its own user. See dbdiffUrlEnv().
1294
+ ...options.urlsOnCommandLine ? [`--server1-url=${options.sourceUrl}`, `--server2-url=${options.targetUrl}`] : [],
1219
1295
  `--type=${options.type}`,
1220
1296
  // Was hardcoded to 'both', silently ignoring options.include. Every caller
1221
1297
  // passes 'both' (sqlToIssues pairs each UP statement with its DOWN
@@ -1255,6 +1331,10 @@ function buildDbDiffArgs(options, outputFile) {
1255
1331
  }
1256
1332
  return args;
1257
1333
  }
1334
+ function dbdiffUrlEnv(options) {
1335
+ if (options.urlsOnCommandLine) return {};
1336
+ return { DBDIFF_SERVER1_URL: options.sourceUrl, DBDIFF_SERVER2_URL: options.targetUrl };
1337
+ }
1258
1338
  function attachProgress(running, onProgress) {
1259
1339
  if (!onProgress) return;
1260
1340
  try {
@@ -1292,7 +1372,7 @@ async function runDbDiff(options) {
1292
1372
  const running = execFileAsync(command, args, {
1293
1373
  timeout: timeoutMs,
1294
1374
  maxBuffer: DBDIFF_MAX_BUFFER,
1295
- ...Object.keys(pgTools).length ? { env: { ...process.env, ...pgTools } } : {}
1375
+ env: { ...process.env, ...pgTools, ...dbdiffUrlEnv(options) }
1296
1376
  });
1297
1377
  attachProgress(running, options.onProgress);
1298
1378
  const { stdout } = await running;
@@ -1312,6 +1392,9 @@ async function runDbDiff(options) {
1312
1392
  if (options.units !== false && /"--units" option does not exist/.test(`${combined} ${stdout}`)) {
1313
1393
  return runDbDiff({ ...options, units: false });
1314
1394
  }
1395
+ if (!options.urlsOnCommandLine && /Missing input argument/.test(`${combined} ${stdout}`)) {
1396
+ return runDbDiff({ ...options, urlsOnCommandLine: true });
1397
+ }
1315
1398
  if (dbdiffNotInstalled(errObj.code, stderr)) {
1316
1399
  throw new DiagnosticError(
1317
1400
  "@dbdiff/cli is not installed. Install it with: npm install @dbdiff/cli"
@@ -1541,12 +1624,45 @@ function platformExtensionMoves(issues) {
1541
1624
  });
1542
1625
  }
1543
1626
  var quoteIdent2 = (name) => /^[a-z_][a-z0-9_$]*$/.test(name) ? name : `"${name.replace(/"/g, '""')}"`;
1544
- function withPlatformExtensionCalls(issues, moves, functions) {
1545
- const rules = moves.flatMap((move) => [...functions.get(move.name) ?? []].map((fn) => ({ move, fn })));
1627
+ var accepts = (fn, args) => args >= fn.minArgs && args <= fn.maxArgs;
1628
+ function argumentCount(sql, mask, open) {
1629
+ let depth = 0;
1630
+ let commas = 0;
1631
+ let empty = true;
1632
+ for (let i = open; i < mask.length; i++) {
1633
+ const c = mask[i];
1634
+ if (c === "(" || c === "[") {
1635
+ depth++;
1636
+ if (depth > 1) empty = false;
1637
+ continue;
1638
+ }
1639
+ if (c === ")" || c === "]") {
1640
+ if (--depth === 0) return empty ? 0 : commas + 1;
1641
+ continue;
1642
+ }
1643
+ if (depth === 1 && c === ",") commas++;
1644
+ if (depth >= 1 && !/\s/.test(sql[i])) empty = false;
1645
+ }
1646
+ return void 0;
1647
+ }
1648
+ var DEFINES = /\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:FUNCTION|PROCEDURE|AGGREGATE)\s*$/i;
1649
+ function withPlatformExtensionCalls(issues, moves, functions, shadows = []) {
1650
+ const rules = moves.flatMap((move) => (functions.get(move.name) ?? []).map((fn) => ({ move, fn })));
1546
1651
  if (!rules.length) return issues;
1547
1652
  const nameRe = String.raw`("(?:[^"]|"")+"|[\w$]+)`;
1548
1653
  const call = new RegExp(String.raw`${nameRe}(\s*\.\s*)${nameRe}(?=\s*\()`, "g");
1549
1654
  const unq = (part) => part.startsWith('"') ? part.slice(1, -1).replace(/""/g, '"') : part.toLowerCase();
1655
+ const defined = [...shadows];
1656
+ for (const issue of issues) {
1657
+ for (const sql of issue.sql ? [issue.sql.up, issue.sql.down] : []) {
1658
+ const mask = codeMask(sql);
1659
+ for (const m of mask.matchAll(call)) {
1660
+ if (!DEFINES.test(mask.slice(0, m.index))) continue;
1661
+ const args = argumentCount(sql, mask, mask.indexOf("(", m.index + m[0].length));
1662
+ if (args !== void 0) defined.push({ schema: unq(m[1]), name: unq(m[3]), minArgs: args, maxArgs: args });
1663
+ }
1664
+ }
1665
+ }
1550
1666
  const rewrite = (sql, seen) => {
1551
1667
  const mask = codeMask(sql);
1552
1668
  let out = "";
@@ -1554,8 +1670,12 @@ function withPlatformExtensionCalls(issues, moves, functions) {
1554
1670
  for (const m of mask.matchAll(call)) {
1555
1671
  const schema = unq(m[1]);
1556
1672
  const fn = unq(m[3]);
1557
- const rule = rules.find((r) => r.move.sourceSchema === schema && r.fn === fn);
1673
+ if (DEFINES.test(mask.slice(0, m.index))) continue;
1674
+ const args = argumentCount(sql, mask, mask.indexOf("(", m.index + m[0].length));
1675
+ if (args === void 0) continue;
1676
+ const rule = rules.find((r) => r.move.sourceSchema === schema && r.fn.name === fn && accepts(r.fn, args));
1558
1677
  if (!rule) continue;
1678
+ if (defined.some((d) => d.schema === schema && d.name === fn && accepts(d, args))) continue;
1559
1679
  out += sql.slice(at, m.index) + quoteIdent2(rule.move.targetSchema) + m[2] + sql.slice(m.index + m[1].length + m[2].length, m.index + m[0].length);
1560
1680
  at = m.index + m[0].length;
1561
1681
  seen.add(`${quoteIdent2(schema)}.${quoteIdent2(fn)}() \u2192 ${quoteIdent2(rule.move.targetSchema)}.${quoteIdent2(fn)}()`);
@@ -2925,8 +3045,10 @@ async function sampleInto(psql, fromUrl, intoUrl, schemas, limit) {
2925
3045
  }
2926
3046
  function pipeCopy(psql, fromUrl, intoUrl, out, into) {
2927
3047
  return new Promise((resolve, reject) => {
2928
- const reader = spawn(psql, [fromUrl, "-X", "-q", "-v", "ON_ERROR_STOP=1", "-c", out], { stdio: ["ignore", "pipe", "pipe"] });
2929
- const writer = spawn(psql, [intoUrl, "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", "-"], { stdio: ["pipe", "pipe", "pipe"] });
3048
+ const reading = pgToolConnection(fromUrl);
3049
+ const writing = pgToolConnection(intoUrl);
3050
+ const reader = spawn(psql, [reading.url, "-X", "-q", "-v", "ON_ERROR_STOP=1", "-c", out], { stdio: ["ignore", "pipe", "pipe"], env: reading.env });
3051
+ const writer = spawn(psql, [writing.url, "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", "-"], { stdio: ["pipe", "pipe", "pipe"], env: writing.env });
2930
3052
  let stderr = "";
2931
3053
  reader.stderr.on("data", (d) => {
2932
3054
  stderr += d.toString();
@@ -3026,6 +3148,9 @@ function withDatabase(dbUrl, database) {
3026
3148
  url.pathname = `/${database}`;
3027
3149
  return url.toString();
3028
3150
  }
3151
+ function withoutNotNullConstraints(fingerprint2) {
3152
+ return fingerprint2.split("\n").filter((line) => !/^con .+ NOT NULL (?:"(?:[^"]|"")+"|\S+) valid=t deferrable=f deferred=f$/.test(line)).join("\n");
3153
+ }
3029
3154
  async function fingerprint(dbUrl, schemas) {
3030
3155
  const rows = await pgQuery(dbUrl, fingerprintSql(schemas));
3031
3156
  const value = rows[0]?.fingerprint;
@@ -3155,9 +3280,10 @@ async function proveConvergence(opts) {
3155
3280
  const withData = data ? { ...r, data } : r;
3156
3281
  return notApplied?.length ? { ...withData, notApplied } : withData;
3157
3282
  };
3283
+ const comparable = sourceMajor < 18 ? withoutNotNullConstraints : (fp) => fp;
3158
3284
  const [want, got] = await Promise.all([
3159
- fingerprint(opts.sourceUrl, schemas),
3160
- fingerprint(cloneUrl, schemas)
3285
+ fingerprint(opts.sourceUrl, schemas).then(comparable),
3286
+ fingerprint(cloneUrl, schemas).then(comparable)
3161
3287
  ]);
3162
3288
  if (canonicalArrays(want) === canonicalArrays(got)) return reported({ converged: true, residual: [], cloneName });
3163
3289
  roundTripName = `${cloneName}_src`;
@@ -3166,7 +3292,7 @@ async function proveConvergence(opts) {
3166
3292
  if (roundTrip !== null) {
3167
3293
  sourceCopyCreated = true;
3168
3294
  if (roundTrip.ok) {
3169
- const wantRoundTripped = await fingerprint(roundTripUrl, schemas);
3295
+ const wantRoundTripped = comparable(await fingerprint(roundTripUrl, schemas));
3170
3296
  if (canonicalArrays(wantRoundTripped) === canonicalArrays(got)) return reported({ converged: true, residual: [], cloneName });
3171
3297
  const residual2 = await describeDifference2(roundTripUrl, cloneUrl, schemas, wantRoundTripped, got);
3172
3298
  return reported(withinScope(residual2, before && diffState(await schemaState(roundTripUrl, schemas), before), opts.checks, cloneName));
@@ -3200,8 +3326,9 @@ async function copyStructure(fromUrl, intoUrl, schemas, tools, migratingFrom) {
3200
3326
  if (present.has(name) && !supporting.includes(name)) supporting.push(name);
3201
3327
  }
3202
3328
  }
3329
+ const from = pgToolConnection(fromUrl);
3203
3330
  const dumpArgs = [
3204
- fromUrl,
3331
+ from.url,
3205
3332
  "--schema-only",
3206
3333
  "--no-owner",
3207
3334
  "--no-privileges",
@@ -3209,7 +3336,8 @@ async function copyStructure(fromUrl, intoUrl, schemas, tools, migratingFrom) {
3209
3336
  ];
3210
3337
  const { stdout: structure } = await exec(tools.pgDump, dumpArgs, {
3211
3338
  maxBuffer: 256 * 1024 * 1024,
3212
- timeout: 3e5
3339
+ timeout: 3e5,
3340
+ env: from.env
3213
3341
  });
3214
3342
  const { sql: replayable } = dropUnsupportedSetStatements(
3215
3343
  tolerateExistingSchemas(structure),
@@ -3288,8 +3416,10 @@ function runSql(psqlPath, dbUrl, sql) {
3288
3416
  const trimmed = sql.trim();
3289
3417
  if (!trimmed) return Promise.resolve();
3290
3418
  return new Promise((resolve, reject) => {
3291
- const child = spawn2(psqlPath, [dbUrl, "-v", "ON_ERROR_STOP=1", "-q", "-f", "-"], {
3292
- stdio: ["pipe", "pipe", "pipe"]
3419
+ const conn = pgToolConnection(dbUrl);
3420
+ const child = spawn2(psqlPath, [conn.url, "-v", "ON_ERROR_STOP=1", "-q", "-f", "-"], {
3421
+ stdio: ["pipe", "pipe", "pipe"],
3422
+ env: conn.env
3293
3423
  });
3294
3424
  let stderr = "";
3295
3425
  child.stderr.on("data", (d) => {
@@ -3463,4 +3593,4 @@ export {
3463
3593
  residualHeldBack,
3464
3594
  proofScope
3465
3595
  };
3466
- //# sourceMappingURL=chunk-YABERWV7.js.map
3596
+ //# sourceMappingURL=chunk-WNZCOYOK.js.map
@@ -1,20 +1,20 @@
1
1
  import {
2
2
  migrationsDir,
3
3
  writeMigrationFile
4
- } from "./chunk-JVZYVZUH.js";
4
+ } from "./chunk-CRUFF6K5.js";
5
5
  import {
6
6
  createDefaultRegistry,
7
7
  proveBeforeApply,
8
8
  scan
9
- } from "./chunk-DUTPOR7P.js";
9
+ } from "./chunk-EGXQ37PA.js";
10
10
  import {
11
11
  CHECK_NAMES,
12
12
  promote
13
- } from "./chunk-YABERWV7.js";
13
+ } from "./chunk-WNZCOYOK.js";
14
14
  import {
15
15
  captureSnapshot,
16
16
  unrestorableSchema
17
- } from "./chunk-ZLNP3DUB.js";
17
+ } from "./chunk-3SEVACCT.js";
18
18
  import {
19
19
  checkConnection
20
20
  } from "./chunk-RC7ZU7OV.js";
@@ -530,4 +530,4 @@ export {
530
530
  clearLastScanResult,
531
531
  createServer
532
532
  };
533
- //# sourceMappingURL=chunk-J64XMOXU.js.map
533
+ //# sourceMappingURL=chunk-XTSFAUXI.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  comparedSchemas,
3
3
  fingerprint
4
- } from "./chunk-YABERWV7.js";
4
+ } from "./chunk-WNZCOYOK.js";
5
5
 
6
6
  // src/written-against.ts
7
7
  import { createHash } from "crypto";
@@ -24,4 +24,4 @@ export {
24
24
  writtenAgainstLine,
25
25
  writtenAgainst
26
26
  };
27
- //# sourceMappingURL=chunk-UPWUXQ24.js.map
27
+ //# sourceMappingURL=chunk-YQLVRHJA.js.map
@@ -2,6 +2,120 @@ import {
2
2
  newPgClient
3
3
  } from "./chunk-RC7ZU7OV.js";
4
4
 
5
+ // src/utils/sql-split.ts
6
+ var ROUTINE_HEAD = /^CREATE\s+(?:OR\s+REPLACE\s+)?(?:FUNCTION|PROCEDURE)\b/i;
7
+ function withoutLeadingComments(text) {
8
+ let rest = text.trimStart();
9
+ for (; ; ) {
10
+ if (rest.startsWith("--")) {
11
+ const newline = rest.indexOf("\n");
12
+ rest = newline === -1 ? "" : rest.slice(newline + 1).trimStart();
13
+ } else if (rest.startsWith("/*")) {
14
+ const close = rest.indexOf("*/");
15
+ rest = close === -1 ? "" : rest.slice(close + 2).trimStart();
16
+ } else {
17
+ return rest;
18
+ }
19
+ }
20
+ }
21
+ var DOLLAR_TAG = /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/;
22
+ function splitSqlStatements(sql) {
23
+ const statements = [];
24
+ let start = 0;
25
+ let i = 0;
26
+ let blockDepth = 0;
27
+ let beginDepth = 0;
28
+ const push = (end) => {
29
+ const piece = sql.slice(start, end).trim();
30
+ if (piece.length > 0) statements.push(piece);
31
+ };
32
+ while (i < sql.length) {
33
+ if (blockDepth > 0) {
34
+ if (sql.startsWith("/*", i)) {
35
+ blockDepth++;
36
+ i += 2;
37
+ continue;
38
+ }
39
+ if (sql.startsWith("*/", i)) {
40
+ blockDepth--;
41
+ i += 2;
42
+ continue;
43
+ }
44
+ i++;
45
+ continue;
46
+ }
47
+ if (sql.startsWith("/*", i)) {
48
+ blockDepth = 1;
49
+ i += 2;
50
+ continue;
51
+ }
52
+ if (sql.startsWith("--", i)) {
53
+ const newline = sql.indexOf("\n", i);
54
+ i = newline === -1 ? sql.length : newline + 1;
55
+ continue;
56
+ }
57
+ const ch = sql[i];
58
+ if (ch === "'" || ch === '"') {
59
+ i++;
60
+ while (i < sql.length) {
61
+ if (sql[i] !== ch) {
62
+ i++;
63
+ continue;
64
+ }
65
+ if (sql[i + 1] === ch) {
66
+ i += 2;
67
+ continue;
68
+ }
69
+ i++;
70
+ break;
71
+ }
72
+ continue;
73
+ }
74
+ if (ch === "$") {
75
+ const tag = DOLLAR_TAG.exec(sql.slice(i));
76
+ if (tag) {
77
+ const close = sql.indexOf(tag[0], i + tag[0].length);
78
+ i = close === -1 ? sql.length : close + tag[0].length;
79
+ continue;
80
+ }
81
+ i++;
82
+ continue;
83
+ }
84
+ if (/[A-Za-z_]/.test(ch)) {
85
+ const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(sql.slice(i, i + 64))[0];
86
+ const upper = word.toUpperCase();
87
+ if ((upper === "BEGIN" || upper === "CASE") && ROUTINE_HEAD.test(withoutLeadingComments(sql.slice(start, i)))) {
88
+ beginDepth++;
89
+ } else if (upper === "END" && beginDepth > 0) {
90
+ beginDepth--;
91
+ }
92
+ i += word.length;
93
+ continue;
94
+ }
95
+ if (ch === ";" && beginDepth === 0) {
96
+ push(i);
97
+ i++;
98
+ start = i;
99
+ continue;
100
+ }
101
+ i++;
102
+ }
103
+ push(sql.length);
104
+ return statements;
105
+ }
106
+ function isCommentOnly(statement) {
107
+ const meaningful = statement.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("--"));
108
+ return meaningful.length === 0;
109
+ }
110
+ var PSQL_WRAPPER_LINE = /^[ \t]*\\(?:un)?restrict\b[^\n]*$/gm;
111
+ function stripPsqlMetaCommands(sql) {
112
+ return sql.replace(PSQL_WRAPPER_LINE, "");
113
+ }
114
+ function isPsqlMetaCommand(statement) {
115
+ const meaningful = statement.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("--"));
116
+ return meaningful.length > 0 && meaningful.every((line) => line.startsWith("\\"));
117
+ }
118
+
5
119
  // src/utils/strings.ts
6
120
  var MAX_SLUG_LENGTH = 60;
7
121
  function slugify(name, separator = "_") {
@@ -240,7 +354,31 @@ function getInstallInstructions(majorVersion) {
240
354
  }
241
355
  }
242
356
 
357
+ // src/utils/pg-env.ts
358
+ function pgToolConnection(url, base = process.env) {
359
+ let parsed;
360
+ try {
361
+ parsed = new URL(url);
362
+ } catch {
363
+ return { url, env: base };
364
+ }
365
+ if (!/^postgres(?:ql)?:$/.test(parsed.protocol)) return { url, env: base };
366
+ const inQuery = parsed.searchParams.get("password");
367
+ const password = parsed.password ? decodeURIComponent(parsed.password) : inQuery;
368
+ if (password === null || password === "") return { url, env: base };
369
+ parsed.password = "";
370
+ if (inQuery !== null) {
371
+ const rest = parsed.search.slice(1).split("&").filter((p) => !/^password(?:=|$)/.test(p));
372
+ parsed.search = rest.length ? `?${rest.join("&")}` : "";
373
+ }
374
+ return { url: parsed.toString(), env: { ...base, PGPASSWORD: password } };
375
+ }
376
+
243
377
  export {
378
+ splitSqlStatements,
379
+ isCommentOnly,
380
+ stripPsqlMetaCommands,
381
+ isPsqlMetaCommand,
244
382
  slugify,
245
383
  escapeRegex,
246
384
  parseFlagList,
@@ -252,6 +390,7 @@ export {
252
390
  describeMissingPgDump,
253
391
  getServerMajorVersion,
254
392
  dbdiffPgToolsEnv,
255
- checkPgDumpCompat
393
+ checkPgDumpCompat,
394
+ pgToolConnection
256
395
  };
257
- //# sourceMappingURL=chunk-USIOUMYL.js.map
396
+ //# sourceMappingURL=chunk-YYS4FJ23.js.map
@@ -4,6 +4,13 @@ import { R as RestoreFailure } from '../branch-BppjQBv_.js';
4
4
  import { S as SupaForgeConfig } from '../config-l3ggjw9r.js';
5
5
  import '@oclif/core';
6
6
 
7
+ /** A privilege the clone could not grant, because its role is not on this server. */
8
+ interface NotGranted {
9
+ role: string;
10
+ /** The statement, summarised: `GRANT SELECT ON TABLE public.film TO reader`. */
11
+ statement: string;
12
+ }
13
+
7
14
  /**
8
15
  * Clone a remote environment to a local database and manage clones.
9
16
  *
@@ -36,6 +43,12 @@ declare class Clone extends BaseCommand {
36
43
  * are stated rather than counted as the clone failing — see restoreFailures.
37
44
  */
38
45
  declare function formatUnavailable(items: readonly RestoreFailure[]): string[];
46
+ /**
47
+ * The source's privileges this server has no role for, by role: a clone of a
48
+ * Supabase project onto plain PostgreSQL has no `anon`, so none of its grants.
49
+ * Everything else the source grants is in the clone.
50
+ */
51
+ declare function formatNotGranted(items: readonly NotGranted[]): string[];
39
52
  /**
40
53
  * What pg_restore could not reproduce, for step 1 of the output.
41
54
  *
@@ -63,4 +76,4 @@ declare function formatRestoreFailures(failures: readonly RestoreFailure[]): str
63
76
  */
64
77
  declare function configAfterClone(config: SupaForgeConfig, envName: string, localDbUrl: string): SupaForgeConfig;
65
78
 
66
- export { configAfterClone, Clone as default, formatRestoreFailures, formatUnavailable };
79
+ export { configAfterClone, Clone as default, formatNotGranted, formatRestoreFailures, formatUnavailable };
@@ -3,7 +3,7 @@ import {
3
3
  } from "../chunk-RQCXGO37.js";
4
4
  import {
5
5
  BaseCommand
6
- } from "../chunk-CKH6J7DI.js";
6
+ } from "../chunk-TU5UIODX.js";
7
7
  import {
8
8
  addBranchToManifest,
9
9
  cloneRemoteToLocal,
@@ -13,14 +13,14 @@ import {
13
13
  maintenanceUrl,
14
14
  reconcileClones,
15
15
  replaceDbName
16
- } from "../chunk-KTATU64Y.js";
16
+ } from "../chunk-2XMRTAFX.js";
17
17
  import {
18
18
  captureSnapshot,
19
19
  formatSnapshotLayers
20
- } from "../chunk-ZLNP3DUB.js";
20
+ } from "../chunk-3SEVACCT.js";
21
21
  import {
22
22
  checkPgDumpCompat
23
- } from "../chunk-USIOUMYL.js";
23
+ } from "../chunk-YYS4FJ23.js";
24
24
  import {
25
25
  DEFAULT_LOCAL_PORT,
26
26
  LOCAL_PG_PASSWORD,
@@ -283,6 +283,7 @@ var Clone = class _Clone extends BaseCommand {
283
283
  this.log(` ${dim(`Installed first, in the schema the source keeps them in: ${cloned.extensionsInstalled.join(", ")}`)}`);
284
284
  }
285
285
  for (const line of formatUnavailable(cloned.unavailable)) this.log(line);
286
+ for (const line of formatNotGranted(cloned.notGranted)) this.log(line);
286
287
  for (const line of formatRestoreFailures(cloned.failures)) this.log(line);
287
288
  } catch (err) {
288
289
  progressOut.write("\n");
@@ -338,7 +339,8 @@ var Clone = class _Clone extends BaseCommand {
338
339
  snapshot: snapshot.manifest,
339
340
  config: newConfig,
340
341
  restoreFailures: cloned.failures,
341
- unavailable: cloned.unavailable
342
+ unavailable: cloned.unavailable,
343
+ notGranted: cloned.notGranted
342
344
  });
343
345
  if (missing > 0) this.exit(1);
344
346
  return;
@@ -387,6 +389,13 @@ function formatUnavailable(items) {
387
389
  ];
388
390
  return [` ${dim(`Not available on this server, as expected for a Supabase project: ${parts.join("; ")}`)}`];
389
391
  }
392
+ function formatNotGranted(items) {
393
+ if (items.length === 0) return [];
394
+ const byRole = /* @__PURE__ */ new Map();
395
+ for (const { role } of items) byRole.set(role, (byRole.get(role) ?? 0) + 1);
396
+ const roles = [...byRole].map(([role, n]) => `${role} (${n})`).join(", ");
397
+ return [` ${dim(`Privileges not granted, as these roles are not on this server: ${roles}`)}`];
398
+ }
390
399
  var RESTORE_FAILURES_SHOWN = 15;
391
400
  function formatRestoreFailures(failures) {
392
401
  if (failures.length === 0) return [];
@@ -412,6 +421,7 @@ function configAfterClone(config, envName, localDbUrl) {
412
421
  export {
413
422
  configAfterClone,
414
423
  Clone as default,
424
+ formatNotGranted,
415
425
  formatRestoreFailures,
416
426
  formatUnavailable
417
427
  };
@@ -2,17 +2,16 @@ import {
2
2
  Diff,
3
3
  inertApplyFlags,
4
4
  rollbackHint
5
- } from "../chunk-4RD66RHF.js";
5
+ } from "../chunk-CUGDLO2L.js";
6
6
  import "../chunk-Q43MN6NE.js";
7
- import "../chunk-EMRM4RIV.js";
8
- import "../chunk-DUTPOR7P.js";
9
- import "../chunk-YABERWV7.js";
10
- import "../chunk-WK5YTINL.js";
7
+ import "../chunk-EB6PCOIL.js";
8
+ import "../chunk-EGXQ37PA.js";
9
+ import "../chunk-WNZCOYOK.js";
11
10
  import "../chunk-RQCXGO37.js";
12
- import "../chunk-CKH6J7DI.js";
13
- import "../chunk-KTATU64Y.js";
14
- import "../chunk-ZLNP3DUB.js";
15
- import "../chunk-USIOUMYL.js";
11
+ import "../chunk-TU5UIODX.js";
12
+ import "../chunk-2XMRTAFX.js";
13
+ import "../chunk-3SEVACCT.js";
14
+ import "../chunk-YYS4FJ23.js";
16
15
  import "../chunk-RC7ZU7OV.js";
17
16
  import "../chunk-KHXEES2M.js";
18
17
  import "../chunk-SQ52YBKK.js";