@akal/supaforge 0.0.0-stage → 0.0.31

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 (99) hide show
  1. package/README.md +350 -2
  2. package/bin/dev.js +10 -0
  3. package/bin/run.js +18 -0
  4. package/dist/base-command.d.ts +134 -0
  5. package/dist/base-command.js +9 -0
  6. package/dist/base-command.js.map +1 -0
  7. package/dist/branch-C4ndfoj5.d.ts +58 -0
  8. package/dist/chunk-4OU7KO5Y.js +13 -0
  9. package/dist/chunk-4OU7KO5Y.js.map +1 -0
  10. package/dist/chunk-5QQBTLWO.js +642 -0
  11. package/dist/chunk-5QQBTLWO.js.map +1 -0
  12. package/dist/chunk-5Z3SAIQS.js +2807 -0
  13. package/dist/chunk-5Z3SAIQS.js.map +1 -0
  14. package/dist/chunk-6WAMNZLO.js +336 -0
  15. package/dist/chunk-6WAMNZLO.js.map +1 -0
  16. package/dist/chunk-BHYLBKYD.js +156 -0
  17. package/dist/chunk-BHYLBKYD.js.map +1 -0
  18. package/dist/chunk-BLKJWDTL.js +153 -0
  19. package/dist/chunk-BLKJWDTL.js.map +1 -0
  20. package/dist/chunk-DQQ5E563.js +64 -0
  21. package/dist/chunk-DQQ5E563.js.map +1 -0
  22. package/dist/chunk-G2DIPIYU.js +94 -0
  23. package/dist/chunk-G2DIPIYU.js.map +1 -0
  24. package/dist/chunk-H5MJ5DFX.js +16 -0
  25. package/dist/chunk-H5MJ5DFX.js.map +1 -0
  26. package/dist/chunk-KIFJGON5.js +248 -0
  27. package/dist/chunk-KIFJGON5.js.map +1 -0
  28. package/dist/chunk-LQXF65MC.js +240 -0
  29. package/dist/chunk-LQXF65MC.js.map +1 -0
  30. package/dist/chunk-NXRSAVRU.js +478 -0
  31. package/dist/chunk-NXRSAVRU.js.map +1 -0
  32. package/dist/chunk-PARSNTBD.js +837 -0
  33. package/dist/chunk-PARSNTBD.js.map +1 -0
  34. package/dist/chunk-RRMI5CZD.js +376 -0
  35. package/dist/chunk-RRMI5CZD.js.map +1 -0
  36. package/dist/chunk-SF3YA42C.js +506 -0
  37. package/dist/chunk-SF3YA42C.js.map +1 -0
  38. package/dist/chunk-TQJSQLWA.js +574 -0
  39. package/dist/chunk-TQJSQLWA.js.map +1 -0
  40. package/dist/chunk-VMTBLHN2.js +122 -0
  41. package/dist/chunk-VMTBLHN2.js.map +1 -0
  42. package/dist/chunk-VOXZWQ3N.js +948 -0
  43. package/dist/chunk-VOXZWQ3N.js.map +1 -0
  44. package/dist/chunk-X6V2GGDZ.js +333 -0
  45. package/dist/chunk-X6V2GGDZ.js.map +1 -0
  46. package/dist/chunk-XMYMIURR.js +552 -0
  47. package/dist/chunk-XMYMIURR.js.map +1 -0
  48. package/dist/chunk-YVDSR4GM.js +1264 -0
  49. package/dist/chunk-YVDSR4GM.js.map +1 -0
  50. package/dist/commands/clone.d.ts +66 -0
  51. package/dist/commands/clone.js +416 -0
  52. package/dist/commands/clone.js.map +1 -0
  53. package/dist/commands/diff.d.ts +65 -0
  54. package/dist/commands/diff.js +24 -0
  55. package/dist/commands/diff.js.map +1 -0
  56. package/dist/commands/help.d.ts +32 -0
  57. package/dist/commands/help.js +36 -0
  58. package/dist/commands/help.js.map +1 -0
  59. package/dist/commands/hukam.d.ts +13 -0
  60. package/dist/commands/hukam.js +29 -0
  61. package/dist/commands/hukam.js.map +1 -0
  62. package/dist/commands/init.d.ts +47 -0
  63. package/dist/commands/init.js +388 -0
  64. package/dist/commands/init.js.map +1 -0
  65. package/dist/commands/mcp.d.ts +13 -0
  66. package/dist/commands/mcp.js +44 -0
  67. package/dist/commands/mcp.js.map +1 -0
  68. package/dist/commands/migrate/baseline.d.ts +24 -0
  69. package/dist/commands/migrate/baseline.js +69 -0
  70. package/dist/commands/migrate/baseline.js.map +1 -0
  71. package/dist/commands/migrate/create.d.ts +36 -0
  72. package/dist/commands/migrate/create.js +128 -0
  73. package/dist/commands/migrate/create.js.map +1 -0
  74. package/dist/commands/migrate/list.d.ts +23 -0
  75. package/dist/commands/migrate/list.js +110 -0
  76. package/dist/commands/migrate/list.js.map +1 -0
  77. package/dist/commands/migrate/run.d.ts +61 -0
  78. package/dist/commands/migrate/run.js +19 -0
  79. package/dist/commands/migrate/run.js.map +1 -0
  80. package/dist/commands/report.d.ts +27 -0
  81. package/dist/commands/report.js +210 -0
  82. package/dist/commands/report.js.map +1 -0
  83. package/dist/commands/restore.d.ts +26 -0
  84. package/dist/commands/restore.js +268 -0
  85. package/dist/commands/restore.js.map +1 -0
  86. package/dist/commands/snapshot.d.ts +33 -0
  87. package/dist/commands/snapshot.js +251 -0
  88. package/dist/commands/snapshot.js.map +1 -0
  89. package/dist/commands/sync.d.ts +16 -0
  90. package/dist/commands/sync.js +39 -0
  91. package/dist/commands/sync.js.map +1 -0
  92. package/dist/config-CTbeRlJk.d.ts +134 -0
  93. package/dist/help.d.ts +28 -0
  94. package/dist/help.js +64 -0
  95. package/dist/help.js.map +1 -0
  96. package/dist/index.d.ts +493 -0
  97. package/dist/index.js +147 -0
  98. package/dist/index.js.map +1 -0
  99. package/package.json +74 -4
