@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,10 +1,6 @@
1
1
  import {
2
- names,
3
- parseStatements,
4
- policiesRemoved,
5
- relationName,
6
- sqlSkeleton
7
- } from "./chunk-RRMI5CZD.js";
2
+ splitSqlStatements
3
+ } from "./chunk-G2DIPIYU.js";
8
4
  import {
9
5
  escapeRegex
10
6
  } from "./chunk-DQQ5E563.js";
@@ -12,7 +8,7 @@ import {
12
8
  DiagnosticError,
13
9
  errMsg,
14
10
  friendlyDbError
15
- } from "./chunk-X6V2GGDZ.js";
11
+ } from "./chunk-SQPCWGQO.js";
16
12
  import {
17
13
  DBDIFF_EXEC_TIMEOUT_MS,
18
14
  DBDIFF_MAX_BUFFER,
@@ -27,6 +23,356 @@ import { tmpdir } from "os";
27
23
  import { join } from "path";
28
24
  import { promisify } from "util";
29
25
 
26
+ // src/sql-ast.ts
27
+ import { loadModule, parseSync } from "libpg-query";
28
+ await loadModule();
29
+ function parseStatements(sql) {
30
+ try {
31
+ const tree = parseSync(sql);
32
+ return (tree.stmts ?? []).map(({ stmt }) => {
33
+ const kind = Object.keys(stmt)[0];
34
+ return { kind, node: stmt[kind] };
35
+ });
36
+ } catch {
37
+ return void 0;
38
+ }
39
+ }
40
+ function names(list) {
41
+ return (list ?? []).map((item) => item.String?.sval ?? "").filter(Boolean);
42
+ }
43
+ function relationName(rangeVar) {
44
+ return rangeVar?.relname ?? "";
45
+ }
46
+
47
+ // src/sql-deps.ts
48
+ var PHASE = {
49
+ /** Triggers, policies, views, indexes — dropped before what they depend on. */
50
+ DROP_DEPENDANT: 10,
51
+ /** A schema, before anything is made in it. */
52
+ CREATE_SCHEMA: 15,
53
+ /**
54
+ * An extension, before the types and tables that may use it — an exclusion
55
+ * constraint's btree_gist operator class. Read as OTHER it came after the
56
+ * table, which failed (`no default operator class for access method gist`).
57
+ */
58
+ CREATE_EXTENSION: 20,
59
+ /** Types, domains, sequences: no dependencies of their own. */
60
+ CREATE_BASE: 30,
61
+ CREATE_TABLE: 40,
62
+ /** Columns and constraints, needing every table to exist first. */
63
+ ALTER_TABLE: 50,
64
+ /** Before the triggers that execute them and the views that call them. */
65
+ CREATE_ROUTINE: 60,
66
+ CREATE_INDEX: 70,
67
+ CREATE_VIEW: 80,
68
+ /** Anything unrecognised — grants, comments, ownership. */
69
+ OTHER: 85,
70
+ /** Triggers and policies: the last things to be created. */
71
+ CREATE_DEPENDANT: 90,
72
+ /**
73
+ * Comments, once what they name exists: a policy or trigger is created at
74
+ * CREATE_DEPENDANT, and a COMMENT ON it read as OTHER ran before it.
75
+ */
76
+ COMMENT: 95,
77
+ /** Row changes, once the structure holding them is in place. */
78
+ DATA: 100,
79
+ DROP_TABLE: 110,
80
+ /**
81
+ * Routines, dropped once nothing calls them: the triggers, views and
82
+ * policies come off first, and so do the column defaults, CHECK constraints,
83
+ * expression indexes and tables — all of which can call one, and were still
84
+ * in place when routines were dropped at the start (`cannot drop function
85
+ * ... because other objects depend on it`). Before the types a routine's
86
+ * signature can use.
87
+ */
88
+ DROP_ROUTINE: 115,
89
+ DROP_BASE: 120,
90
+ /** Once nothing that used it is left. */
91
+ DROP_EXTENSION: 125
92
+ };
93
+ var DROP_PHASES = /* @__PURE__ */ new Set([
94
+ PHASE.DROP_DEPENDANT,
95
+ PHASE.DROP_TABLE,
96
+ PHASE.DROP_ROUTINE,
97
+ PHASE.DROP_BASE,
98
+ PHASE.DROP_EXTENSION
99
+ ]);
100
+ var PHASE_RULES = [
101
+ // A column type change grouped with the dependants dbdiff drops and
102
+ // recreates around it (see groupColumnTypeChanges) runs as the column change
103
+ // it is — before a foreign key that needs the new type, for one — not as the
104
+ // view or policy it happens to recreate.
105
+ [/^\s*DROP\s+(?:POLICY|TRIGGER|(?:MATERIALIZED\s+)?VIEW)\b[\s\S]*\bALTER\s+TABLE\s+\S+\s+ALTER\s+COLUMN\s+\S+\s+(?:SET\s+DATA\s+)?TYPE\b/i, PHASE.ALTER_TABLE],
106
+ [/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\b/i, PHASE.CREATE_DEPENDANT],
107
+ [/\bCREATE\s+POLICY\b/i, PHASE.CREATE_DEPENDANT],
108
+ [/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:MATERIALIZED\s+)?VIEW\b/i, PHASE.CREATE_VIEW],
109
+ [/\bCREATE\s+(?:UNIQUE\s+)?INDEX\b/i, PHASE.CREATE_INDEX],
110
+ [/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:FUNCTION|PROCEDURE)\b/i, PHASE.CREATE_ROUTINE],
111
+ [/^\s*COMMENT\s+ON\b/i, PHASE.COMMENT],
112
+ [/^\s*CREATE\s+SCHEMA\b/i, PHASE.CREATE_SCHEMA],
113
+ [/^\s*CREATE\s+EXTENSION\b/i, PHASE.CREATE_EXTENSION],
114
+ [/^\s*DROP\s+EXTENSION\b/i, PHASE.DROP_EXTENSION],
115
+ [/\bCREATE\s+(?:TYPE|DOMAIN|SEQUENCE)\b/i, PHASE.CREATE_BASE],
116
+ [/\bCREATE\s+TABLE\b/i, PHASE.CREATE_TABLE],
117
+ [/^\s*ALTER\s+TABLE\b/i, PHASE.ALTER_TABLE],
118
+ [/^\s*DROP\s+(?:TRIGGER|POLICY|INDEX)\b/i, PHASE.DROP_DEPENDANT],
119
+ [/^\s*DROP\s+(?:MATERIALIZED\s+)?VIEW\b/i, PHASE.DROP_DEPENDANT],
120
+ [/^\s*DROP\s+(?:FUNCTION|PROCEDURE)\b/i, PHASE.DROP_ROUTINE],
121
+ [/^\s*DROP\s+TABLE\b/i, PHASE.DROP_TABLE],
122
+ [/^\s*DROP\s+(?:TYPE|DOMAIN|SEQUENCE)\b/i, PHASE.DROP_BASE],
123
+ [/^\s*(?:INSERT|UPDATE|DELETE)\b/i, PHASE.DATA]
124
+ ];
125
+ function statementPhase(sql) {
126
+ const skeleton = sqlSkeleton(sql);
127
+ for (const [pattern, phase] of PHASE_RULES) {
128
+ if (pattern.test(skeleton)) return phase;
129
+ }
130
+ return PHASE.OTHER;
131
+ }
132
+ var DOLLAR_BODY = /\$([A-Za-z0-9_]*)\$[\s\S]*?\$\1\$/g;
133
+ var STRING_LITERAL = /'[^']*(?:''[^']*)*'/g;
134
+ var LINE_COMMENT = /--[^\n]*/g;
135
+ var BLOCK_COMMENT = /\/\*[\s\S]*?\*\//g;
136
+ function sqlSkeleton(sql) {
137
+ return sql.replace(DOLLAR_BODY, " ").replace(STRING_LITERAL, " '' ").replace(LINE_COMMENT, " ").replace(BLOCK_COMMENT, " ");
138
+ }
139
+ var NAME_PART = String.raw`"(?:[^"]|"")+"|[\w$]+`;
140
+ var IDENT = String.raw`(?:${NAME_PART})(?:\s*\.\s*(?:${NAME_PART}))?`;
141
+ function bareName(identifier) {
142
+ const parts = identifier.match(new RegExp(NAME_PART, "g")) ?? [identifier];
143
+ return unquote(parts[parts.length - 1]).toLowerCase();
144
+ }
145
+ var unquote = (part) => {
146
+ const p = part.trim();
147
+ return p.startsWith('"') ? p.slice(1, -1).replace(/""/g, '"') : p;
148
+ };
149
+ var objectKey = (schema, table, name) => `${(schema || "public").toLowerCase()}.${(table ?? "").toLowerCase()}.${(name ?? "").toLowerCase()}`;
150
+ function schemaQualified(identifier) {
151
+ const parts = identifier.match(new RegExp(NAME_PART, "g")) ?? [identifier];
152
+ const fold = (part) => unquote(part).toLowerCase();
153
+ return `${parts.length > 1 ? fold(parts[0]) : "public"}.${fold(parts[parts.length - 1])}`;
154
+ }
155
+ var CREATES = new RegExp(
156
+ String.raw`\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:UNIQUE\s+|MATERIALIZED\s+|TEMP(?:ORARY)?\s+|CONSTRAINT\s+){0,2}` + String.raw`(?:TABLE|VIEW|FUNCTION|PROCEDURE|TYPE|DOMAIN|SEQUENCE|INDEX|TRIGGER|POLICY)\s+` + String.raw`(?:IF\s+NOT\s+EXISTS\s+)?(${IDENT})`,
157
+ "gi"
158
+ );
159
+ function providedNames(sql) {
160
+ const names2 = /* @__PURE__ */ new Set();
161
+ for (const match of sqlSkeleton(sql).matchAll(CREATES)) {
162
+ names2.add(bareName(match[1]));
163
+ }
164
+ return [...names2];
165
+ }
166
+ function isDropOnly(sql, provides) {
167
+ return provides.length === 0 && /^\s*DROP\b/i.test(sql);
168
+ }
169
+ var BODY_TABLE_REF = new RegExp(String.raw`\b(?:FROM|JOIN|INTO|UPDATE|REFERENCES)\s+(?:ONLY\s+)?(${IDENT})`, "gi");
170
+ var ON_TABLE_REF = new RegExp(String.raw`\bON\s+(?:ONLY\s+)?(${IDENT})\s*(?:USING\b|FOR\b|AS\b|TO\b|\(|;|$)`, "gi");
171
+ var TARGET_TABLE_REF = new RegExp(
172
+ String.raw`^\s*(?:ALTER|DROP)\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?(${IDENT})`,
173
+ "gi"
174
+ );
175
+ var NOT_A_TABLE = /* @__PURE__ */ new Set([
176
+ "on",
177
+ "of",
178
+ "from",
179
+ "join",
180
+ "into",
181
+ "select",
182
+ "lateral",
183
+ "only",
184
+ "conflict",
185
+ "delete",
186
+ "update",
187
+ "insert",
188
+ "constraint",
189
+ "each",
190
+ "row",
191
+ "statement",
192
+ "values"
193
+ ]);
194
+ function createdPolicies(sql) {
195
+ const tree = parseStatements(sql);
196
+ if (tree) {
197
+ return tree.filter((s) => s.kind === "CreatePolicyStmt").map(({ node }) => objectKey(node.table?.schemaname, node.table?.relname, node.policy_name));
198
+ }
199
+ const out = [];
200
+ const re = new RegExp(String.raw`CREATE\s+POLICY\s+(${NAME_PART})\s+ON\s+(${IDENT})`, "gi");
201
+ for (const m of sqlSkeleton(sql).matchAll(re)) {
202
+ out.push(`${schemaQualified(m[2])}.${bareName(m[1])}`);
203
+ }
204
+ return out;
205
+ }
206
+ function droppedPolicies(sql) {
207
+ const tree = parseStatements(sql);
208
+ if (tree) {
209
+ 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))));
210
+ }
211
+ const out = [];
212
+ const re = new RegExp(String.raw`DROP\s+POLICY\s+(?:IF\s+EXISTS\s+)?(${NAME_PART})\s+ON\s+(${IDENT})`, "gi");
213
+ for (const m of sqlSkeleton(sql).matchAll(re)) {
214
+ out.push(`${schemaQualified(m[2])}.${bareName(m[1])}`);
215
+ }
216
+ return out;
217
+ }
218
+ function policiesRemoved(sql) {
219
+ const recreated = new Set(createdPolicies(sql));
220
+ return droppedPolicies(sql).filter((key) => !recreated.has(key));
221
+ }
222
+ function createsOnlyPolicies(sql) {
223
+ if (createdPolicies(sql).length === 0) return false;
224
+ const withoutPolicies = sqlSkeleton(sql).replace(/CREATE\s+POLICY[\s\S]*?(?=;|$)/gi, "").replace(/DROP\s+POLICY[\s\S]*?(?=;|$)/gi, "");
225
+ return !/[A-Za-z]/.test(withoutPolicies);
226
+ }
227
+ function createdTriggers(sql) {
228
+ const tree = parseStatements(sql);
229
+ if (tree) {
230
+ return tree.filter((s) => s.kind === "CreateTrigStmt").map(({ node }) => `${(node.relation?.relname ?? "").toLowerCase()}.${String(node.trigname).toLowerCase()}`);
231
+ }
232
+ const out = [];
233
+ const re = new RegExp(String.raw`CREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\s+(${NAME_PART})[\s\S]*?\sON\s+(${IDENT})`, "gi");
234
+ for (const m of sqlSkeleton(sql).matchAll(re)) {
235
+ out.push(`${bareName(m[2])}.${bareName(m[1])}`);
236
+ }
237
+ return out;
238
+ }
239
+ function createsOnlyTriggers(sql) {
240
+ if (createdTriggers(sql).length === 0) return false;
241
+ const withoutTriggers = sqlSkeleton(sql).replace(/CREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER[\s\S]*?(?=;|$)/gi, "").replace(/DROP\s+TRIGGER[\s\S]*?(?=;|$)/gi, "");
242
+ return !/[A-Za-z]/.test(withoutTriggers);
243
+ }
244
+ function referencedTables(sql) {
245
+ const names2 = /* @__PURE__ */ new Set();
246
+ for (const pattern of [BODY_TABLE_REF, ON_TABLE_REF, TARGET_TABLE_REF]) {
247
+ for (const match of sql.matchAll(pattern)) {
248
+ const name = bareName(match[1]);
249
+ if (!NOT_A_TABLE.has(name)) names2.add(name);
250
+ }
251
+ }
252
+ return [...names2];
253
+ }
254
+ function identifierMatcher(name) {
255
+ return new RegExp(String.raw`(?<![\w$])"?${escapeRegex(name)}"?(?![\w$])`, "i");
256
+ }
257
+ function linkDependencies(nodes, texts, provides) {
258
+ const droppers = texts.map((sql, i) => isDropOnly(sql, provides[i]));
259
+ const uses = texts.map(withoutDropStatements);
260
+ for (let provider = 0; provider < nodes.length; provider++) {
261
+ for (const name of provides[provider]) {
262
+ const matcher = identifierMatcher(name);
263
+ for (let consumer = 0; consumer < nodes.length; consumer++) {
264
+ if (consumer === provider || droppers[consumer]) continue;
265
+ if (provides[consumer].includes(name)) continue;
266
+ if (matcher.test(uses[consumer])) nodes[consumer].after.add(provider);
267
+ }
268
+ }
269
+ }
270
+ }
271
+ function withoutDropStatements(sql) {
272
+ if (!/\bDROP\b/i.test(sql)) return sql;
273
+ return splitSqlStatements(sql).filter((s) => !/^\s*DROP\b/i.test(sqlSkeleton(s))).join("\n");
274
+ }
275
+ function nextReady(remaining, nodes, done) {
276
+ const ready = remaining.filter((i) => isSatisfied(nodes[i].after, done));
277
+ const first = (from, key) => from.reduce((best, i) => best === void 0 || key(nodes[i]) < key(nodes[best]) ? i : best, void 0);
278
+ const head = first(ready.filter((i) => nodes[i].rank !== void 0), (n) => n.rank);
279
+ const free = first(ready.filter((i) => nodes[i].rank === void 0), (n) => n.phase);
280
+ if (head === void 0 || free === void 0) return head ?? free ?? remaining[0];
281
+ const sequence = Math.min(...remaining.filter((i) => nodes[i].rank !== void 0 && !DROP_PHASES.has(nodes[i].phase)).map((i) => nodes[i].phase));
282
+ return nodes[free].phase < sequence ? free : head;
283
+ }
284
+ function isSatisfied(after, done) {
285
+ for (const dep of after) {
286
+ if (!done.has(dep)) return false;
287
+ }
288
+ return true;
289
+ }
290
+ function orderStatements(items, sqlOf, rankOf = () => void 0) {
291
+ if (items.length < 2) return [...items];
292
+ const texts = items.map(sqlOf);
293
+ const provides = texts.map(providedNames);
294
+ const nodes = texts.map((sql, i) => ({ phase: statementPhase(sql), rank: rankOf(items[i]), after: /* @__PURE__ */ new Set() }));
295
+ linkDependencies(nodes, texts, provides);
296
+ const done = /* @__PURE__ */ new Set();
297
+ let remaining = texts.map((_, i) => i);
298
+ const ordered = [];
299
+ while (remaining.length > 0) {
300
+ const next = nextReady(remaining, nodes, done);
301
+ ordered.push(items[next]);
302
+ done.add(next);
303
+ remaining = remaining.filter((i) => i !== next);
304
+ }
305
+ return ordered;
306
+ }
307
+ function splitQualified(identifier) {
308
+ const parts = identifier.match(/"[^"]+"|[\w$]+/g) ?? [];
309
+ const clean = parts.map((p) => p.replace(/^"|"$/g, ""));
310
+ if (clean.length >= 2) return { schema: clean[clean.length - 2], name: clean[clean.length - 1] };
311
+ return { schema: null, name: clean[0] ?? "" };
312
+ }
313
+ var IDENT3 = String.raw`(?:"[^"]+"|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|[\w$]+)){0,2}`;
314
+ var OBJECT_KIND = String.raw`(?:TABLE|VIEW|MATERIALIZED\s+VIEW|FOREIGN\s+TABLE|FUNCTION|PROCEDURE|ROUTINE|AGGREGATE|SEQUENCE|TYPE|DOMAIN|INDEX|SCHEMA)`;
315
+ var SUBJECT_RULES = [
316
+ // CREATE/DROP/ALTER TRIGGER|POLICY name ... ON <table>
317
+ [new RegExp(String.raw`^\s*(?:CREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?|DROP\s+|ALTER\s+)(?:TRIGGER|POLICY)\s+(?:IF\s+EXISTS\s+)?(?:"[^"]+"|[\w$]+)[\s\S]*?\bON\s+(?:ONLY\s+)?(${IDENT})`, "i"), "object"],
318
+ // CREATE RULE name AS ON <event> TO <table>
319
+ [new RegExp(String.raw`^\s*CREATE\s+(?:OR\s+REPLACE\s+)?RULE\s+(?:"[^"]+"|[\w$]+)\s+AS\s+ON\s+\w+\s+TO\s+(${IDENT})`, "i"), "object"],
320
+ // CREATE [UNIQUE] INDEX [CONCURRENTLY] [IF NOT EXISTS] [name] ON [ONLY] <table>
321
+ [new RegExp(String.raw`^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\b[\s\S]*?\bON\s+(?:ONLY\s+)?(${IDENT})`, "i"), "object"],
322
+ // COMMENT ON TRIGGER|POLICY|RULE|CONSTRAINT name ON <table>
323
+ [new RegExp(String.raw`^\s*COMMENT\s+ON\s+(?:TRIGGER|POLICY|RULE|CONSTRAINT)\s+(?:"[^"]+"|[\w$]+)\s+ON\s+(?:DOMAIN\s+)?(${IDENT})`, "i"), "object"],
324
+ [new RegExp(String.raw`^\s*COMMENT\s+ON\s+COLUMN\s+(${IDENT3})`, "i"), "column"],
325
+ [new RegExp(String.raw`^\s*COMMENT\s+ON\s+SCHEMA\s+((?:"[^"]+"|[\w$]+))`, "i"), "schema"],
326
+ [new RegExp(String.raw`^\s*COMMENT\s+ON\s+${OBJECT_KIND}\s+(${IDENT})`, "i"), "object"],
327
+ // GRANT/REVOKE ... ON SCHEMA <schema> | ON ALL <kind> IN SCHEMA <schema> | ON [kind] <name>
328
+ [new RegExp(String.raw`^\s*(?:GRANT|REVOKE)\b[\s\S]*?\bON\s+SCHEMA\s+((?:"[^"]+"|[\w$]+))`, "i"), "schema"],
329
+ [new RegExp(String.raw`^\s*(?:GRANT|REVOKE)\b[\s\S]*?\bON\s+ALL\s+\w+\s+IN\s+SCHEMA\s+((?:"[^"]+"|[\w$]+))`, "i"), "schema"],
330
+ [new RegExp(String.raw`^\s*(?:GRANT|REVOKE)\b[\s\S]*?\bON\s+(?:${OBJECT_KIND}\s+)?(${IDENT})`, "i"), "object"],
331
+ // ALTER DEFAULT PRIVILEGES ... IN SCHEMA <schema>
332
+ [new RegExp(String.raw`^\s*ALTER\s+DEFAULT\s+PRIVILEGES\b[\s\S]*?\bIN\s+SCHEMA\s+((?:"[^"]+"|[\w$]+))`, "i"), "schema"],
333
+ // CREATE|ALTER|DROP SCHEMA <schema>
334
+ [new RegExp(String.raw`^\s*(?:CREATE|ALTER|DROP)\s+SCHEMA\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?((?:"[^"]+"|[\w$]+))`, "i"), "schema"],
335
+ // CREATE [OR REPLACE] [modifiers] <kind> [IF NOT EXISTS] <name>
336
+ [new RegExp(String.raw`^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:(?:TEMP|TEMPORARY|UNLOGGED|RECURSIVE)\s+)*${OBJECT_KIND}\s+(?:IF\s+NOT\s+EXISTS\s+)?(${IDENT})`, "i"), "object"],
337
+ // ALTER|DROP <kind> [IF EXISTS] [ONLY] <name>
338
+ [new RegExp(String.raw`^\s*(?:ALTER|DROP)\s+${OBJECT_KIND}\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?(${IDENT})`, "i"), "object"]
339
+ ];
340
+ function statementSubject(sql) {
341
+ const skeleton = sqlSkeleton(sql);
342
+ for (const [rule, captures] of SUBJECT_RULES) {
343
+ const match = rule.exec(skeleton);
344
+ if (!match) continue;
345
+ const parts = (match[1].match(/"[^"]+"|[\w$]+/g) ?? []).map((p) => p.replace(/^"|"$/g, ""));
346
+ if (captures === "schema") return { schema: parts[0], name: parts[0] };
347
+ if (captures === "column") {
348
+ return parts.length >= 3 ? { schema: parts[parts.length - 3], name: parts[parts.length - 2] } : { schema: null, name: parts[0] ?? "" };
349
+ }
350
+ return splitQualified(match[1]);
351
+ }
352
+ return void 0;
353
+ }
354
+ function policyOnlyKeys(sql) {
355
+ if (!sql) return null;
356
+ const statements = splitSqlStatements(sql).filter((s) => sqlSkeleton(s).trim() !== "");
357
+ if (statements.length === 0) return null;
358
+ if (!statements.every((s) => /^\s*(?:CREATE|DROP)\s+POLICY\b/i.test(sqlSkeleton(s)))) return null;
359
+ return [.../* @__PURE__ */ new Set([...createdPolicies(sql), ...droppedPolicies(sql)])];
360
+ }
361
+ function rolesOf({ kind, node }) {
362
+ const specs = kind === "GrantStmt" && node.is_grant ? node.grantees ?? [] : kind === "GrantRoleStmt" && node.is_grant ? node.grantee_roles ?? [] : kind === "CreatePolicyStmt" || kind === "AlterPolicyStmt" ? node.roles ?? [] : [];
363
+ 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_"));
364
+ }
365
+ var ROLE_KEYWORDS = /* @__PURE__ */ new Set(["public", "current_user", "current_role", "session_user"]);
366
+ function rolesNamedBy(sql) {
367
+ const statements = parseStatements(sql);
368
+ if (statements) return [...new Set(statements.flatMap(rolesOf))];
369
+ const skeleton = sqlSkeleton(sql);
370
+ const list = /^\s*GRANT\b[\s\S]*?\bTO\s+([\s\S]*?)(?=\s+WITH\b|\s+GRANTED\s+BY\b|\s*;|\s*$)/i.exec(skeleton) ?? /^\s*(?:CREATE|ALTER)\s+POLICY\b(?![\s\S]*\bRENAME\s+TO\b)[\s\S]*?\bTO\s+([\s\S]*?)(?=\s+USING\b|\s+WITH\s+CHECK\b|\s*;|\s*$)/i.exec(skeleton);
371
+ if (!list) return [];
372
+ const roles = (list[1].match(/"(?:[^"]|"")+"|[\w$]+/g) ?? []).map((r) => r.startsWith('"') ? r.slice(1, -1).replace(/""/g, '"') : r.toLowerCase()).filter((r) => !ROLE_KEYWORDS.has(r.toLowerCase()) && !r.startsWith("pg_"));
373
+ return [...new Set(roles)];
374
+ }
375
+
30
376
  // src/dbdiff-units.ts
31
377
  var BEGIN = /^-- dbdiff:unit (\S+)(?: (.*))?$/;
32
378
  var END = "-- dbdiff:end";
@@ -71,6 +417,10 @@ var REPLACING_KINDS = {
71
417
 
72
418
  // src/dbdiff.ts
73
419
  var execFileAsync = promisify(execFile);
420
+ function dbdiffNotInstalled(code, stderr) {
421
+ if (code === "ENOENT") return true;
422
+ return /ERR_MODULE_NOT_FOUND|could not determine executable|npm (?:ERR!|error) (?:code E404|404)|\bE404\b|command not found|: not found\s*$/m.test(stderr);
423
+ }
74
424
  function resolveDbDiffBin() {
75
425
  const override = process.env.SUPAFORGE_DBDIFF_BIN?.trim();
76
426
  if (override) return { command: override, prefixArgs: [] };
@@ -201,7 +551,7 @@ async function runDbDiff(options) {
201
551
  if (options.units !== false && /"--units" option does not exist/.test(`${combined} ${stdout}`)) {
202
552
  return runDbDiff({ ...options, units: false });
203
553
  }
204
- if (combined.includes("ENOENT") || combined.includes("not found") || combined.includes("ERR_MODULE_NOT_FOUND") || combined.includes("could not determine executable") || combined.includes("404")) {
554
+ if (dbdiffNotInstalled(errObj.code, stderr)) {
205
555
  throw new DiagnosticError(
206
556
  "@dbdiff/cli is not installed. Install it with: npm install @dbdiff/cli"
207
557
  );
@@ -940,9 +1290,22 @@ function extractRoutineArgs(sql) {
940
1290
  }
941
1291
 
942
1292
  export {
1293
+ parseStatements,
1294
+ sqlSkeleton,
1295
+ bareName,
1296
+ createdPolicies,
1297
+ createsOnlyPolicies,
1298
+ createdTriggers,
1299
+ createsOnlyTriggers,
1300
+ referencedTables,
1301
+ identifierMatcher,
1302
+ orderStatements,
1303
+ statementSubject,
1304
+ policyOnlyKeys,
1305
+ rolesNamedBy,
943
1306
  runDbDiff,
944
1307
  isDestructiveSql,
945
1308
  destructiveReason,
946
1309
  sqlToIssues
947
1310
  };
948
- //# sourceMappingURL=chunk-VOXZWQ3N.js.map
1311
+ //# sourceMappingURL=chunk-BUOWHE36.js.map
@@ -1,22 +1,26 @@
1
+ import {
2
+ runLikeApply
3
+ } from "./chunk-UWAVXC57.js";
1
4
  import {
2
5
  rolesNamedBy,
3
6
  sqlSkeleton
4
- } from "./chunk-RRMI5CZD.js";
7
+ } from "./chunk-BUOWHE36.js";
5
8
  import {
6
9
  isCommentOnly,
7
10
  splitSqlStatements
8
11
  } from "./chunk-G2DIPIYU.js";
9
12
  import {
13
+ describeMissingPgDump,
10
14
  getServerMajorVersion,
11
15
  resolvePgDumpPath
12
- } from "./chunk-YVDSR4GM.js";
16
+ } from "./chunk-MIRLB5JM.js";
13
17
  import {
14
18
  globToRegExp
15
19
  } from "./chunk-DQQ5E563.js";
16
20
  import {
17
21
  pgQuery,
18
22
  quoteName
19
- } from "./chunk-X6V2GGDZ.js";
23
+ } from "./chunk-SQPCWGQO.js";
20
24
 
21
25
  // src/prove.ts
22
26
  import { randomBytes } from "crypto";
@@ -269,7 +273,7 @@ async function proveConvergence(opts) {
269
273
  sourceMajor = await getServerMajorVersion(opts.sourceUrl).catch(() => serverMajor);
270
274
  const resolved = await resolvePgDumpPath(Math.max(serverMajor, sourceMajor)) ?? await resolvePgDumpPath(serverMajor);
271
275
  if (!resolved) {
272
- return { converged: false, residual: [], cloneName, skipped: "pg_dump not available" };
276
+ return { converged: false, residual: [], cloneName, skipped: await describeMissingPgDump(serverMajor) };
273
277
  }
274
278
  pgDump = resolved.path;
275
279
  clientMajor = resolved.major;
@@ -310,12 +314,29 @@ async function proveConvergence(opts) {
310
314
  await copyStructure(opts.targetUrl, cloneUrl, schemas, tools, opts.sourceUrl);
311
315
  const scoped = opts.checks !== void 0 && !opts.checks.includes("schema");
312
316
  const before = scoped ? await schemaState(cloneUrl, schemas) : void 0;
313
- await runSql(psql, cloneUrl, opts.migrationSql);
317
+ let notApplied;
318
+ if (opts.fixes) {
319
+ const replayed = await runLikeApply(cloneUrl, opts.fixes);
320
+ const unmet = replayed.errors.filter((e) => / — not applied: /.test(e.error));
321
+ const failed = replayed.errors.filter((e) => !unmet.includes(e));
322
+ if (failed.length > 0) {
323
+ return {
324
+ converged: false,
325
+ cloneName,
326
+ residual: failed.map((e) => `fix ${e.issueId} failed: ${e.error}`)
327
+ };
328
+ }
329
+ const byId = new Map(opts.fixes.map((f) => [f.issueId, f.sql]));
330
+ notApplied = unmet.map((e) => ({ issueId: e.issueId, sql: byId.get(e.issueId) ?? "", reason: e.error }));
331
+ } else {
332
+ await runSql(psql, cloneUrl, opts.migrationSql);
333
+ }
334
+ const reported = (r) => notApplied?.length ? { ...r, notApplied } : r;
314
335
  const [want, got] = await Promise.all([
315
336
  fingerprint(opts.sourceUrl, schemas),
316
337
  fingerprint(cloneUrl, schemas)
317
338
  ]);
318
- if (want === got) return { converged: true, residual: [], cloneName };
339
+ if (want === got) return reported({ converged: true, residual: [], cloneName });
319
340
  roundTripName = `${cloneName}_src`;
320
341
  const roundTripUrl = withDatabase(opts.targetUrl, roundTripName);
321
342
  const roundTrip = await copyOfSource(adminUrl, opts.sourceUrl, roundTripUrl, roundTripName, schemas, tools);
@@ -323,9 +344,9 @@ async function proveConvergence(opts) {
323
344
  sourceCopyCreated = true;
324
345
  if (roundTrip.ok) {
325
346
  const wantRoundTripped = await fingerprint(roundTripUrl, schemas);
326
- if (wantRoundTripped === got) return { converged: true, residual: [], cloneName };
347
+ if (wantRoundTripped === got) return reported({ converged: true, residual: [], cloneName });
327
348
  const residual2 = await describeDifference(roundTripUrl, cloneUrl, schemas, wantRoundTripped, got);
328
- return withinScope(residual2, before && diffState(await schemaState(roundTripUrl, schemas), before), opts.checks, cloneName);
349
+ return reported(withinScope(residual2, before && diffState(await schemaState(roundTripUrl, schemas), before), opts.checks, cloneName));
329
350
  }
330
351
  }
331
352
  if (sourceMajor !== serverMajor) {
@@ -337,7 +358,7 @@ async function proveConvergence(opts) {
337
358
  };
338
359
  }
339
360
  const residual = await describeDifference(opts.sourceUrl, cloneUrl, schemas, want, got);
340
- return withinScope(residual, before && diffState(await schemaState(opts.sourceUrl, schemas), before), opts.checks, cloneName);
361
+ return reported(withinScope(residual, before && diffState(await schemaState(opts.sourceUrl, schemas), before), opts.checks, cloneName));
341
362
  } finally {
342
363
  if (sourceCopyCreated && roundTripName) {
343
364
  await dropDatabase(adminUrl, roundTripName);
@@ -506,17 +527,24 @@ function explainStructureFailure(message, clientMajor, serverMajor) {
506
527
  return `could not replay the target's structure onto the clone: ${message}${versionGap}`;
507
528
  }
508
529
  var DROPPED_NAME = /\bDROP\s+(?:TABLE|VIEW|MATERIALIZED\s+VIEW|TYPE|DOMAIN|SEQUENCE|FUNCTION|PROCEDURE|INDEX|COLUMN|CONSTRAINT|POLICY|TRIGGER)\s+(?:IF\s+EXISTS\s+)?(?:(?:"[^"]+"|[\w$]+)\s*\.\s*)?("[^"]+"|[\w$]+)/gi;
530
+ var CREATED_NAME = /\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:UNIQUE\s+)?(?:TABLE|VIEW|MATERIALIZED\s+VIEW|TYPE|DOMAIN|SEQUENCE|FUNCTION|PROCEDURE|INDEX|POLICY|TRIGGER|EXTENSION)\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:(?:"[^"]+"|[\w$]+)\s*\.\s*)?("[^"]+"|[\w$]+)/gi;
509
531
  function residualHeldBack(residual, heldBackSql) {
510
532
  const dropped = /* @__PURE__ */ new Set();
511
533
  for (const sql of heldBackSql) {
512
534
  for (const m of sql.matchAll(DROPPED_NAME)) dropped.add(m[1].replace(/^"|"$/g, "").toLowerCase());
513
535
  }
536
+ const created = [];
537
+ for (const sql of heldBackSql) {
538
+ for (const m of sql.matchAll(CREATED_NAME)) created.push(m[1].replace(/^"|"$/g, "").toLowerCase());
539
+ }
514
540
  const heldBack = [];
515
541
  const unexplained = [];
516
542
  for (const line of residual) {
517
543
  const subject = /^[a-z ]+?\s([^\s:]+(?:\s[^\s:]+)?):\s*unexpected$/i.exec(line)?.[1];
518
544
  const name = subject?.split(/[.\s]/).pop()?.replace(/^"|"$/g, "").toLowerCase();
545
+ const missing = /^(.*):\s*missing$/i.exec(line)?.[1].toLowerCase();
519
546
  if (name && dropped.has(name)) heldBack.push(line);
547
+ else if (missing && created.some((n) => missing.endsWith(` ${n}`) || missing.endsWith(`.${n}`))) heldBack.push(line);
520
548
  else unexplained.push(line);
521
549
  }
522
550
  return { heldBack, unexplained };
@@ -571,4 +599,4 @@ export {
571
599
  residualHeldBack,
572
600
  proofScope
573
601
  };
574
- //# sourceMappingURL=chunk-TQJSQLWA.js.map
602
+ //# sourceMappingURL=chunk-DMIWAJRB.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  CHECK_META,
3
3
  isComparisonCheck
4
- } from "./chunk-5Z3SAIQS.js";
4
+ } from "./chunk-UWAVXC57.js";
5
5
  import {
6
6
  CHECK_LINE_PADDING,
7
7
  bold,
@@ -133,7 +133,7 @@ function formatCheckLine(lr) {
133
133
  const count = lr.issues.length;
134
134
  const noun = count === 1 ? "issue" : "issues";
135
135
  const severity = highestSeverity(lr);
136
- const sevLabel = severity ? colorSeverity(severity) : "";
136
+ const sevLabel = severity ? ` ${colorSeverity(severity)}` : "";
137
137
  const errText = lr.error || (lr.status === "error" ? "check failed" : "");
138
138
  const errLabel = errText ? ` ${warn(`(error: ${errText})`)}` : "";
139
139
  const folded = (lr.folded ?? []).map((f) => ` ${dim(`(+${f.count} reported under ${CHECK_META[f.into].label})`)}`).join("");
@@ -237,4 +237,4 @@ export {
237
237
  renderDetailed,
238
238
  formatSkips
239
239
  };
240
- //# sourceMappingURL=chunk-LQXF65MC.js.map
240
+ //# sourceMappingURL=chunk-GEHPTPNZ.js.map