@akal/supaforge 0.0.33 → 0.0.35
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.
- package/README.md +67 -14
- package/dist/base-command.d.ts +1 -1
- package/dist/base-command.js +4 -3
- package/dist/{branch-C4ndfoj5.d.ts → branch-BppjQBv_.d.ts} +1 -1
- package/dist/{chunk-4IVN7QVY.js → chunk-44UVQJV2.js} +159 -18
- package/dist/{chunk-3HGAV5CC.js → chunk-4AGJRRBT.js} +390 -43
- package/dist/{chunk-SQPCWGQO.js → chunk-4M6OQLPO.js} +22 -121
- package/dist/{chunk-2SELREHW.js → chunk-5Q6LSLA3.js} +56 -9
- package/dist/{chunk-7NAZGZPV.js → chunk-7N63OPFN.js} +28 -21
- package/dist/chunk-AGONS5JJ.js +242 -0
- package/dist/chunk-GQPGH6YR.js +50 -0
- package/dist/{chunk-GEHPTPNZ.js → chunk-H2D3YSKM.js} +7 -3
- package/dist/{chunk-6Q7MHFBM.js → chunk-HNJ6BNNZ.js} +2 -2
- package/dist/{chunk-6WAMNZLO.js → chunk-KNXHLVF7.js} +126 -4
- package/dist/{chunk-DMIWAJRB.js → chunk-NEM5AEPQ.js} +172 -22
- package/dist/{chunk-6LJERPUN.js → chunk-NX2KKUS7.js} +20 -12
- package/dist/{chunk-SC2XHGIS.js → chunk-O5ERC2SE.js} +3 -3
- package/dist/{chunk-MIRLB5JM.js → chunk-SM7HP6EP.js} +64 -182
- package/dist/{chunk-BUOWHE36.js → chunk-T7GMPGUO.js} +613 -66
- package/dist/{chunk-G2DIPIYU.js → chunk-WK5YTINL.js} +29 -2
- package/dist/{chunk-UWAVXC57.js → chunk-WNTCZM2J.js} +34 -482
- package/dist/{chunk-GZREXCQZ.js → chunk-XLZCX6R2.js} +17 -10
- package/dist/{chunk-ORQJVE57.js → chunk-YWERIWFD.js} +18 -17
- package/dist/{chunk-NTUASFQ3.js → chunk-YZM76W22.js} +5 -5
- package/dist/{chunk-BLKJWDTL.js → chunk-ZI435CAU.js} +2 -2
- package/dist/commands/clone.d.ts +2 -2
- package/dist/commands/clone.js +14 -13
- package/dist/commands/diff.d.ts +37 -23
- package/dist/commands/diff.js +20 -17
- package/dist/commands/hukam.d.ts +2 -3
- package/dist/commands/hukam.js +16 -15
- package/dist/commands/init.d.ts +1 -1
- package/dist/commands/init.js +5 -1
- package/dist/commands/mcp.js +16 -10
- package/dist/commands/migrate/baseline.d.ts +1 -1
- package/dist/commands/migrate/baseline.js +5 -4
- package/dist/commands/migrate/create.d.ts +1 -1
- package/dist/commands/migrate/create.js +15 -9
- package/dist/commands/migrate/list.d.ts +1 -1
- package/dist/commands/migrate/list.js +6 -5
- package/dist/commands/migrate/run.d.ts +4 -1
- package/dist/commands/migrate/run.js +10 -8
- package/dist/commands/report.d.ts +1 -1
- package/dist/commands/report.js +5 -4
- package/dist/commands/restore.d.ts +1 -1
- package/dist/commands/restore.js +14 -13
- package/dist/commands/snapshot.d.ts +8 -1
- package/dist/commands/snapshot.js +37 -9
- package/dist/commands/sync.d.ts +2 -3
- package/dist/commands/sync.js +16 -15
- package/dist/{config-CTbeRlJk.d.ts → config-l3ggjw9r.d.ts} +2 -0
- package/dist/index.d.ts +21 -4
- package/dist/index.js +15 -15
- package/package.json +2 -2
- package/dist/chunk-DQQ5E563.js +0 -64
|
@@ -1,19 +1,126 @@
|
|
|
1
1
|
import {
|
|
2
|
+
isCommentOnly,
|
|
2
3
|
splitSqlStatements
|
|
3
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-WK5YTINL.js";
|
|
4
5
|
import {
|
|
5
|
-
escapeRegex
|
|
6
|
-
|
|
6
|
+
escapeRegex,
|
|
7
|
+
globToRegExp,
|
|
8
|
+
matchesGlob,
|
|
9
|
+
parseFlagList
|
|
10
|
+
} from "./chunk-AGONS5JJ.js";
|
|
7
11
|
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
friendlyDbError
|
|
11
|
-
} from "./chunk-SQPCWGQO.js";
|
|
12
|
+
newPgClient
|
|
13
|
+
} from "./chunk-4M6OQLPO.js";
|
|
12
14
|
import {
|
|
13
15
|
DBDIFF_EXEC_TIMEOUT_MS,
|
|
14
16
|
DBDIFF_MAX_BUFFER,
|
|
17
|
+
DiagnosticError,
|
|
18
|
+
errMsg,
|
|
19
|
+
friendlyDbError,
|
|
15
20
|
schemaDiffIgnores
|
|
16
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-KNXHLVF7.js";
|
|
22
|
+
|
|
23
|
+
// src/utils/table-filter.ts
|
|
24
|
+
var parseTableList = parseFlagList;
|
|
25
|
+
function resolveTableFilter(config, cli = {}) {
|
|
26
|
+
const cliTables = parseTableList(cli.tables);
|
|
27
|
+
const cliExclude = parseTableList(cli.excludeTables);
|
|
28
|
+
const configTables = Array.isArray(config?.checks?.tables) ? config.checks.tables : [];
|
|
29
|
+
const configExclude = Array.isArray(config?.checks?.excludeTables) ? config.checks.excludeTables : [];
|
|
30
|
+
const tables = cliTables.length > 0 ? cliTables : parseTableList(configTables);
|
|
31
|
+
const excludeTables = [.../* @__PURE__ */ new Set([...parseTableList(configExclude), ...cliExclude])];
|
|
32
|
+
const filter = {};
|
|
33
|
+
if (tables.length > 0) filter.tables = tables;
|
|
34
|
+
if (excludeTables.length > 0) filter.excludeTables = excludeTables;
|
|
35
|
+
return filter;
|
|
36
|
+
}
|
|
37
|
+
function isFiltered(filter) {
|
|
38
|
+
return Boolean(filter?.tables?.length || filter?.excludeTables?.length);
|
|
39
|
+
}
|
|
40
|
+
function describeTableFilter(filter) {
|
|
41
|
+
if (!isFiltered(filter)) return null;
|
|
42
|
+
const parts = [];
|
|
43
|
+
if (filter?.tables?.length) parts.push(`only ${filter.tables.join(", ")}`);
|
|
44
|
+
if (filter?.excludeTables?.length) parts.push(`excluding ${filter.excludeTables.join(", ")}`);
|
|
45
|
+
return `Scoped to ${parts.join(", ")} \u2014 applies to the schema and data checks; other layers are unfiltered.`;
|
|
46
|
+
}
|
|
47
|
+
function matchesPattern(name, pattern) {
|
|
48
|
+
const candidates = [name.toLowerCase()];
|
|
49
|
+
const dot = name.indexOf(".");
|
|
50
|
+
if (dot !== -1) candidates.push(name.slice(dot + 1).toLowerCase());
|
|
51
|
+
const rx = globToRegExp(pattern.toLowerCase());
|
|
52
|
+
return candidates.some((c) => rx.test(c));
|
|
53
|
+
}
|
|
54
|
+
function applyTableFilter(names2, filter) {
|
|
55
|
+
if (!isFiltered(filter)) return names2;
|
|
56
|
+
let out = names2;
|
|
57
|
+
if (filter?.tables?.length) {
|
|
58
|
+
out = out.filter((n) => filter.tables.some((p) => matchesPattern(n, p)));
|
|
59
|
+
}
|
|
60
|
+
if (filter?.excludeTables?.length) {
|
|
61
|
+
out = out.filter((n) => !filter.excludeTables.some((p) => matchesPattern(n, p)));
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// src/types/drift.ts
|
|
67
|
+
var CHECK_NAMES = [
|
|
68
|
+
"schema",
|
|
69
|
+
"rls",
|
|
70
|
+
"rls-coverage",
|
|
71
|
+
"edge-functions",
|
|
72
|
+
"storage",
|
|
73
|
+
"auth",
|
|
74
|
+
"cron",
|
|
75
|
+
"data",
|
|
76
|
+
"webhooks",
|
|
77
|
+
"realtime",
|
|
78
|
+
"vault",
|
|
79
|
+
"extensions",
|
|
80
|
+
"migrations",
|
|
81
|
+
"roles",
|
|
82
|
+
"queues",
|
|
83
|
+
"partitions"
|
|
84
|
+
];
|
|
85
|
+
var CHECK_META = {
|
|
86
|
+
"schema": { number: 1, emoji: "\u{1F5C4}\uFE0F", label: "Schema" },
|
|
87
|
+
"rls": { number: 2, emoji: "\u{1F512}", label: "RLS Policies" },
|
|
88
|
+
"rls-coverage": { number: 3, emoji: "\u{1F6E1}\uFE0F", label: "RLS Coverage" },
|
|
89
|
+
"edge-functions": { number: 4, emoji: "\u26A1", label: "Edge Functions" },
|
|
90
|
+
"storage": { number: 5, emoji: "\u{1FAA3}", label: "Storage" },
|
|
91
|
+
"auth": { number: 6, emoji: "\u{1F511}", label: "Auth Config" },
|
|
92
|
+
"cron": { number: 7, emoji: "\u23F0", label: "Cron Jobs" },
|
|
93
|
+
"data": { number: 8, emoji: "\u{1F5C3}\uFE0F", label: "Reference Data" },
|
|
94
|
+
"webhooks": { number: 9, emoji: "\u26A1\u{1F517}", label: "Webhooks" },
|
|
95
|
+
"realtime": { number: 10, emoji: "\u{1F4E1}", label: "Realtime Publications" },
|
|
96
|
+
"vault": { number: 11, emoji: "\u{1F510}", label: "Vault Secrets" },
|
|
97
|
+
"extensions": { number: 12, emoji: "\u{1F9E9}", label: "Postgres Extensions" },
|
|
98
|
+
"migrations": { number: 13, emoji: "\u{1F4CB}", label: "Migration History" },
|
|
99
|
+
"roles": { number: 14, emoji: "\u{1F464}", label: "Postgres Roles & Grants" },
|
|
100
|
+
"queues": { number: 15, emoji: "\u{1F4EC}", label: "Queues" },
|
|
101
|
+
"partitions": { number: 16, emoji: "\u{1F5C2}\uFE0F", label: "Partition Sets" }
|
|
102
|
+
};
|
|
103
|
+
var CHECK_KIND = {
|
|
104
|
+
"schema": "comparison",
|
|
105
|
+
"rls": "comparison",
|
|
106
|
+
"rls-coverage": "posture",
|
|
107
|
+
"edge-functions": "comparison",
|
|
108
|
+
"storage": "comparison",
|
|
109
|
+
"auth": "comparison",
|
|
110
|
+
"cron": "comparison",
|
|
111
|
+
"data": "comparison",
|
|
112
|
+
"webhooks": "comparison",
|
|
113
|
+
"realtime": "comparison",
|
|
114
|
+
"vault": "comparison",
|
|
115
|
+
"extensions": "comparison",
|
|
116
|
+
"migrations": "posture",
|
|
117
|
+
"roles": "comparison",
|
|
118
|
+
"queues": "comparison",
|
|
119
|
+
"partitions": "comparison"
|
|
120
|
+
};
|
|
121
|
+
function isComparisonCheck(name) {
|
|
122
|
+
return CHECK_KIND[name] === "comparison";
|
|
123
|
+
}
|
|
17
124
|
|
|
18
125
|
// src/dbdiff.ts
|
|
19
126
|
import { execFile } from "child_process";
|
|
@@ -412,11 +519,15 @@ var REPLACING_KINDS = {
|
|
|
412
519
|
AlterPolicy: "policy",
|
|
413
520
|
AlterTrigger: "trigger",
|
|
414
521
|
AlterView: "view",
|
|
415
|
-
AlterMatView: "view"
|
|
522
|
+
AlterMatView: "view",
|
|
523
|
+
AlterCollation: "collation"
|
|
416
524
|
};
|
|
417
525
|
|
|
418
526
|
// src/dbdiff.ts
|
|
419
527
|
var execFileAsync = promisify(execFile);
|
|
528
|
+
function dbdiffNotices(stdout) {
|
|
529
|
+
return stdout.replace(/\u001b\[[0-9;]*m/g, "").split("\n").map((line) => line.trim()).filter((line) => line.startsWith("\u26A0")).map((line) => line.replace(/^⚠\s*/, ""));
|
|
530
|
+
}
|
|
420
531
|
function dbdiffNotInstalled(code, stderr) {
|
|
421
532
|
if (code === "ENOENT") return true;
|
|
422
533
|
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);
|
|
@@ -535,13 +646,14 @@ async function runDbDiff(options) {
|
|
|
535
646
|
maxBuffer: DBDIFF_MAX_BUFFER
|
|
536
647
|
});
|
|
537
648
|
attachProgress(running, options.onProgress);
|
|
538
|
-
await running;
|
|
649
|
+
const { stdout } = await running;
|
|
650
|
+
const notices = dbdiffNotices(String(stdout ?? ""));
|
|
539
651
|
const fileExists = await access(outputFile).then(() => true, () => false);
|
|
540
652
|
if (!fileExists) {
|
|
541
|
-
return { up: "", down: "" };
|
|
653
|
+
return { up: "", down: "", notices };
|
|
542
654
|
}
|
|
543
655
|
const output = await readFile(outputFile, "utf8");
|
|
544
|
-
return parseDbDiffOutput(output);
|
|
656
|
+
return { ...parseDbDiffOutput(output), notices };
|
|
545
657
|
} catch (err) {
|
|
546
658
|
const errObj = err ?? {};
|
|
547
659
|
const message = errMsg(err);
|
|
@@ -585,11 +697,14 @@ var UP_MARKER = "-- ==================== UP ====================";
|
|
|
585
697
|
var DOWN_MARKER = "-- ==================== DOWN ====================";
|
|
586
698
|
var CREATE_FUNCTION = "create-function";
|
|
587
699
|
var DROP_FUNCTION = "drop-function";
|
|
588
|
-
var DROP_TYPES = ["drop", "drop-view", DROP_FUNCTION, "drop-trigger", "drop-type", "drop-sequence"];
|
|
700
|
+
var DROP_TYPES = ["drop", "drop-view", DROP_FUNCTION, "drop-trigger", "drop-type", "drop-sequence", "drop-collation"];
|
|
589
701
|
function isDestructiveSql(sql) {
|
|
590
702
|
return destructiveReason(sql) !== void 0;
|
|
591
703
|
}
|
|
592
704
|
function destructiveReason(sql, recreatedElsewhere = /* @__PURE__ */ new Set()) {
|
|
705
|
+
if (/\bPGMQ\s*\.\s*"?DROP_QUEUE"?\s*\(/.test(sqlSkeleton(sql).toUpperCase())) {
|
|
706
|
+
return "drops a queue and the messages in it";
|
|
707
|
+
}
|
|
593
708
|
const statements = parseStatements(sql);
|
|
594
709
|
return statements ? destructiveInTree(statements, recreatedElsewhere) : destructiveInText(sql, recreatedElsewhere);
|
|
595
710
|
}
|
|
@@ -659,6 +774,14 @@ function sqlToIssues(result, check, ignoreSchemas, ignoredSchemaTables) {
|
|
|
659
774
|
const issues = unfoldedIssues(result, check, ignoreSchemas, ignoredSchemaTables);
|
|
660
775
|
return check === "schema" ? foldCommentsIntoCreates(issues) : issues;
|
|
661
776
|
}
|
|
777
|
+
var COMPARED_ELSEWHERE = /^Publication objects are not compared/;
|
|
778
|
+
function schemaNotices(notices) {
|
|
779
|
+
return notices.filter((n) => !COMPARED_ELSEWHERE.test(n)).map((notice) => {
|
|
780
|
+
const [what, advice] = notice.split(" \u2014 ");
|
|
781
|
+
const title = /not compared/.test(what) ? `Not compared: ${what.replace(/ objects are not compared/, "")}` : what;
|
|
782
|
+
return advice ? `${title} \u2014 ${advice}.` : `${title}.`;
|
|
783
|
+
});
|
|
784
|
+
}
|
|
662
785
|
var COMMENT_TITLE = /^(?:Comment changed|Comment missing): (?:schema (.+)|(.+) \(([a-z ]+)\))$/;
|
|
663
786
|
var CREATE_TITLE = /^(Schema|Table|View|Function|Procedure|Type|Domain|Sequence|Index|Policy|Trigger|Extension) (?:missing|modified): (.+)$/;
|
|
664
787
|
var ON_A_TABLE = /* @__PURE__ */ new Set(["column", "constraint", "trigger", "policy", "rule"]);
|
|
@@ -765,6 +888,18 @@ function issuesFromUnits(upUnits, downUnits, check, ignoreSchemas, ignoredSchema
|
|
|
765
888
|
...manual
|
|
766
889
|
};
|
|
767
890
|
}
|
|
891
|
+
const modified = modifiedTitle(up, statements);
|
|
892
|
+
if (modified) {
|
|
893
|
+
return {
|
|
894
|
+
id: `${check}-alter-${up.kind.replace(/^Alter/, "").toLowerCase()}-${i + 1}`,
|
|
895
|
+
check,
|
|
896
|
+
severity: "warning",
|
|
897
|
+
title: modified,
|
|
898
|
+
description: "Definition differs between source and target.",
|
|
899
|
+
sql: { up: upSql, down: downSql },
|
|
900
|
+
...manual
|
|
901
|
+
};
|
|
902
|
+
}
|
|
768
903
|
const lead = leadStatement(up, statements);
|
|
769
904
|
const type = classifyStatement(lead);
|
|
770
905
|
return {
|
|
@@ -789,8 +924,10 @@ function isCrossSchemaFkUnit(up, down, schemas, ignoredSchemaTables) {
|
|
|
789
924
|
}
|
|
790
925
|
function replacedObject(unit, statements) {
|
|
791
926
|
const kind = REPLACING_KINDS[unit.kind];
|
|
927
|
+
if (!kind) return void 0;
|
|
928
|
+
if (kind === "view") return replacedView(unit, statements);
|
|
792
929
|
const drop = statements.find((sql) => replaceablePart(sql)?.drop);
|
|
793
|
-
if (!
|
|
930
|
+
if (!drop) return void 0;
|
|
794
931
|
if (kind === "type") return { kind, name: unit.object };
|
|
795
932
|
const create = [...statements].reverse().find((sql) => replaceablePart(sql)?.drop === false) ?? drop;
|
|
796
933
|
return {
|
|
@@ -798,6 +935,37 @@ function replacedObject(unit, statements) {
|
|
|
798
935
|
name: kind === "routine" ? extractRoutineName(create) + extractRoutineArgs(drop) : REPLACEABLE_NAME[kind](create)
|
|
799
936
|
};
|
|
800
937
|
}
|
|
938
|
+
function replacedView(unit, statements) {
|
|
939
|
+
const views = statements.filter((sql) => replaceablePart(sql)?.kind === "view");
|
|
940
|
+
const own = (sql) => bareName2(REPLACEABLE_NAME.view(sql)) === bareName2(unit.object);
|
|
941
|
+
const create = views.find((sql) => replaceablePart(sql)?.drop === false && own(sql)) ?? views.filter((sql) => replaceablePart(sql)?.drop === false).pop();
|
|
942
|
+
const drop = views.find((sql) => replaceablePart(sql)?.drop && own(sql)) ?? views.find((sql) => replaceablePart(sql)?.drop);
|
|
943
|
+
const named2 = create ?? drop;
|
|
944
|
+
return named2 ? { kind: "view", name: REPLACEABLE_NAME.view(named2) } : void 0;
|
|
945
|
+
}
|
|
946
|
+
var bareName2 = (name) => name.slice(name.lastIndexOf(".") + 1).replace(/"/g, "").toLowerCase();
|
|
947
|
+
var MODIFIED_KINDS = {
|
|
948
|
+
AlterRangeType: "Type modified",
|
|
949
|
+
AlterAggregate: "Aggregate modified",
|
|
950
|
+
AlterRule: "Rule modified",
|
|
951
|
+
AlterStatistics: "Statistics modified",
|
|
952
|
+
AlterEventTrigger: "Event trigger modified",
|
|
953
|
+
AlterCast: "Cast modified",
|
|
954
|
+
AlterTextSearchConfiguration: "Text search configuration modified",
|
|
955
|
+
AlterTextSearchDictionary: "Text search dictionary modified",
|
|
956
|
+
AlterForeignServer: "Foreign server modified",
|
|
957
|
+
AlterUserMapping: "User mapping modified",
|
|
958
|
+
AlterForeignTable: "Foreign table modified",
|
|
959
|
+
AlterDefaultPrivileges: "Default privileges differ"
|
|
960
|
+
};
|
|
961
|
+
function modifiedTitle(unit, statements) {
|
|
962
|
+
const label = MODIFIED_KINDS[unit.kind];
|
|
963
|
+
if (!label) return void 0;
|
|
964
|
+
const making = statements.find((sql) => !/^\s*DROP\b/i.test(sql)) ?? statements[0];
|
|
965
|
+
const summary = making ? summariseStatement(making, "schema") : "";
|
|
966
|
+
const name = summary.slice(summary.indexOf(": ") + 2);
|
|
967
|
+
return `${label}: ${name || unit.object}`;
|
|
968
|
+
}
|
|
801
969
|
function leadStatement(unit, statements) {
|
|
802
970
|
if (unit.kind.startsWith("AlterTable")) {
|
|
803
971
|
const alter = statements.find((sql) => /^\s*ALTER\s+TABLE\b/i.test(sql));
|
|
@@ -898,7 +1066,8 @@ var REPLACEABLE_NAME = {
|
|
|
898
1066
|
policy: (sql) => policyLabel(sql),
|
|
899
1067
|
// `schema.table.trigger`, for the same reason.
|
|
900
1068
|
trigger: (sql) => triggerLabel(sql),
|
|
901
|
-
view: (sql) => extractQualifiedName(sql, AFTER.view)
|
|
1069
|
+
view: (sql) => extractQualifiedName(sql, AFTER.view),
|
|
1070
|
+
collation: (sql) => extractQualifiedName(sql, AFTER.collation)
|
|
902
1071
|
};
|
|
903
1072
|
var REPLACEABLE_REPORT = {
|
|
904
1073
|
routine: { idPart: "function", label: "Function modified", what: "Function body" },
|
|
@@ -906,7 +1075,8 @@ var REPLACEABLE_REPORT = {
|
|
|
906
1075
|
sequence: { idPart: "sequence", label: "Sequence modified", what: "Sequence definition" },
|
|
907
1076
|
policy: { idPart: "policy", label: "Policy modified", what: "Policy definition" },
|
|
908
1077
|
trigger: { idPart: "trigger", label: "Trigger modified", what: "Trigger definition" },
|
|
909
|
-
view: { idPart: "view", label: "View modified", what: "View definition" }
|
|
1078
|
+
view: { idPart: "view", label: "View modified", what: "View definition" },
|
|
1079
|
+
collation: { idPart: "collation", label: "Collation modified", what: "Collation definition" }
|
|
910
1080
|
};
|
|
911
1081
|
function replaceablePart(sql) {
|
|
912
1082
|
if (/^\s*DROP\s+POLICY\b/i.test(sql)) return { kind: "policy", drop: true };
|
|
@@ -928,6 +1098,10 @@ function replaceablePart(sql) {
|
|
|
928
1098
|
return { kind: "sequence", drop: false };
|
|
929
1099
|
case "drop-sequence":
|
|
930
1100
|
return { kind: "sequence", drop: true };
|
|
1101
|
+
case "create-collation":
|
|
1102
|
+
return { kind: "collation", drop: false };
|
|
1103
|
+
case "drop-collation":
|
|
1104
|
+
return { kind: "collation", drop: true };
|
|
931
1105
|
default:
|
|
932
1106
|
return void 0;
|
|
933
1107
|
}
|
|
@@ -1037,45 +1211,7 @@ function hasBrokenRef(sql) {
|
|
|
1037
1211
|
}
|
|
1038
1212
|
function splitStatements(sql) {
|
|
1039
1213
|
if (!sql) return [];
|
|
1040
|
-
|
|
1041
|
-
let buf = "";
|
|
1042
|
-
let i = 0;
|
|
1043
|
-
while (i < sql.length) {
|
|
1044
|
-
if (sql[i] === "$") {
|
|
1045
|
-
const tagMatch = sql.slice(i + 1).match(/^([A-Za-z0-9_]*)\$/);
|
|
1046
|
-
if (tagMatch) {
|
|
1047
|
-
const tag = `$${tagMatch[1]}$`;
|
|
1048
|
-
const closeIdx = sql.indexOf(tag, i + tag.length);
|
|
1049
|
-
if (closeIdx !== -1) {
|
|
1050
|
-
buf += sql.slice(i, closeIdx + tag.length);
|
|
1051
|
-
i = closeIdx + tag.length;
|
|
1052
|
-
continue;
|
|
1053
|
-
}
|
|
1054
|
-
}
|
|
1055
|
-
}
|
|
1056
|
-
if (sql[i] === ";") {
|
|
1057
|
-
buf += ";";
|
|
1058
|
-
i++;
|
|
1059
|
-
let j = i;
|
|
1060
|
-
while (j < sql.length && (sql[j] === " " || sql[j] === " " || sql[j] === "\r")) j++;
|
|
1061
|
-
if (j >= sql.length || sql[j] === "\n") {
|
|
1062
|
-
const stmt = withoutLeadingComments(buf);
|
|
1063
|
-
if (stmt.length > 0) {
|
|
1064
|
-
statements.push(stmt);
|
|
1065
|
-
}
|
|
1066
|
-
buf = "";
|
|
1067
|
-
i = j < sql.length ? j + 1 : j;
|
|
1068
|
-
}
|
|
1069
|
-
continue;
|
|
1070
|
-
}
|
|
1071
|
-
buf += sql[i];
|
|
1072
|
-
i++;
|
|
1073
|
-
}
|
|
1074
|
-
const last = withoutLeadingComments(buf);
|
|
1075
|
-
if (last.length > 0) {
|
|
1076
|
-
statements.push(last.endsWith(";") ? last : `${last};`);
|
|
1077
|
-
}
|
|
1078
|
-
return statements;
|
|
1214
|
+
return splitSqlStatements(sql).map((statement) => withoutLeadingComments(statement)).filter((statement) => statement.length > 0).map((statement) => `${statement};`);
|
|
1079
1215
|
}
|
|
1080
1216
|
function withoutLeadingComments(chunk) {
|
|
1081
1217
|
return chunk.trim().replace(/^(?:--[^\n]*(?:\n|$)\s*)+/, "").trim();
|
|
@@ -1104,6 +1240,9 @@ function classifyStatement(sql) {
|
|
|
1104
1240
|
if (upper.startsWith("DROP TABLE")) return "drop";
|
|
1105
1241
|
if (upper.startsWith("CREATE INDEX") || upper.startsWith("CREATE UNIQUE INDEX")) return "create-index";
|
|
1106
1242
|
if (upper.startsWith("DROP INDEX")) return "drop";
|
|
1243
|
+
if (upper.startsWith("CREATE COLLATION")) return "create-collation";
|
|
1244
|
+
if (upper.startsWith("ALTER COLLATION")) return "alter-collation";
|
|
1245
|
+
if (upper.startsWith("DROP COLLATION")) return "drop-collation";
|
|
1107
1246
|
if (upper.startsWith("CREATE SEQUENCE")) return "create-sequence";
|
|
1108
1247
|
if (upper.startsWith("ALTER SEQUENCE")) return "alter-sequence";
|
|
1109
1248
|
if (upper.startsWith("DROP SEQUENCE")) return "drop-sequence";
|
|
@@ -1121,9 +1260,41 @@ var AFTER = {
|
|
|
1121
1260
|
table: /\bTABLE\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?(?:ONLY\s+)?/i,
|
|
1122
1261
|
index: /\bINDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i,
|
|
1123
1262
|
policy: /\bPOLICY\s+(?:IF\s+EXISTS\s+)?/i,
|
|
1263
|
+
collation: /\bCOLLATION\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i,
|
|
1264
|
+
eventTrigger: /\bEVENT\s+TRIGGER\s+(?:IF\s+EXISTS\s+)?/i,
|
|
1265
|
+
aggregate: /\bAGGREGATE\s+(?:IF\s+EXISTS\s+)?/i,
|
|
1266
|
+
statistics: /\bSTATISTICS\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i,
|
|
1267
|
+
textSearch: /\bTEXT\s+SEARCH\s+(?:CONFIGURATION|DICTIONARY)\s+(?:IF\s+EXISTS\s+)?/i,
|
|
1268
|
+
server: /\bSERVER\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i,
|
|
1269
|
+
foreignTable: /\bFOREIGN\s+TABLE\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i,
|
|
1124
1270
|
on: /\bON\s+(?:ONLY\s+)?/i
|
|
1125
1271
|
};
|
|
1126
1272
|
var named = (head) => (sql) => extractQualifiedName(sql, head);
|
|
1273
|
+
function renameLabel(sql) {
|
|
1274
|
+
const table = extractQualifiedName(sql, /\b(?:TABLE|INDEX)\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?/i);
|
|
1275
|
+
const to = /\bTO\s+("(?:[^"]|"")*"|[\w$]+)\s*;?\s*$/i.exec(sql.trim())?.[1];
|
|
1276
|
+
const from = /\bRENAME\s+(?:COLUMN|CONSTRAINT)\s+("(?:[^"]|"")*"|[\w$]+)/i.exec(sql)?.[1];
|
|
1277
|
+
return `${qualifySchemaName(table)}${from ? "." + unquoted(from) : ""} \u2192 ${to ? unquoted(to) : UNKNOWN_NAME}`;
|
|
1278
|
+
}
|
|
1279
|
+
function defaultPrivilegesLabel(sql) {
|
|
1280
|
+
const role = /\bFOR\s+ROLE\s+("(?:[^"]|"")*"|\S+)/i.exec(sql)?.[1];
|
|
1281
|
+
const schema = /\bIN\s+SCHEMA\s+("(?:[^"]|"")*"|\S+)/i.exec(sql)?.[1];
|
|
1282
|
+
const kind = /\bON\s+(TABLES|SEQUENCES|FUNCTIONS|ROUTINES|TYPES|SCHEMAS)\b/i.exec(sql)?.[1];
|
|
1283
|
+
return [role && unquoted(role), schema ? `in ${unquoted(schema)}` : "in every schema", kind && `on ${kind.toLowerCase()}`].filter(Boolean).join(" ");
|
|
1284
|
+
}
|
|
1285
|
+
function ruleLabel(sql) {
|
|
1286
|
+
const rule = extractQualifiedName(sql, /\bRULE\s+(?:IF\s+EXISTS\s+)?/i);
|
|
1287
|
+
const table = /\bTO\s+((?:"(?:[^"]|"")*"|[\w$]+)(?:\.(?:"(?:[^"]|"")*"|[\w$]+))?)/i.exec(sql)?.[1] ?? /\bON\s+((?:"(?:[^"]|"")*"|[\w$]+)(?:\.(?:"(?:[^"]|"")*"|[\w$]+))?)/i.exec(sql)?.[1];
|
|
1288
|
+
return table ? `${unquoted(table.split(".").pop() ?? table)}.${rule.split(".").pop()}` : rule;
|
|
1289
|
+
}
|
|
1290
|
+
function castLabel(sql) {
|
|
1291
|
+
return /\(([^()]+?\s+AS\s+[^()]+?)\)/i.exec(sql)?.[1] ?? UNKNOWN_NAME;
|
|
1292
|
+
}
|
|
1293
|
+
function userMappingLabel(sql) {
|
|
1294
|
+
const user = /\bFOR\s+("(?:[^"]|"")*"|\S+)/i.exec(sql)?.[1] ?? "unknown";
|
|
1295
|
+
const server = /\bSERVER\s+("(?:[^"]|"")*"|[^\s;]+)/i.exec(sql)?.[1] ?? "unknown";
|
|
1296
|
+
return `${unquoted(user)}@${unquoted(server)}`;
|
|
1297
|
+
}
|
|
1127
1298
|
function policyLabel(sql) {
|
|
1128
1299
|
const policy = extractQualifiedName(sql, AFTER.policy);
|
|
1129
1300
|
const table = extractQualifiedName(sql, AFTER.on);
|
|
@@ -1175,6 +1346,10 @@ var SCHEMA_RULES = [
|
|
|
1175
1346
|
{ match: /^\s*CREATE\s+DOMAIN\b/i, label: "Domain missing", name: named(AFTER.domain) },
|
|
1176
1347
|
{ match: /^\s*ALTER\s+DOMAIN\b/i, label: "Domain altered", name: named(AFTER.domain) },
|
|
1177
1348
|
{ match: /^\s*DROP\s+DOMAIN\b/i, label: "Extra domain", name: named(AFTER.domain) },
|
|
1349
|
+
{ match: /^\s*ALTER\s+TABLE\b[^;]*\bRENAME\s+COLUMN\b/is, label: "Column renamed", name: renameLabel, unqualified: true },
|
|
1350
|
+
{ match: /^\s*ALTER\s+TABLE\b[^;]*\bRENAME\s+CONSTRAINT\b/is, label: "Constraint renamed", name: renameLabel, unqualified: true },
|
|
1351
|
+
{ match: /^\s*ALTER\s+TABLE\b[^;]*\bRENAME\s+TO\b/is, label: "Table renamed", name: renameLabel, unqualified: true },
|
|
1352
|
+
{ match: /^\s*ALTER\s+INDEX\b[^;]*\bRENAME\s+TO\b/is, label: "Index renamed", name: renameLabel, unqualified: true },
|
|
1178
1353
|
{ match: /^\s*ALTER\s+TABLE\b/i, label: "Table altered", name: named(AFTER.table) },
|
|
1179
1354
|
{ match: /^\s*CREATE\s+TABLE\b/i, label: "Table missing", name: named(AFTER.table) },
|
|
1180
1355
|
{ match: /^\s*DROP\s+TABLE\b/i, label: "Extra table", name: named(AFTER.table) },
|
|
@@ -1193,6 +1368,31 @@ var SCHEMA_RULES = [
|
|
|
1193
1368
|
{ match: /^\s*COMMENT\s+ON\b/i, label: "Comment changed", name: commentLabel },
|
|
1194
1369
|
{ match: /^\s*CREATE\s+EXTENSION\b/i, label: "Extension missing", name: extensionLabel },
|
|
1195
1370
|
{ match: /^\s*DROP\s+EXTENSION\b/i, label: "Extra extension", name: extensionLabel },
|
|
1371
|
+
{ match: /^\s*CREATE\s+COLLATION\b/i, label: "Collation missing", name: named(AFTER.collation) },
|
|
1372
|
+
{ match: /^\s*ALTER\s+COLLATION\b/i, label: "Collation altered", name: named(AFTER.collation) },
|
|
1373
|
+
{ match: /^\s*DROP\s+COLLATION\b/i, label: "Extra collation", name: named(AFTER.collation) },
|
|
1374
|
+
{ match: /^\s*ALTER\s+DEFAULT\s+PRIVILEGES\b/i, label: "Default privileges differ", name: defaultPrivilegesLabel, unqualified: true },
|
|
1375
|
+
{ match: /^\s*CREATE\s+EVENT\s+TRIGGER\b/i, label: "Event trigger missing", name: named(AFTER.eventTrigger) },
|
|
1376
|
+
{ match: /^\s*DROP\s+EVENT\s+TRIGGER\b/i, label: "Extra event trigger", name: named(AFTER.eventTrigger) },
|
|
1377
|
+
{ match: /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?RULE\b/i, label: "Rule missing", name: ruleLabel },
|
|
1378
|
+
{ match: /^\s*DROP\s+RULE\b/i, label: "Extra rule", name: ruleLabel },
|
|
1379
|
+
{ match: /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?AGGREGATE\b/i, label: "Aggregate missing", name: named(AFTER.aggregate) },
|
|
1380
|
+
{ match: /^\s*DROP\s+AGGREGATE\b/i, label: "Extra aggregate", name: named(AFTER.aggregate) },
|
|
1381
|
+
{ match: /^\s*CREATE\s+STATISTICS\b/i, label: "Statistics missing", name: named(AFTER.statistics) },
|
|
1382
|
+
{ match: /^\s*DROP\s+STATISTICS\b/i, label: "Extra statistics", name: named(AFTER.statistics) },
|
|
1383
|
+
{ match: /^\s*(?:CREATE|ALTER)\s+TEXT\s+SEARCH\s+CONFIGURATION\b/i, label: "Text search configuration missing", name: named(AFTER.textSearch) },
|
|
1384
|
+
{ match: /^\s*DROP\s+TEXT\s+SEARCH\s+CONFIGURATION\b/i, label: "Extra text search configuration", name: named(AFTER.textSearch) },
|
|
1385
|
+
{ match: /^\s*CREATE\s+TEXT\s+SEARCH\s+DICTIONARY\b/i, label: "Text search dictionary missing", name: named(AFTER.textSearch) },
|
|
1386
|
+
{ match: /^\s*DROP\s+TEXT\s+SEARCH\s+DICTIONARY\b/i, label: "Extra text search dictionary", name: named(AFTER.textSearch) },
|
|
1387
|
+
{ match: /^\s*CREATE\s+CAST\b/i, label: "Cast missing", name: castLabel, unqualified: true },
|
|
1388
|
+
{ match: /^\s*DROP\s+CAST\b/i, label: "Extra cast", name: castLabel, unqualified: true },
|
|
1389
|
+
{ match: /^\s*CREATE\s+SERVER\b/i, label: "Foreign server missing", name: named(AFTER.server) },
|
|
1390
|
+
{ match: /^\s*ALTER\s+SERVER\b/i, label: "Foreign server altered", name: named(AFTER.server) },
|
|
1391
|
+
{ match: /^\s*DROP\s+SERVER\b/i, label: "Extra foreign server", name: named(AFTER.server) },
|
|
1392
|
+
{ match: /^\s*(?:CREATE|ALTER)\s+USER\s+MAPPING\b/i, label: "User mapping missing", name: userMappingLabel, unqualified: true },
|
|
1393
|
+
{ match: /^\s*DROP\s+USER\s+MAPPING\b/i, label: "Extra user mapping", name: userMappingLabel, unqualified: true },
|
|
1394
|
+
{ match: /^\s*CREATE\s+FOREIGN\s+TABLE\b/i, label: "Foreign table missing", name: named(AFTER.foreignTable) },
|
|
1395
|
+
{ match: /^\s*DROP\s+FOREIGN\s+TABLE\b/i, label: "Extra foreign table", name: named(AFTER.foreignTable) },
|
|
1196
1396
|
{ match: /^\s*CREATE\s+SEQUENCE\b/i, label: "Sequence missing", name: named(AFTER.sequence) },
|
|
1197
1397
|
{ match: /^\s*ALTER\s+SEQUENCE\b/i, label: "Sequence altered", name: named(AFTER.sequence) },
|
|
1198
1398
|
{ match: /^\s*DROP\s+SEQUENCE\b/i, label: "Extra sequence", name: named(AFTER.sequence) }
|
|
@@ -1240,7 +1440,8 @@ function summariseStatement(sql, check, downSql) {
|
|
|
1240
1440
|
for (const rule of SCHEMA_RULES) {
|
|
1241
1441
|
if (rule.match.test(sql)) {
|
|
1242
1442
|
const label = rule.name === commentLabel ? commentChange(sql, downSql) : rule.label;
|
|
1243
|
-
|
|
1443
|
+
const name = rule.name(sql, downSql);
|
|
1444
|
+
return `${label}: ${rule.unqualified ? name : qualifySchemaName(name)}`;
|
|
1244
1445
|
}
|
|
1245
1446
|
}
|
|
1246
1447
|
return `Schema change: ${qualifySchemaName(
|
|
@@ -1289,23 +1490,369 @@ function extractRoutineArgs(sql) {
|
|
|
1289
1490
|
return "";
|
|
1290
1491
|
}
|
|
1291
1492
|
|
|
1493
|
+
// src/pg-errors.ts
|
|
1494
|
+
var ABSENT_ON_TARGET = /* @__PURE__ */ new Set(["42P01", "42883", "3F000", "42704"]);
|
|
1495
|
+
var UNDEFINED_COLUMN = "42703";
|
|
1496
|
+
var EXTENSION_UNAVAILABLE = /* @__PURE__ */ new Set(["0A000", "58P01"]);
|
|
1497
|
+
function sqlState(err) {
|
|
1498
|
+
const code = err?.code;
|
|
1499
|
+
return typeof code === "string" ? code : void 0;
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// src/promote.ts
|
|
1503
|
+
function outOfScopeReason(sql, filter) {
|
|
1504
|
+
if (!isFiltered(filter)) return null;
|
|
1505
|
+
const referenced = referencedTables(sql);
|
|
1506
|
+
if (referenced.length === 0) return null;
|
|
1507
|
+
const excluded = referenced.filter((t) => applyTableFilter([t], filter).length === 0);
|
|
1508
|
+
if (excluded.length === 0) return null;
|
|
1509
|
+
const names2 = excluded.map((t) => `'${t}'`).join(", ");
|
|
1510
|
+
const flag = filter?.tables?.length ? "--tables" : "--exclude-tables";
|
|
1511
|
+
const noun = excluded.length === 1 ? "table" : "tables";
|
|
1512
|
+
return `Depends on ${noun} ${names2}, excluded by ${flag}`;
|
|
1513
|
+
}
|
|
1514
|
+
function isSelected(issueId, only) {
|
|
1515
|
+
if (!only?.length) return true;
|
|
1516
|
+
return only.some((pattern) => matchesGlob(issueId, pattern));
|
|
1517
|
+
}
|
|
1518
|
+
function withDefaultGrantRevokes(scanResult, only) {
|
|
1519
|
+
if (!only?.length) return only;
|
|
1520
|
+
const issues = scanResult.checks.flatMap((c) => c.issues);
|
|
1521
|
+
const created = new Set(issues.filter((i) => i.sql?.up && isSelected(i.id, only)).flatMap((i) => relationsCreatedBy(i.sql.up)));
|
|
1522
|
+
if (created.size === 0) return only;
|
|
1523
|
+
const companions = issues.filter((i) => i.id.startsWith("roles-grant-default-") && [...created].some((rel) => rel.endsWith("(") ? i.id.toLowerCase().includes(`.${rel}`) : i.id.toLowerCase().endsWith(`.${rel}`))).map((i) => i.id);
|
|
1524
|
+
return [...only, ...companions];
|
|
1525
|
+
}
|
|
1526
|
+
function relationsCreatedBy(sql) {
|
|
1527
|
+
const statements = parseStatements(sql);
|
|
1528
|
+
if (!statements) return [];
|
|
1529
|
+
return statements.flatMap(({ kind, node }) => {
|
|
1530
|
+
if (kind === "CreateFunctionStmt") {
|
|
1531
|
+
const parts = (node.funcname ?? []).map((n) => n.String?.sval ?? "");
|
|
1532
|
+
const name = parts.at(-1);
|
|
1533
|
+
return name ? [`${(parts.length > 1 ? parts.at(-2) : "public").toLowerCase()}.${name.toLowerCase()}(`] : [];
|
|
1534
|
+
}
|
|
1535
|
+
const rel = kind === "CreateStmt" ? node.relation : kind === "ViewStmt" ? node.view : kind === "CreateTableAsStmt" ? node.into?.rel : void 0;
|
|
1536
|
+
return rel?.relname ? [`${(rel.schemaname || "public").toLowerCase()}.${String(rel.relname).toLowerCase()}`] : [];
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
function classifyIssue(issue, options, recreatedPolicies = /* @__PURE__ */ new Set()) {
|
|
1540
|
+
if (!isSelected(issue.id, options.only)) {
|
|
1541
|
+
return { kind: "skip", reason: "Not selected by --only" };
|
|
1542
|
+
}
|
|
1543
|
+
if (issue.manualOnly) return { kind: "skip", reason: issue.manualOnly };
|
|
1544
|
+
if (!issue.sql?.up) {
|
|
1545
|
+
if (issue.action?.method === "DELETE" && !options.allowDestructive) {
|
|
1546
|
+
return { kind: "skip", reason: `Destructive \u2014 ${issue.action.label}; re-run with --allow-destructive to apply` };
|
|
1547
|
+
}
|
|
1548
|
+
if (issue.action) return { kind: "api", action: issue.action };
|
|
1549
|
+
return { kind: "skip", reason: issue.manualOnly ?? "No SQL fix or API action available" };
|
|
1550
|
+
}
|
|
1551
|
+
if (!options.allowDestructive) {
|
|
1552
|
+
const why = issue.destructive ?? destructiveReason(issue.sql.up, recreatedPolicies);
|
|
1553
|
+
if (why) {
|
|
1554
|
+
return { kind: "skip", reason: `Destructive \u2014 ${why}; re-run with --allow-destructive to apply` };
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
const outOfScope = outOfScopeReason(issue.sql.up, options.tableFilter);
|
|
1558
|
+
if (outOfScope) return { kind: "skip", reason: outOfScope };
|
|
1559
|
+
return { kind: "sql", sql: issue.sql.up };
|
|
1560
|
+
}
|
|
1561
|
+
function policiesCreatedBySelectedFixes(checks, options) {
|
|
1562
|
+
const created = /* @__PURE__ */ new Set();
|
|
1563
|
+
for (const check of checks) {
|
|
1564
|
+
const askedForExplicitly = options.checks?.includes(check.check) ?? false;
|
|
1565
|
+
if (!isComparisonCheck(check.check) && !options.applyPosture && !askedForExplicitly) continue;
|
|
1566
|
+
for (const issue of check.issues) {
|
|
1567
|
+
const sql = issue.sql?.up;
|
|
1568
|
+
if (!sql || !isSelected(issue.id, options.only)) continue;
|
|
1569
|
+
if (!options.allowDestructive && destructiveReason(sql)) continue;
|
|
1570
|
+
if (outOfScopeReason(sql, options.tableFilter)) continue;
|
|
1571
|
+
for (const key of createdPolicies(sql)) created.add(key);
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
return created;
|
|
1575
|
+
}
|
|
1576
|
+
function planWork(scanResult, options = {}) {
|
|
1577
|
+
options = { ...options, only: withDefaultGrantRevokes(scanResult, options.only) };
|
|
1578
|
+
const plan = { sqlStatements: [], apiActions: [], skipped: [] };
|
|
1579
|
+
const relevant = scanResult.checks.filter(
|
|
1580
|
+
(c) => c.status === "drifted" && (!options.checks || options.checks.includes(c.check))
|
|
1581
|
+
);
|
|
1582
|
+
const recreatedPolicies = policiesCreatedBySelectedFixes(relevant, options);
|
|
1583
|
+
const keptBack = [];
|
|
1584
|
+
for (const checkResult of relevant) {
|
|
1585
|
+
const askedForExplicitly = options.checks?.includes(checkResult.check) ?? false;
|
|
1586
|
+
if (!isComparisonCheck(checkResult.check) && !options.applyPosture && !askedForExplicitly) {
|
|
1587
|
+
for (const issue of checkResult.issues) {
|
|
1588
|
+
plan.skipped.push({
|
|
1589
|
+
check: checkResult.check,
|
|
1590
|
+
issueId: issue.id,
|
|
1591
|
+
reason: "Posture finding about the target, not drift from the source \u2014 applying it would create drift. Use --apply-posture to apply anyway."
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
continue;
|
|
1595
|
+
}
|
|
1596
|
+
for (const issue of checkResult.issues) {
|
|
1597
|
+
const at = { check: checkResult.check, issueId: issue.id };
|
|
1598
|
+
const outcome = classifyIssue(issue, options, recreatedPolicies);
|
|
1599
|
+
if (outcome.kind === "sql") plan.sqlStatements.push({ ...at, sql: outcome.sql });
|
|
1600
|
+
else if (outcome.kind === "api") plan.apiActions.push({ ...at, action: outcome.action });
|
|
1601
|
+
else {
|
|
1602
|
+
plan.skipped.push({ ...at, reason: outcome.reason });
|
|
1603
|
+
if (outcome.reason.startsWith("Destructive") && issue.sql?.down) {
|
|
1604
|
+
keptBack.push({ issueId: issue.id, definition: issue.sql.down });
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
plan.sqlStatements = holdBackDropsStillInUse(plan.sqlStatements, keptBack, plan.skipped, downsOf(relevant));
|
|
1610
|
+
const dbdiffOrder = new Map(plan.sqlStatements.filter((s) => s.check === "schema").map((s, i) => [s, i]));
|
|
1611
|
+
plan.sqlStatements = orderStatements(plan.sqlStatements, (s) => s.sql, (s) => dbdiffOrder.get(s));
|
|
1612
|
+
plan.sqlStatements = dropDuplicateObjectFixes(plan.sqlStatements, plan.skipped);
|
|
1613
|
+
return plan;
|
|
1614
|
+
}
|
|
1615
|
+
var DROPS_SUPPORTING_OBJECT = /^\s*DROP\s+(?:TYPE|DOMAIN|FUNCTION|PROCEDURE|ROUTINE|SEQUENCE)\s+(?:IF\s+EXISTS\s+)?((?:"[^"]+"|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|[\w$]+))?)/i;
|
|
1616
|
+
function holdBackDropsStillInUse(statements, keptBack, skipped, downs = /* @__PURE__ */ new Map()) {
|
|
1617
|
+
const kept = keptBack.map((k) => ({ issueId: k.issueId, skeleton: sqlSkeleton(k.definition) }));
|
|
1618
|
+
let remaining = statements;
|
|
1619
|
+
for (let changed = kept.length > 0; changed; ) {
|
|
1620
|
+
changed = false;
|
|
1621
|
+
remaining = remaining.filter((statement) => {
|
|
1622
|
+
const names2 = droppedSupportingObjects(statement.sql);
|
|
1623
|
+
if (names2.length === 0) return true;
|
|
1624
|
+
const user = kept.find((k) => names2.some((n) => identifierMatcher(bareName(n)).test(k.skeleton)));
|
|
1625
|
+
if (!user) return true;
|
|
1626
|
+
skipped.push({
|
|
1627
|
+
check: statement.check,
|
|
1628
|
+
issueId: statement.issueId,
|
|
1629
|
+
reason: `Still used by what ${user.issueId} keeps, which is held back as destructive; re-run with --allow-destructive to apply both`
|
|
1630
|
+
});
|
|
1631
|
+
const definition = downs.get(statement.issueId);
|
|
1632
|
+
if (definition) kept.push({ issueId: user.issueId, skeleton: sqlSkeleton(definition) });
|
|
1633
|
+
changed = true;
|
|
1634
|
+
return false;
|
|
1635
|
+
});
|
|
1636
|
+
}
|
|
1637
|
+
return remaining;
|
|
1638
|
+
}
|
|
1639
|
+
function droppedSupportingObjects(sql) {
|
|
1640
|
+
const parts = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
|
|
1641
|
+
const names2 = parts.map((s) => DROPS_SUPPORTING_OBJECT.exec(sqlSkeleton(s))?.[1]);
|
|
1642
|
+
return names2.length > 0 && names2.every((n) => n !== void 0) ? names2 : [];
|
|
1643
|
+
}
|
|
1644
|
+
function downsOf(checks) {
|
|
1645
|
+
const downs = /* @__PURE__ */ new Map();
|
|
1646
|
+
for (const check of checks) {
|
|
1647
|
+
for (const issue of check.issues) {
|
|
1648
|
+
if (issue.sql?.down) downs.set(issue.id, issue.sql.down);
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
return downs;
|
|
1652
|
+
}
|
|
1653
|
+
function dropDuplicateObjectFixes(statements, skipped) {
|
|
1654
|
+
const kinds = [
|
|
1655
|
+
{ what: "policy", created: createdPolicies, onlyThis: createsOnlyPolicies, seen: /* @__PURE__ */ new Set() },
|
|
1656
|
+
{ what: "trigger", created: createdTriggers, onlyThis: createsOnlyTriggers, seen: /* @__PURE__ */ new Set() }
|
|
1657
|
+
];
|
|
1658
|
+
const kept = [];
|
|
1659
|
+
for (const statement of statements) {
|
|
1660
|
+
const duplicate = kinds.find((kind) => {
|
|
1661
|
+
const names2 = kind.created(statement.sql);
|
|
1662
|
+
return names2.length > 0 && names2.every((n) => kind.seen.has(n)) && kind.onlyThis(statement.sql);
|
|
1663
|
+
});
|
|
1664
|
+
if (duplicate) {
|
|
1665
|
+
skipped.push({
|
|
1666
|
+
check: statement.check,
|
|
1667
|
+
issueId: statement.issueId,
|
|
1668
|
+
reason: `Already created by the schema fix for the same ${duplicate.what}`
|
|
1669
|
+
});
|
|
1670
|
+
continue;
|
|
1671
|
+
}
|
|
1672
|
+
for (const kind of kinds) {
|
|
1673
|
+
for (const name of kind.created(statement.sql)) kind.seen.add(name);
|
|
1674
|
+
}
|
|
1675
|
+
kept.push(statement);
|
|
1676
|
+
}
|
|
1677
|
+
return kept;
|
|
1678
|
+
}
|
|
1679
|
+
async function executeSql(dbUrl, statements, result, transactional) {
|
|
1680
|
+
if (statements.length === 0) return;
|
|
1681
|
+
const client = newPgClient(dbUrl);
|
|
1682
|
+
await client.connect();
|
|
1683
|
+
try {
|
|
1684
|
+
if (transactional) await runInTransaction(client, statements, result);
|
|
1685
|
+
else await runIndependently(client, statements, result);
|
|
1686
|
+
} finally {
|
|
1687
|
+
await client.end();
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
async function runLikeApply(dbUrl, statements) {
|
|
1691
|
+
const result = { applied: [], skipped: [], errors: [] };
|
|
1692
|
+
await executeSql(dbUrl, statements, result, true);
|
|
1693
|
+
return result;
|
|
1694
|
+
}
|
|
1695
|
+
async function runIndependently(client, statements, result) {
|
|
1696
|
+
for (const stmt of statements) {
|
|
1697
|
+
try {
|
|
1698
|
+
await client.query(stmt.sql);
|
|
1699
|
+
result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
|
|
1700
|
+
} catch (err) {
|
|
1701
|
+
result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) });
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
function isEnumValueAddition(sql) {
|
|
1706
|
+
const statements = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
|
|
1707
|
+
return statements.length > 0 && statements.every((s) => /^\s*ALTER\s+TYPE\s+\S+\s+ADD\s+VALUE\b/i.test(sqlSkeleton(s)));
|
|
1708
|
+
}
|
|
1709
|
+
async function runInTransaction(client, statements, result) {
|
|
1710
|
+
const additions = statements.filter((s) => isEnumValueAddition(s.sql));
|
|
1711
|
+
const rest = statements.filter((s) => !isEnumValueAddition(s.sql));
|
|
1712
|
+
if (additions.length > 0 && !await runBatch(client, additions, result)) return;
|
|
1713
|
+
await runBatch(client, rest, result);
|
|
1714
|
+
}
|
|
1715
|
+
function unmetDependency(sql, err) {
|
|
1716
|
+
const code = sqlState(err);
|
|
1717
|
+
if (!code) return void 0;
|
|
1718
|
+
if (/^\s*CREATE\s+EXTENSION\b/i.test(sqlSkeleton(sql))) {
|
|
1719
|
+
return EXTENSION_UNAVAILABLE.has(code) ? "this server does not ship it" : void 0;
|
|
1720
|
+
}
|
|
1721
|
+
if (ABSENT_ON_TARGET.has(code) || code === UNDEFINED_COLUMN) {
|
|
1722
|
+
return "it needs something the target does not have";
|
|
1723
|
+
}
|
|
1724
|
+
return void 0;
|
|
1725
|
+
}
|
|
1726
|
+
async function runBatch(client, statements, result) {
|
|
1727
|
+
if (statements.length === 0) return true;
|
|
1728
|
+
const done = [];
|
|
1729
|
+
await client.query("BEGIN");
|
|
1730
|
+
let pending = statements;
|
|
1731
|
+
let unmet = [];
|
|
1732
|
+
while (pending.length > 0) {
|
|
1733
|
+
unmet = [];
|
|
1734
|
+
for (const stmt of pending) {
|
|
1735
|
+
await client.query("SAVEPOINT sf_fix");
|
|
1736
|
+
try {
|
|
1737
|
+
await client.query(stmt.sql);
|
|
1738
|
+
await client.query("RELEASE SAVEPOINT sf_fix");
|
|
1739
|
+
done.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
|
|
1740
|
+
} catch (err) {
|
|
1741
|
+
const why = unmetDependency(stmt.sql, err);
|
|
1742
|
+
if (why && await client.query("ROLLBACK TO SAVEPOINT sf_fix").then(() => true, () => false)) {
|
|
1743
|
+
unmet.push({ stmt, err, why });
|
|
1744
|
+
continue;
|
|
1745
|
+
}
|
|
1746
|
+
await client.query("ROLLBACK").catch(() => {
|
|
1747
|
+
});
|
|
1748
|
+
result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) });
|
|
1749
|
+
result.rolledBack = [...result.rolledBack ?? [], ...done];
|
|
1750
|
+
return false;
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
if (unmet.length === pending.length) break;
|
|
1754
|
+
pending = unmet.map((u) => u.stmt);
|
|
1755
|
+
}
|
|
1756
|
+
await client.query("COMMIT");
|
|
1757
|
+
result.applied.push(...done);
|
|
1758
|
+
for (const { stmt, err, why } of unmet) {
|
|
1759
|
+
result.errors.push({
|
|
1760
|
+
check: stmt.check,
|
|
1761
|
+
issueId: stmt.issueId,
|
|
1762
|
+
error: `${errMsg(err)} \u2014 not applied: ${why}. The other fixes were.`
|
|
1763
|
+
});
|
|
1764
|
+
}
|
|
1765
|
+
return true;
|
|
1766
|
+
}
|
|
1767
|
+
async function executeApiActions(actions, fetchFn, result) {
|
|
1768
|
+
for (const act of actions) {
|
|
1769
|
+
try {
|
|
1770
|
+
const init = {
|
|
1771
|
+
method: act.action.method,
|
|
1772
|
+
headers: { "Content-Type": "application/json", ...act.action.headers }
|
|
1773
|
+
};
|
|
1774
|
+
if (act.action.body !== void 0) {
|
|
1775
|
+
init.body = JSON.stringify(act.action.body);
|
|
1776
|
+
}
|
|
1777
|
+
const res = await fetchFn(act.action.url, init);
|
|
1778
|
+
if (!res.ok) {
|
|
1779
|
+
const text = await res.text().catch(() => res.statusText);
|
|
1780
|
+
throw new Error(`${act.action.method} ${act.action.url} \u2192 ${res.status}: ${text}`);
|
|
1781
|
+
}
|
|
1782
|
+
result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label });
|
|
1783
|
+
} catch (err) {
|
|
1784
|
+
result.errors.push({ check: act.check, issueId: act.issueId, error: errMsg(err) });
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
async function promote(options) {
|
|
1789
|
+
const {
|
|
1790
|
+
dbUrl,
|
|
1791
|
+
scanResult,
|
|
1792
|
+
checks,
|
|
1793
|
+
dryRun = false,
|
|
1794
|
+
allowDestructive = false,
|
|
1795
|
+
tableFilter,
|
|
1796
|
+
only,
|
|
1797
|
+
applyPosture = false,
|
|
1798
|
+
transactional = true,
|
|
1799
|
+
fetchFn = globalThis.fetch.bind(globalThis)
|
|
1800
|
+
} = options;
|
|
1801
|
+
const { sqlStatements, apiActions, skipped } = planWork(scanResult, {
|
|
1802
|
+
checks,
|
|
1803
|
+
allowDestructive,
|
|
1804
|
+
tableFilter,
|
|
1805
|
+
only,
|
|
1806
|
+
applyPosture
|
|
1807
|
+
});
|
|
1808
|
+
const result = { applied: [], skipped, errors: [] };
|
|
1809
|
+
if (dryRun) {
|
|
1810
|
+
for (const stmt of sqlStatements) {
|
|
1811
|
+
result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
|
|
1812
|
+
}
|
|
1813
|
+
for (const act of apiActions) {
|
|
1814
|
+
result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label });
|
|
1815
|
+
}
|
|
1816
|
+
return result;
|
|
1817
|
+
}
|
|
1818
|
+
await executeSql(dbUrl, sqlStatements, result, transactional);
|
|
1819
|
+
if (result.rolledBack) {
|
|
1820
|
+
for (const act of apiActions) {
|
|
1821
|
+
result.skipped.push({
|
|
1822
|
+
check: act.check,
|
|
1823
|
+
issueId: act.issueId,
|
|
1824
|
+
reason: "Not attempted \u2014 the SQL fixes were rolled back"
|
|
1825
|
+
});
|
|
1826
|
+
}
|
|
1827
|
+
return result;
|
|
1828
|
+
}
|
|
1829
|
+
await executeApiActions(apiActions, fetchFn, result);
|
|
1830
|
+
return result;
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1292
1833
|
export {
|
|
1293
1834
|
parseStatements,
|
|
1835
|
+
relationName,
|
|
1294
1836
|
sqlSkeleton,
|
|
1295
|
-
bareName,
|
|
1296
|
-
createdPolicies,
|
|
1297
|
-
createsOnlyPolicies,
|
|
1298
|
-
createdTriggers,
|
|
1299
|
-
createsOnlyTriggers,
|
|
1300
|
-
referencedTables,
|
|
1301
|
-
identifierMatcher,
|
|
1302
|
-
orderStatements,
|
|
1303
1837
|
statementSubject,
|
|
1304
1838
|
policyOnlyKeys,
|
|
1305
1839
|
rolesNamedBy,
|
|
1840
|
+
resolveTableFilter,
|
|
1841
|
+
isFiltered,
|
|
1842
|
+
describeTableFilter,
|
|
1843
|
+
applyTableFilter,
|
|
1844
|
+
CHECK_NAMES,
|
|
1845
|
+
CHECK_META,
|
|
1846
|
+
isComparisonCheck,
|
|
1306
1847
|
runDbDiff,
|
|
1307
1848
|
isDestructiveSql,
|
|
1308
1849
|
destructiveReason,
|
|
1309
|
-
sqlToIssues
|
|
1850
|
+
sqlToIssues,
|
|
1851
|
+
schemaNotices,
|
|
1852
|
+
ABSENT_ON_TARGET,
|
|
1853
|
+
EXTENSION_UNAVAILABLE,
|
|
1854
|
+
planWork,
|
|
1855
|
+
runLikeApply,
|
|
1856
|
+
promote
|
|
1310
1857
|
};
|
|
1311
|
-
//# sourceMappingURL=chunk-
|
|
1858
|
+
//# sourceMappingURL=chunk-T7GMPGUO.js.map
|