@akal/supaforge 0.0.34 → 0.0.36
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 +32 -13
- package/dist/base-command.d.ts +1 -1
- package/dist/base-command.js +4 -4
- package/dist/{branch-C4ndfoj5.d.ts → branch-BppjQBv_.d.ts} +1 -1
- package/dist/{chunk-ICSCHS72.js → chunk-5UHIWFQG.js} +76 -186
- package/dist/{chunk-S5L4A3UR.js → chunk-AL6INEFX.js} +3 -3
- package/dist/{chunk-OB5GP7UB.js → chunk-CAQ3QQFP.js} +437 -45
- package/dist/{chunk-TPX2MAO4.js → chunk-CCB7ARZU.js} +54 -5
- package/dist/{chunk-V2SBZERO.js → chunk-EWNZIRCD.js} +4 -4
- package/dist/{chunk-EFKQOQGG.js → chunk-FD2JKEJA.js} +7 -5
- package/dist/{chunk-3WKWPSFN.js → chunk-GGZ7YWBZ.js} +191 -32
- package/dist/{chunk-F46FFUKC.js → chunk-JX5L253P.js} +56 -18
- package/dist/{chunk-GQPGH6YR.js → chunk-KHXEES2M.js} +2 -2
- package/dist/{chunk-MG3SFV5J.js → chunk-KT7NMELZ.js} +77 -7
- package/dist/{chunk-PYAGSMFB.js → chunk-M2564IGT.js} +159 -19
- package/dist/{chunk-7DL63NWP.js → chunk-MRXIE55Y.js} +7 -3
- package/dist/{chunk-6ERVCWLY.js → chunk-MZPWRWBL.js} +7 -7
- package/dist/{chunk-5STH2A6K.js → chunk-OXS42LJH.js} +4 -4
- package/dist/{chunk-HNJ6BNNZ.js → chunk-Q43MN6NE.js} +2 -2
- package/dist/{chunk-ZI435CAU.js → chunk-RQCXGO37.js} +2 -2
- package/dist/{chunk-KNXHLVF7.js → chunk-SQ52YBKK.js} +3 -2
- package/dist/{chunk-N5VNNOA2.js → chunk-YUJ2MHLM.js} +1236 -22
- package/dist/chunk-Z2YUOA4W.js +242 -0
- package/dist/commands/clone.d.ts +2 -2
- package/dist/commands/clone.js +10 -9
- package/dist/commands/diff.d.ts +25 -22
- package/dist/commands/diff.js +14 -15
- package/dist/commands/hukam.d.ts +2 -3
- package/dist/commands/hukam.js +14 -15
- package/dist/commands/init.d.ts +1 -1
- package/dist/commands/init.js +2 -2
- package/dist/commands/mcp.js +9 -10
- package/dist/commands/migrate/baseline.d.ts +1 -1
- package/dist/commands/migrate/baseline.js +5 -5
- package/dist/commands/migrate/create.d.ts +1 -1
- package/dist/commands/migrate/create.js +27 -13
- package/dist/commands/migrate/list.d.ts +1 -1
- package/dist/commands/migrate/list.js +5 -5
- package/dist/commands/migrate/run.d.ts +4 -1
- package/dist/commands/migrate/run.js +9 -8
- package/dist/commands/report.d.ts +1 -1
- package/dist/commands/report.js +5 -5
- package/dist/commands/restore.d.ts +1 -1
- package/dist/commands/restore.js +14 -13
- package/dist/commands/snapshot.d.ts +1 -1
- package/dist/commands/snapshot.js +8 -8
- package/dist/commands/sync.d.ts +2 -3
- package/dist/commands/sync.js +14 -15
- package/dist/{config-CTbeRlJk.d.ts → config-l3ggjw9r.d.ts} +2 -0
- package/dist/index.d.ts +38 -4
- package/dist/index.js +13 -14
- package/package.json +2 -2
- package/dist/chunk-DQJSSTIJ.js +0 -940
- package/dist/chunk-DQQ5E563.js +0 -64
|
@@ -1,17 +1,625 @@
|
|
|
1
1
|
import {
|
|
2
|
+
isCommentOnly,
|
|
2
3
|
splitSqlStatements
|
|
3
4
|
} from "./chunk-WK5YTINL.js";
|
|
4
5
|
import {
|
|
5
|
-
escapeRegex
|
|
6
|
-
|
|
6
|
+
escapeRegex,
|
|
7
|
+
globToRegExp,
|
|
8
|
+
matchesGlob,
|
|
9
|
+
parseFlagList
|
|
10
|
+
} from "./chunk-Z2YUOA4W.js";
|
|
11
|
+
import {
|
|
12
|
+
Check,
|
|
13
|
+
heldSnapshot,
|
|
14
|
+
newPgClient,
|
|
15
|
+
pgQuery,
|
|
16
|
+
quoteName,
|
|
17
|
+
snapshotsOff
|
|
18
|
+
} from "./chunk-KT7NMELZ.js";
|
|
7
19
|
import {
|
|
8
20
|
DBDIFF_EXEC_TIMEOUT_MS,
|
|
9
21
|
DBDIFF_MAX_BUFFER,
|
|
10
22
|
DiagnosticError,
|
|
23
|
+
SUPABASE_PLATFORM_SCHEMAS,
|
|
11
24
|
errMsg,
|
|
12
25
|
friendlyDbError,
|
|
13
26
|
schemaDiffIgnores
|
|
14
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-SQ52YBKK.js";
|
|
28
|
+
|
|
29
|
+
// src/utils/table-filter.ts
|
|
30
|
+
var parseTableList = parseFlagList;
|
|
31
|
+
function resolveTableFilter(config, cli = {}) {
|
|
32
|
+
const cliTables = parseTableList(cli.tables);
|
|
33
|
+
const cliExclude = parseTableList(cli.excludeTables);
|
|
34
|
+
const configTables = Array.isArray(config?.checks?.tables) ? config.checks.tables : [];
|
|
35
|
+
const configExclude = Array.isArray(config?.checks?.excludeTables) ? config.checks.excludeTables : [];
|
|
36
|
+
const tables = cliTables.length > 0 ? cliTables : parseTableList(configTables);
|
|
37
|
+
const excludeTables = [.../* @__PURE__ */ new Set([...parseTableList(configExclude), ...cliExclude])];
|
|
38
|
+
const filter = {};
|
|
39
|
+
if (tables.length > 0) filter.tables = tables;
|
|
40
|
+
if (excludeTables.length > 0) filter.excludeTables = excludeTables;
|
|
41
|
+
return filter;
|
|
42
|
+
}
|
|
43
|
+
function isFiltered(filter) {
|
|
44
|
+
return Boolean(filter?.tables?.length || filter?.excludeTables?.length);
|
|
45
|
+
}
|
|
46
|
+
function describeTableFilter(filter) {
|
|
47
|
+
if (!isFiltered(filter)) return null;
|
|
48
|
+
const parts = [];
|
|
49
|
+
if (filter?.tables?.length) parts.push(`only ${filter.tables.join(", ")}`);
|
|
50
|
+
if (filter?.excludeTables?.length) parts.push(`excluding ${filter.excludeTables.join(", ")}`);
|
|
51
|
+
return `Scoped to ${parts.join(", ")} \u2014 applies to the schema and data checks; other layers are unfiltered.`;
|
|
52
|
+
}
|
|
53
|
+
function matchesPattern(name, pattern) {
|
|
54
|
+
const candidates = [name.toLowerCase()];
|
|
55
|
+
const dot = name.indexOf(".");
|
|
56
|
+
if (dot !== -1) candidates.push(name.slice(dot + 1).toLowerCase());
|
|
57
|
+
const rx = globToRegExp(pattern.toLowerCase());
|
|
58
|
+
return candidates.some((c) => rx.test(c));
|
|
59
|
+
}
|
|
60
|
+
function applyTableFilter(names2, filter) {
|
|
61
|
+
if (!isFiltered(filter)) return names2;
|
|
62
|
+
let out = names2;
|
|
63
|
+
if (filter?.tables?.length) {
|
|
64
|
+
out = out.filter((n) => filter.tables.some((p) => matchesPattern(n, p)));
|
|
65
|
+
}
|
|
66
|
+
if (filter?.excludeTables?.length) {
|
|
67
|
+
out = out.filter((n) => !filter.excludeTables.some((p) => matchesPattern(n, p)));
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// src/types/drift.ts
|
|
73
|
+
var CHECK_NAMES = [
|
|
74
|
+
"schema",
|
|
75
|
+
"rls",
|
|
76
|
+
"rls-coverage",
|
|
77
|
+
"edge-functions",
|
|
78
|
+
"storage",
|
|
79
|
+
"auth",
|
|
80
|
+
"cron",
|
|
81
|
+
"data",
|
|
82
|
+
"webhooks",
|
|
83
|
+
"realtime",
|
|
84
|
+
"vault",
|
|
85
|
+
"extensions",
|
|
86
|
+
"migrations",
|
|
87
|
+
"roles",
|
|
88
|
+
"queues",
|
|
89
|
+
"partitions"
|
|
90
|
+
];
|
|
91
|
+
var CHECK_META = {
|
|
92
|
+
"schema": { number: 1, emoji: "\u{1F5C4}\uFE0F", label: "Schema" },
|
|
93
|
+
"rls": { number: 2, emoji: "\u{1F512}", label: "RLS Policies" },
|
|
94
|
+
"rls-coverage": { number: 3, emoji: "\u{1F6E1}\uFE0F", label: "RLS Coverage" },
|
|
95
|
+
"edge-functions": { number: 4, emoji: "\u26A1", label: "Edge Functions" },
|
|
96
|
+
"storage": { number: 5, emoji: "\u{1FAA3}", label: "Storage" },
|
|
97
|
+
"auth": { number: 6, emoji: "\u{1F511}", label: "Auth Config" },
|
|
98
|
+
"cron": { number: 7, emoji: "\u23F0", label: "Cron Jobs" },
|
|
99
|
+
"data": { number: 8, emoji: "\u{1F5C3}\uFE0F", label: "Reference Data" },
|
|
100
|
+
"webhooks": { number: 9, emoji: "\u26A1\u{1F517}", label: "Webhooks" },
|
|
101
|
+
"realtime": { number: 10, emoji: "\u{1F4E1}", label: "Realtime Publications" },
|
|
102
|
+
"vault": { number: 11, emoji: "\u{1F510}", label: "Vault Secrets" },
|
|
103
|
+
"extensions": { number: 12, emoji: "\u{1F9E9}", label: "Postgres Extensions" },
|
|
104
|
+
"migrations": { number: 13, emoji: "\u{1F4CB}", label: "Migration History" },
|
|
105
|
+
"roles": { number: 14, emoji: "\u{1F464}", label: "Postgres Roles & Grants" },
|
|
106
|
+
"queues": { number: 15, emoji: "\u{1F4EC}", label: "Queues" },
|
|
107
|
+
"partitions": { number: 16, emoji: "\u{1F5C2}\uFE0F", label: "Partition Sets" }
|
|
108
|
+
};
|
|
109
|
+
var CHECK_KIND = {
|
|
110
|
+
"schema": "comparison",
|
|
111
|
+
"rls": "comparison",
|
|
112
|
+
"rls-coverage": "posture",
|
|
113
|
+
"edge-functions": "comparison",
|
|
114
|
+
"storage": "comparison",
|
|
115
|
+
"auth": "comparison",
|
|
116
|
+
"cron": "comparison",
|
|
117
|
+
"data": "comparison",
|
|
118
|
+
"webhooks": "comparison",
|
|
119
|
+
"realtime": "comparison",
|
|
120
|
+
"vault": "comparison",
|
|
121
|
+
"extensions": "comparison",
|
|
122
|
+
"migrations": "posture",
|
|
123
|
+
"roles": "comparison",
|
|
124
|
+
"queues": "comparison",
|
|
125
|
+
"partitions": "comparison"
|
|
126
|
+
};
|
|
127
|
+
function isComparisonCheck(name) {
|
|
128
|
+
return CHECK_KIND[name] === "comparison";
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// src/checks/roles.ts
|
|
132
|
+
var PLATFORM_ROLES = [
|
|
133
|
+
"postgres",
|
|
134
|
+
"supabase_admin",
|
|
135
|
+
"authenticator",
|
|
136
|
+
"supabase_auth_admin",
|
|
137
|
+
"supabase_storage_admin",
|
|
138
|
+
"dashboard_user",
|
|
139
|
+
"pgbouncer",
|
|
140
|
+
"supavisor",
|
|
141
|
+
// Created by Supabase's own images for Edge Functions, Realtime, read
|
|
142
|
+
// replicas and logical replication. Diffing a project against plain
|
|
143
|
+
// PostgreSQL offered to create all four on the target.
|
|
144
|
+
"supabase_functions_admin",
|
|
145
|
+
"supabase_realtime_admin",
|
|
146
|
+
"supabase_read_only_user",
|
|
147
|
+
"supabase_replication_admin"
|
|
148
|
+
];
|
|
149
|
+
var API_ROLES = ["anon", "authenticated", "service_role"];
|
|
150
|
+
var quoted = (names2) => names2.map((n) => `'${n.replace(/'/g, "''")}'`).join(", ");
|
|
151
|
+
var ROLES_SQL = `
|
|
152
|
+
SELECT
|
|
153
|
+
rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb,
|
|
154
|
+
rolcanlogin, rolreplication, rolbypassrls, rolconnlimit,
|
|
155
|
+
rolvaliduntil::text AS rolvaliduntil
|
|
156
|
+
FROM pg_roles
|
|
157
|
+
WHERE NOT (rolname LIKE 'pg_%')
|
|
158
|
+
AND rolname NOT IN (${quoted([...PLATFORM_ROLES, ...API_ROLES])})
|
|
159
|
+
AND rolname <> current_user
|
|
160
|
+
ORDER BY rolname
|
|
161
|
+
`;
|
|
162
|
+
function grantSchemaFilter(ignoreSchemas) {
|
|
163
|
+
const excluded = [.../* @__PURE__ */ new Set([...SUPABASE_PLATFORM_SCHEMAS, ...ignoreSchemas])];
|
|
164
|
+
return `NOT IN (${quoted(excluded)})`;
|
|
165
|
+
}
|
|
166
|
+
var grantsSql = (ignoreSchemas) => `
|
|
167
|
+
SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
|
|
168
|
+
n.nspname AS table_schema, c.relname AS table_name,
|
|
169
|
+
a.privilege_type, a.is_grantable,
|
|
170
|
+
CASE c.relkind WHEN 'S' THEN 'sequence' ELSE 'table' END AS object_kind
|
|
171
|
+
FROM pg_class c
|
|
172
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
173
|
+
CROSS JOIN LATERAL aclexplode(c.relacl) a
|
|
174
|
+
WHERE c.relacl IS NOT NULL
|
|
175
|
+
AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')
|
|
176
|
+
AND a.grantee <> c.relowner
|
|
177
|
+
AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
|
|
178
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
|
|
179
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
|
|
180
|
+
ORDER BY 1, 2, 3, 4
|
|
181
|
+
`;
|
|
182
|
+
var schemaGrantsSql = (ignoreSchemas) => `
|
|
183
|
+
SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
|
|
184
|
+
n.nspname AS table_schema, '' AS table_name,
|
|
185
|
+
a.privilege_type, a.is_grantable, 'schema' AS object_kind
|
|
186
|
+
FROM pg_namespace n
|
|
187
|
+
CROSS JOIN LATERAL aclexplode(n.nspacl) a
|
|
188
|
+
WHERE n.nspacl IS NOT NULL
|
|
189
|
+
AND a.grantee <> n.nspowner
|
|
190
|
+
AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
|
|
191
|
+
AND n.nspname NOT LIKE 'pg\\_%' AND n.nspname <> 'information_schema'
|
|
192
|
+
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_namespace'::regclass AND d.objid = n.oid AND d.deptype = 'e')
|
|
193
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
|
|
194
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
|
|
195
|
+
ORDER BY 1, 2, 4
|
|
196
|
+
`;
|
|
197
|
+
var schemasSql = (ignoreSchemas) => `
|
|
198
|
+
SELECT nspname AS table_schema, '' AS table_name, 'schema' AS object_kind
|
|
199
|
+
FROM pg_namespace
|
|
200
|
+
WHERE nspname ${grantSchemaFilter(ignoreSchemas)}
|
|
201
|
+
`;
|
|
202
|
+
var columnGrantsSql = (ignoreSchemas) => `
|
|
203
|
+
SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
|
|
204
|
+
n.nspname AS table_schema, c.relname AS table_name, att.attname AS column_name,
|
|
205
|
+
a.privilege_type, a.is_grantable
|
|
206
|
+
FROM pg_attribute att
|
|
207
|
+
JOIN pg_class c ON c.oid = att.attrelid
|
|
208
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
209
|
+
CROSS JOIN LATERAL aclexplode(att.attacl) a
|
|
210
|
+
WHERE att.attacl IS NOT NULL AND att.attnum > 0 AND NOT att.attisdropped
|
|
211
|
+
AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
|
|
212
|
+
AND a.grantee <> c.relowner
|
|
213
|
+
AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
|
|
214
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
|
|
215
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
|
|
216
|
+
ORDER BY 1, 2, 3, 4, 5
|
|
217
|
+
`;
|
|
218
|
+
var functionGrantsSql = (ignoreSchemas) => `
|
|
219
|
+
SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
|
|
220
|
+
n.nspname AS table_schema, p.proname AS table_name,
|
|
221
|
+
pg_get_function_identity_arguments(p.oid) AS args,
|
|
222
|
+
CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END AS object_kind,
|
|
223
|
+
a.privilege_type, a.is_grantable
|
|
224
|
+
FROM pg_proc p
|
|
225
|
+
JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
226
|
+
CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) a
|
|
227
|
+
WHERE a.grantee <> p.proowner
|
|
228
|
+
AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
|
|
229
|
+
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')
|
|
230
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
|
|
231
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
|
|
232
|
+
ORDER BY 1, 2, 3, 4, 6
|
|
233
|
+
`;
|
|
234
|
+
var routinesSql = (ignoreSchemas) => `
|
|
235
|
+
SELECT n.nspname AS table_schema, p.proname AS table_name,
|
|
236
|
+
pg_get_function_identity_arguments(p.oid) AS args,
|
|
237
|
+
CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END AS object_kind
|
|
238
|
+
FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
239
|
+
WHERE n.nspname ${grantSchemaFilter(ignoreSchemas)}
|
|
240
|
+
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')
|
|
241
|
+
`;
|
|
242
|
+
var relationsSql = (ignoreSchemas) => `
|
|
243
|
+
SELECT n.nspname AS table_schema, c.relname AS table_name,
|
|
244
|
+
CASE c.relkind WHEN 'S' THEN 'sequence' ELSE 'table' END AS object_kind
|
|
245
|
+
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
246
|
+
WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')
|
|
247
|
+
AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
|
|
248
|
+
`;
|
|
249
|
+
var DEFAULT_GRANTS_SQL = `
|
|
250
|
+
SELECT CASE d.defaclobjtype WHEN 'S' THEN 'sequence' WHEN 'f' THEN 'function' ELSE 'table' END AS object_kind,
|
|
251
|
+
n.nspname AS table_schema,
|
|
252
|
+
CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
|
|
253
|
+
a.privilege_type, a.is_grantable
|
|
254
|
+
FROM pg_default_acl d
|
|
255
|
+
LEFT JOIN pg_namespace n ON n.oid = d.defaclnamespace
|
|
256
|
+
CROSS JOIN LATERAL aclexplode(d.defaclacl) a
|
|
257
|
+
WHERE d.defaclobjtype IN ('r', 'S', 'f') AND d.defaclrole = current_user::regrole::oid
|
|
258
|
+
AND a.grantee <> d.defaclrole
|
|
259
|
+
UNION ALL
|
|
260
|
+
SELECT 'function', NULL, 'PUBLIC', 'EXECUTE', false
|
|
261
|
+
WHERE NOT EXISTS (
|
|
262
|
+
SELECT 1 FROM pg_default_acl d
|
|
263
|
+
WHERE d.defaclobjtype = 'f' AND d.defaclnamespace = 0 AND d.defaclrole = current_user::regrole::oid)
|
|
264
|
+
`;
|
|
265
|
+
function objectKey(o) {
|
|
266
|
+
if (o.object_kind === "schema") return `schema:${o.table_schema}`;
|
|
267
|
+
const routine = o.object_kind === "function" || o.object_kind === "procedure";
|
|
268
|
+
return `${routine ? "routine" : o.object_kind ?? "table"}:${o.table_schema}.${o.table_name}${routine ? `(${o.args ?? ""})` : ""}`;
|
|
269
|
+
}
|
|
270
|
+
function defaultKind(kind) {
|
|
271
|
+
return kind === "procedure" ? "function" : kind ?? "table";
|
|
272
|
+
}
|
|
273
|
+
function grantedByDefault(relations, defaults) {
|
|
274
|
+
const present = new Set(relations.map(objectKey));
|
|
275
|
+
const granted = new Set(defaults.map((d) => `${defaultKind(d.object_kind)}|${d.table_schema ?? "*"}|${d.grantee}|${d.privilege_type}|${Boolean(d.is_grantable)}`));
|
|
276
|
+
return (g) => !g.column_name && !present.has(objectKey(g)) && [g.table_schema, "*"].some((schema) => granted.has(`${defaultKind(g.object_kind)}|${schema}|${g.grantee}|${g.privilege_type}|${Boolean(g.is_grantable)}`));
|
|
277
|
+
}
|
|
278
|
+
function defaultGrantsToRevoke(sourceRelations, targetRelations, defaults, sourceGrants) {
|
|
279
|
+
const present = new Set(targetRelations.map(objectKey));
|
|
280
|
+
const held = new Set(sourceGrants.filter((g) => !g.column_name).map((g) => `${objectKey(g)}|${g.grantee}|${g.privilege_type}`));
|
|
281
|
+
const issues = [];
|
|
282
|
+
for (const rel of sourceRelations) {
|
|
283
|
+
if (present.has(objectKey(rel))) continue;
|
|
284
|
+
const name = `${rel.table_schema}.${rel.table_name}`;
|
|
285
|
+
const extra = /* @__PURE__ */ new Map();
|
|
286
|
+
for (const d of defaults) {
|
|
287
|
+
if (defaultKind(d.object_kind) !== defaultKind(rel.object_kind)) continue;
|
|
288
|
+
if (d.table_schema !== null && d.table_schema !== rel.table_schema) continue;
|
|
289
|
+
if (held.has(`${objectKey(rel)}|${d.grantee}|${d.privilege_type}`)) continue;
|
|
290
|
+
extra.set(d.grantee, (extra.get(d.grantee) ?? /* @__PURE__ */ new Set()).add(d.privilege_type));
|
|
291
|
+
}
|
|
292
|
+
for (const [grantee, privileges] of [...extra].sort(([a], [b]) => a.localeCompare(b))) {
|
|
293
|
+
const gs = [...privileges].sort().map((privilege_type) => ({
|
|
294
|
+
grantee,
|
|
295
|
+
table_schema: rel.table_schema,
|
|
296
|
+
table_name: rel.table_name,
|
|
297
|
+
privilege_type,
|
|
298
|
+
is_grantable: false,
|
|
299
|
+
...rel.object_kind && rel.object_kind !== "table" ? { object_kind: rel.object_kind } : {},
|
|
300
|
+
...rel.args !== void 0 ? { args: rel.args } : {}
|
|
301
|
+
}));
|
|
302
|
+
const routine = rel.object_kind === "function" || rel.object_kind === "procedure";
|
|
303
|
+
issues.push({
|
|
304
|
+
// Tables keep the id they have always had; others say what they are.
|
|
305
|
+
id: `roles-grant-default-${grantee}.${name}${routine ? `(${rel.args ?? ""})` : ""}`,
|
|
306
|
+
check: "roles",
|
|
307
|
+
severity: extraGrantSeverity(grantee),
|
|
308
|
+
title: `Default grants to take back: ${describeGroup(gs)}`,
|
|
309
|
+
description: `Creating ${describeObject(gs[0])} on the target gives ${grantee} what its default privileges grant. The source does not grant "${describeGroup(gs)}", so it is revoked once it exists.`,
|
|
310
|
+
targetValue: gs,
|
|
311
|
+
sql: {
|
|
312
|
+
up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(grantee)};`,
|
|
313
|
+
down: `GRANT ${groupTarget(gs)} TO ${granteeSql(grantee)};`
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return issues;
|
|
319
|
+
}
|
|
320
|
+
var OPEN_GRANTEES = /* @__PURE__ */ new Set(["anon", "authenticated", "PUBLIC"]);
|
|
321
|
+
function extraGrantSeverity(grantee) {
|
|
322
|
+
return OPEN_GRANTEES.has(grantee) ? "critical" : "warning";
|
|
323
|
+
}
|
|
324
|
+
var RolesCheck = class extends Check {
|
|
325
|
+
/**
|
|
326
|
+
* `explicit`: report a grant the source has even where the target's
|
|
327
|
+
* default privileges would make it. A migration file is replayed on
|
|
328
|
+
* databases whose defaults differ — Supabase stopped granting the Data API
|
|
329
|
+
* roles on new tables in `public` — so it must say every grant itself.
|
|
330
|
+
*/
|
|
331
|
+
constructor(queryFn = pgQuery, options = {}) {
|
|
332
|
+
super();
|
|
333
|
+
this.queryFn = queryFn;
|
|
334
|
+
this.options = options;
|
|
335
|
+
}
|
|
336
|
+
name = "roles";
|
|
337
|
+
async scan(ctx) {
|
|
338
|
+
const ignore = ctx.config.ignoreSchemas ?? [];
|
|
339
|
+
const version = async (url) => Number((await this.queryFn(url, `SELECT current_setting('server_version_num') AS v`))[0]?.v ?? 0);
|
|
340
|
+
const [
|
|
341
|
+
sourceRoles,
|
|
342
|
+
targetRoles,
|
|
343
|
+
sourceGrants,
|
|
344
|
+
targetGrants,
|
|
345
|
+
sourceColumns,
|
|
346
|
+
targetColumns,
|
|
347
|
+
sourceVersion,
|
|
348
|
+
targetVersion,
|
|
349
|
+
sourceRelations,
|
|
350
|
+
targetRelations,
|
|
351
|
+
targetDefaults,
|
|
352
|
+
sourceRoutineGrants,
|
|
353
|
+
targetRoutineGrants,
|
|
354
|
+
sourceRoutines,
|
|
355
|
+
targetRoutines,
|
|
356
|
+
sourceSchemaGrants,
|
|
357
|
+
targetSchemaGrants,
|
|
358
|
+
sourceSchemas
|
|
359
|
+
] = await Promise.all([
|
|
360
|
+
this.queryFn(ctx.source.dbUrl, ROLES_SQL),
|
|
361
|
+
this.queryFn(ctx.target.dbUrl, ROLES_SQL),
|
|
362
|
+
this.queryFn(ctx.source.dbUrl, grantsSql(ignore)),
|
|
363
|
+
this.queryFn(ctx.target.dbUrl, grantsSql(ignore)),
|
|
364
|
+
this.queryFn(ctx.source.dbUrl, columnGrantsSql(ignore)),
|
|
365
|
+
this.queryFn(ctx.target.dbUrl, columnGrantsSql(ignore)),
|
|
366
|
+
version(ctx.source.dbUrl),
|
|
367
|
+
version(ctx.target.dbUrl),
|
|
368
|
+
this.queryFn(ctx.source.dbUrl, relationsSql(ignore)),
|
|
369
|
+
this.queryFn(ctx.target.dbUrl, relationsSql(ignore)),
|
|
370
|
+
this.queryFn(ctx.target.dbUrl, DEFAULT_GRANTS_SQL),
|
|
371
|
+
this.queryFn(ctx.source.dbUrl, functionGrantsSql(ignore)),
|
|
372
|
+
this.queryFn(ctx.target.dbUrl, functionGrantsSql(ignore)),
|
|
373
|
+
this.queryFn(ctx.source.dbUrl, routinesSql(ignore)),
|
|
374
|
+
this.queryFn(ctx.target.dbUrl, routinesSql(ignore)),
|
|
375
|
+
this.queryFn(ctx.source.dbUrl, schemaGrantsSql(ignore)),
|
|
376
|
+
this.queryFn(ctx.target.dbUrl, schemaGrantsSql(ignore)),
|
|
377
|
+
this.queryFn(ctx.source.dbUrl, schemasSql(ignore))
|
|
378
|
+
]);
|
|
379
|
+
const sourceObjects = [...sourceRelations ?? [], ...sourceRoutines ?? [], ...sourceSchemas ?? []];
|
|
380
|
+
const targetObjects = [...targetRelations ?? [], ...targetRoutines ?? []];
|
|
381
|
+
const sourceAll = [...sourceGrants ?? [], ...sourceRoutineGrants ?? [], ...sourceSchemaGrants ?? []];
|
|
382
|
+
const inSource = new Set(sourceObjects.map(objectKey));
|
|
383
|
+
const targetAll = [...targetGrants ?? [], ...targetRoutineGrants ?? [], ...targetSchemaGrants ?? []].filter((g) => !g.object_kind || g.object_kind === "table" || inSource.has(objectKey(g)));
|
|
384
|
+
const comparable = comparablePrivileges(sourceVersion, targetVersion);
|
|
385
|
+
const byDefault = this.options.explicit ? () => false : grantedByDefault(targetObjects, targetDefaults ?? []);
|
|
386
|
+
return [
|
|
387
|
+
...diffRoles(sourceRoles, targetRoles),
|
|
388
|
+
...diffGrants(
|
|
389
|
+
[...sourceAll, ...sourceColumns ?? []].filter((g) => comparable(g) && !byDefault(g)),
|
|
390
|
+
[...targetAll, ...targetColumns ?? []].filter(comparable),
|
|
391
|
+
absentOn(targetRoles, sourceRoles)
|
|
392
|
+
),
|
|
393
|
+
...defaultGrantsToRevoke(
|
|
394
|
+
sourceObjects,
|
|
395
|
+
targetObjects,
|
|
396
|
+
(targetDefaults ?? []).filter((d) => comparable(d)),
|
|
397
|
+
sourceAll
|
|
398
|
+
)
|
|
399
|
+
];
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
function absentOn(target, source) {
|
|
403
|
+
const present = new Set((target ?? []).map((r) => r.rolname));
|
|
404
|
+
return new Set((source ?? []).map((r) => r.rolname).filter((name) => !present.has(name)));
|
|
405
|
+
}
|
|
406
|
+
function roleAttrs(r) {
|
|
407
|
+
const attrs = [];
|
|
408
|
+
if (r.rolsuper) attrs.push("SUPERUSER");
|
|
409
|
+
if (r.rolinherit) attrs.push("INHERIT");
|
|
410
|
+
if (r.rolcreaterole) attrs.push("CREATEROLE");
|
|
411
|
+
if (r.rolcreatedb) attrs.push("CREATEDB");
|
|
412
|
+
if (r.rolcanlogin) attrs.push("LOGIN");
|
|
413
|
+
if (r.rolreplication) attrs.push("REPLICATION");
|
|
414
|
+
if (r.rolbypassrls) attrs.push("BYPASSRLS");
|
|
415
|
+
if (r.rolconnlimit >= 0) attrs.push(`CONNECTION LIMIT ${r.rolconnlimit}`);
|
|
416
|
+
if (r.rolvaliduntil) attrs.push(`VALID UNTIL '${r.rolvaliduntil}'`);
|
|
417
|
+
return attrs.length > 0 ? attrs.join(" ") : "NOLOGIN";
|
|
418
|
+
}
|
|
419
|
+
function rolesEqual(a, b) {
|
|
420
|
+
return a.rolsuper === b.rolsuper && a.rolinherit === b.rolinherit && a.rolcreaterole === b.rolcreaterole && a.rolcreatedb === b.rolcreatedb && a.rolcanlogin === b.rolcanlogin && a.rolreplication === b.rolreplication && a.rolbypassrls === b.rolbypassrls && a.rolconnlimit === b.rolconnlimit && a.rolvaliduntil === b.rolvaliduntil;
|
|
421
|
+
}
|
|
422
|
+
function diffRoles(source, target) {
|
|
423
|
+
const issues = [];
|
|
424
|
+
const sourceMap = new Map(source.map((r) => [r.rolname, r]));
|
|
425
|
+
const targetMap = new Map(target.map((r) => [r.rolname, r]));
|
|
426
|
+
for (const [name, sr] of sourceMap) {
|
|
427
|
+
if (!targetMap.has(name)) {
|
|
428
|
+
issues.push({
|
|
429
|
+
id: `roles-missing-${name}`,
|
|
430
|
+
check: "roles",
|
|
431
|
+
severity: "critical",
|
|
432
|
+
title: `Missing role: ${name}`,
|
|
433
|
+
description: `Role "${name}" exists in source but is missing from target. Any RLS policies or grants referencing this role will be silently ineffective.`,
|
|
434
|
+
sourceValue: sr,
|
|
435
|
+
sql: {
|
|
436
|
+
up: `CREATE ROLE ${quoteName(name)} ${roleAttrs(sr)};`,
|
|
437
|
+
down: `DROP ROLE IF EXISTS ${quoteName(name)};`
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
for (const [name, tr] of targetMap) {
|
|
443
|
+
if (!sourceMap.has(name)) {
|
|
444
|
+
issues.push({
|
|
445
|
+
id: `roles-extra-${name}`,
|
|
446
|
+
check: "roles",
|
|
447
|
+
severity: "warning",
|
|
448
|
+
title: `Extra role: ${name}`,
|
|
449
|
+
description: `Role "${name}" exists in target but not in source.`,
|
|
450
|
+
targetValue: tr,
|
|
451
|
+
sql: {
|
|
452
|
+
up: `DROP ROLE IF EXISTS ${quoteName(name)};`,
|
|
453
|
+
down: `CREATE ROLE ${quoteName(name)} ${roleAttrs(tr)};`
|
|
454
|
+
}
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
for (const [name, sr] of sourceMap) {
|
|
459
|
+
const tr = targetMap.get(name);
|
|
460
|
+
if (tr && !rolesEqual(sr, tr)) {
|
|
461
|
+
issues.push({
|
|
462
|
+
id: `roles-modified-${name}`,
|
|
463
|
+
check: "roles",
|
|
464
|
+
severity: "warning",
|
|
465
|
+
title: `Modified role: ${name}`,
|
|
466
|
+
description: `Role "${name}" has different attributes between source and target.`,
|
|
467
|
+
sourceValue: sr,
|
|
468
|
+
targetValue: tr,
|
|
469
|
+
sql: {
|
|
470
|
+
up: `ALTER ROLE ${quoteName(name)} ${roleAttrs(sr)};`,
|
|
471
|
+
down: `ALTER ROLE ${quoteName(name)} ${roleAttrs(tr)};`
|
|
472
|
+
}
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return issues;
|
|
477
|
+
}
|
|
478
|
+
function grantKey(g) {
|
|
479
|
+
const column = g.column_name ? `.${g.column_name}` : "";
|
|
480
|
+
const routine = g.object_kind === "function" || g.object_kind === "procedure";
|
|
481
|
+
return `${g.grantee}.${g.table_schema}.${g.table_name}${routine ? `(${g.args ?? ""})` : ""}${column}.${g.privilege_type}`;
|
|
482
|
+
}
|
|
483
|
+
function objectSql(g) {
|
|
484
|
+
const name = `${quoteName(g.table_schema)}.${quoteName(g.table_name)}`;
|
|
485
|
+
switch (g.object_kind) {
|
|
486
|
+
case "schema":
|
|
487
|
+
return `SCHEMA ${quoteName(g.table_schema)}`;
|
|
488
|
+
case "sequence":
|
|
489
|
+
return `SEQUENCE ${name}`;
|
|
490
|
+
case "function":
|
|
491
|
+
return `FUNCTION ${name}(${g.args ?? ""})`;
|
|
492
|
+
case "procedure":
|
|
493
|
+
return `PROCEDURE ${name}(${g.args ?? ""})`;
|
|
494
|
+
default:
|
|
495
|
+
return name;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
function describeObject(g) {
|
|
499
|
+
const name = `${g.table_schema}.${g.table_name}`;
|
|
500
|
+
switch (g.object_kind) {
|
|
501
|
+
case "schema":
|
|
502
|
+
return `schema ${g.table_schema}`;
|
|
503
|
+
case "sequence":
|
|
504
|
+
return `sequence ${name}`;
|
|
505
|
+
case "function":
|
|
506
|
+
return `function ${name}(${g.args ?? ""})`;
|
|
507
|
+
case "procedure":
|
|
508
|
+
return `procedure ${name}(${g.args ?? ""})`;
|
|
509
|
+
default:
|
|
510
|
+
return name;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
function granteeSql(grantee) {
|
|
514
|
+
return grantee === "PUBLIC" ? "PUBLIC" : `"${grantee.replace(/"/g, '""')}"`;
|
|
515
|
+
}
|
|
516
|
+
function grantTarget(g) {
|
|
517
|
+
const column = g.column_name ? ` ("${g.column_name.replace(/"/g, '""')}")` : "";
|
|
518
|
+
return `${g.privilege_type}${column} ON ${objectSql(g)}`;
|
|
519
|
+
}
|
|
520
|
+
function describeGrant(g) {
|
|
521
|
+
const column = g.column_name ? `(${g.column_name}) ` : "";
|
|
522
|
+
return `${g.privilege_type} ${column}ON ${describeObject(g)} TO ${g.grantee}`;
|
|
523
|
+
}
|
|
524
|
+
var grantSql = (g, withOption = g.is_grantable) => `GRANT ${grantTarget(g)} TO ${granteeSql(g.grantee)}${withOption ? " WITH GRANT OPTION" : ""};`;
|
|
525
|
+
function comparablePrivileges(sourceVersion, targetVersion) {
|
|
526
|
+
const both = Math.min(sourceVersion || Infinity, targetVersion || Infinity);
|
|
527
|
+
const acrossFifteen = Boolean(sourceVersion && targetVersion) && sourceVersion < 15e4 !== targetVersion < 15e4;
|
|
528
|
+
return (g) => (g.privilege_type !== "MAINTAIN" || both >= 17e4) && !(acrossFifteen && g.object_kind === "schema" && g.table_schema === "public" && g.grantee === "PUBLIC" && g.privilege_type === "CREATE");
|
|
529
|
+
}
|
|
530
|
+
function grouped(grants) {
|
|
531
|
+
const groups = /* @__PURE__ */ new Map();
|
|
532
|
+
for (const g of grants) {
|
|
533
|
+
const key = `${grantKey(g).replace(/\.[^.]+$/, "")}.${Boolean(g.is_grantable)}`;
|
|
534
|
+
groups.set(key, [...groups.get(key) ?? [], g]);
|
|
535
|
+
}
|
|
536
|
+
return [...groups.values()];
|
|
537
|
+
}
|
|
538
|
+
function groupTarget(gs) {
|
|
539
|
+
const column = gs[0].column_name ? ` ("${gs[0].column_name.replace(/"/g, '""')}")` : "";
|
|
540
|
+
return `${gs.map((g) => `${g.privilege_type}${column}`).join(", ")} ON ${objectSql(gs[0])}`;
|
|
541
|
+
}
|
|
542
|
+
function describeGroup(gs) {
|
|
543
|
+
const column = gs[0].column_name ? `(${gs[0].column_name}) ` : "";
|
|
544
|
+
return `${gs.map((g) => g.privilege_type).join(", ")} ${column}ON ${describeObject(gs[0])} TO ${gs[0].grantee}`;
|
|
545
|
+
}
|
|
546
|
+
var groupKey = (gs) => grantKey(gs[0]).replace(/\.[^.]+$/, "");
|
|
547
|
+
function grantsToMissingRoles(grants) {
|
|
548
|
+
const byRole = /* @__PURE__ */ new Map();
|
|
549
|
+
for (const g of grants) byRole.set(g.grantee, [...byRole.get(g.grantee) ?? [], g]);
|
|
550
|
+
return [...byRole].map(([role, gs]) => {
|
|
551
|
+
const groups = grouped(gs);
|
|
552
|
+
const objects = new Set(gs.map((g) => describeObject(g))).size;
|
|
553
|
+
const what = `${gs.length} privilege${gs.length === 1 ? "" : "s"} on ${objects} object${objects === 1 ? "" : "s"}`;
|
|
554
|
+
return {
|
|
555
|
+
id: `roles-grant-missing-role-${role}`,
|
|
556
|
+
check: "roles",
|
|
557
|
+
severity: "warning",
|
|
558
|
+
title: `Missing grants: ${what} to ${role}, a role the target does not have`,
|
|
559
|
+
description: `The source grants ${what} to "${role}", which the target lacks. They can only be applied once the role exists (see "Missing role"); on a target that is not meant to have it, skip the roles check.`,
|
|
560
|
+
sourceValue: gs,
|
|
561
|
+
sql: {
|
|
562
|
+
up: groups.map((g) => `GRANT ${groupTarget(g)} TO ${granteeSql(role)}${g[0].is_grantable ? " WITH GRANT OPTION" : ""};`).join("\n"),
|
|
563
|
+
down: groups.map((g) => `REVOKE ${groupTarget(g)} FROM ${granteeSql(role)};`).reverse().join("\n")
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
function diffGrants(source, target, missingRoles = /* @__PURE__ */ new Set()) {
|
|
569
|
+
const issues = [];
|
|
570
|
+
const sourceMap = new Map(source.map((g) => [grantKey(g), g]));
|
|
571
|
+
const targetMap = new Map(target.map((g) => [grantKey(g), g]));
|
|
572
|
+
const missing = [...sourceMap].filter(([key]) => !targetMap.has(key)).map(([, g]) => g);
|
|
573
|
+
issues.push(...grantsToMissingRoles(missing.filter((g) => missingRoles.has(g.grantee))));
|
|
574
|
+
for (const gs of grouped(missing.filter((g) => !missingRoles.has(g.grantee)))) {
|
|
575
|
+
const plural = gs.length > 1 ? "s" : "";
|
|
576
|
+
issues.push({
|
|
577
|
+
id: `roles-grant-missing-${groupKey(gs)}`,
|
|
578
|
+
check: "roles",
|
|
579
|
+
severity: "warning",
|
|
580
|
+
title: `Missing grant${plural}: ${describeGroup(gs)}`,
|
|
581
|
+
description: `Grant${plural} "${describeGroup(gs)}" ${gs.length > 1 ? "are" : "is"} missing from target.`,
|
|
582
|
+
sourceValue: gs.length > 1 ? gs : gs[0],
|
|
583
|
+
sql: {
|
|
584
|
+
up: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? " WITH GRANT OPTION" : ""};`,
|
|
585
|
+
down: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`
|
|
586
|
+
}
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
for (const [key, sg] of sourceMap) {
|
|
590
|
+
const tg = targetMap.get(key);
|
|
591
|
+
if (tg && Boolean(sg.is_grantable) !== Boolean(tg.is_grantable)) {
|
|
592
|
+
const revokeOption = `REVOKE GRANT OPTION FOR ${grantTarget(sg)} FROM ${granteeSql(sg.grantee)};`;
|
|
593
|
+
issues.push({
|
|
594
|
+
id: `roles-grant-option-${key}`,
|
|
595
|
+
check: "roles",
|
|
596
|
+
severity: "warning",
|
|
597
|
+
title: `Grant option differs: ${describeGrant(sg)}`,
|
|
598
|
+
description: `"${describeGrant(sg)}" is held ${sg.is_grantable ? "with" : "without"} the grant option in source and ${tg.is_grantable ? "with" : "without"} it in target.`,
|
|
599
|
+
sourceValue: sg,
|
|
600
|
+
targetValue: tg,
|
|
601
|
+
sql: sg.is_grantable ? { up: grantSql(sg, true), down: revokeOption } : { up: revokeOption, down: grantSql(tg, true) }
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
const extra = [...targetMap].filter(([key]) => !sourceMap.has(key)).map(([, g]) => g);
|
|
606
|
+
for (const gs of grouped(extra)) {
|
|
607
|
+
const plural = gs.length > 1 ? "s" : "";
|
|
608
|
+
issues.push({
|
|
609
|
+
id: `roles-grant-extra-${groupKey(gs)}`,
|
|
610
|
+
check: "roles",
|
|
611
|
+
severity: extraGrantSeverity(gs[0].grantee),
|
|
612
|
+
title: `Extra grant${plural}: ${describeGroup(gs)}`,
|
|
613
|
+
description: `Grant${plural} "${describeGroup(gs)}" exist${gs.length > 1 ? "" : "s"} in target but not in source.`,
|
|
614
|
+
targetValue: gs.length > 1 ? gs : gs[0],
|
|
615
|
+
sql: {
|
|
616
|
+
up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`,
|
|
617
|
+
down: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? " WITH GRANT OPTION" : ""};`
|
|
618
|
+
}
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
return issues;
|
|
622
|
+
}
|
|
15
623
|
|
|
16
624
|
// src/dbdiff.ts
|
|
17
625
|
import { execFile } from "child_process";
|
|
@@ -144,7 +752,7 @@ var unquote = (part) => {
|
|
|
144
752
|
const p = part.trim();
|
|
145
753
|
return p.startsWith('"') ? p.slice(1, -1).replace(/""/g, '"') : p;
|
|
146
754
|
};
|
|
147
|
-
var
|
|
755
|
+
var objectKey2 = (schema, table, name) => `${(schema || "public").toLowerCase()}.${(table ?? "").toLowerCase()}.${(name ?? "").toLowerCase()}`;
|
|
148
756
|
function schemaQualified(identifier) {
|
|
149
757
|
const parts = identifier.match(new RegExp(NAME_PART, "g")) ?? [identifier];
|
|
150
758
|
const fold = (part) => unquote(part).toLowerCase();
|
|
@@ -192,7 +800,7 @@ var NOT_A_TABLE = /* @__PURE__ */ new Set([
|
|
|
192
800
|
function createdPolicies(sql) {
|
|
193
801
|
const tree = parseStatements(sql);
|
|
194
802
|
if (tree) {
|
|
195
|
-
return tree.filter((s) => s.kind === "CreatePolicyStmt").map(({ node }) =>
|
|
803
|
+
return tree.filter((s) => s.kind === "CreatePolicyStmt").map(({ node }) => objectKey2(node.table?.schemaname, node.table?.relname, node.policy_name));
|
|
196
804
|
}
|
|
197
805
|
const out = [];
|
|
198
806
|
const re = new RegExp(String.raw`CREATE\s+POLICY\s+(${NAME_PART})\s+ON\s+(${IDENT})`, "gi");
|
|
@@ -204,7 +812,7 @@ function createdPolicies(sql) {
|
|
|
204
812
|
function droppedPolicies(sql) {
|
|
205
813
|
const tree = parseStatements(sql);
|
|
206
814
|
if (tree) {
|
|
207
|
-
return tree.filter((s) => s.kind === "DropStmt" && s.node.removeType === "OBJECT_POLICY").flatMap(({ node }) => node.objects.map((o) => (o.List?.items ?? []).map((i) => i.String?.sval)).map((parts) =>
|
|
815
|
+
return tree.filter((s) => s.kind === "DropStmt" && s.node.removeType === "OBJECT_POLICY").flatMap(({ node }) => node.objects.map((o) => (o.List?.items ?? []).map((i) => i.String?.sval)).map((parts) => objectKey2(parts.at(-3), parts.at(-2), parts.at(-1))));
|
|
208
816
|
}
|
|
209
817
|
const out = [];
|
|
210
818
|
const re = new RegExp(String.raw`DROP\s+POLICY\s+(?:IF\s+EXISTS\s+)?(${NAME_PART})\s+ON\s+(${IDENT})`, "gi");
|
|
@@ -357,7 +965,10 @@ function policyOnlyKeys(sql) {
|
|
|
357
965
|
return [.../* @__PURE__ */ new Set([...createdPolicies(sql), ...droppedPolicies(sql)])];
|
|
358
966
|
}
|
|
359
967
|
function rolesOf({ kind, node }) {
|
|
360
|
-
const specs = kind === "GrantStmt" && node.is_grant ? node.grantees ?? [] : kind === "GrantRoleStmt" && node.is_grant ? node.grantee_roles ?? [] : kind === "CreatePolicyStmt" || kind === "AlterPolicyStmt" ? node.roles ?? [] : [
|
|
968
|
+
const specs = kind === "GrantStmt" && node.is_grant ? node.grantees ?? [] : kind === "GrantRoleStmt" && node.is_grant ? node.grantee_roles ?? [] : kind === "CreatePolicyStmt" || kind === "AlterPolicyStmt" ? node.roles ?? [] : kind === "AlterDefaultPrivilegesStmt" ? [
|
|
969
|
+
...(node.options ?? []).filter((o) => o.DefElem?.defname === "roles").flatMap((o) => o.DefElem.arg?.List?.items ?? []),
|
|
970
|
+
...node.action?.is_grant ? node.action.grantees ?? [] : []
|
|
971
|
+
] : [];
|
|
361
972
|
return specs.map((spec) => spec.RoleSpec).filter((role) => role?.roletype === "ROLESPEC_CSTRING" && typeof role.rolename === "string").map((role) => role.rolename).filter((name) => !name.startsWith("pg_"));
|
|
362
973
|
}
|
|
363
974
|
var ROLE_KEYWORDS = /* @__PURE__ */ new Set(["public", "current_user", "current_role", "session_user"]);
|
|
@@ -416,6 +1027,9 @@ var REPLACING_KINDS = {
|
|
|
416
1027
|
|
|
417
1028
|
// src/dbdiff.ts
|
|
418
1029
|
var execFileAsync = promisify(execFile);
|
|
1030
|
+
function dbdiffNotices(stdout) {
|
|
1031
|
+
return stdout.replace(/\u001b\[[0-9;]*m/g, "").split("\n").map((line) => line.trim()).filter((line) => line.startsWith("\u26A0")).map((line) => line.replace(/^⚠\s*/, ""));
|
|
1032
|
+
}
|
|
419
1033
|
function dbdiffNotInstalled(code, stderr) {
|
|
420
1034
|
if (code === "ENOENT") return true;
|
|
421
1035
|
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);
|
|
@@ -455,6 +1069,15 @@ var DBDIFF_NOISE_LINE = /^\s*[ℹ✔✓⚠⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]/u;
|
|
|
455
1069
|
function stripDbDiffNoise(text) {
|
|
456
1070
|
return text.split("\n").filter((line) => line.trim() !== "" && !DBDIFF_NOISE_LINE.test(line)).join("\n").trim();
|
|
457
1071
|
}
|
|
1072
|
+
function snapshotArgs(sourceUrl, targetUrl) {
|
|
1073
|
+
if (snapshotsOff()) return ["--no-snapshot"];
|
|
1074
|
+
const source = heldSnapshot(sourceUrl);
|
|
1075
|
+
const target = heldSnapshot(targetUrl);
|
|
1076
|
+
return [
|
|
1077
|
+
...source ? [`--source-snapshot=${source}`] : [],
|
|
1078
|
+
...target ? [`--target-snapshot=${target}`] : []
|
|
1079
|
+
];
|
|
1080
|
+
}
|
|
458
1081
|
function buildDbDiffArgs(options, outputFile) {
|
|
459
1082
|
const args = [
|
|
460
1083
|
"diff",
|
|
@@ -467,6 +1090,9 @@ function buildDbDiffArgs(options, outputFile) {
|
|
|
467
1090
|
// public interface and did nothing.
|
|
468
1091
|
`--include=${options.include}`,
|
|
469
1092
|
"--nocomments",
|
|
1093
|
+
// The instant the scan reads each side as of, so the schema and data
|
|
1094
|
+
// diffs see what every other check does; or none, under --no-snapshot.
|
|
1095
|
+
...snapshotArgs(options.sourceUrl, options.targetUrl),
|
|
470
1096
|
// @dbdiff/cli >= 3.0.0-rc.3 refuses to emit a migration containing
|
|
471
1097
|
// DROP TABLE or DROP COLUMN unless this is passed, exiting non-zero and
|
|
472
1098
|
// writing no output file. SupaForge is a *detection* tool: an extra table
|
|
@@ -534,13 +1160,14 @@ async function runDbDiff(options) {
|
|
|
534
1160
|
maxBuffer: DBDIFF_MAX_BUFFER
|
|
535
1161
|
});
|
|
536
1162
|
attachProgress(running, options.onProgress);
|
|
537
|
-
await running;
|
|
1163
|
+
const { stdout } = await running;
|
|
1164
|
+
const notices = dbdiffNotices(String(stdout ?? ""));
|
|
538
1165
|
const fileExists = await access(outputFile).then(() => true, () => false);
|
|
539
1166
|
if (!fileExists) {
|
|
540
|
-
return { up: "", down: "" };
|
|
1167
|
+
return { up: "", down: "", notices };
|
|
541
1168
|
}
|
|
542
1169
|
const output = await readFile(outputFile, "utf8");
|
|
543
|
-
return parseDbDiffOutput(output);
|
|
1170
|
+
return { ...parseDbDiffOutput(output), notices };
|
|
544
1171
|
} catch (err) {
|
|
545
1172
|
const errObj = err ?? {};
|
|
546
1173
|
const message = errMsg(err);
|
|
@@ -589,6 +1216,9 @@ function isDestructiveSql(sql) {
|
|
|
589
1216
|
return destructiveReason(sql) !== void 0;
|
|
590
1217
|
}
|
|
591
1218
|
function destructiveReason(sql, recreatedElsewhere = /* @__PURE__ */ new Set()) {
|
|
1219
|
+
if (/\bPGMQ\s*\.\s*"?DROP_QUEUE"?\s*\(/.test(sqlSkeleton(sql).toUpperCase())) {
|
|
1220
|
+
return "drops a queue and the messages in it";
|
|
1221
|
+
}
|
|
592
1222
|
const statements = parseStatements(sql);
|
|
593
1223
|
return statements ? destructiveInTree(statements, recreatedElsewhere) : destructiveInText(sql, recreatedElsewhere);
|
|
594
1224
|
}
|
|
@@ -658,6 +1288,14 @@ function sqlToIssues(result, check, ignoreSchemas, ignoredSchemaTables) {
|
|
|
658
1288
|
const issues = unfoldedIssues(result, check, ignoreSchemas, ignoredSchemaTables);
|
|
659
1289
|
return check === "schema" ? foldCommentsIntoCreates(issues) : issues;
|
|
660
1290
|
}
|
|
1291
|
+
var COMPARED_ELSEWHERE = /^Publication objects are not compared/;
|
|
1292
|
+
function schemaNotices(notices) {
|
|
1293
|
+
return notices.filter((n) => !COMPARED_ELSEWHERE.test(n)).map((notice) => {
|
|
1294
|
+
const [what, advice] = notice.split(" \u2014 ");
|
|
1295
|
+
const title = /not compared/.test(what) ? `Not compared: ${what.replace(/ objects are not compared/, "")}` : what;
|
|
1296
|
+
return advice ? `${title} \u2014 ${advice}.` : `${title}.`;
|
|
1297
|
+
});
|
|
1298
|
+
}
|
|
661
1299
|
var COMMENT_TITLE = /^(?:Comment changed|Comment missing): (?:schema (.+)|(.+) \(([a-z ]+)\))$/;
|
|
662
1300
|
var CREATE_TITLE = /^(Schema|Table|View|Function|Procedure|Type|Domain|Sequence|Index|Policy|Trigger|Extension) (?:missing|modified): (.+)$/;
|
|
663
1301
|
var ON_A_TABLE = /* @__PURE__ */ new Set(["column", "constraint", "trigger", "policy", "rule"]);
|
|
@@ -743,8 +1381,14 @@ function unfoldedIssues(result, check, ignoreSchemas, ignoredSchemaTables) {
|
|
|
743
1381
|
};
|
|
744
1382
|
});
|
|
745
1383
|
}
|
|
1384
|
+
function platformDefaultPrivileges(sql) {
|
|
1385
|
+
const role = /^\s*ALTER\s+DEFAULT\s+PRIVILEGES\s+FOR\s+ROLE\s+("(?:[^"]|"")+"|[\w$]+)/i.exec(sql)?.[1];
|
|
1386
|
+
if (!role) return false;
|
|
1387
|
+
const name = role.startsWith('"') ? role.slice(1, -1).replace(/""/g, '"') : role.toLowerCase();
|
|
1388
|
+
return name !== "postgres" && PLATFORM_ROLES.includes(name);
|
|
1389
|
+
}
|
|
746
1390
|
function issuesFromUnits(upUnits, downUnits, check, ignoreSchemas, ignoredSchemaTables) {
|
|
747
|
-
const pairs = pairUnits(upUnits, downUnits).filter(({ up, down }) => !(ignoreSchemas?.length && isCrossSchemaFkUnit(up, down, ignoreSchemas, ignoredSchemaTables)));
|
|
1391
|
+
const pairs = pairUnits(upUnits, downUnits).filter(({ up, down }) => !(ignoreSchemas?.length && isCrossSchemaFkUnit(up, down, ignoreSchemas, ignoredSchemaTables)) && !platformDefaultPrivileges(up.sql));
|
|
748
1392
|
return pairs.map(({ up, down }, i) => {
|
|
749
1393
|
const upSql = up.sql;
|
|
750
1394
|
const downSql = down?.sql ?? "";
|
|
@@ -764,6 +1408,18 @@ function issuesFromUnits(upUnits, downUnits, check, ignoreSchemas, ignoredSchema
|
|
|
764
1408
|
...manual
|
|
765
1409
|
};
|
|
766
1410
|
}
|
|
1411
|
+
const modified = modifiedTitle(up, statements);
|
|
1412
|
+
if (modified) {
|
|
1413
|
+
return {
|
|
1414
|
+
id: `${check}-alter-${up.kind.replace(/^Alter/, "").toLowerCase()}-${i + 1}`,
|
|
1415
|
+
check,
|
|
1416
|
+
severity: "warning",
|
|
1417
|
+
title: modified,
|
|
1418
|
+
description: "Definition differs between source and target.",
|
|
1419
|
+
sql: { up: upSql, down: downSql },
|
|
1420
|
+
...manual
|
|
1421
|
+
};
|
|
1422
|
+
}
|
|
767
1423
|
const lead = leadStatement(up, statements);
|
|
768
1424
|
const type = classifyStatement(lead);
|
|
769
1425
|
return {
|
|
@@ -808,6 +1464,28 @@ function replacedView(unit, statements) {
|
|
|
808
1464
|
return named2 ? { kind: "view", name: REPLACEABLE_NAME.view(named2) } : void 0;
|
|
809
1465
|
}
|
|
810
1466
|
var bareName2 = (name) => name.slice(name.lastIndexOf(".") + 1).replace(/"/g, "").toLowerCase();
|
|
1467
|
+
var MODIFIED_KINDS = {
|
|
1468
|
+
AlterRangeType: "Type modified",
|
|
1469
|
+
AlterAggregate: "Aggregate modified",
|
|
1470
|
+
AlterRule: "Rule modified",
|
|
1471
|
+
AlterStatistics: "Statistics modified",
|
|
1472
|
+
AlterEventTrigger: "Event trigger modified",
|
|
1473
|
+
AlterCast: "Cast modified",
|
|
1474
|
+
AlterTextSearchConfiguration: "Text search configuration modified",
|
|
1475
|
+
AlterTextSearchDictionary: "Text search dictionary modified",
|
|
1476
|
+
AlterForeignServer: "Foreign server modified",
|
|
1477
|
+
AlterUserMapping: "User mapping modified",
|
|
1478
|
+
AlterForeignTable: "Foreign table modified",
|
|
1479
|
+
AlterDefaultPrivileges: "Default privileges differ"
|
|
1480
|
+
};
|
|
1481
|
+
function modifiedTitle(unit, statements) {
|
|
1482
|
+
const label = MODIFIED_KINDS[unit.kind];
|
|
1483
|
+
if (!label) return void 0;
|
|
1484
|
+
const making = statements.find((sql) => !/^\s*DROP\b/i.test(sql)) ?? statements[0];
|
|
1485
|
+
const summary = making ? summariseStatement(making, "schema") : "";
|
|
1486
|
+
const name = summary.slice(summary.indexOf(": ") + 2);
|
|
1487
|
+
return `${label}: ${name || unit.object}`;
|
|
1488
|
+
}
|
|
811
1489
|
function leadStatement(unit, statements) {
|
|
812
1490
|
if (unit.kind.startsWith("AlterTable")) {
|
|
813
1491
|
const alter = statements.find((sql) => /^\s*ALTER\s+TABLE\b/i.test(sql));
|
|
@@ -1103,9 +1781,40 @@ var AFTER = {
|
|
|
1103
1781
|
index: /\bINDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i,
|
|
1104
1782
|
policy: /\bPOLICY\s+(?:IF\s+EXISTS\s+)?/i,
|
|
1105
1783
|
collation: /\bCOLLATION\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i,
|
|
1784
|
+
eventTrigger: /\bEVENT\s+TRIGGER\s+(?:IF\s+EXISTS\s+)?/i,
|
|
1785
|
+
aggregate: /\bAGGREGATE\s+(?:IF\s+EXISTS\s+)?/i,
|
|
1786
|
+
statistics: /\bSTATISTICS\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i,
|
|
1787
|
+
textSearch: /\bTEXT\s+SEARCH\s+(?:CONFIGURATION|DICTIONARY)\s+(?:IF\s+EXISTS\s+)?/i,
|
|
1788
|
+
server: /\bSERVER\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i,
|
|
1789
|
+
foreignTable: /\bFOREIGN\s+TABLE\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?/i,
|
|
1106
1790
|
on: /\bON\s+(?:ONLY\s+)?/i
|
|
1107
1791
|
};
|
|
1108
1792
|
var named = (head) => (sql) => extractQualifiedName(sql, head);
|
|
1793
|
+
function renameLabel(sql) {
|
|
1794
|
+
const table = extractQualifiedName(sql, /\b(?:TABLE|INDEX)\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?/i);
|
|
1795
|
+
const to = /\bTO\s+("(?:[^"]|"")*"|[\w$]+)\s*;?\s*$/i.exec(sql.trim())?.[1];
|
|
1796
|
+
const from = /\bRENAME\s+(?:COLUMN|CONSTRAINT)\s+("(?:[^"]|"")*"|[\w$]+)/i.exec(sql)?.[1];
|
|
1797
|
+
return `${qualifySchemaName(table)}${from ? "." + unquoted(from) : ""} \u2192 ${to ? unquoted(to) : UNKNOWN_NAME}`;
|
|
1798
|
+
}
|
|
1799
|
+
function defaultPrivilegesLabel(sql) {
|
|
1800
|
+
const role = /\bFOR\s+ROLE\s+("(?:[^"]|"")*"|\S+)/i.exec(sql)?.[1];
|
|
1801
|
+
const schema = /\bIN\s+SCHEMA\s+("(?:[^"]|"")*"|\S+)/i.exec(sql)?.[1];
|
|
1802
|
+
const kind = /\bON\s+(TABLES|SEQUENCES|FUNCTIONS|ROUTINES|TYPES|SCHEMAS)\b/i.exec(sql)?.[1];
|
|
1803
|
+
return [role && unquoted(role), schema ? `in ${unquoted(schema)}` : "in every schema", kind && `on ${kind.toLowerCase()}`].filter(Boolean).join(" ");
|
|
1804
|
+
}
|
|
1805
|
+
function ruleLabel(sql) {
|
|
1806
|
+
const rule = extractQualifiedName(sql, /\bRULE\s+(?:IF\s+EXISTS\s+)?/i);
|
|
1807
|
+
const table = /\bTO\s+((?:"(?:[^"]|"")*"|[\w$]+)(?:\.(?:"(?:[^"]|"")*"|[\w$]+))?)/i.exec(sql)?.[1] ?? /\bON\s+((?:"(?:[^"]|"")*"|[\w$]+)(?:\.(?:"(?:[^"]|"")*"|[\w$]+))?)/i.exec(sql)?.[1];
|
|
1808
|
+
return table ? `${unquoted(table.split(".").pop() ?? table)}.${rule.split(".").pop()}` : rule;
|
|
1809
|
+
}
|
|
1810
|
+
function castLabel(sql) {
|
|
1811
|
+
return /\(([^()]+?\s+AS\s+[^()]+?)\)/i.exec(sql)?.[1] ?? UNKNOWN_NAME;
|
|
1812
|
+
}
|
|
1813
|
+
function userMappingLabel(sql) {
|
|
1814
|
+
const user = /\bFOR\s+("(?:[^"]|"")*"|\S+)/i.exec(sql)?.[1] ?? "unknown";
|
|
1815
|
+
const server = /\bSERVER\s+("(?:[^"]|"")*"|[^\s;]+)/i.exec(sql)?.[1] ?? "unknown";
|
|
1816
|
+
return `${unquoted(user)}@${unquoted(server)}`;
|
|
1817
|
+
}
|
|
1109
1818
|
function policyLabel(sql) {
|
|
1110
1819
|
const policy = extractQualifiedName(sql, AFTER.policy);
|
|
1111
1820
|
const table = extractQualifiedName(sql, AFTER.on);
|
|
@@ -1157,6 +1866,10 @@ var SCHEMA_RULES = [
|
|
|
1157
1866
|
{ match: /^\s*CREATE\s+DOMAIN\b/i, label: "Domain missing", name: named(AFTER.domain) },
|
|
1158
1867
|
{ match: /^\s*ALTER\s+DOMAIN\b/i, label: "Domain altered", name: named(AFTER.domain) },
|
|
1159
1868
|
{ match: /^\s*DROP\s+DOMAIN\b/i, label: "Extra domain", name: named(AFTER.domain) },
|
|
1869
|
+
{ match: /^\s*ALTER\s+TABLE\b[^;]*\bRENAME\s+COLUMN\b/is, label: "Column renamed", name: renameLabel, unqualified: true },
|
|
1870
|
+
{ match: /^\s*ALTER\s+TABLE\b[^;]*\bRENAME\s+CONSTRAINT\b/is, label: "Constraint renamed", name: renameLabel, unqualified: true },
|
|
1871
|
+
{ match: /^\s*ALTER\s+TABLE\b[^;]*\bRENAME\s+TO\b/is, label: "Table renamed", name: renameLabel, unqualified: true },
|
|
1872
|
+
{ match: /^\s*ALTER\s+INDEX\b[^;]*\bRENAME\s+TO\b/is, label: "Index renamed", name: renameLabel, unqualified: true },
|
|
1160
1873
|
{ match: /^\s*ALTER\s+TABLE\b/i, label: "Table altered", name: named(AFTER.table) },
|
|
1161
1874
|
{ match: /^\s*CREATE\s+TABLE\b/i, label: "Table missing", name: named(AFTER.table) },
|
|
1162
1875
|
{ match: /^\s*DROP\s+TABLE\b/i, label: "Extra table", name: named(AFTER.table) },
|
|
@@ -1178,6 +1891,28 @@ var SCHEMA_RULES = [
|
|
|
1178
1891
|
{ match: /^\s*CREATE\s+COLLATION\b/i, label: "Collation missing", name: named(AFTER.collation) },
|
|
1179
1892
|
{ match: /^\s*ALTER\s+COLLATION\b/i, label: "Collation altered", name: named(AFTER.collation) },
|
|
1180
1893
|
{ match: /^\s*DROP\s+COLLATION\b/i, label: "Extra collation", name: named(AFTER.collation) },
|
|
1894
|
+
{ match: /^\s*ALTER\s+DEFAULT\s+PRIVILEGES\b/i, label: "Default privileges differ", name: defaultPrivilegesLabel, unqualified: true },
|
|
1895
|
+
{ match: /^\s*CREATE\s+EVENT\s+TRIGGER\b/i, label: "Event trigger missing", name: named(AFTER.eventTrigger) },
|
|
1896
|
+
{ match: /^\s*DROP\s+EVENT\s+TRIGGER\b/i, label: "Extra event trigger", name: named(AFTER.eventTrigger) },
|
|
1897
|
+
{ match: /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?RULE\b/i, label: "Rule missing", name: ruleLabel },
|
|
1898
|
+
{ match: /^\s*DROP\s+RULE\b/i, label: "Extra rule", name: ruleLabel },
|
|
1899
|
+
{ match: /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?AGGREGATE\b/i, label: "Aggregate missing", name: named(AFTER.aggregate) },
|
|
1900
|
+
{ match: /^\s*DROP\s+AGGREGATE\b/i, label: "Extra aggregate", name: named(AFTER.aggregate) },
|
|
1901
|
+
{ match: /^\s*CREATE\s+STATISTICS\b/i, label: "Statistics missing", name: named(AFTER.statistics) },
|
|
1902
|
+
{ match: /^\s*DROP\s+STATISTICS\b/i, label: "Extra statistics", name: named(AFTER.statistics) },
|
|
1903
|
+
{ match: /^\s*(?:CREATE|ALTER)\s+TEXT\s+SEARCH\s+CONFIGURATION\b/i, label: "Text search configuration missing", name: named(AFTER.textSearch) },
|
|
1904
|
+
{ match: /^\s*DROP\s+TEXT\s+SEARCH\s+CONFIGURATION\b/i, label: "Extra text search configuration", name: named(AFTER.textSearch) },
|
|
1905
|
+
{ match: /^\s*CREATE\s+TEXT\s+SEARCH\s+DICTIONARY\b/i, label: "Text search dictionary missing", name: named(AFTER.textSearch) },
|
|
1906
|
+
{ match: /^\s*DROP\s+TEXT\s+SEARCH\s+DICTIONARY\b/i, label: "Extra text search dictionary", name: named(AFTER.textSearch) },
|
|
1907
|
+
{ match: /^\s*CREATE\s+CAST\b/i, label: "Cast missing", name: castLabel, unqualified: true },
|
|
1908
|
+
{ match: /^\s*DROP\s+CAST\b/i, label: "Extra cast", name: castLabel, unqualified: true },
|
|
1909
|
+
{ match: /^\s*CREATE\s+SERVER\b/i, label: "Foreign server missing", name: named(AFTER.server) },
|
|
1910
|
+
{ match: /^\s*ALTER\s+SERVER\b/i, label: "Foreign server altered", name: named(AFTER.server) },
|
|
1911
|
+
{ match: /^\s*DROP\s+SERVER\b/i, label: "Extra foreign server", name: named(AFTER.server) },
|
|
1912
|
+
{ match: /^\s*(?:CREATE|ALTER)\s+USER\s+MAPPING\b/i, label: "User mapping missing", name: userMappingLabel, unqualified: true },
|
|
1913
|
+
{ match: /^\s*DROP\s+USER\s+MAPPING\b/i, label: "Extra user mapping", name: userMappingLabel, unqualified: true },
|
|
1914
|
+
{ match: /^\s*CREATE\s+FOREIGN\s+TABLE\b/i, label: "Foreign table missing", name: named(AFTER.foreignTable) },
|
|
1915
|
+
{ match: /^\s*DROP\s+FOREIGN\s+TABLE\b/i, label: "Extra foreign table", name: named(AFTER.foreignTable) },
|
|
1181
1916
|
{ match: /^\s*CREATE\s+SEQUENCE\b/i, label: "Sequence missing", name: named(AFTER.sequence) },
|
|
1182
1917
|
{ match: /^\s*ALTER\s+SEQUENCE\b/i, label: "Sequence altered", name: named(AFTER.sequence) },
|
|
1183
1918
|
{ match: /^\s*DROP\s+SEQUENCE\b/i, label: "Extra sequence", name: named(AFTER.sequence) }
|
|
@@ -1225,7 +1960,8 @@ function summariseStatement(sql, check, downSql) {
|
|
|
1225
1960
|
for (const rule of SCHEMA_RULES) {
|
|
1226
1961
|
if (rule.match.test(sql)) {
|
|
1227
1962
|
const label = rule.name === commentLabel ? commentChange(sql, downSql) : rule.label;
|
|
1228
|
-
|
|
1963
|
+
const name = rule.name(sql, downSql);
|
|
1964
|
+
return `${label}: ${rule.unqualified ? name : qualifySchemaName(name)}`;
|
|
1229
1965
|
}
|
|
1230
1966
|
}
|
|
1231
1967
|
return `Schema change: ${qualifySchemaName(
|
|
@@ -1273,24 +2009,502 @@ function extractRoutineArgs(sql) {
|
|
|
1273
2009
|
}
|
|
1274
2010
|
return "";
|
|
1275
2011
|
}
|
|
2012
|
+
function rolesAddressed(sql) {
|
|
2013
|
+
const names2 = (specs = []) => specs.map((s) => s.RoleSpec).filter((r) => r?.roletype === "ROLESPEC_CSTRING" && typeof r.rolename === "string" && !r.rolename.startsWith("pg_")).map((r) => r.rolename);
|
|
2014
|
+
return (parseStatements(sql) ?? []).flatMap(({ kind, node }) => kind === "GrantStmt" ? names2(node.grantees) : kind === "CreatePolicyStmt" || kind === "AlterPolicyStmt" ? names2(node.roles) : kind === "AlterDefaultPrivilegesStmt" ? [...names2(node.action?.grantees), ...names2((node.options ?? []).filter((o) => o.DefElem?.defname === "roles").flatMap((o) => o.DefElem.arg?.List?.items ?? []))] : []);
|
|
2015
|
+
}
|
|
2016
|
+
function withoutAbsentRoles(issues, targetRoles) {
|
|
2017
|
+
const absentIn = (sql) => rolesAddressed(sql).filter((r) => !targetRoles.has(r));
|
|
2018
|
+
return issues.map((issue) => {
|
|
2019
|
+
if (!issue.sql) return issue;
|
|
2020
|
+
const missing = /* @__PURE__ */ new Set();
|
|
2021
|
+
const keep = (sql) => splitStatements(sql).filter((statement) => {
|
|
2022
|
+
const absent = absentIn(statement);
|
|
2023
|
+
absent.forEach((r) => missing.add(r));
|
|
2024
|
+
return absent.length === 0;
|
|
2025
|
+
});
|
|
2026
|
+
const up = keep(issue.sql.up);
|
|
2027
|
+
if (missing.size === 0) return issue;
|
|
2028
|
+
const down = keep(issue.sql.down ?? "");
|
|
2029
|
+
const roles = [...missing].sort().join(", ") + (missing.size > 1 ? ", roles" : ", a role");
|
|
2030
|
+
if (up.length === 0) return { ...issue, manualOnly: `it names ${roles} the target does not have` };
|
|
2031
|
+
return {
|
|
2032
|
+
...issue,
|
|
2033
|
+
description: `${issue.description} What it grants to ${roles} the target does not have is left out.`,
|
|
2034
|
+
sql: { up: up.join("\n"), down: down.join("\n") }
|
|
2035
|
+
};
|
|
2036
|
+
});
|
|
2037
|
+
}
|
|
2038
|
+
|
|
2039
|
+
// src/pg-errors.ts
|
|
2040
|
+
var ABSENT_ON_TARGET = /* @__PURE__ */ new Set(["42P01", "42883", "3F000", "42704"]);
|
|
2041
|
+
var UNDEFINED_COLUMN = "42703";
|
|
2042
|
+
var EXTENSION_UNAVAILABLE = /* @__PURE__ */ new Set(["0A000", "58P01"]);
|
|
2043
|
+
function sqlState(err) {
|
|
2044
|
+
const code = err?.code;
|
|
2045
|
+
return typeof code === "string" ? code : void 0;
|
|
2046
|
+
}
|
|
2047
|
+
var OLDER_SERVER = /* @__PURE__ */ new Set(["42601", "0A000", "22023"]);
|
|
2048
|
+
|
|
2049
|
+
// src/lock-budget.ts
|
|
2050
|
+
var INDEXED = /* @__PURE__ */ new Set(["CONSTR_PRIMARY", "CONSTR_UNIQUE", "CONSTR_EXCLUSION"]);
|
|
2051
|
+
function estimateLocks(statements) {
|
|
2052
|
+
const relations = /* @__PURE__ */ new Set();
|
|
2053
|
+
let made = 0;
|
|
2054
|
+
for (const sql of statements) {
|
|
2055
|
+
const parsed = parseStatements(sql);
|
|
2056
|
+
if (!parsed) {
|
|
2057
|
+
made += 1;
|
|
2058
|
+
continue;
|
|
2059
|
+
}
|
|
2060
|
+
for (const { kind, node } of parsed) {
|
|
2061
|
+
if (kind === "CreateStmt") made += 2;
|
|
2062
|
+
if (kind === "IndexStmt") made += 1;
|
|
2063
|
+
walk(node, (key, value) => {
|
|
2064
|
+
if (typeof value.relname === "string") relations.add(`${value.schemaname ?? ""}.${value.relname}`.toLowerCase());
|
|
2065
|
+
if (key === "Constraint" && (INDEXED.has(value.contype) || value.contype === "CONSTR_IDENTITY")) made += 1;
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
return relations.size + made;
|
|
2070
|
+
}
|
|
2071
|
+
function walk(node, visit) {
|
|
2072
|
+
if (Array.isArray(node)) {
|
|
2073
|
+
for (const item of node) walk(item, visit);
|
|
2074
|
+
} else if (node && typeof node === "object") {
|
|
2075
|
+
for (const [key, value] of Object.entries(node)) {
|
|
2076
|
+
if (value && typeof value === "object" && !Array.isArray(value)) visit(key, value);
|
|
2077
|
+
walk(value, visit);
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
async function readLockBudget(client) {
|
|
2082
|
+
try {
|
|
2083
|
+
const { rows: [row] } = await client.query(`
|
|
2084
|
+
SELECT current_setting('max_locks_per_transaction')::bigint
|
|
2085
|
+
* (current_setting('max_connections')::bigint
|
|
2086
|
+
+ coalesce(current_setting('autovacuum_worker_slots', true), current_setting('autovacuum_max_workers'))::bigint + 1
|
|
2087
|
+
+ current_setting('max_worker_processes')::bigint
|
|
2088
|
+
+ current_setting('max_wal_senders')::bigint
|
|
2089
|
+
+ current_setting('max_prepared_transactions')::bigint) AS capacity,
|
|
2090
|
+
(SELECT count(*) FROM pg_locks WHERE NOT fastpath) AS in_use`);
|
|
2091
|
+
return { capacity: Number(row.capacity), inUse: Number(row.in_use) };
|
|
2092
|
+
} catch {
|
|
2093
|
+
return void 0;
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
function lockBudgetWarning(needed, budget, what) {
|
|
2097
|
+
if (!budget) return void 0;
|
|
2098
|
+
const free = budget.capacity - budget.inUse - Math.ceil(budget.capacity / 10);
|
|
2099
|
+
if (needed <= free) return void 0;
|
|
2100
|
+
return `${what} takes about ${needed} locks in one transaction, and the target has room for about ${Math.max(free, 0)} (max_locks_per_transaction for each connection slot, less what other sessions hold). It may fail with "out of shared memory" and roll back. Raising max_locks_per_transaction on the target (a restart) makes room; --no-transaction commits as it goes instead.`;
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
// src/promote.ts
|
|
2104
|
+
function outOfScopeReason(sql, filter) {
|
|
2105
|
+
if (!isFiltered(filter)) return null;
|
|
2106
|
+
const referenced = referencedTables(sql);
|
|
2107
|
+
if (referenced.length === 0) return null;
|
|
2108
|
+
const excluded = referenced.filter((t) => applyTableFilter([t], filter).length === 0);
|
|
2109
|
+
if (excluded.length === 0) return null;
|
|
2110
|
+
const names2 = excluded.map((t) => `'${t}'`).join(", ");
|
|
2111
|
+
const flag = filter?.tables?.length ? "--tables" : "--exclude-tables";
|
|
2112
|
+
const noun = excluded.length === 1 ? "table" : "tables";
|
|
2113
|
+
return `Depends on ${noun} ${names2}, excluded by ${flag}`;
|
|
2114
|
+
}
|
|
2115
|
+
function isSelected(issueId, only) {
|
|
2116
|
+
if (!only?.length) return true;
|
|
2117
|
+
return only.some((pattern) => matchesGlob(issueId, pattern));
|
|
2118
|
+
}
|
|
2119
|
+
function withDefaultGrantRevokes(scanResult, only) {
|
|
2120
|
+
if (!only?.length) return only;
|
|
2121
|
+
const issues = scanResult.checks.flatMap((c) => c.issues);
|
|
2122
|
+
const created = new Set(issues.filter((i) => i.sql?.up && isSelected(i.id, only)).flatMap((i) => relationsCreatedBy(i.sql.up)));
|
|
2123
|
+
if (created.size === 0) return only;
|
|
2124
|
+
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);
|
|
2125
|
+
return [...only, ...companions];
|
|
2126
|
+
}
|
|
2127
|
+
function relationsCreatedBy(sql) {
|
|
2128
|
+
const statements = parseStatements(sql);
|
|
2129
|
+
if (!statements) return [];
|
|
2130
|
+
return statements.flatMap(({ kind, node }) => {
|
|
2131
|
+
if (kind === "CreateFunctionStmt") {
|
|
2132
|
+
const parts = (node.funcname ?? []).map((n) => n.String?.sval ?? "");
|
|
2133
|
+
const name = parts.at(-1);
|
|
2134
|
+
return name ? [`${(parts.length > 1 ? parts.at(-2) : "public").toLowerCase()}.${name.toLowerCase()}(`] : [];
|
|
2135
|
+
}
|
|
2136
|
+
const rel = kind === "CreateStmt" ? node.relation : kind === "ViewStmt" ? node.view : kind === "CreateTableAsStmt" ? node.into?.rel : void 0;
|
|
2137
|
+
return rel?.relname ? [`${(rel.schemaname || "public").toLowerCase()}.${String(rel.relname).toLowerCase()}`] : [];
|
|
2138
|
+
});
|
|
2139
|
+
}
|
|
2140
|
+
function classifyIssue(issue, options, recreatedPolicies = /* @__PURE__ */ new Set()) {
|
|
2141
|
+
if (!isSelected(issue.id, options.only)) {
|
|
2142
|
+
return { kind: "skip", reason: "Not selected by --only" };
|
|
2143
|
+
}
|
|
2144
|
+
if (issue.manualOnly) return { kind: "skip", reason: issue.manualOnly };
|
|
2145
|
+
if (!issue.sql?.up) {
|
|
2146
|
+
if (issue.action?.method === "DELETE" && !options.allowDestructive) {
|
|
2147
|
+
return { kind: "skip", reason: `Destructive \u2014 ${issue.action.label}; re-run with --allow-destructive to apply` };
|
|
2148
|
+
}
|
|
2149
|
+
if (issue.action) return { kind: "api", action: issue.action };
|
|
2150
|
+
return { kind: "skip", reason: issue.manualOnly ?? "No SQL fix or API action available" };
|
|
2151
|
+
}
|
|
2152
|
+
if (!options.allowDestructive) {
|
|
2153
|
+
const why = issue.destructive ?? destructiveReason(issue.sql.up, recreatedPolicies);
|
|
2154
|
+
if (why) {
|
|
2155
|
+
return { kind: "skip", reason: `Destructive \u2014 ${why}; re-run with --allow-destructive to apply` };
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
const outOfScope = outOfScopeReason(issue.sql.up, options.tableFilter);
|
|
2159
|
+
if (outOfScope) return { kind: "skip", reason: outOfScope };
|
|
2160
|
+
return { kind: "sql", sql: issue.sql.up };
|
|
2161
|
+
}
|
|
2162
|
+
function policiesCreatedBySelectedFixes(checks, options) {
|
|
2163
|
+
const created = /* @__PURE__ */ new Set();
|
|
2164
|
+
for (const check of checks) {
|
|
2165
|
+
const askedForExplicitly = options.checks?.includes(check.check) ?? false;
|
|
2166
|
+
if (!isComparisonCheck(check.check) && !options.applyPosture && !askedForExplicitly) continue;
|
|
2167
|
+
for (const issue of check.issues) {
|
|
2168
|
+
const sql = issue.sql?.up;
|
|
2169
|
+
if (!sql || !isSelected(issue.id, options.only)) continue;
|
|
2170
|
+
if (!options.allowDestructive && destructiveReason(sql)) continue;
|
|
2171
|
+
if (outOfScopeReason(sql, options.tableFilter)) continue;
|
|
2172
|
+
for (const key of createdPolicies(sql)) created.add(key);
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
return created;
|
|
2176
|
+
}
|
|
2177
|
+
function planWork(scanResult, options = {}) {
|
|
2178
|
+
options = { ...options, only: withDefaultGrantRevokes(scanResult, options.only) };
|
|
2179
|
+
const plan = { sqlStatements: [], apiActions: [], skipped: [] };
|
|
2180
|
+
const relevant = scanResult.checks.filter(
|
|
2181
|
+
(c) => c.status === "drifted" && (!options.checks || options.checks.includes(c.check))
|
|
2182
|
+
);
|
|
2183
|
+
const recreatedPolicies = policiesCreatedBySelectedFixes(relevant, options);
|
|
2184
|
+
const keptBack = [];
|
|
2185
|
+
for (const checkResult of relevant) {
|
|
2186
|
+
const askedForExplicitly = options.checks?.includes(checkResult.check) ?? false;
|
|
2187
|
+
if (!isComparisonCheck(checkResult.check) && !options.applyPosture && !askedForExplicitly) {
|
|
2188
|
+
for (const issue of checkResult.issues) {
|
|
2189
|
+
plan.skipped.push({
|
|
2190
|
+
check: checkResult.check,
|
|
2191
|
+
issueId: issue.id,
|
|
2192
|
+
reason: "Posture finding about the target, not drift from the source \u2014 applying it would create drift. Use --apply-posture to apply anyway."
|
|
2193
|
+
});
|
|
2194
|
+
}
|
|
2195
|
+
continue;
|
|
2196
|
+
}
|
|
2197
|
+
for (const issue of checkResult.issues) {
|
|
2198
|
+
const at = { check: checkResult.check, issueId: issue.id };
|
|
2199
|
+
const outcome = classifyIssue(issue, options, recreatedPolicies);
|
|
2200
|
+
if (outcome.kind === "sql") plan.sqlStatements.push({ ...at, sql: outcome.sql });
|
|
2201
|
+
else if (outcome.kind === "api") plan.apiActions.push({ ...at, action: outcome.action });
|
|
2202
|
+
else {
|
|
2203
|
+
plan.skipped.push({ ...at, reason: outcome.reason });
|
|
2204
|
+
if (outcome.reason.startsWith("Destructive") && issue.sql?.down) {
|
|
2205
|
+
keptBack.push({ issueId: issue.id, definition: issue.sql.down });
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
plan.sqlStatements = holdBackDropsStillInUse(plan.sqlStatements, keptBack, plan.skipped, downsOf(relevant));
|
|
2211
|
+
const dbdiffOrder = new Map(plan.sqlStatements.filter((s) => s.check === "schema").map((s, i) => [s, i]));
|
|
2212
|
+
plan.sqlStatements = orderStatements(plan.sqlStatements, (s) => s.sql, (s) => dbdiffOrder.get(s));
|
|
2213
|
+
plan.sqlStatements = dropDuplicateObjectFixes(plan.sqlStatements, plan.skipped);
|
|
2214
|
+
return plan;
|
|
2215
|
+
}
|
|
2216
|
+
var DROPS_SUPPORTING_OBJECT = /^\s*DROP\s+(?:TYPE|DOMAIN|FUNCTION|PROCEDURE|ROUTINE|SEQUENCE)\s+(?:IF\s+EXISTS\s+)?((?:"[^"]+"|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|[\w$]+))?)/i;
|
|
2217
|
+
function holdBackDropsStillInUse(statements, keptBack, skipped, downs = /* @__PURE__ */ new Map()) {
|
|
2218
|
+
const kept = keptBack.map((k) => ({ issueId: k.issueId, skeleton: sqlSkeleton(k.definition) }));
|
|
2219
|
+
let remaining = statements;
|
|
2220
|
+
for (let changed = kept.length > 0; changed; ) {
|
|
2221
|
+
changed = false;
|
|
2222
|
+
remaining = remaining.filter((statement) => {
|
|
2223
|
+
const names2 = droppedSupportingObjects(statement.sql);
|
|
2224
|
+
if (names2.length === 0) return true;
|
|
2225
|
+
const user = kept.find((k) => names2.some((n) => identifierMatcher(bareName(n)).test(k.skeleton)));
|
|
2226
|
+
if (!user) return true;
|
|
2227
|
+
skipped.push({
|
|
2228
|
+
check: statement.check,
|
|
2229
|
+
issueId: statement.issueId,
|
|
2230
|
+
reason: `Still used by what ${user.issueId} keeps, which is held back as destructive; re-run with --allow-destructive to apply both`
|
|
2231
|
+
});
|
|
2232
|
+
const definition = downs.get(statement.issueId);
|
|
2233
|
+
if (definition) kept.push({ issueId: user.issueId, skeleton: sqlSkeleton(definition) });
|
|
2234
|
+
changed = true;
|
|
2235
|
+
return false;
|
|
2236
|
+
});
|
|
2237
|
+
}
|
|
2238
|
+
return remaining;
|
|
2239
|
+
}
|
|
2240
|
+
function droppedSupportingObjects(sql) {
|
|
2241
|
+
const parts = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
|
|
2242
|
+
const names2 = parts.map((s) => DROPS_SUPPORTING_OBJECT.exec(sqlSkeleton(s))?.[1]);
|
|
2243
|
+
return names2.length > 0 && names2.every((n) => n !== void 0) ? names2 : [];
|
|
2244
|
+
}
|
|
2245
|
+
function downsOf(checks) {
|
|
2246
|
+
const downs = /* @__PURE__ */ new Map();
|
|
2247
|
+
for (const check of checks) {
|
|
2248
|
+
for (const issue of check.issues) {
|
|
2249
|
+
if (issue.sql?.down) downs.set(issue.id, issue.sql.down);
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
return downs;
|
|
2253
|
+
}
|
|
2254
|
+
function dropDuplicateObjectFixes(statements, skipped) {
|
|
2255
|
+
const kinds = [
|
|
2256
|
+
{ what: "policy", created: createdPolicies, onlyThis: createsOnlyPolicies, seen: /* @__PURE__ */ new Set() },
|
|
2257
|
+
{ what: "trigger", created: createdTriggers, onlyThis: createsOnlyTriggers, seen: /* @__PURE__ */ new Set() }
|
|
2258
|
+
];
|
|
2259
|
+
const kept = [];
|
|
2260
|
+
for (const statement of statements) {
|
|
2261
|
+
const duplicate = kinds.find((kind) => {
|
|
2262
|
+
const names2 = kind.created(statement.sql);
|
|
2263
|
+
return names2.length > 0 && names2.every((n) => kind.seen.has(n)) && kind.onlyThis(statement.sql);
|
|
2264
|
+
});
|
|
2265
|
+
if (duplicate) {
|
|
2266
|
+
skipped.push({
|
|
2267
|
+
check: statement.check,
|
|
2268
|
+
issueId: statement.issueId,
|
|
2269
|
+
reason: `Already created by the schema fix for the same ${duplicate.what}`
|
|
2270
|
+
});
|
|
2271
|
+
continue;
|
|
2272
|
+
}
|
|
2273
|
+
for (const kind of kinds) {
|
|
2274
|
+
for (const name of kind.created(statement.sql)) kind.seen.add(name);
|
|
2275
|
+
}
|
|
2276
|
+
kept.push(statement);
|
|
2277
|
+
}
|
|
2278
|
+
return kept;
|
|
2279
|
+
}
|
|
2280
|
+
async function executeSql(dbUrl, statements, result, transactional, sourceMajor) {
|
|
2281
|
+
if (statements.length === 0) return;
|
|
2282
|
+
const client = newPgClient(dbUrl);
|
|
2283
|
+
await client.connect();
|
|
2284
|
+
try {
|
|
2285
|
+
const olderTarget = sourceMajor !== void 0 && await majorOf(client) < sourceMajor;
|
|
2286
|
+
if (transactional) await runInTransaction(client, statements, result, olderTarget);
|
|
2287
|
+
else await runIndependently(client, statements, result);
|
|
2288
|
+
} finally {
|
|
2289
|
+
await client.end();
|
|
2290
|
+
}
|
|
2291
|
+
}
|
|
2292
|
+
async function runLikeApply(dbUrl, statements, sourceMajor) {
|
|
2293
|
+
const result = { applied: [], skipped: [], errors: [] };
|
|
2294
|
+
await executeSql(dbUrl, statements, result, true, sourceMajor);
|
|
2295
|
+
return result;
|
|
2296
|
+
}
|
|
2297
|
+
async function majorOf(client) {
|
|
2298
|
+
const { rows: [row] } = await client.query(`SELECT current_setting('server_version_num') AS v`);
|
|
2299
|
+
return Math.floor(Number(row?.v ?? 0) / 1e4);
|
|
2300
|
+
}
|
|
2301
|
+
async function serverMajor(dbUrl) {
|
|
2302
|
+
const client = newPgClient(dbUrl);
|
|
2303
|
+
try {
|
|
2304
|
+
await client.connect();
|
|
2305
|
+
return await majorOf(client);
|
|
2306
|
+
} catch {
|
|
2307
|
+
return void 0;
|
|
2308
|
+
} finally {
|
|
2309
|
+
await client.end().catch(() => {
|
|
2310
|
+
});
|
|
2311
|
+
}
|
|
2312
|
+
}
|
|
2313
|
+
async function runIndependently(client, statements, result) {
|
|
2314
|
+
for (const stmt of statements) {
|
|
2315
|
+
try {
|
|
2316
|
+
await client.query(stmt.sql);
|
|
2317
|
+
result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
|
|
2318
|
+
} catch (err) {
|
|
2319
|
+
result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) });
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
}
|
|
2323
|
+
function isEnumValueAddition(sql) {
|
|
2324
|
+
const statements = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
|
|
2325
|
+
return statements.length > 0 && statements.every((s) => /^\s*ALTER\s+TYPE\s+\S+\s+ADD\s+VALUE\b/i.test(sqlSkeleton(s)));
|
|
2326
|
+
}
|
|
2327
|
+
async function runInTransaction(client, statements, result, olderTarget = false) {
|
|
2328
|
+
const additions = statements.filter((s) => isEnumValueAddition(s.sql));
|
|
2329
|
+
const rest = statements.filter((s) => !isEnumValueAddition(s.sql));
|
|
2330
|
+
const warning = lockBudgetWarning(estimateLocks(rest.map((s) => s.sql)), await readLockBudget(client), "This apply");
|
|
2331
|
+
if (warning) result.warnings = [...result.warnings ?? [], warning];
|
|
2332
|
+
if (additions.length > 0 && !await runBatch(client, additions, result, olderTarget)) return;
|
|
2333
|
+
await runBatch(client, rest, result, olderTarget);
|
|
2334
|
+
}
|
|
2335
|
+
function unmetDependency(sql, err, olderTarget = false) {
|
|
2336
|
+
const code = sqlState(err);
|
|
2337
|
+
if (!code) return void 0;
|
|
2338
|
+
if (olderTarget && OLDER_SERVER.has(code)) {
|
|
2339
|
+
return "the target's PostgreSQL is older than the source's and does not support it";
|
|
2340
|
+
}
|
|
2341
|
+
if (/(?:^|;)\s*CREATE\s+EXTENSION\b/i.test(sqlSkeleton(sql))) {
|
|
2342
|
+
return EXTENSION_UNAVAILABLE.has(code) ? "this server does not ship it" : void 0;
|
|
2343
|
+
}
|
|
2344
|
+
if (ABSENT_ON_TARGET.has(code) || code === UNDEFINED_COLUMN) {
|
|
2345
|
+
return "it needs something the target does not have";
|
|
2346
|
+
}
|
|
2347
|
+
return void 0;
|
|
2348
|
+
}
|
|
2349
|
+
function revokesFromAbsent(sql) {
|
|
2350
|
+
const statements = parseStatements(sql);
|
|
2351
|
+
if (!statements?.length) return false;
|
|
2352
|
+
const targets = /* @__PURE__ */ new Set();
|
|
2353
|
+
for (const { kind, node } of statements) {
|
|
2354
|
+
if (kind !== "GrantStmt" || node.is_grant || node.targtype !== "ACL_TARGET_OBJECT") return false;
|
|
2355
|
+
if ((node.objects ?? []).length !== 1) return false;
|
|
2356
|
+
targets.add(JSON.stringify([node.objtype, node.objects[0]], (key, value) => key === "location" ? void 0 : value));
|
|
2357
|
+
}
|
|
2358
|
+
return targets.size === 1;
|
|
2359
|
+
}
|
|
2360
|
+
async function runBatch(client, statements, result, olderTarget = false) {
|
|
2361
|
+
if (statements.length === 0) return true;
|
|
2362
|
+
const done = [];
|
|
2363
|
+
await client.query("BEGIN");
|
|
2364
|
+
let pending = statements;
|
|
2365
|
+
let unmet = [];
|
|
2366
|
+
while (pending.length > 0) {
|
|
2367
|
+
unmet = [];
|
|
2368
|
+
for (const stmt of pending) {
|
|
2369
|
+
await client.query("SAVEPOINT sf_fix");
|
|
2370
|
+
try {
|
|
2371
|
+
await client.query(stmt.sql);
|
|
2372
|
+
await client.query("RELEASE SAVEPOINT sf_fix");
|
|
2373
|
+
done.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
|
|
2374
|
+
} catch (err) {
|
|
2375
|
+
const why = unmetDependency(stmt.sql, err, olderTarget);
|
|
2376
|
+
if (why && await client.query("ROLLBACK TO SAVEPOINT sf_fix").then(() => true, () => false)) {
|
|
2377
|
+
unmet.push({ stmt, err, why });
|
|
2378
|
+
continue;
|
|
2379
|
+
}
|
|
2380
|
+
await client.query("ROLLBACK").catch(() => {
|
|
2381
|
+
});
|
|
2382
|
+
result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) });
|
|
2383
|
+
result.rolledBack = [...result.rolledBack ?? [], ...done];
|
|
2384
|
+
return false;
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
if (unmet.length === pending.length) break;
|
|
2388
|
+
pending = unmet.map((u) => u.stmt);
|
|
2389
|
+
}
|
|
2390
|
+
const gone = unmet.filter((u) => revokesFromAbsent(u.stmt.sql));
|
|
2391
|
+
unmet = unmet.filter((u) => !gone.includes(u));
|
|
2392
|
+
for (const { stmt } of gone) {
|
|
2393
|
+
done.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql, note: "nothing to revoke: the object is not on the target" });
|
|
2394
|
+
}
|
|
2395
|
+
await client.query("COMMIT");
|
|
2396
|
+
result.applied.push(...done);
|
|
2397
|
+
for (const { stmt, err, why } of unmet) {
|
|
2398
|
+
result.errors.push({
|
|
2399
|
+
check: stmt.check,
|
|
2400
|
+
issueId: stmt.issueId,
|
|
2401
|
+
error: `${errMsg(err)} \u2014 not applied: ${why}. The other fixes were.`
|
|
2402
|
+
});
|
|
2403
|
+
}
|
|
2404
|
+
return true;
|
|
2405
|
+
}
|
|
2406
|
+
async function executeApiActions(actions, fetchFn, result) {
|
|
2407
|
+
for (const act of actions) {
|
|
2408
|
+
try {
|
|
2409
|
+
const init = {
|
|
2410
|
+
method: act.action.method,
|
|
2411
|
+
headers: { "Content-Type": "application/json", ...act.action.headers }
|
|
2412
|
+
};
|
|
2413
|
+
if (act.action.body !== void 0) {
|
|
2414
|
+
init.body = JSON.stringify(act.action.body);
|
|
2415
|
+
}
|
|
2416
|
+
const res = await fetchFn(act.action.url, init);
|
|
2417
|
+
if (!res.ok) {
|
|
2418
|
+
const text = await res.text().catch(() => res.statusText);
|
|
2419
|
+
throw new Error(`${act.action.method} ${act.action.url} \u2192 ${res.status}: ${text}`);
|
|
2420
|
+
}
|
|
2421
|
+
result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label });
|
|
2422
|
+
} catch (err) {
|
|
2423
|
+
result.errors.push({ check: act.check, issueId: act.issueId, error: errMsg(err) });
|
|
2424
|
+
}
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
async function promote(options) {
|
|
2428
|
+
const {
|
|
2429
|
+
dbUrl,
|
|
2430
|
+
scanResult,
|
|
2431
|
+
checks,
|
|
2432
|
+
dryRun = false,
|
|
2433
|
+
allowDestructive = false,
|
|
2434
|
+
tableFilter,
|
|
2435
|
+
only,
|
|
2436
|
+
applyPosture = false,
|
|
2437
|
+
transactional = true,
|
|
2438
|
+
fetchFn = globalThis.fetch.bind(globalThis)
|
|
2439
|
+
} = options;
|
|
2440
|
+
const { sqlStatements, apiActions, skipped } = planWork(scanResult, {
|
|
2441
|
+
checks,
|
|
2442
|
+
allowDestructive,
|
|
2443
|
+
tableFilter,
|
|
2444
|
+
only,
|
|
2445
|
+
applyPosture
|
|
2446
|
+
});
|
|
2447
|
+
const result = { applied: [], skipped, errors: [] };
|
|
2448
|
+
if (dryRun) {
|
|
2449
|
+
for (const stmt of sqlStatements) {
|
|
2450
|
+
result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
|
|
2451
|
+
}
|
|
2452
|
+
for (const act of apiActions) {
|
|
2453
|
+
result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label });
|
|
2454
|
+
}
|
|
2455
|
+
return result;
|
|
2456
|
+
}
|
|
2457
|
+
await executeSql(
|
|
2458
|
+
dbUrl,
|
|
2459
|
+
sqlStatements,
|
|
2460
|
+
result,
|
|
2461
|
+
transactional,
|
|
2462
|
+
options.sourceUrl ? await serverMajor(options.sourceUrl) : void 0
|
|
2463
|
+
);
|
|
2464
|
+
if (result.rolledBack) {
|
|
2465
|
+
for (const act of apiActions) {
|
|
2466
|
+
result.skipped.push({
|
|
2467
|
+
check: act.check,
|
|
2468
|
+
issueId: act.issueId,
|
|
2469
|
+
reason: "Not attempted \u2014 the SQL fixes were rolled back"
|
|
2470
|
+
});
|
|
2471
|
+
}
|
|
2472
|
+
return result;
|
|
2473
|
+
}
|
|
2474
|
+
await executeApiActions(apiActions, fetchFn, result);
|
|
2475
|
+
return result;
|
|
2476
|
+
}
|
|
1276
2477
|
|
|
1277
2478
|
export {
|
|
1278
2479
|
parseStatements,
|
|
2480
|
+
relationName,
|
|
1279
2481
|
sqlSkeleton,
|
|
1280
|
-
bareName,
|
|
1281
|
-
createdPolicies,
|
|
1282
|
-
createsOnlyPolicies,
|
|
1283
|
-
createdTriggers,
|
|
1284
|
-
createsOnlyTriggers,
|
|
1285
|
-
referencedTables,
|
|
1286
|
-
identifierMatcher,
|
|
1287
|
-
orderStatements,
|
|
1288
2482
|
statementSubject,
|
|
1289
2483
|
policyOnlyKeys,
|
|
1290
2484
|
rolesNamedBy,
|
|
2485
|
+
resolveTableFilter,
|
|
2486
|
+
isFiltered,
|
|
2487
|
+
describeTableFilter,
|
|
2488
|
+
applyTableFilter,
|
|
2489
|
+
CHECK_NAMES,
|
|
2490
|
+
CHECK_META,
|
|
2491
|
+
isComparisonCheck,
|
|
2492
|
+
PLATFORM_ROLES,
|
|
2493
|
+
RolesCheck,
|
|
1291
2494
|
runDbDiff,
|
|
1292
2495
|
isDestructiveSql,
|
|
1293
2496
|
destructiveReason,
|
|
1294
|
-
sqlToIssues
|
|
2497
|
+
sqlToIssues,
|
|
2498
|
+
schemaNotices,
|
|
2499
|
+
withoutAbsentRoles,
|
|
2500
|
+
ABSENT_ON_TARGET,
|
|
2501
|
+
EXTENSION_UNAVAILABLE,
|
|
2502
|
+
OLDER_SERVER,
|
|
2503
|
+
estimateLocks,
|
|
2504
|
+
readLockBudget,
|
|
2505
|
+
lockBudgetWarning,
|
|
2506
|
+
planWork,
|
|
2507
|
+
runLikeApply,
|
|
2508
|
+
promote
|
|
1295
2509
|
};
|
|
1296
|
-
//# sourceMappingURL=chunk-
|
|
2510
|
+
//# sourceMappingURL=chunk-YUJ2MHLM.js.map
|