@@ -0,0 +1,948 @@
1
+ import {
2
+ names,
3
+ parseStatements,
4
+ policiesRemoved,
5
+ relationName,
6
+ sqlSkeleton
7
+ } from "./chunk-RRMI5CZD.js";
8
+ import {
9
+ escapeRegex
10
+ } from "./chunk-DQQ5E563.js";
11
+ import {
12
+ DiagnosticError,
13
+ errMsg,
14
+ friendlyDbError
15
+ } from "./chunk-X6V2GGDZ.js";
16
+ import {
17
+ DBDIFF_EXEC_TIMEOUT_MS,
18
+ DBDIFF_MAX_BUFFER,
19
+ schemaDiffIgnores
20
+ } from "./chunk-6WAMNZLO.js";
21
+
22
+ // src/dbdiff.ts
23
+ import { execFile } from "child_process";
24
+ import { createRequire } from "module";
25
+ import { readFile, unlink, access } from "fs/promises";
26
+ import { tmpdir } from "os";
27
+ import { join } from "path";
28
+ import { promisify } from "util";
29
+
30
+ // src/dbdiff-units.ts
31
+ var BEGIN = /^-- dbdiff:unit (\S+)(?: (.*))?$/;
32
+ var END = "-- dbdiff:end";
33
+ function parseUnits(section) {
34
+ if (!section.includes("-- dbdiff:unit ")) return void 0;
35
+ const units = [];
36
+ let open;
37
+ for (const line of section.split("\n")) {
38
+ const begin = BEGIN.exec(line.trimEnd());
39
+ if (begin) {
40
+ open = { kind: begin[1], object: (begin[2] ?? "").trim(), lines: [] };
41
+ } else if (line.trimEnd() === END && open) {
42
+ units.push({ kind: open.kind, object: open.object, sql: open.lines.join("\n").trim() });
43
+ open = void 0;
44
+ } else if (open) {
45
+ open.lines.push(line);
46
+ }
47
+ }
48
+ return units.filter((u) => u.sql !== "");
49
+ }
50
+ function unitKey(unit) {
51
+ return `${unit.kind} ${unit.object}`;
52
+ }
53
+ function pairUnits(up, down) {
54
+ const unclaimed = /* @__PURE__ */ new Map();
55
+ for (const unit of down) {
56
+ const key = unitKey(unit);
57
+ unclaimed.set(key, [...unclaimed.get(key) ?? [], unit]);
58
+ }
59
+ return up.map((unit) => ({ up: unit, down: unclaimed.get(unitKey(unit))?.shift() }));
60
+ }
61
+ var REPLACING_KINDS = {
62
+ AlterRoutine: "routine",
63
+ AlterEnum: "type",
64
+ AlterCompositeType: "type",
65
+ AlterDomain: "type",
66
+ AlterPolicy: "policy",
67
+ AlterTrigger: "trigger",
68
+ AlterView: "view",
69
+ AlterMatView: "view"
70
+ };
71
+
72
+ // src/dbdiff.ts
73
+ var execFileAsync = promisify(execFile);
74
+ function resolveDbDiffBin() {
75
+ const override = process.env.SUPAFORGE_DBDIFF_BIN?.trim();
76
+ if (override) return { command: override, prefixArgs: [] };
77
+ try {
78
+ const require2 = createRequire(import.meta.url);
79
+ const binPath = require2.resolve("@dbdiff/cli/bin/dbdiff.js");
80
+ return { command: process.execPath, prefixArgs: [binPath] };
81
+ } catch {
82
+ return { command: "npx", prefixArgs: ["@dbdiff/cli"] };
83
+ }
84
+ }
85
+ function resolveDbDiffTimeoutMs(configuredSeconds) {
86
+ const raw = process.env.SUPAFORGE_DBDIFF_TIMEOUT;
87
+ if (raw) {
88
+ const secs = Number(raw);
89
+ if (Number.isFinite(secs) && secs > 0) return Math.round(secs * 1e3);
90
+ }
91
+ if (Number.isFinite(configuredSeconds) && configuredSeconds > 0) {
92
+ return Math.round(configuredSeconds * 1e3);
93
+ }
94
+ return DBDIFF_EXEC_TIMEOUT_MS;
95
+ }
96
+ var DBDIFF_TABLE_LINE = /calculating schema diff for table [`"']?([\w.$]+)/i;
97
+ function parseDbDiffProgress(line) {
98
+ return DBDIFF_TABLE_LINE.exec(line)?.[1] ?? null;
99
+ }
100
+ function resolveDbDiffMemoryLimit() {
101
+ const raw = process.env.SUPAFORGE_DBDIFF_MEMORY?.trim();
102
+ if (!raw) return void 0;
103
+ return /^-?\d+[KMG]?$/i.test(raw) ? raw : void 0;
104
+ }
105
+ var DBDIFF_NOISE_LINE = /^\s*[ℹ✔✓⚠⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]/u;
106
+ function stripDbDiffNoise(text) {
107
+ return text.split("\n").filter((line) => line.trim() !== "" && !DBDIFF_NOISE_LINE.test(line)).join("\n").trim();
108
+ }
109
+ function buildDbDiffArgs(options, outputFile) {
110
+ const args = [
111
+ "diff",
112
+ `--server1-url=${options.sourceUrl}`,
113
+ `--server2-url=${options.targetUrl}`,
114
+ `--type=${options.type}`,
115
+ // Was hardcoded to 'both', silently ignoring options.include. Every caller
116
+ // passes 'both' (sqlToIssues pairs each UP statement with its DOWN
117
+ // counterpart, so it needs both directions), but the option was part of the
118
+ // public interface and did nothing.
119
+ `--include=${options.include}`,
120
+ "--nocomments",
121
+ // @dbdiff/cli >= 3.0.0-rc.3 refuses to emit a migration containing
122
+ // DROP TABLE or DROP COLUMN unless this is passed, exiting non-zero and
123
+ // writing no output file. SupaForge is a *detection* tool: an extra table
124
+ // or column on the target is the single most common form of drift, and it
125
+ // has to be reported rather than turned into a hard failure. The safety
126
+ // gate belongs at apply time instead — see isDestructiveSql()/promote(),
127
+ // which skip these statements unless the user opts in explicitly.
128
+ "--allow-destructive",
129
+ `--output=${outputFile}`
130
+ ];
131
+ if (options.type === "schema" && options.units !== false) {
132
+ args.push("--units");
133
+ }
134
+ const memoryLimit = resolveDbDiffMemoryLimit();
135
+ if (memoryLimit) {
136
+ args.push(`--memory-limit=${memoryLimit}`);
137
+ }
138
+ if (options.type === "schema" && options.ignoreSchemas) {
139
+ args.push(`--ignore-schemas=${schemaDiffIgnores(options.ignoreSchemas).join(",")}`);
140
+ }
141
+ const ignore = options.ignoreTables ?? [];
142
+ if (options.tables?.length) {
143
+ args.push(`--tables=${options.tables.join(",")}`);
144
+ }
145
+ if (ignore.length) {
146
+ args.push(`--ignore-tables=${ignore.join(",")}`);
147
+ }
148
+ return args;
149
+ }
150
+ function attachProgress(running, onProgress) {
151
+ if (!onProgress) return;
152
+ try {
153
+ const stdout = running.child?.stdout;
154
+ if (!stdout) return;
155
+ let buffer = "";
156
+ let tablesSeen = 0;
157
+ stdout.on("data", (chunk) => {
158
+ try {
159
+ buffer += String(chunk);
160
+ const lines = buffer.split("\n");
161
+ buffer = lines.pop() ?? "";
162
+ for (const line of lines) {
163
+ const table = parseDbDiffProgress(line);
164
+ if (table) {
165
+ tablesSeen++;
166
+ onProgress({ table, tablesSeen });
167
+ }
168
+ }
169
+ } catch {
170
+ }
171
+ });
172
+ stdout.on("error", () => {
173
+ });
174
+ } catch {
175
+ }
176
+ }
177
+ async function runDbDiff(options) {
178
+ const { command, prefixArgs } = resolveDbDiffBin();
179
+ const outputFile = join(tmpdir(), `supaforge-dbdiff-${Date.now()}-${Math.random().toString(36).slice(2)}.sql`);
180
+ const args = [...prefixArgs, ...buildDbDiffArgs(options, outputFile)];
181
+ const timeoutMs = resolveDbDiffTimeoutMs(options.timeoutSeconds);
182
+ try {
183
+ const running = execFileAsync(command, args, {
184
+ timeout: timeoutMs,
185
+ maxBuffer: DBDIFF_MAX_BUFFER
186
+ });
187
+ attachProgress(running, options.onProgress);
188
+ await running;
189
+ const fileExists = await access(outputFile).then(() => true, () => false);
190
+ if (!fileExists) {
191
+ return { up: "", down: "" };
192
+ }
193
+ const output = await readFile(outputFile, "utf8");
194
+ return parseDbDiffOutput(output);
195
+ } catch (err) {
196
+ const errObj = err ?? {};
197
+ const message = errMsg(err);
198
+ const stderr = String(errObj.stderr ?? "").trim();
199
+ const stdout = String(errObj.stdout ?? "").trim();
200
+ const combined = `${message} ${stderr}`;
201
+ if (options.units !== false && /"--units" option does not exist/.test(`${combined} ${stdout}`)) {
202
+ return runDbDiff({ ...options, units: false });
203
+ }
204
+ if (combined.includes("ENOENT") || combined.includes("not found") || combined.includes("ERR_MODULE_NOT_FOUND") || combined.includes("could not determine executable") || combined.includes("404")) {
205
+ throw new DiagnosticError(
206
+ "@dbdiff/cli is not installed. Install it with: npm install @dbdiff/cli"
207
+ );
208
+ }
209
+ const fileExists = await access(outputFile).then(() => true, () => false);
210
+ if (fileExists) {
211
+ const output = await readFile(outputFile, "utf8");
212
+ const parsed = parseDbDiffOutput(output);
213
+ if (parsed.up || parsed.down) return parsed;
214
+ }
215
+ const timedOut = errObj.killed === true || errObj.signal === "SIGTERM" || errObj.code === "ETIMEDOUT" || /ETIMEDOUT|timed out/i.test(combined);
216
+ if (timedOut) {
217
+ const secs = Math.round(timeoutMs / 1e3);
218
+ throw new DiagnosticError(
219
+ `Schema diff timed out after ${secs}s \u2014 the schema is very large or the database connection is slow.
220
+ Remediations:
221
+ \u2022 Raise the limit: set SUPAFORGE_DBDIFF_TIMEOUT=600 (seconds) and re-run.
222
+ \u2022 Narrow the scan: diff one layer at a time with --check=schema.
223
+ \u2022 Exclude large internal schemas via "ignoreSchemas" in supaforge.config.json.`
224
+ );
225
+ }
226
+ const realError = stderr || stripDbDiffNoise(stdout);
227
+ const cleanMessage = realError ? realError : message.replace(/^Command failed:[^\n]*/m, "").trim() || "dbdiff failed with no error output";
228
+ throw new Error(friendlyDbError(cleanMessage, options.sourceUrl));
229
+ } finally {
230
+ await unlink(outputFile).catch(() => {
231
+ });
232
+ }
233
+ }
234
+ var UP_MARKER = "-- ==================== UP ====================";
235
+ var DOWN_MARKER = "-- ==================== DOWN ====================";
236
+ var CREATE_FUNCTION = "create-function";
237
+ var DROP_FUNCTION = "drop-function";
238
+ var DROP_TYPES = ["drop", "drop-view", DROP_FUNCTION, "drop-trigger", "drop-type", "drop-sequence"];
239
+ function isDestructiveSql(sql) {
240
+ return destructiveReason(sql) !== void 0;
241
+ }
242
+ function destructiveReason(sql, recreatedElsewhere = /* @__PURE__ */ new Set()) {
243
+ const statements = parseStatements(sql);
244
+ return statements ? destructiveInTree(statements, recreatedElsewhere) : destructiveInText(sql, recreatedElsewhere);
245
+ }
246
+ function destructiveInTree(statements, recreatedElsewhere) {
247
+ const dropped = (type) => statements.some((s) => s.kind === "DropStmt" && s.node.removeType === type);
248
+ if (dropped("OBJECT_SCHEMA")) return "drops a schema and everything in it";
249
+ if (dropped("OBJECT_TABLE")) return "drops a table and its rows";
250
+ if (statements.some((s) => s.kind === "TruncateStmt")) return "deletes every row in a table";
251
+ if (columnsDroppedForGoodInTree(statements).length > 0) return "drops a column and its values";
252
+ if (statements.some((s) => s.kind === "DeleteStmt")) return "deletes rows";
253
+ if (statements.some((s) => s.kind === "DropRoleStmt")) return "drops a role, and every login and grant it holds";
254
+ const key = (schema, table, policy) => `${(schema || "public").toLowerCase()}.${table.toLowerCase()}.${policy.toLowerCase()}`;
255
+ const created = new Set(statements.filter((s) => s.kind === "CreatePolicyStmt").map((s) => key(s.node.table?.schemaname, relationName(s.node.table), s.node.policy_name)));
256
+ const policies = statements.filter((s) => s.kind === "DropStmt" && s.node.removeType === "OBJECT_POLICY").flatMap((s) => s.node.objects.map((o) => names(o.List?.items))).map((parts) => key(parts.at(-3), parts.at(-2) ?? "", parts.at(-1) ?? "")).filter((k) => !created.has(k) && !recreatedElsewhere.has(k));
257
+ if (policies.length > 0) {
258
+ return policies.length === 1 ? `removes the policy ${policies[0]}, which may widen access` : `removes ${policies.length} policies, which may widen access`;
259
+ }
260
+ return void 0;
261
+ }
262
+ function columnsDroppedForGoodInTree(statements) {
263
+ const commands = statements.filter((s) => s.kind === "AlterTableStmt").flatMap((s) => s.node.cmds.map((c) => ({ table: relationName(s.node.relation), cmd: c.AlterTableCmd })));
264
+ return commands.flatMap(({ table, cmd }, i) => {
265
+ if (cmd?.subtype !== "AT_DropColumn") return [];
266
+ const readded = commands.slice(i + 1).some((later) => later.table === table && later.cmd?.subtype === "AT_AddColumn" && later.cmd.def?.ColumnDef?.colname === cmd.name);
267
+ return readded ? [] : [cmd.name];
268
+ });
269
+ }
270
+ function destructiveInText(sql, recreatedElsewhere) {
271
+ const skeleton = sqlSkeleton(sql).toUpperCase();
272
+ if (/\bDROP\s+SCHEMA\b/.test(skeleton)) return "drops a schema and everything in it";
273
+ if (/\bDROP\s+TABLE\b/.test(skeleton)) return "drops a table and its rows";
274
+ if (/(?:^|;)\s*TRUNCATE\b/.test(skeleton)) return "deletes every row in a table";
275
+ if (columnsDroppedForGood(skeleton).length > 0) return "drops a column and its values";
276
+ if (/\bDELETE\s+FROM\b/.test(skeleton)) return "deletes rows";
277
+ if (/(?:^|;)\s*DROP\s+(?:ROLE|USER|GROUP)\b/.test(skeleton)) return "drops a role, and every login and grant it holds";
278
+ const policies = policiesRemoved(sql).filter((key) => !recreatedElsewhere.has(key));
279
+ if (policies.length > 0) {
280
+ return policies.length === 1 ? `removes the policy ${policies[0]}, which may widen access` : `removes ${policies.length} policies, which may widen access`;
281
+ }
282
+ return void 0;
283
+ }
284
+ function columnsDroppedForGood(skeleton) {
285
+ const ident = String.raw`("(?:[^"]|"")+"|[\w$]+)`;
286
+ const dropped = [...skeleton.matchAll(new RegExp(String.raw`\bDROP\s+COLUMN\s+(?:IF\s+EXISTS\s+)?` + ident, "g"))];
287
+ return dropped.filter((m) => !new RegExp(String.raw`\bADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?` + escapeRegex(m[1]) + String.raw`(?![\w$"])`).test(skeleton.slice((m.index ?? 0) + m[0].length))).map((m) => m[1]);
288
+ }
289
+ function parseDbDiffOutput(output) {
290
+ const upIdx = output.indexOf(UP_MARKER);
291
+ const downIdx = output.indexOf(DOWN_MARKER);
292
+ if (upIdx === -1 && downIdx === -1) {
293
+ return { up: output.trim(), down: "" };
294
+ }
295
+ let up = "";
296
+ let down = "";
297
+ if (upIdx !== -1) {
298
+ const upStart = upIdx + UP_MARKER.length;
299
+ const upEnd = downIdx !== -1 ? downIdx : output.length;
300
+ up = output.slice(upStart, upEnd).trim();
301
+ }
302
+ if (downIdx !== -1) {
303
+ const downStart = downIdx + DOWN_MARKER.length;
304
+ down = output.slice(downStart).trim();
305
+ }
306
+ return { up, down };
307
+ }
308
+ function sqlToIssues(result, check, ignoreSchemas, ignoredSchemaTables) {
309
+ const issues = unfoldedIssues(result, check, ignoreSchemas, ignoredSchemaTables);
310
+ return check === "schema" ? foldCommentsIntoCreates(issues) : issues;
311
+ }
312
+ var COMMENT_TITLE = /^(?:Comment changed|Comment missing): (?:schema (.+)|(.+) \(([a-z ]+)\))$/;
313
+ var CREATE_TITLE = /^(Schema|Table|View|Function|Procedure|Type|Domain|Sequence|Index|Policy|Trigger|Extension) (?:missing|modified): (.+)$/;
314
+ var ON_A_TABLE = /* @__PURE__ */ new Set(["column", "constraint", "trigger", "policy", "rule"]);
315
+ function foldCommentsIntoCreates(issues) {
316
+ const creates = /* @__PURE__ */ new Map();
317
+ const routines = /* @__PURE__ */ new Map();
318
+ for (const issue of issues) {
319
+ const m = CREATE_TITLE.exec(issue.title);
320
+ if (!m) continue;
321
+ creates.set(`${m[1] === "Schema" ? "schema" : "object"}:${m[2]}`, issue);
322
+ if (m[1] === "Function" || m[1] === "Procedure") {
323
+ const base = routineBaseName(m[2]);
324
+ routines.set(base, [...routines.get(base) ?? [], issue]);
325
+ }
326
+ }
327
+ return issues.filter((issue) => {
328
+ const up = issue.sql?.up;
329
+ if (!up) return true;
330
+ const owner = commentOwner(issue, up, creates, routines) ?? rlsFlagsOwner(issue, up, creates);
331
+ if (!owner?.sql) return true;
332
+ owner.sql = { ...owner.sql, up: `${owner.sql.up.trimEnd()}
333
+ ${up.trim()}` };
334
+ return false;
335
+ });
336
+ }
337
+ function commentOwner(issue, up, creates, routines) {
338
+ const m = COMMENT_TITLE.exec(issue.title);
339
+ if (!m || splitStatements(up).length !== 1) return void 0;
340
+ const [, schema, name, kind] = m;
341
+ const candidates = schema !== void 0 ? [`schema:${schema}`] : [`object:${name}`, ...ON_A_TABLE.has(kind) ? [`object:${name.slice(0, name.lastIndexOf("."))}`] : []];
342
+ const exact = candidates.map((c) => creates.get(c)).find(Boolean);
343
+ if (exact || kind !== "function" && kind !== "procedure") return exact;
344
+ const sameName = routines.get(routineBaseName(name)) ?? [];
345
+ return sameName.length === 1 ? sameName[0] : void 0;
346
+ }
347
+ var routineBaseName = (name) => name.includes("(") ? name.slice(0, name.indexOf("(")) : name;
348
+ var RLS_FLAG = /^\s*ALTER\s+TABLE\s+(?:ONLY\s+)?\S+\s+(?:ENABLE|DISABLE|(?:NO\s+)?FORCE)\s+ROW\s+LEVEL\s+SECURITY\s*;?\s*$/i;
349
+ function rlsFlagsOwner(issue, up, creates) {
350
+ const m = /^Table altered: (.+)$/.exec(issue.title);
351
+ if (!m || !splitStatements(up).every((sql) => RLS_FLAG.test(sql))) return void 0;
352
+ return creates.get(`object:${m[1]}`);
353
+ }
354
+ function unfoldedIssues(result, check, ignoreSchemas, ignoredSchemaTables) {
355
+ if (!result.up && !result.down) return [];
356
+ const upUnits = parseUnits(result.up);
357
+ if (upUnits) {
358
+ return issuesFromUnits(upUnits, parseUnits(result.down) ?? [], check, ignoreSchemas, ignoredSchemaTables);
359
+ }
360
+ let upStatements = splitStatements(result.up);
361
+ let downStatements = splitStatements(result.down);
362
+ if (ignoreSchemas?.length && check === "schema") {
363
+ const keep = filterCrossSchemaFks(upStatements, downStatements, ignoreSchemas, ignoredSchemaTables);
364
+ upStatements = upStatements.filter((_, i) => keep[i]);
365
+ downStatements = downStatements.filter((_, i) => keep[i]);
366
+ }
367
+ if (upStatements.length === 0) return [];
368
+ upStatements = groupColumnTypeChanges(upStatements);
369
+ downStatements = groupColumnTypeChanges(downStatements);
370
+ const merged = mergeReplacements(upStatements, downStatements);
371
+ return merged.map(({ up: upSql, down: downSql, modified }, i) => {
372
+ const lead = columnTypeChangeOf(upSql) ?? upSql;
373
+ const type = classifyStatement(lead);
374
+ if (modified) {
375
+ const report = REPLACEABLE_REPORT[modified.kind];
376
+ return {
377
+ id: `${check}-alter-${report.idPart}-${i + 1}`,
378
+ check,
379
+ severity: "warning",
380
+ title: `${report.label}: ${qualifySchemaName(modified.name)}`,
381
+ description: `${report.what} differs between source and target.`,
382
+ sql: { up: upSql, down: downSql }
383
+ };
384
+ }
385
+ return {
386
+ id: `${check}-${type}-${i + 1}`,
387
+ check,
388
+ severity: DROP_TYPES.includes(type) ? "critical" : "warning",
389
+ // The DOWN counterpart is passed so a title can recover a schema the UP
390
+ // statement does not carry — see routineLabel (issue #47).
391
+ title: summariseStatement(lead, check, downSql),
392
+ description: `${check === "schema" ? "Schema" : "Data"} difference detected by @dbdiff/cli.`,
393
+ sql: { up: upSql, down: downSql }
394
+ };
395
+ });
396
+ }
397
+ function issuesFromUnits(upUnits, downUnits, check, ignoreSchemas, ignoredSchemaTables) {
398
+ const pairs = pairUnits(upUnits, downUnits).filter(({ up, down }) => !(ignoreSchemas?.length && isCrossSchemaFkUnit(up, down, ignoreSchemas, ignoredSchemaTables)));
399
+ return pairs.map(({ up, down }, i) => {
400
+ const upSql = up.sql;
401
+ const downSql = down?.sql ?? "";
402
+ const statements = splitStatements(upSql);
403
+ const replaced = replacedObject(up, statements);
404
+ const manualOnly = manualEnumChange(up);
405
+ const manual = manualOnly ? { manualOnly } : {};
406
+ if (replaced) {
407
+ const report = REPLACEABLE_REPORT[replaced.kind];
408
+ return {
409
+ id: `${check}-alter-${report.idPart}-${i + 1}`,
410
+ check,
411
+ severity: "warning",
412
+ title: `${report.label}: ${qualifySchemaName(replaced.name)}`,
413
+ description: `${report.what} differs between source and target.`,
414
+ sql: { up: upSql, down: downSql },
415
+ ...manual
416
+ };
417
+ }
418
+ const lead = leadStatement(up, statements);
419
+ const type = classifyStatement(lead);
420
+ return {
421
+ id: `${check}-${type}-${i + 1}`,
422
+ check,
423
+ severity: DROP_TYPES.includes(type) ? "critical" : "warning",
424
+ title: summariseStatement(lead, check, downSql),
425
+ description: `${check === "schema" ? "Schema" : "Data"} difference detected by @dbdiff/cli.`,
426
+ sql: { up: upSql, down: downSql },
427
+ ...manual
428
+ };
429
+ });
430
+ }
431
+ function manualEnumChange(unit) {
432
+ if (unit.kind !== "AlterEnum" || !/^--.*\benum labels\b/im.test(unit.sql)) return void 0;
433
+ const blockers = [...unit.sql.matchAll(/^--\s{3}(.+)$/gm)].map((m) => m[1].trim());
434
+ return "removing or reordering these enum labels needs the type replaced" + (blockers.length > 0 ? `, and these use it in ways that cannot be moved automatically: ${blockers.join(", ")}` : "") + ". Migrate them first, then re-run, or apply the change by hand.";
435
+ }
436
+ function isCrossSchemaFkUnit(up, down, schemas, ignoredSchemaTables) {
437
+ if (!/Constraint$/.test(up.kind)) return false;
438
+ return [up.sql, down?.sql ?? ""].some((sql) => /\bFOREIGN\s+KEY\b/i.test(sql) && (hasCrossSchemaRef(sql, schemas, ignoredSchemaTables) || hasBrokenRef(sql)));
439
+ }
440
+ function replacedObject(unit, statements) {
441
+ const kind = REPLACING_KINDS[unit.kind];
442
+ const drop = statements.find((sql) => replaceablePart(sql)?.drop);
443
+ if (!kind || !drop) return void 0;
444
+ if (kind === "type") return { kind, name: unit.object };
445
+ const create = [...statements].reverse().find((sql) => replaceablePart(sql)?.drop === false) ?? drop;
446
+ return {
447
+ kind,
448
+ name: kind === "routine" ? extractRoutineName(create) + extractRoutineArgs(drop) : REPLACEABLE_NAME[kind](create)
449
+ };
450
+ }
451
+ function leadStatement(unit, statements) {
452
+ if (unit.kind.startsWith("AlterTable")) {
453
+ const alter = statements.find((sql) => /^\s*ALTER\s+TABLE\b/i.test(sql));
454
+ if (alter) return alter;
455
+ }
456
+ return statements[0] ?? unit.sql;
457
+ }
458
+ var ALTER_COLUMN_TYPE = /^\s*ALTER\s+TABLE\s+(?:ONLY\s+)?((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)\s+ALTER\s+COLUMN\s+("[^"]+"|[\w$]+)\s+(?:SET\s+DATA\s+)?TYPE\b/i;
459
+ function columnTypeChangeOf(sql) {
460
+ if (!/^\s*DROP\s+/i.test(sql)) return void 0;
461
+ return splitStatements(sql).find((s) => ALTER_COLUMN_TYPE.test(s));
462
+ }
463
+ function plainName(identifier) {
464
+ return identifier.replace(/"/g, "").replace(/^public\./i, "").trim();
465
+ }
466
+ function groupColumnTypeChanges(statements) {
467
+ const out = [];
468
+ let i = 0;
469
+ while (i < statements.length) {
470
+ const alter = ALTER_COLUMN_TYPE.exec(statements[i]);
471
+ if (!alter) {
472
+ out.push(statements[i]);
473
+ i++;
474
+ continue;
475
+ }
476
+ const [, table, column] = alter;
477
+ const views = /* @__PURE__ */ new Set();
478
+ const attached = /* @__PURE__ */ new Set();
479
+ const drops = [];
480
+ let start = out.length;
481
+ while (start > 0) {
482
+ const drop = /^\s*DROP\s+(?:(MATERIALIZED\s+VIEW|VIEW)|(POLICY|TRIGGER))\s+IF\s+EXISTS\s+((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)(?:\s+ON\s+((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?))?\s*;?\s*$/i.exec(out[start - 1]);
483
+ if (!drop) break;
484
+ if (drop[1]) {
485
+ views.add(plainName(drop[3]));
486
+ drops.unshift({ index: start - 1, view: plainName(drop[3]) });
487
+ } else {
488
+ const key = `${plainName(drop[3])}@${plainName(drop[4] ?? "")}`;
489
+ attached.add(key);
490
+ drops.unshift({ index: start - 1, attached: key, table: plainName(drop[4] ?? "") });
491
+ }
492
+ start--;
493
+ }
494
+ if (drops.length === 0) {
495
+ out.push(statements[i]);
496
+ i++;
497
+ continue;
498
+ }
499
+ const onView = (name) => views.has(plainName(name));
500
+ const recreated = /* @__PURE__ */ new Set();
501
+ const belongs = (sql) => {
502
+ const sameColumn = ALTER_COLUMN_TYPE.exec(sql) ?? /^\s*ALTER\s+TABLE\s+(?:ONLY\s+)?((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)\s+ALTER\s+COLUMN\s+("[^"]+"|[\w$]+)\s+(?:SET|DROP)\b/i.exec(sql);
503
+ if (sameColumn) return plainName(sameColumn[1]) === plainName(table) && plainName(sameColumn[2]) === plainName(column);
504
+ let m = /^\s*CREATE\s+(?:MATERIALIZED\s+)?VIEW\s+((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)/i.exec(sql);
505
+ if (m) return onView(m[1]);
506
+ m = /^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\b[\s\S]*?\bON\s+(?:ONLY\s+)?((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)/i.exec(sql);
507
+ if (m) return onView(m[1]);
508
+ m = /^\s*(?:GRANT|REVOKE)\b[\s\S]*?\bON\s+(?:TABLE\s+)?((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)\s+(?:TO|FROM)\b/i.exec(sql);
509
+ if (m) return onView(m[1]);
510
+ m = /^\s*COMMENT\s+ON\s+(?:MATERIALIZED\s+VIEW|VIEW)\s+((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)/i.exec(sql);
511
+ if (m) return onView(m[1]);
512
+ m = /^\s*COMMENT\s+ON\s+COLUMN\s+((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)\.(?:"[^"]+"|[\w$]+)\s+IS\b/i.exec(sql);
513
+ if (m) return onView(m[1]);
514
+ m = /^\s*CREATE\s+(?:POLICY|(?:CONSTRAINT\s+)?TRIGGER)\s+("[^"]+"|[\w$]+)[\s\S]*?\bON\s+((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)/i.exec(sql);
515
+ if (m) {
516
+ const key = `${plainName(m[1])}@${plainName(m[2])}`;
517
+ if (attached.has(key)) {
518
+ recreated.add(key);
519
+ return true;
520
+ }
521
+ return onView(m[2]);
522
+ }
523
+ return false;
524
+ };
525
+ let end = i + 1;
526
+ while (end < statements.length && belongs(statements[end])) end++;
527
+ const foreign = (d) => d.attached !== void 0 && d.table !== plainName(table) && !recreated.has(d.attached);
528
+ while (drops.length > 0 && foreign(drops[0])) {
529
+ drops.shift();
530
+ start++;
531
+ }
532
+ if (drops.length === 0) {
533
+ out.push(statements[i]);
534
+ i++;
535
+ continue;
536
+ }
537
+ const group = [...out.splice(start), ...statements.slice(i, end)];
538
+ out.push(group.join("\n"));
539
+ i = end;
540
+ }
541
+ return out;
542
+ }
543
+ var REPLACEABLE_NAME = {
544
+ routine: extractRoutineName,
545
+ type: (sql) => extractQualifiedName(sql, /\b(?:TYPE|DOMAIN)\s+(?:IF\s+EXISTS\s+)?/i),
546
+ sequence: (sql) => extractQualifiedName(sql, /\bSEQUENCE\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i),
547
+ // `table.policy`: a policy name is unique only per table.
548
+ policy: (sql) => policyLabel(sql),
549
+ // `schema.table.trigger`, for the same reason.
550
+ trigger: (sql) => triggerLabel(sql),
551
+ view: (sql) => extractQualifiedName(sql, AFTER.view)
552
+ };
553
+ var REPLACEABLE_REPORT = {
554
+ routine: { idPart: "function", label: "Function modified", what: "Function body" },
555
+ type: { idPart: "type", label: "Type modified", what: "Type definition" },
556
+ sequence: { idPart: "sequence", label: "Sequence modified", what: "Sequence definition" },
557
+ policy: { idPart: "policy", label: "Policy modified", what: "Policy definition" },
558
+ trigger: { idPart: "trigger", label: "Trigger modified", what: "Trigger definition" },
559
+ view: { idPart: "view", label: "View modified", what: "View definition" }
560
+ };
561
+ function replaceablePart(sql) {
562
+ if (/^\s*DROP\s+POLICY\b/i.test(sql)) return { kind: "policy", drop: true };
563
+ if (/^\s*CREATE\s+POLICY\b/i.test(sql)) return { kind: "policy", drop: false };
564
+ if (/^\s*DROP\s+TRIGGER\b/i.test(sql)) return { kind: "trigger", drop: true };
565
+ if (/^\s*DROP\s+(?:MATERIALIZED\s+)?VIEW\b/i.test(sql)) return { kind: "view", drop: true };
566
+ if (/^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:MATERIALIZED\s+)?VIEW\b/i.test(sql)) return { kind: "view", drop: false };
567
+ if (/^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\b/i.test(sql)) return { kind: "trigger", drop: false };
568
+ switch (classifyStatement(sql)) {
569
+ case CREATE_FUNCTION:
570
+ return { kind: "routine", drop: false };
571
+ case DROP_FUNCTION:
572
+ return { kind: "routine", drop: true };
573
+ case "create-type":
574
+ return { kind: "type", drop: false };
575
+ case "drop-type":
576
+ return { kind: "type", drop: true };
577
+ case "create-sequence":
578
+ return { kind: "sequence", drop: false };
579
+ case "drop-sequence":
580
+ return { kind: "sequence", drop: true };
581
+ default:
582
+ return void 0;
583
+ }
584
+ }
585
+ function replacementKey(kind, sql) {
586
+ const name = REPLACEABLE_NAME[kind](sql);
587
+ if (kind === "policy") return `policy:${name.replace(/"/g, "").toLowerCase()}`;
588
+ if (kind === "trigger") return `trigger:${name.split(".").slice(-2).join(".").toLowerCase()}`;
589
+ return `${kind}:${name.slice(name.lastIndexOf(".") + 1).toLowerCase()}`;
590
+ }
591
+ function mergeReplacements(upStatements, downStatements) {
592
+ const unclaimedCreates = /* @__PURE__ */ new Map();
593
+ const dropCounts = /* @__PURE__ */ new Map();
594
+ upStatements.forEach((sql, i) => {
595
+ const part = replaceablePart(sql);
596
+ if (!part) return;
597
+ const key = replacementKey(part.kind, sql);
598
+ if (part.drop) {
599
+ dropCounts.set(key, (dropCounts.get(key) ?? 0) + 1);
600
+ } else {
601
+ unclaimedCreates.set(key, [...unclaimedCreates.get(key) ?? [], i]);
602
+ }
603
+ });
604
+ const absorbed = /* @__PURE__ */ new Set();
605
+ const out = [];
606
+ upStatements.forEach((upSql, i) => {
607
+ if (absorbed.has(i)) return;
608
+ const down = downStatements[i] ?? "";
609
+ const part = replaceablePart(upSql);
610
+ if (!part?.drop) {
611
+ out.push({ up: upSql, down });
612
+ return;
613
+ }
614
+ const key = replacementKey(part.kind, upSql);
615
+ const unambiguous = dropCounts.get(key) === 1 && unclaimedCreates.get(key)?.length === 1;
616
+ const createIdx = claimCreateFor(unclaimedCreates, key, i, unambiguous);
617
+ if (createIdx === void 0) {
618
+ out.push({ up: upSql, down });
619
+ return;
620
+ }
621
+ const createSql = upStatements[createIdx];
622
+ absorbed.add(createIdx);
623
+ out.push({
624
+ // Drop first, create second, in one statement. Kept together rather than
625
+ // ordered apart because `orderStatements` sends drops to the last phase
626
+ // and creates to an early one, which put the CREATE before the DROP it
627
+ // was replacing — `type "order_state" already exists`, and the whole
628
+ // apply rolled back (issue #81). Phasing reads the CREATE in a merged
629
+ // pair, so the pair runs where the object it leaves behind belongs.
630
+ up: `${upSql}
631
+ ${createSql}`,
632
+ down: [down, downStatements[createIdx] ?? ""].filter(Boolean).join("\n"),
633
+ modified: {
634
+ kind: part.kind,
635
+ // A routine's name is qualified by its argument types, since overloads
636
+ // share a name; nothing else can be overloaded.
637
+ name: part.kind === "routine" ? extractRoutineName(createSql) + extractRoutineArgs(upSql) : REPLACEABLE_NAME[part.kind](createSql)
638
+ }
639
+ });
640
+ });
641
+ return out;
642
+ }
643
+ function claimCreateFor(unclaimed, key, dropIdx, unambiguous) {
644
+ const queue = unclaimed.get(key);
645
+ if (!queue) return void 0;
646
+ const at = queue.findIndex((idx) => unambiguous ? idx > dropIdx : idx === dropIdx + 1);
647
+ if (at === -1) return void 0;
648
+ return queue.splice(at, 1)[0];
649
+ }
650
+ function filterCrossSchemaFks(upStmts, downStmts, schemas, ignoredSchemaTables) {
651
+ const keep = new Array(upStmts.length).fill(true);
652
+ const crossSchemaConstraints = /* @__PURE__ */ new Set();
653
+ for (let i = 0; i < upStmts.length; i++) {
654
+ const upper = upStmts[i].toUpperCase();
655
+ if (!upper.includes("ADD CONSTRAINT") || !upper.includes("FOREIGN KEY")) continue;
656
+ const isCrossSchema = hasCrossSchemaRef(upStmts[i], schemas, ignoredSchemaTables) || downStmts[i] != null && hasBrokenRef(downStmts[i]);
657
+ if (isCrossSchema) {
658
+ keep[i] = false;
659
+ const name = upStmts[i].match(/CONSTRAINT\s+"([^"]+)"/i)?.[1];
660
+ if (name) crossSchemaConstraints.add(name);
661
+ }
662
+ }
663
+ for (let i = 0; i < upStmts.length; i++) {
664
+ if (!keep[i]) continue;
665
+ const upper = upStmts[i].toUpperCase();
666
+ if (!upper.includes("DROP CONSTRAINT")) continue;
667
+ const name = upStmts[i].match(/DROP\s+CONSTRAINT\s+"([^"]+)"/i)?.[1];
668
+ if (name && crossSchemaConstraints.has(name)) {
669
+ keep[i] = false;
670
+ }
671
+ }
672
+ return keep;
673
+ }
674
+ function hasCrossSchemaRef(sql, schemas, ignoredSchemaTables) {
675
+ const refsMatch = sql.match(/REFERENCES\s+"([^"]*)"(?:\s*\.\s*"([^"]*)")?\s*\(\s*"([^"]*)"\s*\)/i);
676
+ if (!refsMatch) return false;
677
+ const [, first, second] = refsMatch;
678
+ if (first === "") return true;
679
+ if (second !== void 0) {
680
+ if (!schemas.some((s) => s.toLowerCase() === first.toLowerCase())) return false;
681
+ return !ignoredSchemaTables?.has(`${first}.${second}`.toLowerCase());
682
+ }
683
+ return ignoredSchemaTables ? ignoredSchemaTables.has(first.toLowerCase()) : false;
684
+ }
685
+ function hasBrokenRef(sql) {
686
+ return /REFERENCES\s+""\s*\(\s*""\s*\)/i.test(sql);
687
+ }
688
+ function splitStatements(sql) {
689
+ if (!sql) return [];
690
+ const statements = [];
691
+ let buf = "";
692
+ let i = 0;
693
+ while (i < sql.length) {
694
+ if (sql[i] === "$") {
695
+ const tagMatch = sql.slice(i + 1).match(/^([A-Za-z0-9_]*)\$/);
696
+ if (tagMatch) {
697
+ const tag = `$${tagMatch[1]}$`;
698
+ const closeIdx = sql.indexOf(tag, i + tag.length);
699
+ if (closeIdx !== -1) {
700
+ buf += sql.slice(i, closeIdx + tag.length);
701
+ i = closeIdx + tag.length;
702
+ continue;
703
+ }
704
+ }
705
+ }
706
+ if (sql[i] === ";") {
707
+ buf += ";";
708
+ i++;
709
+ let j = i;
710
+ while (j < sql.length && (sql[j] === " " || sql[j] === " " || sql[j] === "\r")) j++;
711
+ if (j >= sql.length || sql[j] === "\n") {
712
+ const stmt = withoutLeadingComments(buf);
713
+ if (stmt.length > 0) {
714
+ statements.push(stmt);
715
+ }
716
+ buf = "";
717
+ i = j < sql.length ? j + 1 : j;
718
+ }
719
+ continue;
720
+ }
721
+ buf += sql[i];
722
+ i++;
723
+ }
724
+ const last = withoutLeadingComments(buf);
725
+ if (last.length > 0) {
726
+ statements.push(last.endsWith(";") ? last : `${last};`);
727
+ }
728
+ return statements;
729
+ }
730
+ function withoutLeadingComments(chunk) {
731
+ return chunk.trim().replace(/^(?:--[^\n]*(?:\n|$)\s*)+/, "").trim();
732
+ }
733
+ function classifyStatement(sql) {
734
+ const upper = sql.toUpperCase().trimStart();
735
+ if (upper.startsWith("CREATE VIEW") || upper.startsWith("CREATE OR REPLACE VIEW")) return "create-view";
736
+ if (upper.startsWith("ALTER VIEW")) return "alter-view";
737
+ if (upper.startsWith("DROP VIEW")) return "drop-view";
738
+ if (upper.startsWith("CREATE FUNCTION") || upper.startsWith("CREATE OR REPLACE FUNCTION")) return CREATE_FUNCTION;
739
+ if (upper.startsWith("ALTER FUNCTION")) return "alter-function";
740
+ if (upper.startsWith("DROP FUNCTION")) return DROP_FUNCTION;
741
+ if (upper.startsWith("CREATE PROCEDURE") || upper.startsWith("CREATE OR REPLACE PROCEDURE")) return CREATE_FUNCTION;
742
+ if (upper.startsWith("DROP PROCEDURE")) return DROP_FUNCTION;
743
+ if (upper.startsWith("CREATE TRIGGER") || upper.startsWith("CREATE OR REPLACE TRIGGER")) return "create-trigger";
744
+ if (upper.startsWith("ALTER TRIGGER")) return "alter-trigger";
745
+ if (upper.startsWith("DROP TRIGGER")) return "drop-trigger";
746
+ if (upper.startsWith("CREATE TYPE")) return "create-type";
747
+ if (upper.startsWith("ALTER TYPE")) return "alter-type";
748
+ if (upper.startsWith("DROP TYPE")) return "drop-type";
749
+ if (upper.startsWith("CREATE DOMAIN")) return "create-type";
750
+ if (upper.startsWith("ALTER DOMAIN")) return "alter-type";
751
+ if (upper.startsWith("DROP DOMAIN")) return "drop-type";
752
+ if (upper.startsWith("ALTER TABLE")) return "alter";
753
+ if (upper.startsWith("CREATE TABLE")) return "create-table";
754
+ if (upper.startsWith("DROP TABLE")) return "drop";
755
+ if (upper.startsWith("CREATE INDEX") || upper.startsWith("CREATE UNIQUE INDEX")) return "create-index";
756
+ if (upper.startsWith("DROP INDEX")) return "drop";
757
+ if (upper.startsWith("CREATE SEQUENCE")) return "create-sequence";
758
+ if (upper.startsWith("ALTER SEQUENCE")) return "alter-sequence";
759
+ if (upper.startsWith("DROP SEQUENCE")) return "drop-sequence";
760
+ if (upper.startsWith("INSERT")) return "insert";
761
+ if (upper.startsWith("UPDATE")) return "update";
762
+ if (upper.startsWith("DELETE")) return "delete";
763
+ return "change";
764
+ }
765
+ var AFTER = {
766
+ view: /\bVIEW\s+(?:IF\s+EXISTS\s+)?/i,
767
+ trigger: /\bTRIGGER\s+(?:IF\s+EXISTS\s+)?/i,
768
+ type: /\bTYPE\s+(?:IF\s+EXISTS\s+)?/i,
769
+ domain: /\bDOMAIN\s+(?:IF\s+EXISTS\s+)?/i,
770
+ sequence: /\bSEQUENCE\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i,
771
+ table: /\bTABLE\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?(?:ONLY\s+)?/i,
772
+ index: /\bINDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i,
773
+ policy: /\bPOLICY\s+(?:IF\s+EXISTS\s+)?/i,
774
+ on: /\bON\s+(?:ONLY\s+)?/i
775
+ };
776
+ var named = (head) => (sql) => extractQualifiedName(sql, head);
777
+ function policyLabel(sql) {
778
+ const policy = extractQualifiedName(sql, AFTER.policy);
779
+ const table = extractQualifiedName(sql, AFTER.on);
780
+ if (policy === UNKNOWN_NAME) return UNKNOWN_NAME;
781
+ if (table === UNKNOWN_NAME) return policy;
782
+ return `${qualifySchemaName(table)}.${policy}`;
783
+ }
784
+ function triggerLabel(sql, downSql) {
785
+ const trigger = extractQualifiedName(sql, AFTER.trigger);
786
+ let table = extractQualifiedName(sql, AFTER.on);
787
+ if (trigger === UNKNOWN_NAME) return UNKNOWN_NAME;
788
+ if (table === UNKNOWN_NAME) return trigger;
789
+ if (!table.includes(".") && downSql) {
790
+ const counterpart = extractQualifiedName(downSql, AFTER.on);
791
+ if (counterpart.includes(".") && unqualify(counterpart) === table.toLowerCase()) table = counterpart;
792
+ }
793
+ return `${qualifySchemaName(table)}.${trigger}`;
794
+ }
795
+ var DBDIFF_SCHEMA = "public";
796
+ function qualifySchemaName(name) {
797
+ if (name === UNKNOWN_NAME) return name;
798
+ const paren = name.indexOf("(");
799
+ const head = paren === -1 ? name : name.slice(0, paren);
800
+ if (head.includes(".")) return name;
801
+ return `${DBDIFF_SCHEMA}.${name}`;
802
+ }
803
+ function indexLabel(sql) {
804
+ const name = extractQualifiedName(sql, AFTER.index);
805
+ if (name === UNKNOWN_NAME || name.includes(".")) return name;
806
+ const table = extractQualifiedName(sql, AFTER.on);
807
+ const dot = table.lastIndexOf(".");
808
+ return dot === -1 ? name : `${table.slice(0, dot)}.${name}`;
809
+ }
810
+ var SCHEMA_RULES = [
811
+ { match: /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:MATERIALIZED\s+)?VIEW\b/i, label: "View missing", name: named(AFTER.view) },
812
+ { match: /^\s*ALTER\s+(?:MATERIALIZED\s+)?VIEW\b/i, label: "View altered", name: named(AFTER.view) },
813
+ { match: /^\s*DROP\s+(?:MATERIALIZED\s+)?VIEW\b/i, label: "Extra view", name: named(AFTER.view) },
814
+ { match: /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION\b/i, label: "Function missing", name: routineLabel },
815
+ { match: /^\s*ALTER\s+FUNCTION\b/i, label: "Function altered", name: routineLabel },
816
+ { match: /^\s*DROP\s+FUNCTION\b/i, label: "Extra function", name: routineLabel },
817
+ { match: /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?PROCEDURE\b/i, label: "Procedure missing", name: routineLabel },
818
+ { match: /^\s*DROP\s+PROCEDURE\b/i, label: "Extra procedure", name: routineLabel },
819
+ { match: /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\b/i, label: "Trigger missing", name: triggerLabel },
820
+ { match: /^\s*ALTER\s+TRIGGER\b/i, label: "Trigger altered", name: triggerLabel },
821
+ { match: /^\s*DROP\s+TRIGGER\b/i, label: "Extra trigger", name: triggerLabel },
822
+ { match: /^\s*CREATE\s+TYPE\b/i, label: "Type missing", name: named(AFTER.type) },
823
+ { match: /^\s*ALTER\s+TYPE\b/i, label: "Type altered", name: named(AFTER.type) },
824
+ { match: /^\s*DROP\s+TYPE\b/i, label: "Extra type", name: named(AFTER.type) },
825
+ { match: /^\s*CREATE\s+DOMAIN\b/i, label: "Domain missing", name: named(AFTER.domain) },
826
+ { match: /^\s*ALTER\s+DOMAIN\b/i, label: "Domain altered", name: named(AFTER.domain) },
827
+ { match: /^\s*DROP\s+DOMAIN\b/i, label: "Extra domain", name: named(AFTER.domain) },
828
+ { match: /^\s*ALTER\s+TABLE\b/i, label: "Table altered", name: named(AFTER.table) },
829
+ { match: /^\s*CREATE\s+TABLE\b/i, label: "Table missing", name: named(AFTER.table) },
830
+ { match: /^\s*DROP\s+TABLE\b/i, label: "Extra table", name: named(AFTER.table) },
831
+ { match: /^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\b/i, label: "Index missing", name: indexLabel },
832
+ { match: /^\s*DROP\s+INDEX\b/i, label: "Extra index", name: named(AFTER.index) },
833
+ // Policies. Without these, dbdiff's own CREATE/DROP POLICY statements fell
834
+ // through to the catch-all and were titled "Schema change: unknown" — the
835
+ // one finding in a report that named no object at all (issue #97). Keyed
836
+ // `table.policy`, which is how a policy is identified and how the RLS check
837
+ // names the same one.
838
+ { match: /^\s*CREATE\s+POLICY\b/i, label: "Policy missing", name: policyLabel },
839
+ { match: /^\s*ALTER\s+POLICY\b/i, label: "Policy altered", name: policyLabel },
840
+ { match: /^\s*DROP\s+POLICY\b/i, label: "Extra policy", name: policyLabel },
841
+ // Comments (rc.21) and extensions (rc.22), named like everything else, and
842
+ // a comment by the object it is on and that object's kind.
843
+ { match: /^\s*COMMENT\s+ON\b/i, label: "Comment changed", name: commentLabel },
844
+ { match: /^\s*CREATE\s+EXTENSION\b/i, label: "Extension missing", name: extensionLabel },
845
+ { match: /^\s*DROP\s+EXTENSION\b/i, label: "Extra extension", name: extensionLabel },
846
+ { match: /^\s*CREATE\s+SEQUENCE\b/i, label: "Sequence missing", name: named(AFTER.sequence) },
847
+ { match: /^\s*ALTER\s+SEQUENCE\b/i, label: "Sequence altered", name: named(AFTER.sequence) },
848
+ { match: /^\s*DROP\s+SEQUENCE\b/i, label: "Extra sequence", name: named(AFTER.sequence) }
849
+ ];
850
+ var unquoted = (part) => part.replace(/^"|"$/g, "").replace(/""/g, '"');
851
+ function commentLabel(sql) {
852
+ const m = /^\s*COMMENT\s+ON\s+(MATERIALIZED\s+VIEW|FOREIGN\s+TABLE|[A-Z]+)\s+([\s\S]*?)\s+IS\s/i.exec(sql);
853
+ if (!m) return UNKNOWN_NAME;
854
+ const kind = m[1].toLowerCase().replace(/\s+/g, " ");
855
+ const on = /^("(?:[^"]|"")+"|\S+)\s+ON\s+(?:DOMAIN\s+)?([\s\S]+)$/i.exec(m[2].trim());
856
+ const object = on ? `${on[2].trim()}.${on[1]}` : m[2].trim();
857
+ const name = object.split(/\.(?=(?:[^"]*"[^"]*")*[^"]*$)/).map(unquoted).join(".");
858
+ return `${name} (${kind})`;
859
+ }
860
+ function extensionLabel(sql) {
861
+ const name = /\bEXTENSION\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?("[^"]+"|[\w$-]+)/i.exec(sql)?.[1];
862
+ const schema = /\bSCHEMA\s+("[^"]+"|[\w$]+)/i.exec(sql)?.[1];
863
+ if (!name) return UNKNOWN_NAME;
864
+ return schema ? `${unquoted(schema)}.${unquoted(name)}` : unquoted(name);
865
+ }
866
+ function schemaTitle(sql, downSql) {
867
+ const m = /^\s*(CREATE|DROP|COMMENT\s+ON)\s+SCHEMA\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?("[^"]+"|[\w$]+)/i.exec(sql);
868
+ if (!m) return void 0;
869
+ const label = { CREATE: "Schema missing", DROP: "Extra schema" }[m[1].toUpperCase()];
870
+ return label ? `${label}: ${unquoted(m[2])}` : `${commentChange(sql, downSql)}: schema ${unquoted(m[2])}`;
871
+ }
872
+ var CLEARS_COMMENT = /\bIS\s+NULL\s*;?\s*$/i;
873
+ function commentChange(sql, downSql) {
874
+ if (CLEARS_COMMENT.test(sql)) return "Extra comment";
875
+ if (downSql && CLEARS_COMMENT.test(downSql)) return "Comment missing";
876
+ return "Comment changed";
877
+ }
878
+ function summariseDataStatement(sql) {
879
+ const table = extractQualifiedName(sql, /\b(?:INTO|FROM|UPDATE)\s+(?:ONLY\s+)?/i);
880
+ const upper = sql.toUpperCase().trimStart();
881
+ if (upper.startsWith("INSERT")) return `Missing row in ${table}`;
882
+ if (upper.startsWith("DELETE")) return `Extra row in ${table}`;
883
+ if (upper.startsWith("UPDATE")) return `Modified row in ${table}`;
884
+ return `Data change in ${table}`;
885
+ }
886
+ function summariseStatement(sql, check, downSql) {
887
+ if (check === "data") return summariseDataStatement(sql);
888
+ const schema = schemaTitle(sql, downSql);
889
+ if (schema) return schema;
890
+ for (const rule of SCHEMA_RULES) {
891
+ if (rule.match.test(sql)) {
892
+ const label = rule.name === commentLabel ? commentChange(sql, downSql) : rule.label;
893
+ return `${label}: ${qualifySchemaName(rule.name(sql, downSql))}`;
894
+ }
895
+ }
896
+ return `Schema change: ${qualifySchemaName(
897
+ extractQualifiedName(sql, /\b(?:TABLE|INTO|FROM|UPDATE)\s+(?:ONLY\s+)?/i)
898
+ )}`;
899
+ }
900
+ function routineLabel(sql, downSql) {
901
+ const name = extractRoutineName(sql);
902
+ const args = extractRoutineArgs(sql);
903
+ if (!downSql || name === UNKNOWN_NAME || name.includes(".")) return name + args;
904
+ const counterpart = extractRoutineName(downSql);
905
+ const sameRoutine = unqualify(counterpart) === unqualify(name);
906
+ return (counterpart.includes(".") && sameRoutine ? counterpart : name) + args;
907
+ }
908
+ function unqualify(name) {
909
+ return name.slice(name.lastIndexOf(".") + 1).toLowerCase();
910
+ }
911
+ function extractRoutineName(sql) {
912
+ return extractQualifiedName(sql, /\b(?:FUNCTION|PROCEDURE)\s+(?:IF\s+EXISTS\s+)?/i);
913
+ }
914
+ var UNKNOWN_NAME = "unknown";
915
+ function extractQualifiedName(sql, head) {
916
+ const found = head.exec(sql);
917
+ if (!found) return UNKNOWN_NAME;
918
+ let rest = sql.slice(found.index + found[0].length);
919
+ const parts = [];
920
+ for (let depth = 0; depth < 2; depth++) {
921
+ const ident = /^(?:"((?:[^"]|"")*)"|([\w$]+))/.exec(rest);
922
+ if (!ident) break;
923
+ parts.push(ident[1] !== void 0 ? ident[1].replace(/""/g, '"') : ident[2]);
924
+ rest = rest.slice(ident[0].length);
925
+ const dot = /^\s*\.\s*/.exec(rest);
926
+ if (!dot) break;
927
+ rest = rest.slice(dot[0].length);
928
+ }
929
+ return parts.length > 0 ? parts.join(".") : UNKNOWN_NAME;
930
+ }
931
+ function extractRoutineArgs(sql) {
932
+ const open = sql.indexOf("(");
933
+ if (open === -1) return "";
934
+ let depth = 0;
935
+ for (let i = open; i < sql.length; i++) {
936
+ if (sql[i] === "(") depth++;
937
+ else if (sql[i] === ")" && --depth === 0) return sql.slice(open, i + 1);
938
+ }
939
+ return "";
940
+ }
941
+
942
+ export {
943
+ runDbDiff,
944
+ isDestructiveSql,
945
+ destructiveReason,
946
+ sqlToIssues
947
+ };
948
+ //# sourceMappingURL=chunk-VOXZWQ3N.js.map