@culpritsql/ci 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/README.md +249 -2
- package/dist/cli.d.ts +32 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +2880 -0
- package/dist/cli.js.map +1 -0
- package/dist/glob.d.ts +10 -0
- package/dist/glob.d.ts.map +1 -0
- package/dist/glob.js +162 -0
- package/dist/glob.js.map +1 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +145 -0
- package/dist/index.js.map +1 -0
- package/dist/lexer.d.ts +48 -0
- package/dist/lexer.d.ts.map +1 -0
- package/dist/lexer.js +612 -0
- package/dist/lexer.js.map +1 -0
- package/dist/linter.d.ts +9 -0
- package/dist/linter.d.ts.map +1 -0
- package/dist/linter.js +1317 -0
- package/dist/linter.js.map +1 -0
- package/dist/plans.d.ts +18 -0
- package/dist/plans.d.ts.map +1 -0
- package/dist/plans.js +398 -0
- package/dist/plans.js.map +1 -0
- package/dist/reporters.d.ts +79 -0
- package/dist/reporters.d.ts.map +1 -0
- package/dist/reporters.js +256 -0
- package/dist/reporters.js.map +1 -0
- package/dist/share.d.ts +44 -0
- package/dist/share.d.ts.map +1 -0
- package/dist/share.js +79 -0
- package/dist/share.js.map +1 -0
- package/dist/types.d.ts +125 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +52 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,2880 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
5
|
+
import path3 from "node:path";
|
|
6
|
+
|
|
7
|
+
// src/index.ts
|
|
8
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
9
|
+
import path2 from "node:path";
|
|
10
|
+
|
|
11
|
+
// src/glob.ts
|
|
12
|
+
import { readdir, stat } from "node:fs/promises";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
function expandBraces(pattern) {
|
|
15
|
+
const open = pattern.indexOf("{");
|
|
16
|
+
if (open === -1) return [pattern];
|
|
17
|
+
const close = pattern.indexOf("}", open);
|
|
18
|
+
if (close === -1) return [pattern];
|
|
19
|
+
const prefix = pattern.slice(0, open);
|
|
20
|
+
const suffix = pattern.slice(close + 1);
|
|
21
|
+
const choices = pattern.slice(open + 1, close).split(",");
|
|
22
|
+
const results = [];
|
|
23
|
+
for (const choice of choices) {
|
|
24
|
+
for (const expanded of expandBraces(`${prefix}${choice}${suffix}`)) {
|
|
25
|
+
results.push(expanded);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return results;
|
|
29
|
+
}
|
|
30
|
+
function globToRegExp(globPattern) {
|
|
31
|
+
const normalized = globPattern.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
32
|
+
let regex = "^";
|
|
33
|
+
let i = 0;
|
|
34
|
+
while (i < normalized.length) {
|
|
35
|
+
const ch = normalized[i];
|
|
36
|
+
if (ch === "*") {
|
|
37
|
+
if (normalized[i + 1] === "*") {
|
|
38
|
+
if (normalized[i + 2] === "/") {
|
|
39
|
+
regex += "(?:.*/)?";
|
|
40
|
+
i += 3;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
regex += ".*";
|
|
44
|
+
i += 2;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
regex += "[^/]*";
|
|
48
|
+
i += 1;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (ch === "?") {
|
|
52
|
+
regex += "[^/]";
|
|
53
|
+
i += 1;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if ("+.^$|()[]{}".includes(ch)) {
|
|
57
|
+
regex += `\\${ch}`;
|
|
58
|
+
} else {
|
|
59
|
+
regex += ch;
|
|
60
|
+
}
|
|
61
|
+
i += 1;
|
|
62
|
+
}
|
|
63
|
+
regex += "$";
|
|
64
|
+
return new RegExp(regex);
|
|
65
|
+
}
|
|
66
|
+
function hasGlobMagic(pattern) {
|
|
67
|
+
return /[*?{}]/.test(pattern);
|
|
68
|
+
}
|
|
69
|
+
function staticBaseDir(pattern) {
|
|
70
|
+
const normalized = pattern.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
71
|
+
const segments = normalized.split("/");
|
|
72
|
+
const staticParts = [];
|
|
73
|
+
for (const seg of segments) {
|
|
74
|
+
if (hasGlobMagic(seg)) break;
|
|
75
|
+
staticParts.push(seg);
|
|
76
|
+
}
|
|
77
|
+
if (staticParts.length === 0) return ".";
|
|
78
|
+
return staticParts.join("/");
|
|
79
|
+
}
|
|
80
|
+
async function walkDirectory(dir, rootCwd, out) {
|
|
81
|
+
let entries;
|
|
82
|
+
try {
|
|
83
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
84
|
+
} catch {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
for (const entry of entries) {
|
|
88
|
+
if (entry.name === ".git" || entry.name === "node_modules" || entry.name === "dist") {
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const full = path.join(dir, entry.name);
|
|
92
|
+
if (entry.isDirectory()) {
|
|
93
|
+
await walkDirectory(full, rootCwd, out);
|
|
94
|
+
} else if (entry.isFile()) {
|
|
95
|
+
const rel = path.relative(rootCwd, full).split(path.sep).join("/");
|
|
96
|
+
out.push(rel);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function toRelativeDisplayPath(filePath, cwd = process.cwd()) {
|
|
101
|
+
const resolved = path.resolve(cwd, filePath);
|
|
102
|
+
const rel = path.relative(cwd, resolved).split(path.sep).join("/");
|
|
103
|
+
if (!rel.startsWith("..") && !path.isAbsolute(rel)) {
|
|
104
|
+
return rel || path.basename(resolved);
|
|
105
|
+
}
|
|
106
|
+
return path.basename(resolved);
|
|
107
|
+
}
|
|
108
|
+
async function resolveSqlInputs(patterns, cwd = process.cwd()) {
|
|
109
|
+
const splitPatterns = [];
|
|
110
|
+
for (const raw of patterns) {
|
|
111
|
+
for (const part of raw.split(/\r?\n/)) {
|
|
112
|
+
const trimmed = part.trim();
|
|
113
|
+
if (!trimmed) continue;
|
|
114
|
+
for (const expanded of expandBraces(trimmed)) {
|
|
115
|
+
splitPatterns.push(expanded);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const found = /* @__PURE__ */ new Map();
|
|
120
|
+
for (const pat of splitPatterns) {
|
|
121
|
+
if (!hasGlobMagic(pat)) {
|
|
122
|
+
const abs = path.resolve(cwd, pat);
|
|
123
|
+
try {
|
|
124
|
+
const st = await stat(abs);
|
|
125
|
+
if (st.isFile()) {
|
|
126
|
+
found.set(abs, toRelativeDisplayPath(abs, cwd));
|
|
127
|
+
} else if (st.isDirectory()) {
|
|
128
|
+
const allInDir = [];
|
|
129
|
+
await walkDirectory(abs, cwd, allInDir);
|
|
130
|
+
for (const rel of allInDir) {
|
|
131
|
+
if (rel.endsWith(".sql")) {
|
|
132
|
+
found.set(path.resolve(cwd, rel), rel);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
} catch {
|
|
137
|
+
throw new Error(`SQL input path does not exist: ${pat}`);
|
|
138
|
+
}
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
const isAbsGlob = path.isAbsolute(pat);
|
|
142
|
+
const searchRoot = isAbsGlob ? staticBaseDir(pat) || "/" : path.resolve(cwd, staticBaseDir(pat));
|
|
143
|
+
const walkBase = isAbsGlob ? searchRoot : cwd;
|
|
144
|
+
const candidates = [];
|
|
145
|
+
await walkDirectory(searchRoot, walkBase, candidates);
|
|
146
|
+
const matcher = globToRegExp(isAbsGlob ? path.relative(walkBase, pat) : pat);
|
|
147
|
+
for (const rel of candidates) {
|
|
148
|
+
if (matcher.test(rel)) {
|
|
149
|
+
const abs = path.resolve(walkBase, rel);
|
|
150
|
+
found.set(abs, toRelativeDisplayPath(abs, cwd));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return [...found.entries()].map(([absPath, displayPath]) => ({ absPath, displayPath })).sort((a, b) => a.displayPath.localeCompare(b.displayPath));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// src/lexer.ts
|
|
158
|
+
var PRAGMA_FILE_RE = /culprit-ignore-file\s*:?\s*([A-Za-z0-9_,\s*]+)/gi;
|
|
159
|
+
var PRAGMA_STMT_RE = /culprit-ignore(?!-file)\s*:?\s*([A-Za-z0-9_,\s*]+)/gi;
|
|
160
|
+
function parseRuleList(rawList, target) {
|
|
161
|
+
const tokens = rawList.split(/[\s,]+/).map((s) => s.trim().toUpperCase()).filter(Boolean);
|
|
162
|
+
for (const tok of tokens) {
|
|
163
|
+
if (tok === "ALL" || tok === "*") {
|
|
164
|
+
target.add("*");
|
|
165
|
+
} else if (/^(MIG|QRY|PLAN)\d{3}$/.test(tok)) {
|
|
166
|
+
target.add(tok);
|
|
167
|
+
} else {
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
function extractIgnorePragmas(commentRaw, stmtRules, fileRules) {
|
|
173
|
+
if (fileRules) {
|
|
174
|
+
PRAGMA_FILE_RE.lastIndex = 0;
|
|
175
|
+
let fileMatch = PRAGMA_FILE_RE.exec(commentRaw);
|
|
176
|
+
while (fileMatch) {
|
|
177
|
+
parseRuleList(fileMatch[1] ?? "", fileRules);
|
|
178
|
+
fileMatch = PRAGMA_FILE_RE.exec(commentRaw);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
PRAGMA_STMT_RE.lastIndex = 0;
|
|
182
|
+
let stmtMatch = PRAGMA_STMT_RE.exec(commentRaw);
|
|
183
|
+
while (stmtMatch) {
|
|
184
|
+
parseRuleList(stmtMatch[1] ?? "", stmtRules);
|
|
185
|
+
stmtMatch = PRAGMA_STMT_RE.exec(commentRaw);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function isAsciiLetter(code) {
|
|
189
|
+
return code >= 65 && code <= 90 || code >= 97 && code <= 122;
|
|
190
|
+
}
|
|
191
|
+
function isAsciiDigit(code) {
|
|
192
|
+
return code >= 48 && code <= 57;
|
|
193
|
+
}
|
|
194
|
+
function isWordStart(code) {
|
|
195
|
+
return isAsciiLetter(code) || code === 95 || code === 64 || code === 35 || code > 127;
|
|
196
|
+
}
|
|
197
|
+
function isWordPart(code) {
|
|
198
|
+
return isWordStart(code) || isAsciiDigit(code) || code === 36;
|
|
199
|
+
}
|
|
200
|
+
function matchDollarQuoteTag(sql, index) {
|
|
201
|
+
if (sql.charCodeAt(index) !== 36) return null;
|
|
202
|
+
let cursor = index + 1;
|
|
203
|
+
if (cursor < sql.length && sql.charCodeAt(cursor) === 36) {
|
|
204
|
+
return "$$";
|
|
205
|
+
}
|
|
206
|
+
if (cursor >= sql.length) return null;
|
|
207
|
+
const first = sql.charCodeAt(cursor);
|
|
208
|
+
if (!isAsciiLetter(first) && first !== 95 && first <= 127) {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
cursor += 1;
|
|
212
|
+
while (cursor < sql.length) {
|
|
213
|
+
const ch = sql.charCodeAt(cursor);
|
|
214
|
+
if (ch === 36) {
|
|
215
|
+
return sql.slice(index, cursor + 1);
|
|
216
|
+
}
|
|
217
|
+
if (!isAsciiLetter(ch) && !isAsciiDigit(ch) && ch !== 95 && ch <= 127) {
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
cursor += 1;
|
|
221
|
+
}
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
function tokenizeSql(sql) {
|
|
225
|
+
const tokens = [];
|
|
226
|
+
const len = sql.length;
|
|
227
|
+
let i = 0;
|
|
228
|
+
let line = 1;
|
|
229
|
+
let col = 1;
|
|
230
|
+
const advance = (count = 1) => {
|
|
231
|
+
for (let step = 0; step < count && i < len; step++) {
|
|
232
|
+
const ch = sql.charCodeAt(i);
|
|
233
|
+
if (ch === 10) {
|
|
234
|
+
i += 1;
|
|
235
|
+
line += 1;
|
|
236
|
+
col = 1;
|
|
237
|
+
} else if (ch === 13) {
|
|
238
|
+
i += 1;
|
|
239
|
+
if (i < len && sql.charCodeAt(i) === 10) {
|
|
240
|
+
col += 1;
|
|
241
|
+
} else {
|
|
242
|
+
line += 1;
|
|
243
|
+
col = 1;
|
|
244
|
+
}
|
|
245
|
+
} else {
|
|
246
|
+
i += 1;
|
|
247
|
+
col += 1;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
while (i < len) {
|
|
252
|
+
const ch = sql.charCodeAt(i);
|
|
253
|
+
if (ch === 32 || ch === 9 || ch === 10 || ch === 13 || ch === 12) {
|
|
254
|
+
advance(1);
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
const startOffset = i;
|
|
258
|
+
const startLine = line;
|
|
259
|
+
const startCol = col;
|
|
260
|
+
if (ch === 45 && i + 1 < len && sql.charCodeAt(i + 1) === 45) {
|
|
261
|
+
advance(2);
|
|
262
|
+
while (i < len && sql.charCodeAt(i) !== 10 && sql.charCodeAt(i) !== 13) {
|
|
263
|
+
advance(1);
|
|
264
|
+
}
|
|
265
|
+
const raw2 = sql.slice(startOffset, i);
|
|
266
|
+
tokens.push({
|
|
267
|
+
kind: "comment",
|
|
268
|
+
raw: raw2,
|
|
269
|
+
upper: "",
|
|
270
|
+
ident: "",
|
|
271
|
+
line: startLine,
|
|
272
|
+
column: startCol,
|
|
273
|
+
endLine: line,
|
|
274
|
+
endColumn: col,
|
|
275
|
+
offset: startOffset,
|
|
276
|
+
endOffset: i
|
|
277
|
+
});
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
if (ch === 47 && i + 1 < len && sql.charCodeAt(i + 1) === 42) {
|
|
281
|
+
let depth = 1;
|
|
282
|
+
advance(2);
|
|
283
|
+
while (i < len && depth > 0) {
|
|
284
|
+
if (sql.charCodeAt(i) === 47 && i + 1 < len && sql.charCodeAt(i + 1) === 42) {
|
|
285
|
+
depth += 1;
|
|
286
|
+
advance(2);
|
|
287
|
+
} else if (sql.charCodeAt(i) === 42 && i + 1 < len && sql.charCodeAt(i + 1) === 47) {
|
|
288
|
+
depth -= 1;
|
|
289
|
+
advance(2);
|
|
290
|
+
} else {
|
|
291
|
+
advance(1);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
const raw2 = sql.slice(startOffset, i);
|
|
295
|
+
tokens.push({
|
|
296
|
+
kind: "comment",
|
|
297
|
+
raw: raw2,
|
|
298
|
+
upper: "",
|
|
299
|
+
ident: "",
|
|
300
|
+
line: startLine,
|
|
301
|
+
column: startCol,
|
|
302
|
+
endLine: line,
|
|
303
|
+
endColumn: col,
|
|
304
|
+
offset: startOffset,
|
|
305
|
+
endOffset: i
|
|
306
|
+
});
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if ((ch === 69 || ch === 101 || ch === 78 || ch === 110 || ch === 88 || ch === 120 || ch === 66 || ch === 98) && i + 1 < len && sql.charCodeAt(i + 1) === 39) {
|
|
310
|
+
const isEscapeString = ch === 69 || ch === 101;
|
|
311
|
+
advance(2);
|
|
312
|
+
while (i < len) {
|
|
313
|
+
const c = sql.charCodeAt(i);
|
|
314
|
+
if (isEscapeString && c === 92 && i + 1 < len) {
|
|
315
|
+
advance(2);
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
if (c === 39) {
|
|
319
|
+
advance(1);
|
|
320
|
+
if (i < len && sql.charCodeAt(i) === 39) {
|
|
321
|
+
advance(1);
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
advance(1);
|
|
327
|
+
}
|
|
328
|
+
const raw2 = sql.slice(startOffset, i);
|
|
329
|
+
tokens.push({
|
|
330
|
+
kind: "string",
|
|
331
|
+
raw: raw2,
|
|
332
|
+
upper: raw2.toUpperCase(),
|
|
333
|
+
ident: "",
|
|
334
|
+
line: startLine,
|
|
335
|
+
column: startCol,
|
|
336
|
+
endLine: line,
|
|
337
|
+
endColumn: col,
|
|
338
|
+
offset: startOffset,
|
|
339
|
+
endOffset: i
|
|
340
|
+
});
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
if (ch === 39) {
|
|
344
|
+
advance(1);
|
|
345
|
+
while (i < len) {
|
|
346
|
+
const c = sql.charCodeAt(i);
|
|
347
|
+
if (c === 39) {
|
|
348
|
+
advance(1);
|
|
349
|
+
if (i < len && sql.charCodeAt(i) === 39) {
|
|
350
|
+
advance(1);
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
355
|
+
advance(1);
|
|
356
|
+
}
|
|
357
|
+
const raw2 = sql.slice(startOffset, i);
|
|
358
|
+
tokens.push({
|
|
359
|
+
kind: "string",
|
|
360
|
+
raw: raw2,
|
|
361
|
+
upper: raw2.toUpperCase(),
|
|
362
|
+
ident: "",
|
|
363
|
+
line: startLine,
|
|
364
|
+
column: startCol,
|
|
365
|
+
endLine: line,
|
|
366
|
+
endColumn: col,
|
|
367
|
+
offset: startOffset,
|
|
368
|
+
endOffset: i
|
|
369
|
+
});
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
if (ch === 36) {
|
|
373
|
+
const tag = matchDollarQuoteTag(sql, i);
|
|
374
|
+
if (tag) {
|
|
375
|
+
advance(tag.length);
|
|
376
|
+
const closeIdx = sql.indexOf(tag, i);
|
|
377
|
+
if (closeIdx === -1) {
|
|
378
|
+
advance(len - i);
|
|
379
|
+
} else {
|
|
380
|
+
advance(closeIdx - i + tag.length);
|
|
381
|
+
}
|
|
382
|
+
const raw2 = sql.slice(startOffset, i);
|
|
383
|
+
tokens.push({
|
|
384
|
+
kind: "string",
|
|
385
|
+
raw: raw2,
|
|
386
|
+
upper: "",
|
|
387
|
+
ident: "",
|
|
388
|
+
line: startLine,
|
|
389
|
+
column: startCol,
|
|
390
|
+
endLine: line,
|
|
391
|
+
endColumn: col,
|
|
392
|
+
offset: startOffset,
|
|
393
|
+
endOffset: i
|
|
394
|
+
});
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
if (i + 1 < len && isAsciiDigit(sql.charCodeAt(i + 1))) {
|
|
398
|
+
advance(1);
|
|
399
|
+
while (i < len && isAsciiDigit(sql.charCodeAt(i))) {
|
|
400
|
+
advance(1);
|
|
401
|
+
}
|
|
402
|
+
const raw2 = sql.slice(startOffset, i);
|
|
403
|
+
tokens.push({
|
|
404
|
+
kind: "punct",
|
|
405
|
+
raw: raw2,
|
|
406
|
+
upper: raw2,
|
|
407
|
+
ident: "",
|
|
408
|
+
line: startLine,
|
|
409
|
+
column: startCol,
|
|
410
|
+
endLine: line,
|
|
411
|
+
endColumn: col,
|
|
412
|
+
offset: startOffset,
|
|
413
|
+
endOffset: i
|
|
414
|
+
});
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
if (ch === 34 || ch === 96) {
|
|
419
|
+
const quote = ch;
|
|
420
|
+
advance(1);
|
|
421
|
+
let inner = "";
|
|
422
|
+
while (i < len) {
|
|
423
|
+
const c = sql.charCodeAt(i);
|
|
424
|
+
if (c === quote) {
|
|
425
|
+
advance(1);
|
|
426
|
+
if (i < len && sql.charCodeAt(i) === quote) {
|
|
427
|
+
inner += String.fromCharCode(quote);
|
|
428
|
+
advance(1);
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
break;
|
|
432
|
+
}
|
|
433
|
+
inner += sql[i];
|
|
434
|
+
advance(1);
|
|
435
|
+
}
|
|
436
|
+
const raw2 = sql.slice(startOffset, i);
|
|
437
|
+
tokens.push({
|
|
438
|
+
kind: "quoted_ident",
|
|
439
|
+
raw: raw2,
|
|
440
|
+
upper: inner.toUpperCase(),
|
|
441
|
+
ident: inner.toLowerCase(),
|
|
442
|
+
line: startLine,
|
|
443
|
+
column: startCol,
|
|
444
|
+
endLine: line,
|
|
445
|
+
endColumn: col,
|
|
446
|
+
offset: startOffset,
|
|
447
|
+
endOffset: i
|
|
448
|
+
});
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
if (ch === 91) {
|
|
452
|
+
advance(1);
|
|
453
|
+
let inner = "";
|
|
454
|
+
while (i < len) {
|
|
455
|
+
const c = sql.charCodeAt(i);
|
|
456
|
+
if (c === 93) {
|
|
457
|
+
advance(1);
|
|
458
|
+
if (i < len && sql.charCodeAt(i) === 93) {
|
|
459
|
+
inner += "]";
|
|
460
|
+
advance(1);
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
break;
|
|
464
|
+
}
|
|
465
|
+
inner += sql[i];
|
|
466
|
+
advance(1);
|
|
467
|
+
}
|
|
468
|
+
const raw2 = sql.slice(startOffset, i);
|
|
469
|
+
tokens.push({
|
|
470
|
+
kind: "quoted_ident",
|
|
471
|
+
raw: raw2,
|
|
472
|
+
upper: inner.toUpperCase(),
|
|
473
|
+
ident: inner.toLowerCase(),
|
|
474
|
+
line: startLine,
|
|
475
|
+
column: startCol,
|
|
476
|
+
endLine: line,
|
|
477
|
+
endColumn: col,
|
|
478
|
+
offset: startOffset,
|
|
479
|
+
endOffset: i
|
|
480
|
+
});
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
if (isAsciiDigit(ch)) {
|
|
484
|
+
advance(1);
|
|
485
|
+
while (i < len && (isAsciiDigit(sql.charCodeAt(i)) || sql.charCodeAt(i) === 95)) {
|
|
486
|
+
advance(1);
|
|
487
|
+
}
|
|
488
|
+
if (i < len && sql.charCodeAt(i) === 46 && i + 1 < len && isAsciiDigit(sql.charCodeAt(i + 1))) {
|
|
489
|
+
advance(1);
|
|
490
|
+
while (i < len && isAsciiDigit(sql.charCodeAt(i))) {
|
|
491
|
+
advance(1);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
const raw2 = sql.slice(startOffset, i);
|
|
495
|
+
tokens.push({
|
|
496
|
+
kind: "number",
|
|
497
|
+
raw: raw2,
|
|
498
|
+
upper: raw2,
|
|
499
|
+
ident: "",
|
|
500
|
+
line: startLine,
|
|
501
|
+
column: startCol,
|
|
502
|
+
endLine: line,
|
|
503
|
+
endColumn: col,
|
|
504
|
+
offset: startOffset,
|
|
505
|
+
endOffset: i
|
|
506
|
+
});
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
if (isWordStart(ch)) {
|
|
510
|
+
advance(1);
|
|
511
|
+
while (i < len && isWordPart(sql.charCodeAt(i))) {
|
|
512
|
+
advance(1);
|
|
513
|
+
}
|
|
514
|
+
const raw2 = sql.slice(startOffset, i);
|
|
515
|
+
tokens.push({
|
|
516
|
+
kind: "word",
|
|
517
|
+
raw: raw2,
|
|
518
|
+
upper: raw2.toUpperCase(),
|
|
519
|
+
ident: raw2.toLowerCase(),
|
|
520
|
+
line: startLine,
|
|
521
|
+
column: startCol,
|
|
522
|
+
endLine: line,
|
|
523
|
+
endColumn: col,
|
|
524
|
+
offset: startOffset,
|
|
525
|
+
endOffset: i
|
|
526
|
+
});
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
if (i + 1 < len) {
|
|
530
|
+
const two = sql.slice(i, i + 2);
|
|
531
|
+
if (two === "::" || two === "!=" || two === "<>" || two === "<=" || two === ">=" || two === "||" || two === "->") {
|
|
532
|
+
if (two === "->" && i + 2 < len && sql.charCodeAt(i + 2) === 62) {
|
|
533
|
+
advance(3);
|
|
534
|
+
const raw3 = "->>";
|
|
535
|
+
tokens.push({
|
|
536
|
+
kind: "punct",
|
|
537
|
+
raw: raw3,
|
|
538
|
+
upper: raw3,
|
|
539
|
+
ident: "",
|
|
540
|
+
line: startLine,
|
|
541
|
+
column: startCol,
|
|
542
|
+
endLine: line,
|
|
543
|
+
endColumn: col,
|
|
544
|
+
offset: startOffset,
|
|
545
|
+
endOffset: i
|
|
546
|
+
});
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
advance(2);
|
|
550
|
+
tokens.push({
|
|
551
|
+
kind: "punct",
|
|
552
|
+
raw: two,
|
|
553
|
+
upper: two,
|
|
554
|
+
ident: "",
|
|
555
|
+
line: startLine,
|
|
556
|
+
column: startCol,
|
|
557
|
+
endLine: line,
|
|
558
|
+
endColumn: col,
|
|
559
|
+
offset: startOffset,
|
|
560
|
+
endOffset: i
|
|
561
|
+
});
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
advance(1);
|
|
566
|
+
const raw = sql.slice(startOffset, i);
|
|
567
|
+
tokens.push({
|
|
568
|
+
kind: "punct",
|
|
569
|
+
raw,
|
|
570
|
+
upper: raw,
|
|
571
|
+
ident: "",
|
|
572
|
+
line: startLine,
|
|
573
|
+
column: startCol,
|
|
574
|
+
endLine: line,
|
|
575
|
+
endColumn: col,
|
|
576
|
+
offset: startOffset,
|
|
577
|
+
endOffset: i
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
return tokens;
|
|
581
|
+
}
|
|
582
|
+
function isStandaloneGoBatchSeparator(tokens, idx) {
|
|
583
|
+
const tok = tokens[idx];
|
|
584
|
+
if (tok.kind !== "word" || tok.upper !== "GO") return false;
|
|
585
|
+
const prevNonComment = (() => {
|
|
586
|
+
for (let j = idx - 1; j >= 0; j--) {
|
|
587
|
+
if (tokens[j].kind !== "comment") return tokens[j];
|
|
588
|
+
}
|
|
589
|
+
return null;
|
|
590
|
+
})();
|
|
591
|
+
if (prevNonComment && prevNonComment.endLine === tok.line) {
|
|
592
|
+
return false;
|
|
593
|
+
}
|
|
594
|
+
const nextNonComment = (() => {
|
|
595
|
+
for (let j = idx + 1; j < tokens.length; j++) {
|
|
596
|
+
if (tokens[j].kind !== "comment") return tokens[j];
|
|
597
|
+
}
|
|
598
|
+
return null;
|
|
599
|
+
})();
|
|
600
|
+
if (nextNonComment && nextNonComment.line === tok.line) {
|
|
601
|
+
if (nextNonComment.kind === "number") {
|
|
602
|
+
const afterNum = (() => {
|
|
603
|
+
for (let j = idx + 2; j < tokens.length; j++) {
|
|
604
|
+
if (tokens[j].kind !== "comment") return tokens[j];
|
|
605
|
+
}
|
|
606
|
+
return null;
|
|
607
|
+
})();
|
|
608
|
+
return !afterNum || afterNum.line > tok.line;
|
|
609
|
+
}
|
|
610
|
+
return false;
|
|
611
|
+
}
|
|
612
|
+
return true;
|
|
613
|
+
}
|
|
614
|
+
function splitSqlStatements(sql) {
|
|
615
|
+
const allTokens = tokenizeSql(sql);
|
|
616
|
+
const statements = [];
|
|
617
|
+
const fileIgnoredRules = /* @__PURE__ */ new Set();
|
|
618
|
+
let currentTokens = [];
|
|
619
|
+
let currentComments = [];
|
|
620
|
+
const flushStatement = (semicolonToken, trailingSameLineComments = []) => {
|
|
621
|
+
if (currentTokens.length === 0) {
|
|
622
|
+
for (const c of currentComments) {
|
|
623
|
+
extractIgnorePragmas(c.raw, /* @__PURE__ */ new Set(), fileIgnoredRules);
|
|
624
|
+
}
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
const allComments = [...currentComments, ...trailingSameLineComments];
|
|
628
|
+
const ignoredRules = new Set(fileIgnoredRules);
|
|
629
|
+
for (const c of allComments) {
|
|
630
|
+
extractIgnorePragmas(c.raw, ignoredRules, fileIgnoredRules);
|
|
631
|
+
}
|
|
632
|
+
for (const r of fileIgnoredRules) {
|
|
633
|
+
ignoredRules.add(r);
|
|
634
|
+
}
|
|
635
|
+
const firstTok = currentTokens[0];
|
|
636
|
+
const lastTok = semicolonToken ?? currentTokens[currentTokens.length - 1];
|
|
637
|
+
statements.push({
|
|
638
|
+
tokens: currentTokens,
|
|
639
|
+
comments: allComments,
|
|
640
|
+
ignoredRules,
|
|
641
|
+
rawSql: sql.slice(firstTok.offset, lastTok.endOffset),
|
|
642
|
+
startLine: firstTok.line,
|
|
643
|
+
startColumn: firstTok.column,
|
|
644
|
+
endLine: lastTok.endLine,
|
|
645
|
+
endColumn: lastTok.endColumn
|
|
646
|
+
});
|
|
647
|
+
currentTokens = [];
|
|
648
|
+
currentComments = [];
|
|
649
|
+
};
|
|
650
|
+
let idx = 0;
|
|
651
|
+
while (idx < allTokens.length) {
|
|
652
|
+
const tok = allTokens[idx];
|
|
653
|
+
if (tok.kind === "comment") {
|
|
654
|
+
extractIgnorePragmas(tok.raw, /* @__PURE__ */ new Set(), fileIgnoredRules);
|
|
655
|
+
currentComments.push(tok);
|
|
656
|
+
idx += 1;
|
|
657
|
+
continue;
|
|
658
|
+
}
|
|
659
|
+
if (tok.kind === "punct" && tok.raw === ";") {
|
|
660
|
+
const trailingSameLine = [];
|
|
661
|
+
let lookahead = idx + 1;
|
|
662
|
+
while (lookahead < allTokens.length && allTokens[lookahead].kind === "comment" && allTokens[lookahead].line === tok.endLine) {
|
|
663
|
+
trailingSameLine.push(allTokens[lookahead]);
|
|
664
|
+
lookahead += 1;
|
|
665
|
+
}
|
|
666
|
+
flushStatement(tok, trailingSameLine);
|
|
667
|
+
idx = lookahead;
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
if (isStandaloneGoBatchSeparator(allTokens, idx)) {
|
|
671
|
+
flushStatement();
|
|
672
|
+
if (idx + 1 < allTokens.length && allTokens[idx + 1].kind === "number" && allTokens[idx + 1].line === tok.line) {
|
|
673
|
+
idx += 2;
|
|
674
|
+
} else {
|
|
675
|
+
idx += 1;
|
|
676
|
+
}
|
|
677
|
+
continue;
|
|
678
|
+
}
|
|
679
|
+
currentTokens.push(tok);
|
|
680
|
+
idx += 1;
|
|
681
|
+
}
|
|
682
|
+
flushStatement();
|
|
683
|
+
if (fileIgnoredRules.size > 0) {
|
|
684
|
+
for (const stmt of statements) {
|
|
685
|
+
for (const rule of fileIgnoredRules) {
|
|
686
|
+
stmt.ignoredRules.add(rule);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
return {
|
|
691
|
+
tokens: allTokens,
|
|
692
|
+
statements,
|
|
693
|
+
fileIgnoredRules
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
function unquoteSqlString(raw) {
|
|
697
|
+
const quoteIdx = raw.indexOf("'");
|
|
698
|
+
if (quoteIdx >= 0 && raw.endsWith("'") && raw.length >= quoteIdx + 2) {
|
|
699
|
+
return raw.slice(quoteIdx + 1, -1).replace(/''/g, "'");
|
|
700
|
+
}
|
|
701
|
+
return raw;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// src/linter.ts
|
|
705
|
+
var DOCS_BASE = "https://github.com/culpritsql/culprit-ci#rule-reference";
|
|
706
|
+
var RULES = {
|
|
707
|
+
MIG001: {
|
|
708
|
+
id: "MIG001",
|
|
709
|
+
severity: "high",
|
|
710
|
+
category: "migration",
|
|
711
|
+
title: "Index creation blocks writes on existing table",
|
|
712
|
+
description: "CREATE INDEX without an online build clause holds locks that block concurrent INSERT, UPDATE, and DELETE traffic on existing tables.",
|
|
713
|
+
helpUri: `${DOCS_BASE}`
|
|
714
|
+
},
|
|
715
|
+
MIG002: {
|
|
716
|
+
id: "MIG002",
|
|
717
|
+
severity: "high",
|
|
718
|
+
category: "migration",
|
|
719
|
+
title: "CREATE INDEX CONCURRENTLY inside transaction block",
|
|
720
|
+
description: "PostgreSQL forbids running CREATE INDEX CONCURRENTLY or DROP INDEX CONCURRENTLY inside an explicit BEGIN / START TRANSACTION block.",
|
|
721
|
+
helpUri: `${DOCS_BASE}`
|
|
722
|
+
},
|
|
723
|
+
MIG003: {
|
|
724
|
+
id: "MIG003",
|
|
725
|
+
severity: "high",
|
|
726
|
+
category: "migration",
|
|
727
|
+
title: "Hazardous column type rewrite or volatile NOT NULL addition",
|
|
728
|
+
description: "Altering an existing column's data type or adding a NOT NULL column without a safe constant default rewrites the table under an exclusive lock.",
|
|
729
|
+
helpUri: `${DOCS_BASE}`
|
|
730
|
+
},
|
|
731
|
+
MIG004: {
|
|
732
|
+
id: "MIG004",
|
|
733
|
+
severity: "medium",
|
|
734
|
+
category: "migration",
|
|
735
|
+
title: "Unindexed foreign key constraint",
|
|
736
|
+
description: "Adding a FOREIGN KEY without an index on its referencing column(s) causes sequential scans during parent-row UPDATE/DELETE cascades and joins.",
|
|
737
|
+
helpUri: `${DOCS_BASE}`
|
|
738
|
+
},
|
|
739
|
+
MIG005: {
|
|
740
|
+
id: "MIG005",
|
|
741
|
+
severity: "high",
|
|
742
|
+
category: "migration",
|
|
743
|
+
title: "Destructive DROP or TRUNCATE without explicit ignore pragma",
|
|
744
|
+
description: "DROP TABLE, DROP COLUMN, and TRUNCATE permanently destroy data and break backward-compatible rolling deployments unless explicitly acknowledged.",
|
|
745
|
+
helpUri: `${DOCS_BASE}`
|
|
746
|
+
},
|
|
747
|
+
MIG006: {
|
|
748
|
+
id: "MIG006",
|
|
749
|
+
severity: "low",
|
|
750
|
+
category: "migration",
|
|
751
|
+
title: "DDL on existing table without lock_timeout guard",
|
|
752
|
+
description: "Acquiring DDL locks without SET lock_timeout (PostgreSQL) or SET LOCK_TIMEOUT (SQL Server) can queue behind a long query and stall all subsequent traffic.",
|
|
753
|
+
helpUri: `${DOCS_BASE}`
|
|
754
|
+
},
|
|
755
|
+
QRY001: {
|
|
756
|
+
id: "QRY001",
|
|
757
|
+
severity: "high",
|
|
758
|
+
category: "query",
|
|
759
|
+
title: "UPDATE or DELETE without WHERE clause",
|
|
760
|
+
description: "Executing an UPDATE or DELETE statement with no top-level WHERE predicate mutates or deletes every row in the target table.",
|
|
761
|
+
helpUri: `${DOCS_BASE}`
|
|
762
|
+
},
|
|
763
|
+
QRY002: {
|
|
764
|
+
id: "QRY002",
|
|
765
|
+
severity: "medium",
|
|
766
|
+
category: "query",
|
|
767
|
+
title: "Non-sargable function wrapping column in WHERE",
|
|
768
|
+
description: "Wrapping an indexed column in LOWER(), UPPER(), DATE(), YEAR(), or CAST() inside WHERE prevents standard B-tree index seeks.",
|
|
769
|
+
helpUri: `${DOCS_BASE}`
|
|
770
|
+
},
|
|
771
|
+
QRY003: {
|
|
772
|
+
id: "QRY003",
|
|
773
|
+
severity: "low",
|
|
774
|
+
category: "query",
|
|
775
|
+
title: "Leading wildcard LIKE / ILIKE predicate",
|
|
776
|
+
description: "A pattern starting with '%' (such as LIKE '%term') cannot use a standard B-tree index for range seeks and forces a scan.",
|
|
777
|
+
helpUri: `${DOCS_BASE}`
|
|
778
|
+
},
|
|
779
|
+
PLAN001: {
|
|
780
|
+
id: "PLAN001",
|
|
781
|
+
severity: "medium",
|
|
782
|
+
category: "plan",
|
|
783
|
+
title: "Full table scan detected in execution plan",
|
|
784
|
+
description: "An execution plan operator scans an entire table without an index seek.",
|
|
785
|
+
helpUri: `${DOCS_BASE}`
|
|
786
|
+
},
|
|
787
|
+
PLAN002: {
|
|
788
|
+
id: "PLAN002",
|
|
789
|
+
severity: "high",
|
|
790
|
+
category: "plan",
|
|
791
|
+
title: "Operator spilled intermediate data to disk",
|
|
792
|
+
description: "Sort, Hash, or Exchange operator exceeded memory allocation and spilled temporary pages to disk.",
|
|
793
|
+
helpUri: `${DOCS_BASE}`
|
|
794
|
+
},
|
|
795
|
+
PLAN003: {
|
|
796
|
+
id: "PLAN003",
|
|
797
|
+
severity: "high",
|
|
798
|
+
category: "plan",
|
|
799
|
+
title: "Execution plan bottleneck insight",
|
|
800
|
+
description: "Culprit's WebAssembly plan analyzer surfaced a high-impact execution bottleneck.",
|
|
801
|
+
helpUri: `${DOCS_BASE}`
|
|
802
|
+
},
|
|
803
|
+
PLAN004: {
|
|
804
|
+
id: "PLAN004",
|
|
805
|
+
severity: "high",
|
|
806
|
+
category: "plan",
|
|
807
|
+
title: "Execution plan exceeded maximum cost threshold",
|
|
808
|
+
description: "Total optimizer subtree cost exceeded the configured CI budget.",
|
|
809
|
+
helpUri: `${DOCS_BASE}`
|
|
810
|
+
},
|
|
811
|
+
PLAN005: {
|
|
812
|
+
id: "PLAN005",
|
|
813
|
+
severity: "high",
|
|
814
|
+
category: "plan",
|
|
815
|
+
title: "Execution plan regression between baseline and candidate",
|
|
816
|
+
description: "Candidate execution plan regressed in runtime, optimizer cost, access path, or spill warnings compared to the baseline plan.",
|
|
817
|
+
helpUri: `${DOCS_BASE}`
|
|
818
|
+
}
|
|
819
|
+
};
|
|
820
|
+
var NON_SARGABLE_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
821
|
+
"LOWER",
|
|
822
|
+
"UPPER",
|
|
823
|
+
"DATE",
|
|
824
|
+
"YEAR",
|
|
825
|
+
"MONTH",
|
|
826
|
+
"DAY",
|
|
827
|
+
"TRIM",
|
|
828
|
+
"LTRIM",
|
|
829
|
+
"RTRIM",
|
|
830
|
+
"BTRIM",
|
|
831
|
+
"SUBSTRING",
|
|
832
|
+
"SUBSTR",
|
|
833
|
+
"LEFT",
|
|
834
|
+
"COALESCE"
|
|
835
|
+
]);
|
|
836
|
+
var VOLATILE_DEFAULT_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
837
|
+
"RANDOM",
|
|
838
|
+
"GEN_RANDOM_UUID",
|
|
839
|
+
"UUID_GENERATE_V4",
|
|
840
|
+
"UUID_GENERATE_V1",
|
|
841
|
+
"CLOCK_TIMESTAMP",
|
|
842
|
+
"TIMEofday",
|
|
843
|
+
"TIMEOFDAY",
|
|
844
|
+
"NEWID",
|
|
845
|
+
"UUID",
|
|
846
|
+
"RAND"
|
|
847
|
+
]);
|
|
848
|
+
var COMPARISON_OPS = /* @__PURE__ */ new Set(["=", "!=", "<>", "<", ">", "<=", ">="]);
|
|
849
|
+
function isIdentifierToken(tok) {
|
|
850
|
+
if (!tok) return false;
|
|
851
|
+
return tok.kind === "word" || tok.kind === "quoted_ident";
|
|
852
|
+
}
|
|
853
|
+
function readQualifiedName(tokens, startIdx) {
|
|
854
|
+
let idx = startIdx;
|
|
855
|
+
if (tokens[idx]?.upper === "ONLY") {
|
|
856
|
+
idx += 1;
|
|
857
|
+
}
|
|
858
|
+
const parts = [];
|
|
859
|
+
const rawParts = [];
|
|
860
|
+
if (!isIdentifierToken(tokens[idx])) {
|
|
861
|
+
return null;
|
|
862
|
+
}
|
|
863
|
+
parts.push(tokens[idx].ident);
|
|
864
|
+
rawParts.push(tokens[idx].raw);
|
|
865
|
+
idx += 1;
|
|
866
|
+
while (idx + 1 < tokens.length && tokens[idx].raw === "." && isIdentifierToken(tokens[idx + 1])) {
|
|
867
|
+
parts.push(tokens[idx + 1].ident);
|
|
868
|
+
rawParts.push(tokens[idx + 1].raw);
|
|
869
|
+
idx += 2;
|
|
870
|
+
}
|
|
871
|
+
const bare = parts[parts.length - 1];
|
|
872
|
+
const full = parts.length >= 2 ? `${parts[parts.length - 2]}.${bare}` : bare;
|
|
873
|
+
return {
|
|
874
|
+
full,
|
|
875
|
+
bare,
|
|
876
|
+
rawDisplay: rawParts.join("."),
|
|
877
|
+
nextIndex: idx
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
var TableSet = class {
|
|
881
|
+
names = /* @__PURE__ */ new Set();
|
|
882
|
+
add(name) {
|
|
883
|
+
this.names.add(name.full);
|
|
884
|
+
this.names.add(name.bare);
|
|
885
|
+
}
|
|
886
|
+
has(name) {
|
|
887
|
+
return this.names.has(name.full) || this.names.has(name.bare);
|
|
888
|
+
}
|
|
889
|
+
};
|
|
890
|
+
var TableIndexRegistry = class {
|
|
891
|
+
byTable = /* @__PURE__ */ new Map();
|
|
892
|
+
add(tableKey, cols) {
|
|
893
|
+
if (cols.length === 0) return;
|
|
894
|
+
const normalizedCols = cols.map((c) => c.toLowerCase());
|
|
895
|
+
const keys = /* @__PURE__ */ new Set([tableKey.toLowerCase()]);
|
|
896
|
+
const dot = tableKey.lastIndexOf(".");
|
|
897
|
+
if (dot >= 0) {
|
|
898
|
+
keys.add(tableKey.slice(dot + 1).toLowerCase());
|
|
899
|
+
}
|
|
900
|
+
for (const k of keys) {
|
|
901
|
+
const list = this.byTable.get(k) ?? [];
|
|
902
|
+
list.push(normalizedCols);
|
|
903
|
+
this.byTable.set(k, list);
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
coversForeignKey(table, fkCols) {
|
|
907
|
+
if (fkCols.length === 0) return true;
|
|
908
|
+
const target = fkCols.map((c) => c.toLowerCase());
|
|
909
|
+
const candidates = [
|
|
910
|
+
...this.byTable.get(table.full) ?? [],
|
|
911
|
+
...this.byTable.get(table.bare) ?? []
|
|
912
|
+
];
|
|
913
|
+
for (const idxCols of candidates) {
|
|
914
|
+
if (idxCols.length < target.length) continue;
|
|
915
|
+
let prefixMatch = true;
|
|
916
|
+
for (let i = 0; i < target.length; i++) {
|
|
917
|
+
if (idxCols[i] !== target[i]) {
|
|
918
|
+
prefixMatch = false;
|
|
919
|
+
break;
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
if (prefixMatch) return true;
|
|
923
|
+
}
|
|
924
|
+
return false;
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
function parseParenColumnList(tokens, openParenIdx) {
|
|
928
|
+
if (tokens[openParenIdx]?.raw !== "(") return null;
|
|
929
|
+
const columns = [];
|
|
930
|
+
let depth = 1;
|
|
931
|
+
let i = openParenIdx + 1;
|
|
932
|
+
let segTokens = [];
|
|
933
|
+
const flushSegment = () => {
|
|
934
|
+
if (segTokens.length === 0) return;
|
|
935
|
+
if (isIdentifierToken(segTokens[0]) && segTokens[1]?.raw !== "(") {
|
|
936
|
+
columns.push(segTokens[0].ident);
|
|
937
|
+
} else if (segTokens.length >= 4 && isIdentifierToken(segTokens[0]) && segTokens[1]?.raw === "(" && isIdentifierToken(segTokens[2])) {
|
|
938
|
+
columns.push(segTokens[2].ident);
|
|
939
|
+
}
|
|
940
|
+
segTokens = [];
|
|
941
|
+
};
|
|
942
|
+
while (i < tokens.length && depth > 0) {
|
|
943
|
+
const tok = tokens[i];
|
|
944
|
+
if (tok.raw === "(") {
|
|
945
|
+
if (depth === 1) segTokens.push(tok);
|
|
946
|
+
depth += 1;
|
|
947
|
+
} else if (tok.raw === ")") {
|
|
948
|
+
depth -= 1;
|
|
949
|
+
if (depth === 0) {
|
|
950
|
+
flushSegment();
|
|
951
|
+
return { columns, closeParenIdx: i };
|
|
952
|
+
}
|
|
953
|
+
if (depth === 1) segTokens.push(tok);
|
|
954
|
+
} else if (tok.raw === "," && depth === 1) {
|
|
955
|
+
flushSegment();
|
|
956
|
+
} else if (depth === 1) {
|
|
957
|
+
segTokens.push(tok);
|
|
958
|
+
} else if (depth === 2 && segTokens.length > 0) {
|
|
959
|
+
segTokens.push(tok);
|
|
960
|
+
}
|
|
961
|
+
i += 1;
|
|
962
|
+
}
|
|
963
|
+
return null;
|
|
964
|
+
}
|
|
965
|
+
function detectSqlEngine(tokens, configured = "auto") {
|
|
966
|
+
if (configured === "postgres" || configured === "yugabyte") return "postgres";
|
|
967
|
+
if (configured === "mssql") return "mssql";
|
|
968
|
+
if (configured === "mysql") return "mysql";
|
|
969
|
+
if (configured === "sqlite") return "sqlite";
|
|
970
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
971
|
+
const t = tokens[i];
|
|
972
|
+
if (t.kind === "quoted_ident") {
|
|
973
|
+
if (t.raw.startsWith("[")) return "mssql";
|
|
974
|
+
if (t.raw.startsWith("`")) return "mysql";
|
|
975
|
+
}
|
|
976
|
+
if (t.kind === "punct" && t.raw === "::") return "postgres";
|
|
977
|
+
if (t.kind === "string" && t.raw.startsWith("$")) return "postgres";
|
|
978
|
+
if (t.kind === "word") {
|
|
979
|
+
if (t.upper === "CONCURRENTLY" || t.upper === "TIMESTAMPTZ" || t.upper === "JSONB" || t.upper === "BIGSERIAL" || t.upper === "ILIKE") {
|
|
980
|
+
return "postgres";
|
|
981
|
+
}
|
|
982
|
+
if (t.upper === "NONCLUSTERED" || t.upper === "CLUSTERED" || t.upper === "NVARCHAR" || t.upper === "GO" && (i === 0 || tokens[i - 1].endLine < t.line)) {
|
|
983
|
+
return "mssql";
|
|
984
|
+
}
|
|
985
|
+
if (t.upper === "AUTO_INCREMENT" || t.upper === "INPLACE") {
|
|
986
|
+
return "mysql";
|
|
987
|
+
}
|
|
988
|
+
if (t.upper === "AUTOINCREMENT" || t.upper === "PRAGMA") {
|
|
989
|
+
return "sqlite";
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
return "postgres";
|
|
994
|
+
}
|
|
995
|
+
function collectSchemaFactsFromStatements(statements, indexRegistry) {
|
|
996
|
+
const foreignKeys = [];
|
|
997
|
+
for (const stmt of statements) {
|
|
998
|
+
const toks = stmt.tokens;
|
|
999
|
+
if (toks.length === 0) continue;
|
|
1000
|
+
if (toks[0].upper === "CREATE") {
|
|
1001
|
+
let idx = 1;
|
|
1002
|
+
if (toks[idx]?.upper === "UNIQUE") idx += 1;
|
|
1003
|
+
if (toks[idx]?.upper === "CLUSTERED" || toks[idx]?.upper === "NONCLUSTERED" || toks[idx]?.upper === "FULLTEXT" || toks[idx]?.upper === "SPATIAL") {
|
|
1004
|
+
idx += 1;
|
|
1005
|
+
}
|
|
1006
|
+
if (toks[idx]?.upper === "INDEX") {
|
|
1007
|
+
for (let j = idx + 1; j < toks.length; j++) {
|
|
1008
|
+
if (toks[j].upper === "ON") {
|
|
1009
|
+
const tbl = readQualifiedName(toks, j + 1);
|
|
1010
|
+
if (tbl) {
|
|
1011
|
+
let afterTbl = tbl.nextIndex;
|
|
1012
|
+
if (toks[afterTbl]?.upper === "USING" && isIdentifierToken(toks[afterTbl + 1])) {
|
|
1013
|
+
afterTbl += 2;
|
|
1014
|
+
}
|
|
1015
|
+
const colList = parseParenColumnList(toks, afterTbl);
|
|
1016
|
+
if (colList && colList.columns.length > 0) {
|
|
1017
|
+
indexRegistry.add(tbl.full, colList.columns);
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
break;
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
if (toks[0].upper === "CREATE") {
|
|
1026
|
+
let idx = 1;
|
|
1027
|
+
if (toks[idx]?.upper === "TEMP" || toks[idx]?.upper === "TEMPORARY" || toks[idx]?.upper === "UNLOGGED") {
|
|
1028
|
+
idx += 1;
|
|
1029
|
+
}
|
|
1030
|
+
if (toks[idx]?.upper === "TABLE") {
|
|
1031
|
+
idx += 1;
|
|
1032
|
+
if (toks[idx]?.upper === "IF" && toks[idx + 1]?.upper === "NOT" && toks[idx + 2]?.upper === "EXISTS") {
|
|
1033
|
+
idx += 3;
|
|
1034
|
+
}
|
|
1035
|
+
const tbl = readQualifiedName(toks, idx);
|
|
1036
|
+
if (tbl && toks[tbl.nextIndex]?.raw === "(") {
|
|
1037
|
+
scanCreateTableElements(toks, tbl.nextIndex, tbl, indexRegistry, foreignKeys);
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
if (toks[0].upper === "ALTER" && toks[1]?.upper === "TABLE") {
|
|
1042
|
+
let idx = 2;
|
|
1043
|
+
if (toks[idx]?.upper === "IF" && toks[idx + 1]?.upper === "EXISTS") {
|
|
1044
|
+
idx += 2;
|
|
1045
|
+
}
|
|
1046
|
+
const tbl = readQualifiedName(toks, idx);
|
|
1047
|
+
if (tbl) {
|
|
1048
|
+
scanAlterTableConstraints(toks, tbl.nextIndex, tbl, indexRegistry, foreignKeys);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
return foreignKeys;
|
|
1053
|
+
}
|
|
1054
|
+
function splitTopLevelParenClauses(tokens, openParenIdx) {
|
|
1055
|
+
if (tokens[openParenIdx]?.raw !== "(") return [];
|
|
1056
|
+
const clauses = [];
|
|
1057
|
+
let current = [];
|
|
1058
|
+
let depth = 1;
|
|
1059
|
+
let i = openParenIdx + 1;
|
|
1060
|
+
while (i < tokens.length && depth > 0) {
|
|
1061
|
+
const tok = tokens[i];
|
|
1062
|
+
if (tok.raw === "(") {
|
|
1063
|
+
depth += 1;
|
|
1064
|
+
current.push(tok);
|
|
1065
|
+
} else if (tok.raw === ")") {
|
|
1066
|
+
depth -= 1;
|
|
1067
|
+
if (depth === 0) {
|
|
1068
|
+
if (current.length > 0) clauses.push(current);
|
|
1069
|
+
break;
|
|
1070
|
+
}
|
|
1071
|
+
current.push(tok);
|
|
1072
|
+
} else if (tok.raw === "," && depth === 1) {
|
|
1073
|
+
if (current.length > 0) clauses.push(current);
|
|
1074
|
+
current = [];
|
|
1075
|
+
} else {
|
|
1076
|
+
current.push(tok);
|
|
1077
|
+
}
|
|
1078
|
+
i += 1;
|
|
1079
|
+
}
|
|
1080
|
+
return clauses;
|
|
1081
|
+
}
|
|
1082
|
+
function scanCreateTableElements(tokens, openParenIdx, table, indexRegistry, foreignKeys) {
|
|
1083
|
+
const elements = splitTopLevelParenClauses(tokens, openParenIdx);
|
|
1084
|
+
for (const elem of elements) {
|
|
1085
|
+
if (elem.length === 0) continue;
|
|
1086
|
+
let start = 0;
|
|
1087
|
+
if (elem[0].upper === "CONSTRAINT" && isIdentifierToken(elem[1])) {
|
|
1088
|
+
start = 2;
|
|
1089
|
+
}
|
|
1090
|
+
if (elem[start]?.upper === "PRIMARY" && elem[start + 1]?.upper === "KEY") {
|
|
1091
|
+
let pIdx = start + 2;
|
|
1092
|
+
if (elem[pIdx]?.upper === "CLUSTERED" || elem[pIdx]?.upper === "NONCLUSTERED") pIdx += 1;
|
|
1093
|
+
const cols = parseParenColumnList(elem, pIdx);
|
|
1094
|
+
if (cols) indexRegistry.add(table.full, cols.columns);
|
|
1095
|
+
continue;
|
|
1096
|
+
}
|
|
1097
|
+
if (elem[start]?.upper === "UNIQUE") {
|
|
1098
|
+
let uIdx = start + 1;
|
|
1099
|
+
if (elem[uIdx]?.upper === "INDEX" || elem[uIdx]?.upper === "KEY") uIdx += 1;
|
|
1100
|
+
if (isIdentifierToken(elem[uIdx]) && elem[uIdx + 1]?.raw === "(") uIdx += 1;
|
|
1101
|
+
const cols = parseParenColumnList(elem, uIdx);
|
|
1102
|
+
if (cols) indexRegistry.add(table.full, cols.columns);
|
|
1103
|
+
continue;
|
|
1104
|
+
}
|
|
1105
|
+
if ((elem[start]?.upper === "INDEX" || elem[start]?.upper === "KEY") && elem.length >= start + 2) {
|
|
1106
|
+
let kIdx = start + 1;
|
|
1107
|
+
if (isIdentifierToken(elem[kIdx])) kIdx += 1;
|
|
1108
|
+
const cols = parseParenColumnList(elem, kIdx);
|
|
1109
|
+
if (cols) indexRegistry.add(table.full, cols.columns);
|
|
1110
|
+
continue;
|
|
1111
|
+
}
|
|
1112
|
+
if (elem[start]?.upper === "FOREIGN" && elem[start + 1]?.upper === "KEY") {
|
|
1113
|
+
const cols = parseParenColumnList(elem, start + 2);
|
|
1114
|
+
if (cols && cols.columns.length > 0) {
|
|
1115
|
+
foreignKeys.push({
|
|
1116
|
+
table,
|
|
1117
|
+
columns: cols.columns,
|
|
1118
|
+
token: elem[0],
|
|
1119
|
+
endToken: elem[elem.length - 1]
|
|
1120
|
+
});
|
|
1121
|
+
}
|
|
1122
|
+
continue;
|
|
1123
|
+
}
|
|
1124
|
+
if (isIdentifierToken(elem[0]) && elem[0].upper !== "CHECK" && elem[0].upper !== "EXCLUDE" && elem[0].upper !== "PERIOD") {
|
|
1125
|
+
const colName = elem[0].ident;
|
|
1126
|
+
for (let k = 1; k < elem.length; k++) {
|
|
1127
|
+
if (elem[k].upper === "PRIMARY" && elem[k + 1]?.upper === "KEY") {
|
|
1128
|
+
indexRegistry.add(table.full, [colName]);
|
|
1129
|
+
} else if (elem[k].upper === "UNIQUE") {
|
|
1130
|
+
indexRegistry.add(table.full, [colName]);
|
|
1131
|
+
} else if (elem[k].upper === "REFERENCES") {
|
|
1132
|
+
foreignKeys.push({
|
|
1133
|
+
table,
|
|
1134
|
+
columns: [colName],
|
|
1135
|
+
token: elem[0],
|
|
1136
|
+
endToken: elem[elem.length - 1]
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
function scanAlterTableConstraints(tokens, startIdx, table, indexRegistry, foreignKeys) {
|
|
1144
|
+
for (let i = startIdx; i < tokens.length; i++) {
|
|
1145
|
+
if (tokens[i].upper === "PRIMARY" && tokens[i + 1]?.upper === "KEY") {
|
|
1146
|
+
let pIdx = i + 2;
|
|
1147
|
+
if (tokens[pIdx]?.upper === "CLUSTERED" || tokens[pIdx]?.upper === "NONCLUSTERED") pIdx += 1;
|
|
1148
|
+
const cols = parseParenColumnList(tokens, pIdx);
|
|
1149
|
+
if (cols) indexRegistry.add(table.full, cols.columns);
|
|
1150
|
+
} else if (tokens[i].upper === "UNIQUE") {
|
|
1151
|
+
let uIdx = i + 1;
|
|
1152
|
+
if (tokens[uIdx]?.upper === "INDEX" || tokens[uIdx]?.upper === "KEY") uIdx += 1;
|
|
1153
|
+
if (isIdentifierToken(tokens[uIdx]) && tokens[uIdx + 1]?.raw === "(") uIdx += 1;
|
|
1154
|
+
const cols = parseParenColumnList(tokens, uIdx);
|
|
1155
|
+
if (cols) indexRegistry.add(table.full, cols.columns);
|
|
1156
|
+
} else if (tokens[i].upper === "FOREIGN" && tokens[i + 1]?.upper === "KEY") {
|
|
1157
|
+
const cols = parseParenColumnList(tokens, i + 2);
|
|
1158
|
+
if (cols && cols.columns.length > 0) {
|
|
1159
|
+
foreignKeys.push({
|
|
1160
|
+
table,
|
|
1161
|
+
columns: cols.columns,
|
|
1162
|
+
token: tokens[i],
|
|
1163
|
+
endToken: tokens[tokens.length - 1]
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
} else if (tokens[i].upper === "ADD") {
|
|
1167
|
+
let aIdx = i + 1;
|
|
1168
|
+
if (tokens[aIdx]?.upper === "COLUMN") aIdx += 1;
|
|
1169
|
+
if (tokens[aIdx]?.upper === "IF" && tokens[aIdx + 1]?.upper === "NOT" && tokens[aIdx + 2]?.upper === "EXISTS") {
|
|
1170
|
+
aIdx += 3;
|
|
1171
|
+
}
|
|
1172
|
+
if (isIdentifierToken(tokens[aIdx]) && tokens[aIdx].upper !== "CONSTRAINT" && tokens[aIdx].upper !== "FOREIGN" && tokens[aIdx].upper !== "PRIMARY" && tokens[aIdx].upper !== "UNIQUE" && tokens[aIdx].upper !== "CHECK" && tokens[aIdx].upper !== "INDEX") {
|
|
1173
|
+
const colName = tokens[aIdx].ident;
|
|
1174
|
+
let depth = 0;
|
|
1175
|
+
for (let k = aIdx + 1; k < tokens.length; k++) {
|
|
1176
|
+
if (tokens[k].raw === "(") depth += 1;
|
|
1177
|
+
else if (tokens[k].raw === ")") depth = Math.max(0, depth - 1);
|
|
1178
|
+
else if (tokens[k].raw === "," && depth === 0) break;
|
|
1179
|
+
if (depth === 0) {
|
|
1180
|
+
if (tokens[k].upper === "PRIMARY" && tokens[k + 1]?.upper === "KEY") {
|
|
1181
|
+
indexRegistry.add(table.full, [colName]);
|
|
1182
|
+
} else if (tokens[k].upper === "UNIQUE") {
|
|
1183
|
+
indexRegistry.add(table.full, [colName]);
|
|
1184
|
+
} else if (tokens[k].upper === "REFERENCES") {
|
|
1185
|
+
foreignKeys.push({
|
|
1186
|
+
table,
|
|
1187
|
+
columns: [colName],
|
|
1188
|
+
token: tokens[i],
|
|
1189
|
+
endToken: tokens[k + 1] ?? tokens[k]
|
|
1190
|
+
});
|
|
1191
|
+
break;
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
function hasOnlineIndexOption(tokens, engine, autoMode) {
|
|
1200
|
+
const hasConcurrently = tokens.some((t) => t.upper === "CONCURRENTLY");
|
|
1201
|
+
const hasMssqlOnline = tokens.some(
|
|
1202
|
+
(t, i) => t.upper === "ONLINE" && tokens[i + 1]?.raw === "=" && tokens[i + 2]?.upper === "ON"
|
|
1203
|
+
);
|
|
1204
|
+
const hasMysqlOnline = tokens.some(
|
|
1205
|
+
(t, i) => t.upper === "LOCK" && (tokens[i + 1]?.raw === "=" && tokens[i + 2]?.upper === "NONE" || tokens[i + 1]?.upper === "NONE") || t.upper === "ALGORITHM" && (tokens[i + 1]?.raw === "=" && (tokens[i + 2]?.upper === "INPLACE" || tokens[i + 2]?.upper === "INSTANT") || tokens[i + 1]?.upper === "INPLACE" || tokens[i + 1]?.upper === "INSTANT")
|
|
1206
|
+
);
|
|
1207
|
+
if (autoMode) {
|
|
1208
|
+
return hasConcurrently || hasMssqlOnline || hasMysqlOnline;
|
|
1209
|
+
}
|
|
1210
|
+
if (engine === "postgres") return hasConcurrently;
|
|
1211
|
+
if (engine === "mssql") return hasMssqlOnline;
|
|
1212
|
+
if (engine === "mysql") return hasMysqlOnline;
|
|
1213
|
+
return true;
|
|
1214
|
+
}
|
|
1215
|
+
function buildOnlineIndexFixSql(stmt, engine) {
|
|
1216
|
+
const trimmed = stmt.rawSql.trim().replace(/;\s*$/, "");
|
|
1217
|
+
if (engine === "postgres") {
|
|
1218
|
+
return `${trimmed.replace(/^(\s*CREATE\s+(?:UNIQUE\s+)?INDEX)\b/i, "$1 CONCURRENTLY")};`;
|
|
1219
|
+
}
|
|
1220
|
+
if (engine === "mssql") {
|
|
1221
|
+
if (/\bWITH\s*\(/i.test(trimmed)) {
|
|
1222
|
+
return `${trimmed.replace(/\bWITH\s*\(/i, "WITH (ONLINE = ON, ")};`;
|
|
1223
|
+
}
|
|
1224
|
+
return `${trimmed} WITH (ONLINE = ON);`;
|
|
1225
|
+
}
|
|
1226
|
+
if (engine === "mysql") {
|
|
1227
|
+
return `${trimmed} ALGORITHM=INPLACE, LOCK=NONE;`;
|
|
1228
|
+
}
|
|
1229
|
+
return `${trimmed};`;
|
|
1230
|
+
}
|
|
1231
|
+
function isLockTimeoutStatement(tokens) {
|
|
1232
|
+
if (tokens[0]?.upper !== "SET") return false;
|
|
1233
|
+
let idx = 1;
|
|
1234
|
+
if (tokens[idx]?.upper === "LOCAL" || tokens[idx]?.upper === "SESSION") {
|
|
1235
|
+
idx += 1;
|
|
1236
|
+
}
|
|
1237
|
+
return tokens[idx]?.upper === "LOCK_TIMEOUT";
|
|
1238
|
+
}
|
|
1239
|
+
function checkMigrationStatement(stmt, engine, autoMode, file, createdTables, state, isRuleEnabled, findings) {
|
|
1240
|
+
const toks = stmt.tokens;
|
|
1241
|
+
if (toks.length === 0) return;
|
|
1242
|
+
if (toks[0].upper === "BEGIN" && toks[1]?.upper !== "ATOMIC" || toks[0].upper === "START" && toks[1]?.upper === "TRANSACTION") {
|
|
1243
|
+
state.inTransaction = true;
|
|
1244
|
+
return;
|
|
1245
|
+
}
|
|
1246
|
+
if (toks[0].upper === "COMMIT" || toks[0].upper === "ROLLBACK" || toks[0].upper === "ABORT" || toks[0].upper === "END" && toks.length <= 3) {
|
|
1247
|
+
state.inTransaction = false;
|
|
1248
|
+
return;
|
|
1249
|
+
}
|
|
1250
|
+
if (isLockTimeoutStatement(toks)) {
|
|
1251
|
+
state.hasLockTimeout = true;
|
|
1252
|
+
return;
|
|
1253
|
+
}
|
|
1254
|
+
if (toks[0].upper === "CREATE") {
|
|
1255
|
+
let cIdx = 1;
|
|
1256
|
+
if (toks[cIdx]?.upper === "TEMP" || toks[cIdx]?.upper === "TEMPORARY" || toks[cIdx]?.upper === "UNLOGGED") {
|
|
1257
|
+
cIdx += 1;
|
|
1258
|
+
}
|
|
1259
|
+
if (toks[cIdx]?.upper === "TABLE") {
|
|
1260
|
+
cIdx += 1;
|
|
1261
|
+
if (toks[cIdx]?.upper === "IF" && toks[cIdx + 1]?.upper === "NOT" && toks[cIdx + 2]?.upper === "EXISTS") {
|
|
1262
|
+
cIdx += 3;
|
|
1263
|
+
}
|
|
1264
|
+
const tbl = readQualifiedName(toks, cIdx);
|
|
1265
|
+
if (tbl) {
|
|
1266
|
+
createdTables.add(tbl);
|
|
1267
|
+
}
|
|
1268
|
+
return;
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
const emitLockTimeoutIfNeeded = (targetTable) => {
|
|
1272
|
+
if (state.hasLockTimeout || state.emittedLockTimeoutWarning) return;
|
|
1273
|
+
if (engine !== "postgres" && engine !== "mssql") return;
|
|
1274
|
+
if (targetTable && createdTables.has(targetTable)) return;
|
|
1275
|
+
if (!isRuleEnabled("MIG006", stmt)) return;
|
|
1276
|
+
state.emittedLockTimeoutWarning = true;
|
|
1277
|
+
const fixSql = engine === "mssql" ? "SET LOCK_TIMEOUT 3000;" : "SET lock_timeout = '3s';";
|
|
1278
|
+
const settingName = engine === "mssql" ? "SET LOCK_TIMEOUT" : "SET lock_timeout";
|
|
1279
|
+
findings.push({
|
|
1280
|
+
ruleId: "MIG006",
|
|
1281
|
+
severity: "low",
|
|
1282
|
+
file,
|
|
1283
|
+
line: stmt.startLine,
|
|
1284
|
+
column: stmt.startColumn,
|
|
1285
|
+
endLine: stmt.endLine,
|
|
1286
|
+
endColumn: stmt.endColumn,
|
|
1287
|
+
title: RULES.MIG006.title,
|
|
1288
|
+
message: `DDL modifies an existing table without setting ${settingName} first. Waiting behind an active query can stall all queued traffic on the table.`,
|
|
1289
|
+
suggestion: `Prepend ${fixSql} at the top of the migration and retry safely if lock acquisition times out.`,
|
|
1290
|
+
fixSql
|
|
1291
|
+
});
|
|
1292
|
+
};
|
|
1293
|
+
if (toks[0].upper === "CREATE" || toks[0].upper === "DROP") {
|
|
1294
|
+
const hasConcurrently = toks.some((t) => t.upper === "CONCURRENTLY");
|
|
1295
|
+
const hasIndexKeyword = toks.some((t, idx) => idx <= 4 && t.upper === "INDEX");
|
|
1296
|
+
if (hasIndexKeyword && hasConcurrently && state.inTransaction) {
|
|
1297
|
+
if (isRuleEnabled("MIG002", stmt)) {
|
|
1298
|
+
const concTok = toks.find((t) => t.upper === "CONCURRENTLY") ?? toks[0];
|
|
1299
|
+
findings.push({
|
|
1300
|
+
ruleId: "MIG002",
|
|
1301
|
+
severity: "high",
|
|
1302
|
+
file,
|
|
1303
|
+
line: concTok.line,
|
|
1304
|
+
column: concTok.column,
|
|
1305
|
+
endLine: stmt.endLine,
|
|
1306
|
+
endColumn: stmt.endColumn,
|
|
1307
|
+
title: RULES.MIG002.title,
|
|
1308
|
+
message: "CREATE/DROP INDEX CONCURRENTLY is placed inside an explicit BEGIN / START TRANSACTION block and will fail at runtime in PostgreSQL.",
|
|
1309
|
+
suggestion: "Remove BEGIN / COMMIT around CONCURRENTLY index builds and configure your migration runner to execute this file outside a transaction."
|
|
1310
|
+
});
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
if (toks[0].upper === "CREATE" && hasIndexKeyword) {
|
|
1314
|
+
let targetTable = null;
|
|
1315
|
+
for (let j = 1; j < toks.length; j++) {
|
|
1316
|
+
if (toks[j].upper === "ON") {
|
|
1317
|
+
targetTable = readQualifiedName(toks, j + 1);
|
|
1318
|
+
break;
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
if (targetTable && !createdTables.has(targetTable)) {
|
|
1322
|
+
emitLockTimeoutIfNeeded(targetTable);
|
|
1323
|
+
if (engine !== "sqlite" && !hasOnlineIndexOption(toks, engine, autoMode) && isRuleEnabled("MIG001", stmt)) {
|
|
1324
|
+
const clauseHint = engine === "mssql" ? "WITH (ONLINE = ON)" : engine === "mysql" ? "ALGORITHM=INPLACE, LOCK=NONE" : "CONCURRENTLY";
|
|
1325
|
+
findings.push({
|
|
1326
|
+
ruleId: "MIG001",
|
|
1327
|
+
severity: "high",
|
|
1328
|
+
file,
|
|
1329
|
+
line: stmt.startLine,
|
|
1330
|
+
column: stmt.startColumn,
|
|
1331
|
+
endLine: stmt.endLine,
|
|
1332
|
+
endColumn: stmt.endColumn,
|
|
1333
|
+
title: RULES.MIG001.title,
|
|
1334
|
+
message: `Creating index on existing table '${targetTable.rawDisplay}' without ${clauseHint} blocks concurrent writes until the index build finishes.`,
|
|
1335
|
+
suggestion: `Add ${clauseHint} so concurrent DML can continue while the index builds.`,
|
|
1336
|
+
fixSql: buildOnlineIndexFixSql(stmt, engine)
|
|
1337
|
+
});
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
return;
|
|
1341
|
+
}
|
|
1342
|
+
if (toks[0].upper === "DROP" && toks[1]?.upper === "TABLE") {
|
|
1343
|
+
let dIdx = 2;
|
|
1344
|
+
if (toks[dIdx]?.upper === "IF" && toks[dIdx + 1]?.upper === "EXISTS") dIdx += 2;
|
|
1345
|
+
const droppedTbl = readQualifiedName(toks, dIdx);
|
|
1346
|
+
emitLockTimeoutIfNeeded(droppedTbl ?? void 0);
|
|
1347
|
+
if (isRuleEnabled("MIG005", stmt)) {
|
|
1348
|
+
const tblLabel = droppedTbl?.rawDisplay ?? "table";
|
|
1349
|
+
findings.push({
|
|
1350
|
+
ruleId: "MIG005",
|
|
1351
|
+
severity: "high",
|
|
1352
|
+
file,
|
|
1353
|
+
line: stmt.startLine,
|
|
1354
|
+
column: stmt.startColumn,
|
|
1355
|
+
endLine: stmt.endLine,
|
|
1356
|
+
endColumn: stmt.endColumn,
|
|
1357
|
+
title: RULES.MIG005.title,
|
|
1358
|
+
message: `DROP TABLE '${tblLabel}' permanently deletes table data and breaks running application instances that still reference it.`,
|
|
1359
|
+
suggestion: "Stop reading/writing the table in an earlier release first, then annotate intentional cleanup with '-- culprit-ignore: MIG005'."
|
|
1360
|
+
});
|
|
1361
|
+
}
|
|
1362
|
+
return;
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
if (toks[0].upper === "TRUNCATE") {
|
|
1366
|
+
let tIdx = 1;
|
|
1367
|
+
if (toks[tIdx]?.upper === "TABLE") tIdx += 1;
|
|
1368
|
+
const truncTbl = readQualifiedName(toks, tIdx);
|
|
1369
|
+
emitLockTimeoutIfNeeded(truncTbl ?? void 0);
|
|
1370
|
+
if (isRuleEnabled("MIG005", stmt)) {
|
|
1371
|
+
findings.push({
|
|
1372
|
+
ruleId: "MIG005",
|
|
1373
|
+
severity: "high",
|
|
1374
|
+
file,
|
|
1375
|
+
line: stmt.startLine,
|
|
1376
|
+
column: stmt.startColumn,
|
|
1377
|
+
endLine: stmt.endLine,
|
|
1378
|
+
endColumn: stmt.endColumn,
|
|
1379
|
+
title: RULES.MIG005.title,
|
|
1380
|
+
message: `TRUNCATE on '${truncTbl?.rawDisplay ?? "table"}' acquires an exclusive lock and permanently removes all rows.`,
|
|
1381
|
+
suggestion: "If purging data in production is intentional, acknowledge with '-- culprit-ignore: MIG005'."
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
if (toks[0].upper === "ALTER" && toks[1]?.upper === "TABLE") {
|
|
1387
|
+
let idx = 2;
|
|
1388
|
+
if (toks[idx]?.upper === "IF" && toks[idx + 1]?.upper === "EXISTS") {
|
|
1389
|
+
idx += 2;
|
|
1390
|
+
}
|
|
1391
|
+
const targetTable = readQualifiedName(toks, idx);
|
|
1392
|
+
if (!targetTable) return;
|
|
1393
|
+
const isBrandNewTable = createdTables.has(targetTable);
|
|
1394
|
+
if (!isBrandNewTable) {
|
|
1395
|
+
emitLockTimeoutIfNeeded(targetTable);
|
|
1396
|
+
}
|
|
1397
|
+
const actionSlices = [];
|
|
1398
|
+
let currentAction = [];
|
|
1399
|
+
let depth = 0;
|
|
1400
|
+
for (let k = targetTable.nextIndex; k < toks.length; k++) {
|
|
1401
|
+
const t = toks[k];
|
|
1402
|
+
if (t.raw === "(") depth += 1;
|
|
1403
|
+
else if (t.raw === ")") depth = Math.max(0, depth - 1);
|
|
1404
|
+
if (t.raw === "," && depth === 0) {
|
|
1405
|
+
if (currentAction.length > 0) actionSlices.push(currentAction);
|
|
1406
|
+
currentAction = [];
|
|
1407
|
+
} else {
|
|
1408
|
+
currentAction.push(t);
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
if (currentAction.length > 0) actionSlices.push(currentAction);
|
|
1412
|
+
for (const action of actionSlices) {
|
|
1413
|
+
if (action.length === 0) continue;
|
|
1414
|
+
const first = action[0];
|
|
1415
|
+
const last = action[action.length - 1];
|
|
1416
|
+
if (first.upper === "DROP") {
|
|
1417
|
+
const second = action[1]?.upper;
|
|
1418
|
+
const isConstraintOrIndex = second === "CONSTRAINT" || second === "INDEX" || second === "KEY" || second === "PRIMARY" || second === "FOREIGN" || second === "CHECK" || second === "PARTITION";
|
|
1419
|
+
if (!isConstraintOrIndex && isRuleEnabled("MIG005", stmt)) {
|
|
1420
|
+
let colIdx = second === "COLUMN" ? 2 : 1;
|
|
1421
|
+
if (action[colIdx]?.upper === "IF" && action[colIdx + 1]?.upper === "EXISTS") {
|
|
1422
|
+
colIdx += 2;
|
|
1423
|
+
}
|
|
1424
|
+
const colName = action[colIdx]?.raw ?? "column";
|
|
1425
|
+
findings.push({
|
|
1426
|
+
ruleId: "MIG005",
|
|
1427
|
+
severity: "high",
|
|
1428
|
+
file,
|
|
1429
|
+
line: first.line,
|
|
1430
|
+
column: first.column,
|
|
1431
|
+
endLine: last.endLine,
|
|
1432
|
+
endColumn: last.endColumn,
|
|
1433
|
+
title: RULES.MIG005.title,
|
|
1434
|
+
message: `Dropping column '${colName}' from '${targetTable.rawDisplay}' breaks in-flight queries that still select or insert that column during a rolling deploy.`,
|
|
1435
|
+
suggestion: "Stop referencing the column in application code first, deploy, then add '-- culprit-ignore: MIG005' when dropping the unused column."
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
continue;
|
|
1439
|
+
}
|
|
1440
|
+
if (isBrandNewTable) continue;
|
|
1441
|
+
if (first.upper === "ALTER") {
|
|
1442
|
+
let aIdx = 1;
|
|
1443
|
+
if (action[aIdx]?.upper === "COLUMN") aIdx += 1;
|
|
1444
|
+
const colTok = action[aIdx];
|
|
1445
|
+
const afterCol = action[aIdx + 1]?.upper;
|
|
1446
|
+
const isPgSetType = afterCol === "TYPE" || afterCol === "SET" && action[aIdx + 2]?.upper === "DATA" && action[aIdx + 3]?.upper === "TYPE";
|
|
1447
|
+
const isMssqlAlterType = engine === "mssql" && isIdentifierToken(colTok) && isIdentifierToken(action[aIdx + 1]) && afterCol !== "ADD" && afterCol !== "DROP";
|
|
1448
|
+
if ((isPgSetType || isMssqlAlterType) && isRuleEnabled("MIG003", stmt)) {
|
|
1449
|
+
findings.push({
|
|
1450
|
+
ruleId: "MIG003",
|
|
1451
|
+
severity: "high",
|
|
1452
|
+
file,
|
|
1453
|
+
line: first.line,
|
|
1454
|
+
column: first.column,
|
|
1455
|
+
endLine: last.endLine,
|
|
1456
|
+
endColumn: last.endColumn,
|
|
1457
|
+
title: RULES.MIG003.title,
|
|
1458
|
+
message: `Changing type of column '${colTok?.raw ?? "column"}' on '${targetTable.rawDisplay}' acquires an exclusive table lock and can rewrite every row on disk.`,
|
|
1459
|
+
suggestion: "Use expand-and-contract instead: add a new nullable column, backfill in small batches, dual-write, and swap."
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
continue;
|
|
1463
|
+
}
|
|
1464
|
+
if ((first.upper === "MODIFY" || first.upper === "CHANGE") && isRuleEnabled("MIG003", stmt)) {
|
|
1465
|
+
const colIdx = action[1]?.upper === "COLUMN" ? 2 : 1;
|
|
1466
|
+
findings.push({
|
|
1467
|
+
ruleId: "MIG003",
|
|
1468
|
+
severity: "high",
|
|
1469
|
+
file,
|
|
1470
|
+
line: first.line,
|
|
1471
|
+
column: first.column,
|
|
1472
|
+
endLine: last.endLine,
|
|
1473
|
+
endColumn: last.endColumn,
|
|
1474
|
+
title: RULES.MIG003.title,
|
|
1475
|
+
message: `Modifying column '${action[colIdx]?.raw ?? "column"}' on '${targetTable.rawDisplay}' can trigger a full table copy and block concurrent writes.`,
|
|
1476
|
+
suggestion: "Verify instant/in-place DDL compatibility or migrate via expand-and-contract with a new column."
|
|
1477
|
+
});
|
|
1478
|
+
continue;
|
|
1479
|
+
}
|
|
1480
|
+
if (first.upper === "ADD") {
|
|
1481
|
+
let aIdx = 1;
|
|
1482
|
+
if (action[aIdx]?.upper === "COLUMN") aIdx += 1;
|
|
1483
|
+
if (action[aIdx]?.upper === "IF" && action[aIdx + 1]?.upper === "NOT" && action[aIdx + 2]?.upper === "EXISTS") {
|
|
1484
|
+
aIdx += 3;
|
|
1485
|
+
}
|
|
1486
|
+
const colTok = action[aIdx];
|
|
1487
|
+
const isConstraintKeyword = colTok?.upper === "CONSTRAINT" || colTok?.upper === "FOREIGN" || colTok?.upper === "PRIMARY" || colTok?.upper === "UNIQUE" || colTok?.upper === "CHECK" || colTok?.upper === "INDEX";
|
|
1488
|
+
if (isIdentifierToken(colTok) && !isConstraintKeyword) {
|
|
1489
|
+
const hasNotNull = action.some(
|
|
1490
|
+
(t, idx2) => t.upper === "NOT" && action[idx2 + 1]?.upper === "NULL"
|
|
1491
|
+
);
|
|
1492
|
+
if (hasNotNull && isRuleEnabled("MIG003", stmt)) {
|
|
1493
|
+
const defaultIdx = action.findIndex((t) => t.upper === "DEFAULT");
|
|
1494
|
+
let volatileFunc = null;
|
|
1495
|
+
if (defaultIdx !== -1) {
|
|
1496
|
+
for (let d = defaultIdx + 1; d < action.length; d++) {
|
|
1497
|
+
const dt = action[d];
|
|
1498
|
+
if (dt.upper === "NOT" || dt.upper === "NULL" || dt.upper === "CONSTRAINT" || dt.upper === "REFERENCES" || dt.upper === "CHECK") {
|
|
1499
|
+
break;
|
|
1500
|
+
}
|
|
1501
|
+
if (dt.kind === "word" && action[d + 1]?.raw === "(" && VOLATILE_DEFAULT_FUNCTIONS.has(dt.upper)) {
|
|
1502
|
+
volatileFunc = `${dt.raw}()`;
|
|
1503
|
+
break;
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
if (defaultIdx === -1) {
|
|
1508
|
+
findings.push({
|
|
1509
|
+
ruleId: "MIG003",
|
|
1510
|
+
severity: "high",
|
|
1511
|
+
file,
|
|
1512
|
+
line: first.line,
|
|
1513
|
+
column: first.column,
|
|
1514
|
+
endLine: last.endLine,
|
|
1515
|
+
endColumn: last.endColumn,
|
|
1516
|
+
title: RULES.MIG003.title,
|
|
1517
|
+
message: `Adding NOT NULL column '${colTok.raw}' to existing table '${targetTable.rawDisplay}' without a DEFAULT fails on non-empty tables or requires an exclusive rewrite.`,
|
|
1518
|
+
suggestion: "Add the column as nullable first, backfill existing rows in batches, and enforce NOT NULL with a NOT VALID check constraint before validating."
|
|
1519
|
+
});
|
|
1520
|
+
} else if (volatileFunc) {
|
|
1521
|
+
findings.push({
|
|
1522
|
+
ruleId: "MIG003",
|
|
1523
|
+
severity: "high",
|
|
1524
|
+
file,
|
|
1525
|
+
line: first.line,
|
|
1526
|
+
column: first.column,
|
|
1527
|
+
endLine: last.endLine,
|
|
1528
|
+
endColumn: last.endColumn,
|
|
1529
|
+
title: RULES.MIG003.title,
|
|
1530
|
+
message: `Adding NOT NULL column '${colTok.raw}' on '${targetTable.rawDisplay}' with volatile default ${volatileFunc} rewrites every row under an ACCESS EXCLUSIVE lock.`,
|
|
1531
|
+
suggestion: "Add the column as nullable with the default for new rows, backfill existing rows in batches, then validate NOT NULL."
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
function findMainStatementStartAfterWith(tokens) {
|
|
1541
|
+
if (tokens[0]?.upper !== "WITH") return 0;
|
|
1542
|
+
let idx = 1;
|
|
1543
|
+
if (tokens[idx]?.upper === "RECURSIVE") idx += 1;
|
|
1544
|
+
let depth = 0;
|
|
1545
|
+
while (idx < tokens.length) {
|
|
1546
|
+
const t = tokens[idx];
|
|
1547
|
+
if (t.raw === "(") {
|
|
1548
|
+
depth += 1;
|
|
1549
|
+
} else if (t.raw === ")") {
|
|
1550
|
+
depth = Math.max(0, depth - 1);
|
|
1551
|
+
if (depth === 0) {
|
|
1552
|
+
if (tokens[idx + 1]?.raw === ",") {
|
|
1553
|
+
idx += 2;
|
|
1554
|
+
continue;
|
|
1555
|
+
}
|
|
1556
|
+
return idx + 1;
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
idx += 1;
|
|
1560
|
+
}
|
|
1561
|
+
return 0;
|
|
1562
|
+
}
|
|
1563
|
+
function checkQueryStatement(stmt, engine, file, isRuleEnabled, findings) {
|
|
1564
|
+
const toks = stmt.tokens;
|
|
1565
|
+
if (toks.length === 0) return;
|
|
1566
|
+
const mainStart = findMainStatementStartAfterWith(toks);
|
|
1567
|
+
const mainVerb = toks[mainStart]?.upper;
|
|
1568
|
+
if ((mainVerb === "UPDATE" || mainVerb === "DELETE") && isRuleEnabled("QRY001", stmt)) {
|
|
1569
|
+
let depth = 0;
|
|
1570
|
+
let hasTopLevelWhere = false;
|
|
1571
|
+
for (let i = mainStart + 1; i < toks.length; i++) {
|
|
1572
|
+
if (toks[i].raw === "(") depth += 1;
|
|
1573
|
+
else if (toks[i].raw === ")") depth = Math.max(0, depth - 1);
|
|
1574
|
+
else if (depth === 0 && toks[i].upper === "WHERE") {
|
|
1575
|
+
hasTopLevelWhere = true;
|
|
1576
|
+
break;
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
if (!hasTopLevelWhere) {
|
|
1580
|
+
const verbTok = toks[mainStart];
|
|
1581
|
+
findings.push({
|
|
1582
|
+
ruleId: "QRY001",
|
|
1583
|
+
severity: "high",
|
|
1584
|
+
file,
|
|
1585
|
+
line: verbTok.line,
|
|
1586
|
+
column: verbTok.column,
|
|
1587
|
+
endLine: stmt.endLine,
|
|
1588
|
+
endColumn: stmt.endColumn,
|
|
1589
|
+
title: RULES.QRY001.title,
|
|
1590
|
+
message: `${mainVerb} statement has no top-level WHERE clause and will modify or delete every row in the target table.`,
|
|
1591
|
+
suggestion: `Add an explicit WHERE predicate (or '-- culprit-ignore: QRY001' if full-table ${mainVerb} is intentional).`
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
if (isRuleEnabled("QRY002", stmt)) {
|
|
1596
|
+
let inWhere = false;
|
|
1597
|
+
let whereParenDepth = 0;
|
|
1598
|
+
for (let i = 0; i < toks.length; i++) {
|
|
1599
|
+
const tok = toks[i];
|
|
1600
|
+
if (tok.raw === "(") {
|
|
1601
|
+
if (inWhere) whereParenDepth += 1;
|
|
1602
|
+
} else if (tok.raw === ")") {
|
|
1603
|
+
if (inWhere) {
|
|
1604
|
+
if (whereParenDepth === 0) {
|
|
1605
|
+
inWhere = false;
|
|
1606
|
+
} else {
|
|
1607
|
+
whereParenDepth -= 1;
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
} else if (tok.upper === "WHERE") {
|
|
1611
|
+
inWhere = true;
|
|
1612
|
+
whereParenDepth = 0;
|
|
1613
|
+
continue;
|
|
1614
|
+
} else if (inWhere && whereParenDepth === 0 && (tok.upper === "GROUP" || tok.upper === "ORDER" || tok.upper === "LIMIT" || tok.upper === "HAVING" || tok.upper === "RETURNING" || tok.upper === "UNION" || tok.upper === "INTERSECT" || tok.upper === "EXCEPT")) {
|
|
1615
|
+
inWhere = false;
|
|
1616
|
+
continue;
|
|
1617
|
+
}
|
|
1618
|
+
if (!inWhere) continue;
|
|
1619
|
+
const isCast = tok.kind === "word" && tok.upper === "CAST" && toks[i + 1]?.raw === "(";
|
|
1620
|
+
const isFunc = tok.kind === "word" && NON_SARGABLE_FUNCTIONS.has(tok.upper) && toks[i + 1]?.raw === "(";
|
|
1621
|
+
if (!isCast && !isFunc) continue;
|
|
1622
|
+
let depth = 1;
|
|
1623
|
+
let closeIdx = -1;
|
|
1624
|
+
for (let k = i + 2; k < toks.length; k++) {
|
|
1625
|
+
if (toks[k].raw === "(") depth += 1;
|
|
1626
|
+
else if (toks[k].raw === ")") {
|
|
1627
|
+
depth -= 1;
|
|
1628
|
+
if (depth === 0) {
|
|
1629
|
+
closeIdx = k;
|
|
1630
|
+
break;
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
if (closeIdx === -1) continue;
|
|
1635
|
+
const argStart = i + 2;
|
|
1636
|
+
const colRef = readQualifiedName(toks, argStart);
|
|
1637
|
+
if (!colRef) continue;
|
|
1638
|
+
const firstArgUpper = toks[argStart]?.upper ?? "";
|
|
1639
|
+
if (firstArgUpper === "NULL" || firstArgUpper === "TRUE" || firstArgUpper === "FALSE" || firstArgUpper === "CURRENT_DATE" || firstArgUpper === "CURRENT_TIMESTAMP" || firstArgUpper === "NOW" || toks[argStart]?.raw.startsWith("@")) {
|
|
1640
|
+
continue;
|
|
1641
|
+
}
|
|
1642
|
+
const nextTok = toks[closeIdx + 1];
|
|
1643
|
+
const prevTok = toks[i - 1];
|
|
1644
|
+
const comparedOnRight = nextTok !== void 0 && (COMPARISON_OPS.has(nextTok.raw) || nextTok.upper === "IN" || nextTok.upper === "BETWEEN" || nextTok.upper === "LIKE" || nextTok.upper === "ILIKE");
|
|
1645
|
+
const comparedOnLeft = prevTok !== void 0 && COMPARISON_OPS.has(prevTok.raw);
|
|
1646
|
+
if (!comparedOnRight && !comparedOnLeft) continue;
|
|
1647
|
+
const fnUpper = tok.upper;
|
|
1648
|
+
const colDisplay = colRef.rawDisplay;
|
|
1649
|
+
let suggestion;
|
|
1650
|
+
let fixSql;
|
|
1651
|
+
if (fnUpper === "LOWER" || fnUpper === "UPPER") {
|
|
1652
|
+
const indexClause = engine === "postgres" ? "CONCURRENTLY " : "";
|
|
1653
|
+
suggestion = `Add a functional index on ${fnUpper}(${colDisplay}) or store normalized/case-insensitive values so the planner can seek directly.`;
|
|
1654
|
+
fixSql = `CREATE INDEX ${indexClause}idx_expr_${fnUpper.toLowerCase()}_${colRef.bare} ON <table> (${fnUpper}(${colRef.bare}));`;
|
|
1655
|
+
} else if (fnUpper === "DATE" || fnUpper === "YEAR" || fnUpper === "MONTH" || fnUpper === "DAY") {
|
|
1656
|
+
suggestion = `Rewrite ${fnUpper}(${colDisplay}) as a half-open range predicate (${colDisplay} >= start_ts AND ${colDisplay} < end_ts) so B-tree indexes on ${colDisplay} remain sargable.`;
|
|
1657
|
+
} else if (fnUpper === "CAST") {
|
|
1658
|
+
suggestion = `Cast the parameter or literal on the other side of the comparison instead of wrapping column '${colDisplay}' in CAST(...).`;
|
|
1659
|
+
} else {
|
|
1660
|
+
suggestion = `Avoid wrapping indexed column '${colDisplay}' in ${fnUpper}(...) inside WHERE, or create a matching expression index.`;
|
|
1661
|
+
}
|
|
1662
|
+
const endTok = comparedOnRight && toks[closeIdx + 2] ? toks[closeIdx + 2] : toks[closeIdx];
|
|
1663
|
+
findings.push({
|
|
1664
|
+
ruleId: "QRY002",
|
|
1665
|
+
severity: "medium",
|
|
1666
|
+
file,
|
|
1667
|
+
line: tok.line,
|
|
1668
|
+
column: tok.column,
|
|
1669
|
+
endLine: endTok.endLine,
|
|
1670
|
+
endColumn: endTok.endColumn,
|
|
1671
|
+
title: RULES.QRY002.title,
|
|
1672
|
+
message: `Non-sargable predicate wraps column '${colDisplay}' in ${fnUpper}(...), preventing standard B-tree index seeks.`,
|
|
1673
|
+
suggestion,
|
|
1674
|
+
...fixSql ? { fixSql } : {}
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
if (isRuleEnabled("QRY003", stmt)) {
|
|
1679
|
+
for (let i = 0; i < toks.length - 1; i++) {
|
|
1680
|
+
const tok = toks[i];
|
|
1681
|
+
if (tok.kind !== "word" || tok.upper !== "LIKE" && tok.upper !== "ILIKE") {
|
|
1682
|
+
continue;
|
|
1683
|
+
}
|
|
1684
|
+
const patTok = toks[i + 1];
|
|
1685
|
+
if (patTok?.kind !== "string") continue;
|
|
1686
|
+
if (!patTok.raw.includes("'")) continue;
|
|
1687
|
+
const patternVal = unquoteSqlString(patTok.raw);
|
|
1688
|
+
if (patternVal.startsWith("%")) {
|
|
1689
|
+
const suggestion = engine === "postgres" ? "Add a pg_trgm GIN index (USING gin (col gin_trgm_ops)), use full-text search (tsvector), or anchor the prefix without a leading '%'." : "Use full-text search, an inverted/n-gram index, or a reversed-column prefix index for suffix lookups.";
|
|
1690
|
+
findings.push({
|
|
1691
|
+
ruleId: "QRY003",
|
|
1692
|
+
severity: "low",
|
|
1693
|
+
file,
|
|
1694
|
+
line: tok.line,
|
|
1695
|
+
column: tok.column,
|
|
1696
|
+
endLine: patTok.endLine,
|
|
1697
|
+
endColumn: patTok.endColumn,
|
|
1698
|
+
title: RULES.QRY003.title,
|
|
1699
|
+
message: `Leading wildcard pattern ${tok.upper} ${patTok.raw} prevents B-tree index range seeks and forces a full index or table scan.`,
|
|
1700
|
+
suggestion
|
|
1701
|
+
});
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
function lintSql(sql, options = {}) {
|
|
1707
|
+
const file = options.file ?? "input.sql";
|
|
1708
|
+
const configuredEngine = options.engine ?? "auto";
|
|
1709
|
+
const mode = options.mode ?? "migration";
|
|
1710
|
+
const disabledSet = new Set((options.disabledRules ?? []).map((r) => r.toUpperCase()));
|
|
1711
|
+
const lexed = splitSqlStatements(sql);
|
|
1712
|
+
const resolvedEngine = detectSqlEngine(lexed.tokens, configuredEngine);
|
|
1713
|
+
const autoMode = configuredEngine === "auto";
|
|
1714
|
+
const isRuleEnabled = (ruleId, stmt) => {
|
|
1715
|
+
const upper = ruleId.toUpperCase();
|
|
1716
|
+
if (disabledSet.has(upper)) return false;
|
|
1717
|
+
if (lexed.fileIgnoredRules.has("*") || lexed.fileIgnoredRules.has(upper)) return false;
|
|
1718
|
+
if (stmt && (stmt.ignoredRules.has("*") || stmt.ignoredRules.has(upper))) return false;
|
|
1719
|
+
return true;
|
|
1720
|
+
};
|
|
1721
|
+
const indexRegistry = new TableIndexRegistry();
|
|
1722
|
+
if (options.existingIndexes) {
|
|
1723
|
+
for (const [tbl, colLists] of Object.entries(options.existingIndexes)) {
|
|
1724
|
+
for (const cols of colLists) {
|
|
1725
|
+
indexRegistry.add(tbl, cols);
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
if (options.schemaSql) {
|
|
1730
|
+
const schemaLexed = splitSqlStatements(options.schemaSql);
|
|
1731
|
+
collectSchemaFactsFromStatements(schemaLexed.statements, indexRegistry);
|
|
1732
|
+
}
|
|
1733
|
+
const fileForeignKeys = collectSchemaFactsFromStatements(lexed.statements, indexRegistry);
|
|
1734
|
+
const findings = [];
|
|
1735
|
+
const createdTables = new TableSet();
|
|
1736
|
+
const migrationState = {
|
|
1737
|
+
inTransaction: false,
|
|
1738
|
+
hasLockTimeout: false,
|
|
1739
|
+
emittedLockTimeoutWarning: false
|
|
1740
|
+
};
|
|
1741
|
+
const runMigrationRules = mode === "migration" || mode === "all";
|
|
1742
|
+
const runQueryRules = mode === "query" || mode === "migration" || mode === "all";
|
|
1743
|
+
for (const stmt of lexed.statements) {
|
|
1744
|
+
if (runMigrationRules) {
|
|
1745
|
+
checkMigrationStatement(
|
|
1746
|
+
stmt,
|
|
1747
|
+
resolvedEngine,
|
|
1748
|
+
autoMode,
|
|
1749
|
+
file,
|
|
1750
|
+
createdTables,
|
|
1751
|
+
migrationState,
|
|
1752
|
+
isRuleEnabled,
|
|
1753
|
+
findings
|
|
1754
|
+
);
|
|
1755
|
+
}
|
|
1756
|
+
if (runQueryRules) {
|
|
1757
|
+
checkQueryStatement(stmt, resolvedEngine, file, isRuleEnabled, findings);
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
if (runMigrationRules) {
|
|
1761
|
+
for (const fk of fileForeignKeys) {
|
|
1762
|
+
const ownerStmt = lexed.statements.find(
|
|
1763
|
+
(s) => fk.token.offset >= s.tokens[0].offset && fk.token.offset <= s.tokens[s.tokens.length - 1].endOffset
|
|
1764
|
+
);
|
|
1765
|
+
if (!isRuleEnabled("MIG004", ownerStmt)) continue;
|
|
1766
|
+
if (!indexRegistry.coversForeignKey(fk.table, fk.columns)) {
|
|
1767
|
+
const colsJoined = fk.columns.join(", ");
|
|
1768
|
+
const colsSlug = fk.columns.join("_");
|
|
1769
|
+
const onlineKw = resolvedEngine === "postgres" && !createdTables.has(fk.table) ? "CONCURRENTLY " : "";
|
|
1770
|
+
const onlineSuffix = resolvedEngine === "mssql" && !createdTables.has(fk.table) ? " WITH (ONLINE = ON)" : "";
|
|
1771
|
+
const fixSql = `CREATE INDEX ${onlineKw}idx_${fk.table.bare}_${colsSlug} ON ${fk.table.rawDisplay} (${colsJoined})${onlineSuffix};`;
|
|
1772
|
+
findings.push({
|
|
1773
|
+
ruleId: "MIG004",
|
|
1774
|
+
severity: "medium",
|
|
1775
|
+
file,
|
|
1776
|
+
line: fk.token.line,
|
|
1777
|
+
column: fk.token.column,
|
|
1778
|
+
endLine: fk.endToken.endLine,
|
|
1779
|
+
endColumn: fk.endToken.endColumn,
|
|
1780
|
+
title: RULES.MIG004.title,
|
|
1781
|
+
message: `Foreign key on '${fk.table.rawDisplay} (${colsJoined})' has no covering index in this migration or schema snapshot.`,
|
|
1782
|
+
suggestion: `Create an index with leading column(s) (${colsJoined}) on '${fk.table.rawDisplay}' to avoid lock amplification and full scans on parent updates/deletes.`,
|
|
1783
|
+
fixSql
|
|
1784
|
+
});
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
findings.sort((a, b) => a.line - b.line || a.column - b.column || a.ruleId.localeCompare(b.ruleId));
|
|
1789
|
+
return findings;
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
// src/plans.ts
|
|
1793
|
+
import { readFile } from "node:fs/promises";
|
|
1794
|
+
import {
|
|
1795
|
+
diffPlans,
|
|
1796
|
+
exportPlan,
|
|
1797
|
+
init,
|
|
1798
|
+
ParserError,
|
|
1799
|
+
parsePlan
|
|
1800
|
+
} from "@culpritsql/plans";
|
|
1801
|
+
|
|
1802
|
+
// src/share.ts
|
|
1803
|
+
import { deflateRawSync, inflateRawSync } from "node:zlib";
|
|
1804
|
+
var MAX_SHARE_HASH_CHARS = 28e3;
|
|
1805
|
+
var DEFAULT_EXPLAIN_BASE_URL = "https://explain.culpritsql.com/";
|
|
1806
|
+
function toBase64Url(bytes) {
|
|
1807
|
+
return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
1808
|
+
}
|
|
1809
|
+
function scrubSqlLiterals(text) {
|
|
1810
|
+
return text.replace(/'(?:''|[^'])*'/g, "'?'").replace(/\b\d+(?:\.\d+)?\b/g, (num) => num === "0" || num === "1" ? num : "?");
|
|
1811
|
+
}
|
|
1812
|
+
function encodeShareHash(payload) {
|
|
1813
|
+
const json = JSON.stringify(payload);
|
|
1814
|
+
const rawBytes = Buffer.from(json, "utf8");
|
|
1815
|
+
const compressed = deflateRawSync(rawBytes, { level: 9 });
|
|
1816
|
+
const encoded = `z1.${toBase64Url(compressed)}`;
|
|
1817
|
+
if (encoded.length > MAX_SHARE_HASH_CHARS) {
|
|
1818
|
+
return { ok: false, reason: "too_large" };
|
|
1819
|
+
}
|
|
1820
|
+
return { ok: true, hash: `#s=${encoded}` };
|
|
1821
|
+
}
|
|
1822
|
+
function buildExplainShareUrl(payload, baseUrl = DEFAULT_EXPLAIN_BASE_URL) {
|
|
1823
|
+
const res = encodeShareHash(payload);
|
|
1824
|
+
if (!res.ok) return null;
|
|
1825
|
+
const normalizedBase = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
|
|
1826
|
+
const fullUrl = `${normalizedBase}${res.hash}`;
|
|
1827
|
+
if (fullUrl.length > MAX_SHARE_HASH_CHARS) {
|
|
1828
|
+
return null;
|
|
1829
|
+
}
|
|
1830
|
+
return fullUrl;
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
// src/plans.ts
|
|
1834
|
+
var wasmInitPromise = null;
|
|
1835
|
+
var EM_DASH_CHAR = String.fromCharCode(8212);
|
|
1836
|
+
function sanitizeText(input) {
|
|
1837
|
+
if (!input.includes(EM_DASH_CHAR)) return input;
|
|
1838
|
+
return input.split(EM_DASH_CHAR).join(" - ");
|
|
1839
|
+
}
|
|
1840
|
+
async function ensurePlansWasm() {
|
|
1841
|
+
if (!wasmInitPromise) {
|
|
1842
|
+
wasmInitPromise = (async () => {
|
|
1843
|
+
try {
|
|
1844
|
+
const entryUrl = import.meta.resolve("@culpritsql/plans");
|
|
1845
|
+
const wasmUrl = new URL("./native/culprit_wasm_bg.wasm", entryUrl);
|
|
1846
|
+
const wasmBytes = await readFile(wasmUrl);
|
|
1847
|
+
await init({ module_or_path: wasmBytes });
|
|
1848
|
+
} catch (err) {
|
|
1849
|
+
wasmInitPromise = null;
|
|
1850
|
+
throw err;
|
|
1851
|
+
}
|
|
1852
|
+
})();
|
|
1853
|
+
}
|
|
1854
|
+
return wasmInitPromise;
|
|
1855
|
+
}
|
|
1856
|
+
function countPlanNodes(root) {
|
|
1857
|
+
let count = 1;
|
|
1858
|
+
for (const child of root.children) {
|
|
1859
|
+
count += countPlanNodes(child);
|
|
1860
|
+
}
|
|
1861
|
+
return count;
|
|
1862
|
+
}
|
|
1863
|
+
function isFullTableScanNode(node) {
|
|
1864
|
+
if (node.kind !== "scan" || !node.object) return false;
|
|
1865
|
+
if (node.index === null) return true;
|
|
1866
|
+
if (node.facts.scan_completion != null) return true;
|
|
1867
|
+
return /seq scan|table scan|clustered index scan|full scan/i.test(node.op);
|
|
1868
|
+
}
|
|
1869
|
+
function collectPlanSignals(root, minScanRows, scans, spills) {
|
|
1870
|
+
const walk = (node) => {
|
|
1871
|
+
if (isFullTableScanNode(node) && node.object) {
|
|
1872
|
+
const observedRows = node.act_rows ?? node.est_rows;
|
|
1873
|
+
if (observedRows >= minScanRows) {
|
|
1874
|
+
scans.push({
|
|
1875
|
+
nodeId: node.id,
|
|
1876
|
+
op: sanitizeText(node.op),
|
|
1877
|
+
table: sanitizeText(node.object),
|
|
1878
|
+
estRows: node.est_rows,
|
|
1879
|
+
actRows: node.act_rows,
|
|
1880
|
+
subtreeCost: node.subtree_cost
|
|
1881
|
+
});
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
const spillPages = node.runtime?.spill_pages ?? 0;
|
|
1885
|
+
const diskUsageKb = node.facts.disk_usage_kb ?? 0;
|
|
1886
|
+
const hasSpillWarning = node.warnings.includes("spill");
|
|
1887
|
+
const sortOnDisk = node.facts.sort_on_disk === true;
|
|
1888
|
+
const exchangeSpill = node.facts.exchange_spill === true;
|
|
1889
|
+
if (hasSpillWarning || sortOnDisk || exchangeSpill || spillPages > 0 || diskUsageKb > 0) {
|
|
1890
|
+
const parts = [];
|
|
1891
|
+
if (spillPages > 0) parts.push(`${spillPages} temp spill pages`);
|
|
1892
|
+
if (diskUsageKb > 0) parts.push(`${diskUsageKb} KB disk usage`);
|
|
1893
|
+
if (sortOnDisk) parts.push("external disk sort");
|
|
1894
|
+
if (exchangeSpill) parts.push("parallel exchange spill");
|
|
1895
|
+
spills.push({
|
|
1896
|
+
nodeId: node.id,
|
|
1897
|
+
op: sanitizeText(node.op),
|
|
1898
|
+
detail: parts.length > 0 ? parts.join(", ") : "operator spilled intermediate data to disk"
|
|
1899
|
+
});
|
|
1900
|
+
}
|
|
1901
|
+
for (const child of node.children) {
|
|
1902
|
+
walk(child);
|
|
1903
|
+
}
|
|
1904
|
+
};
|
|
1905
|
+
walk(root);
|
|
1906
|
+
}
|
|
1907
|
+
function redactPlanPayloadText(plan, rawText, title, redact) {
|
|
1908
|
+
const trimmed = rawText.trim() || plan.raw || "";
|
|
1909
|
+
if (!redact) return trimmed;
|
|
1910
|
+
try {
|
|
1911
|
+
return exportPlan(plan, title, "native", { redact: true, notes: [] }).contents;
|
|
1912
|
+
} catch {
|
|
1913
|
+
return scrubSqlLiterals(trimmed);
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
async function analyzePlanGate(planText, opts = {}) {
|
|
1917
|
+
await ensurePlansWasm();
|
|
1918
|
+
const file = opts.file ?? "plan.json";
|
|
1919
|
+
const engineHint = opts.engine && opts.engine !== "auto" ? opts.engine : void 0;
|
|
1920
|
+
let plan;
|
|
1921
|
+
try {
|
|
1922
|
+
plan = parsePlan(planText.trim(), engineHint);
|
|
1923
|
+
} catch (err) {
|
|
1924
|
+
if (err instanceof ParserError) {
|
|
1925
|
+
throw new Error(`Invalid execution plan (${file}): ${sanitizeText(err.error.message)}`);
|
|
1926
|
+
}
|
|
1927
|
+
throw err;
|
|
1928
|
+
}
|
|
1929
|
+
const nodeCount = countPlanNodes(plan.root);
|
|
1930
|
+
const title = opts.title ?? `${plan.engine.toUpperCase()} Plan (${nodeCount} steps)`;
|
|
1931
|
+
const minScanRows = opts.minScanRows ?? 0;
|
|
1932
|
+
const fullTableScans = [];
|
|
1933
|
+
const diskSpills = [];
|
|
1934
|
+
collectPlanSignals(plan.root, minScanRows, fullTableScans, diskSpills);
|
|
1935
|
+
const findings = [];
|
|
1936
|
+
if (!opts.allowSeqScan) {
|
|
1937
|
+
for (const scan of fullTableScans) {
|
|
1938
|
+
const rowDesc = scan.actRows != null ? `${scan.actRows} actual rows` : `${Math.round(scan.estRows)} estimated rows`;
|
|
1939
|
+
findings.push({
|
|
1940
|
+
ruleId: "PLAN001",
|
|
1941
|
+
severity: "medium",
|
|
1942
|
+
file,
|
|
1943
|
+
line: 1,
|
|
1944
|
+
column: 1,
|
|
1945
|
+
endLine: 1,
|
|
1946
|
+
endColumn: 1,
|
|
1947
|
+
title: RULES.PLAN001.title,
|
|
1948
|
+
message: `Operator #${scan.nodeId} (${scan.op}) performs a full scan on '${scan.table}' (${rowDesc}, cost ${scan.subtreeCost.toFixed(2)}).`,
|
|
1949
|
+
suggestion: `Add a selective index supporting the filter or join columns on '${scan.table}', or pass --allow-seq-scan for small lookup tables.`
|
|
1950
|
+
});
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
for (const spill of diskSpills) {
|
|
1954
|
+
findings.push({
|
|
1955
|
+
ruleId: "PLAN002",
|
|
1956
|
+
severity: "high",
|
|
1957
|
+
file,
|
|
1958
|
+
line: 1,
|
|
1959
|
+
column: 1,
|
|
1960
|
+
endLine: 1,
|
|
1961
|
+
endColumn: 1,
|
|
1962
|
+
title: RULES.PLAN002.title,
|
|
1963
|
+
message: `Operator #${spill.nodeId} (${spill.op}) spilled to disk (${spill.detail}).`,
|
|
1964
|
+
suggestion: "Increase working memory (such as work_mem in PostgreSQL), refresh stale table statistics, or add an index that avoids large sorts/hashes."
|
|
1965
|
+
});
|
|
1966
|
+
}
|
|
1967
|
+
for (const insight of plan.insights?.items ?? []) {
|
|
1968
|
+
if (insight.severity === "high" || insight.severity === "medium") {
|
|
1969
|
+
findings.push({
|
|
1970
|
+
ruleId: "PLAN003",
|
|
1971
|
+
severity: insight.severity,
|
|
1972
|
+
file,
|
|
1973
|
+
line: 1,
|
|
1974
|
+
column: 1,
|
|
1975
|
+
endLine: 1,
|
|
1976
|
+
endColumn: 1,
|
|
1977
|
+
title: sanitizeText(insight.title),
|
|
1978
|
+
message: `${sanitizeText(insight.title)}: ${sanitizeText(insight.detail)}`,
|
|
1979
|
+
suggestion: sanitizeText(insight.fix),
|
|
1980
|
+
...insight.fix_sql ? { fixSql: sanitizeText(insight.fix_sql) } : {}
|
|
1981
|
+
});
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
if (typeof opts.maxCost === "number" && plan.total_cost > opts.maxCost) {
|
|
1985
|
+
findings.push({
|
|
1986
|
+
ruleId: "PLAN004",
|
|
1987
|
+
severity: "high",
|
|
1988
|
+
file,
|
|
1989
|
+
line: 1,
|
|
1990
|
+
column: 1,
|
|
1991
|
+
endLine: 1,
|
|
1992
|
+
endColumn: 1,
|
|
1993
|
+
title: RULES.PLAN004.title,
|
|
1994
|
+
message: `Plan total cost ${plan.total_cost.toFixed(2)} exceeds configured budget of ${opts.maxCost.toFixed(2)}.`,
|
|
1995
|
+
suggestion: "Inspect the highest-cost operators in Culprit Explain and add covering indexes or rewrite expensive joins."
|
|
1996
|
+
});
|
|
1997
|
+
}
|
|
1998
|
+
const redact = opts.redactShare !== false;
|
|
1999
|
+
const redactedRaw = redactPlanPayloadText(plan, planText, title, redact);
|
|
2000
|
+
const redactedQuery = plan.statement ? redact ? scrubSqlLiterals(plan.statement) : plan.statement : void 0;
|
|
2001
|
+
const sharePayload = {
|
|
2002
|
+
v: 1,
|
|
2003
|
+
m: "plan",
|
|
2004
|
+
t: title,
|
|
2005
|
+
e: plan.engine,
|
|
2006
|
+
p: redactedRaw,
|
|
2007
|
+
...redactedQuery ? { q: redactedQuery } : {}
|
|
2008
|
+
};
|
|
2009
|
+
const explainUrl = buildExplainShareUrl(
|
|
2010
|
+
sharePayload,
|
|
2011
|
+
opts.explainBaseUrl ?? DEFAULT_EXPLAIN_BASE_URL
|
|
2012
|
+
);
|
|
2013
|
+
const hasHighFinding = findings.some((f) => f.severity === "high");
|
|
2014
|
+
return {
|
|
2015
|
+
passed: !hasHighFinding,
|
|
2016
|
+
file,
|
|
2017
|
+
title,
|
|
2018
|
+
engine: plan.engine,
|
|
2019
|
+
plan,
|
|
2020
|
+
totalCost: plan.total_cost,
|
|
2021
|
+
elapsedMs: plan.facts.elapsed_ms ?? plan.root.act_time_ms ?? null,
|
|
2022
|
+
nodeCount,
|
|
2023
|
+
fullTableScans,
|
|
2024
|
+
diskSpills,
|
|
2025
|
+
findings,
|
|
2026
|
+
explainUrl
|
|
2027
|
+
};
|
|
2028
|
+
}
|
|
2029
|
+
function collectAccessModesByTable(root) {
|
|
2030
|
+
const byTable = /* @__PURE__ */ new Map();
|
|
2031
|
+
const walk = (node) => {
|
|
2032
|
+
if (node.object) {
|
|
2033
|
+
const key = node.object.toLowerCase();
|
|
2034
|
+
const set = byTable.get(key) ?? /* @__PURE__ */ new Set();
|
|
2035
|
+
if (node.kind === "seek") {
|
|
2036
|
+
set.add("seek");
|
|
2037
|
+
} else if (isFullTableScanNode(node)) {
|
|
2038
|
+
set.add("scan");
|
|
2039
|
+
}
|
|
2040
|
+
if (set.size > 0) byTable.set(key, set);
|
|
2041
|
+
}
|
|
2042
|
+
for (const child of node.children) walk(child);
|
|
2043
|
+
};
|
|
2044
|
+
walk(root);
|
|
2045
|
+
return byTable;
|
|
2046
|
+
}
|
|
2047
|
+
async function comparePlanGate(beforeText, afterText, opts = {}) {
|
|
2048
|
+
await ensurePlansWasm();
|
|
2049
|
+
const beforeFile = opts.beforeFile ?? "before.plan";
|
|
2050
|
+
const afterFile = opts.afterFile ?? "after.plan";
|
|
2051
|
+
const beforeName = opts.beforeName ?? "Before";
|
|
2052
|
+
const afterName = opts.afterName ?? "After";
|
|
2053
|
+
const engineHint = opts.engine && opts.engine !== "auto" ? opts.engine : void 0;
|
|
2054
|
+
let beforePlan;
|
|
2055
|
+
let afterPlan;
|
|
2056
|
+
try {
|
|
2057
|
+
beforePlan = parsePlan(beforeText.trim(), engineHint);
|
|
2058
|
+
} catch (err) {
|
|
2059
|
+
if (err instanceof ParserError) {
|
|
2060
|
+
throw new Error(`Invalid baseline plan (${beforeFile}): ${sanitizeText(err.error.message)}`);
|
|
2061
|
+
}
|
|
2062
|
+
throw err;
|
|
2063
|
+
}
|
|
2064
|
+
try {
|
|
2065
|
+
afterPlan = parsePlan(afterText.trim(), engineHint);
|
|
2066
|
+
} catch (err) {
|
|
2067
|
+
if (err instanceof ParserError) {
|
|
2068
|
+
throw new Error(`Invalid candidate plan (${afterFile}): ${sanitizeText(err.error.message)}`);
|
|
2069
|
+
}
|
|
2070
|
+
throw err;
|
|
2071
|
+
}
|
|
2072
|
+
const diff = diffPlans(beforePlan, beforeName, afterPlan, afterName);
|
|
2073
|
+
diff.headlines = diff.headlines.map(sanitizeText);
|
|
2074
|
+
for (const ch of diff.changes) {
|
|
2075
|
+
ch.title = sanitizeText(ch.title);
|
|
2076
|
+
if (ch.detail) ch.detail = sanitizeText(ch.detail);
|
|
2077
|
+
}
|
|
2078
|
+
for (const sc of diff.scenarios) {
|
|
2079
|
+
sc.title = sanitizeText(sc.title);
|
|
2080
|
+
if (sc.detail) sc.detail = sanitizeText(sc.detail);
|
|
2081
|
+
}
|
|
2082
|
+
const maxCostRegressionRatio = opts.maxCostRegressionRatio ?? 1.25;
|
|
2083
|
+
const maxTimeRegressionRatio = opts.maxTimeRegressionRatio ?? 1.5;
|
|
2084
|
+
const timeA = diff.time_a_ms ?? beforePlan.facts.elapsed_ms ?? null;
|
|
2085
|
+
const timeB = diff.time_b_ms ?? afterPlan.facts.elapsed_ms ?? null;
|
|
2086
|
+
let speedupFactor = null;
|
|
2087
|
+
if (timeA != null && timeB != null && timeA > 0 && timeB > 0) {
|
|
2088
|
+
speedupFactor = timeA / timeB;
|
|
2089
|
+
} else if (diff.cost_ratio != null && diff.cost_ratio > 0) {
|
|
2090
|
+
speedupFactor = 1 / diff.cost_ratio;
|
|
2091
|
+
}
|
|
2092
|
+
const regressionReasons = [];
|
|
2093
|
+
const hasBothTimings = timeA != null && timeB != null && timeA > 0 && timeB > 0;
|
|
2094
|
+
if (hasBothTimings && timeB >= 5 && timeB / timeA >= maxTimeRegressionRatio) {
|
|
2095
|
+
regressionReasons.push(
|
|
2096
|
+
`Measured execution time regressed ${(timeB / timeA).toFixed(2)}x (${timeA.toFixed(2)} ms -> ${timeB.toFixed(2)} ms).`
|
|
2097
|
+
);
|
|
2098
|
+
}
|
|
2099
|
+
if (!hasBothTimings && diff.cost_ratio != null && diff.cost_ratio >= maxCostRegressionRatio) {
|
|
2100
|
+
const costA = (diff.cost_a ?? beforePlan.total_cost).toFixed(2);
|
|
2101
|
+
const costB = (diff.cost_b ?? afterPlan.total_cost).toFixed(2);
|
|
2102
|
+
regressionReasons.push(
|
|
2103
|
+
`Estimated optimizer cost increased ${diff.cost_ratio.toFixed(2)}x (${costA} -> ${costB}).`
|
|
2104
|
+
);
|
|
2105
|
+
}
|
|
2106
|
+
if (diff.warnings_added.length > 0) {
|
|
2107
|
+
regressionReasons.push(
|
|
2108
|
+
`Candidate plan introduced new plan warning(s): ${diff.warnings_added.join(", ")}.`
|
|
2109
|
+
);
|
|
2110
|
+
}
|
|
2111
|
+
const accessBefore = collectAccessModesByTable(beforePlan.root);
|
|
2112
|
+
const accessAfter = collectAccessModesByTable(afterPlan.root);
|
|
2113
|
+
for (const [table, modesBefore] of accessBefore.entries()) {
|
|
2114
|
+
const modesAfter = accessAfter.get(table);
|
|
2115
|
+
if (modesBefore.has("seek") && !modesBefore.has("scan") && modesAfter?.has("scan") && !modesAfter.has("seek")) {
|
|
2116
|
+
regressionReasons.push(
|
|
2117
|
+
`Access path on '${table}' degraded from an index seek in ${beforeName} to a full table scan in ${afterName}.`
|
|
2118
|
+
);
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
const regressed = regressionReasons.length > 0;
|
|
2122
|
+
const findings = regressionReasons.map((reason) => ({
|
|
2123
|
+
ruleId: "PLAN005",
|
|
2124
|
+
severity: "high",
|
|
2125
|
+
file: afterFile,
|
|
2126
|
+
line: 1,
|
|
2127
|
+
column: 1,
|
|
2128
|
+
endLine: 1,
|
|
2129
|
+
endColumn: 1,
|
|
2130
|
+
title: RULES.PLAN005.title,
|
|
2131
|
+
message: reason,
|
|
2132
|
+
suggestion: "Open the side-by-side plan diff in Culprit Explain to inspect operator changes, predicate selectivity, and index usage."
|
|
2133
|
+
}));
|
|
2134
|
+
let verdictSummary;
|
|
2135
|
+
if (hasBothTimings && timeA != null && timeB != null) {
|
|
2136
|
+
if (timeB < timeA) {
|
|
2137
|
+
verdictSummary = `${(timeA / timeB).toFixed(1)}x faster (${timeA.toFixed(2)} ms -> ${timeB.toFixed(2)} ms)`;
|
|
2138
|
+
} else if (timeB > timeA) {
|
|
2139
|
+
verdictSummary = `${(timeB / timeA).toFixed(1)}x slower (${timeA.toFixed(2)} ms -> ${timeB.toFixed(2)} ms)`;
|
|
2140
|
+
} else {
|
|
2141
|
+
verdictSummary = `Unchanged runtime (${timeA.toFixed(2)} ms)`;
|
|
2142
|
+
}
|
|
2143
|
+
} else if (diff.cost_ratio != null && diff.cost_a != null && diff.cost_b != null) {
|
|
2144
|
+
if (diff.cost_ratio < 1) {
|
|
2145
|
+
verdictSummary = `${(1 / diff.cost_ratio).toFixed(1)}x lower cost (${diff.cost_a.toFixed(2)} -> ${diff.cost_b.toFixed(2)})`;
|
|
2146
|
+
} else if (diff.cost_ratio > 1) {
|
|
2147
|
+
verdictSummary = `${diff.cost_ratio.toFixed(1)}x higher cost (${diff.cost_a.toFixed(2)} -> ${diff.cost_b.toFixed(2)})`;
|
|
2148
|
+
} else {
|
|
2149
|
+
verdictSummary = `Identical optimizer cost (${diff.cost_a.toFixed(2)})`;
|
|
2150
|
+
}
|
|
2151
|
+
} else if (diff.same_shape) {
|
|
2152
|
+
verdictSummary = "Identical operator shape";
|
|
2153
|
+
} else {
|
|
2154
|
+
verdictSummary = `${diff.changes.length} structural operator change(s)`;
|
|
2155
|
+
}
|
|
2156
|
+
const redact = opts.redactShare !== false;
|
|
2157
|
+
const redactedPa = redactPlanPayloadText(beforePlan, beforeText, beforeName, redact);
|
|
2158
|
+
const redactedPb = redactPlanPayloadText(afterPlan, afterText, afterName, redact);
|
|
2159
|
+
const sharePayload = {
|
|
2160
|
+
v: 1,
|
|
2161
|
+
m: "compare",
|
|
2162
|
+
...beforePlan.engine === afterPlan.engine ? { e: afterPlan.engine } : {},
|
|
2163
|
+
na: beforeName,
|
|
2164
|
+
pa: redactedPa,
|
|
2165
|
+
nb: afterName,
|
|
2166
|
+
pb: redactedPb
|
|
2167
|
+
};
|
|
2168
|
+
const explainUrl = buildExplainShareUrl(
|
|
2169
|
+
sharePayload,
|
|
2170
|
+
opts.explainBaseUrl ?? DEFAULT_EXPLAIN_BASE_URL
|
|
2171
|
+
);
|
|
2172
|
+
return {
|
|
2173
|
+
passed: !regressed,
|
|
2174
|
+
regressed,
|
|
2175
|
+
regressionReasons,
|
|
2176
|
+
beforeFile,
|
|
2177
|
+
afterFile,
|
|
2178
|
+
beforeName,
|
|
2179
|
+
afterName,
|
|
2180
|
+
engine: afterPlan.engine,
|
|
2181
|
+
beforePlan,
|
|
2182
|
+
afterPlan,
|
|
2183
|
+
diff,
|
|
2184
|
+
speedupFactor,
|
|
2185
|
+
costChangeRatio: diff.cost_ratio,
|
|
2186
|
+
verdictSummary,
|
|
2187
|
+
findings,
|
|
2188
|
+
explainUrl
|
|
2189
|
+
};
|
|
2190
|
+
}
|
|
2191
|
+
|
|
2192
|
+
// src/reporters.ts
|
|
2193
|
+
var STICKY_PR_COMMENT_MARKER = "<!-- culprit-ci-report -->";
|
|
2194
|
+
function severityToSarifLevel(severity) {
|
|
2195
|
+
if (severity === "high") return "error";
|
|
2196
|
+
if (severity === "medium") return "warning";
|
|
2197
|
+
return "note";
|
|
2198
|
+
}
|
|
2199
|
+
function severityToProblemSeverity(severity) {
|
|
2200
|
+
if (severity === "high") return "error";
|
|
2201
|
+
if (severity === "medium") return "warning";
|
|
2202
|
+
return "recommendation";
|
|
2203
|
+
}
|
|
2204
|
+
function normalizeSarifUri(file) {
|
|
2205
|
+
return file.replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "");
|
|
2206
|
+
}
|
|
2207
|
+
function buildRuleDescriptor(meta) {
|
|
2208
|
+
return {
|
|
2209
|
+
id: meta.id,
|
|
2210
|
+
name: meta.title.replace(/[^A-Za-z0-9]+/g, ""),
|
|
2211
|
+
shortDescription: { text: sanitizeText(meta.title) },
|
|
2212
|
+
fullDescription: { text: sanitizeText(meta.description) },
|
|
2213
|
+
helpUri: meta.helpUri,
|
|
2214
|
+
help: {
|
|
2215
|
+
text: `${sanitizeText(meta.title)}: ${sanitizeText(meta.description)}`,
|
|
2216
|
+
markdown: `**${sanitizeText(meta.title)}**
|
|
2217
|
+
|
|
2218
|
+
${sanitizeText(meta.description)}`
|
|
2219
|
+
},
|
|
2220
|
+
defaultConfiguration: {
|
|
2221
|
+
level: severityToSarifLevel(meta.severity)
|
|
2222
|
+
},
|
|
2223
|
+
properties: {
|
|
2224
|
+
tags: ["sql", "database", meta.category],
|
|
2225
|
+
"problem.severity": severityToProblemSeverity(meta.severity)
|
|
2226
|
+
}
|
|
2227
|
+
};
|
|
2228
|
+
}
|
|
2229
|
+
function formatSarif(report) {
|
|
2230
|
+
const usedRuleIds = [];
|
|
2231
|
+
const ruleIndexMap = /* @__PURE__ */ new Map();
|
|
2232
|
+
for (const finding of report.findings) {
|
|
2233
|
+
if (!ruleIndexMap.has(finding.ruleId)) {
|
|
2234
|
+
ruleIndexMap.set(finding.ruleId, usedRuleIds.length);
|
|
2235
|
+
usedRuleIds.push(finding.ruleId);
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
const rules = usedRuleIds.map((id) => {
|
|
2239
|
+
const meta = RULES[id] ?? {
|
|
2240
|
+
id,
|
|
2241
|
+
severity: "medium",
|
|
2242
|
+
category: "migration",
|
|
2243
|
+
title: id,
|
|
2244
|
+
description: `Culprit SQL rule ${id}.`,
|
|
2245
|
+
helpUri: "https://github.com/culpritsql/culprit-ci"
|
|
2246
|
+
};
|
|
2247
|
+
return buildRuleDescriptor(meta);
|
|
2248
|
+
});
|
|
2249
|
+
const results = report.findings.map((f) => {
|
|
2250
|
+
const startLine = Math.max(1, f.line);
|
|
2251
|
+
const startColumn = Math.max(1, f.column);
|
|
2252
|
+
const endLine = Math.max(startLine, f.endLine);
|
|
2253
|
+
const endColumn = endLine === startLine ? Math.max(startColumn, f.endColumn) : Math.max(1, f.endColumn);
|
|
2254
|
+
const textParts = [sanitizeText(f.message)];
|
|
2255
|
+
if (f.suggestion) textParts.push(`Fix: ${sanitizeText(f.suggestion)}`);
|
|
2256
|
+
if (f.fixSql) textParts.push(`SQL: ${sanitizeText(f.fixSql)}`);
|
|
2257
|
+
return {
|
|
2258
|
+
ruleId: f.ruleId,
|
|
2259
|
+
ruleIndex: ruleIndexMap.get(f.ruleId) ?? 0,
|
|
2260
|
+
level: severityToSarifLevel(f.severity),
|
|
2261
|
+
message: {
|
|
2262
|
+
text: textParts.join(" ")
|
|
2263
|
+
},
|
|
2264
|
+
locations: [
|
|
2265
|
+
{
|
|
2266
|
+
physicalLocation: {
|
|
2267
|
+
artifactLocation: {
|
|
2268
|
+
uri: normalizeSarifUri(f.file),
|
|
2269
|
+
uriBaseId: "%SRCROOT%"
|
|
2270
|
+
},
|
|
2271
|
+
region: {
|
|
2272
|
+
startLine,
|
|
2273
|
+
startColumn,
|
|
2274
|
+
endLine,
|
|
2275
|
+
endColumn
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
2279
|
+
]
|
|
2280
|
+
};
|
|
2281
|
+
});
|
|
2282
|
+
const log = {
|
|
2283
|
+
$schema: "https://json.schemastore.org/sarif-2.1.0.json",
|
|
2284
|
+
version: "2.1.0",
|
|
2285
|
+
runs: [
|
|
2286
|
+
{
|
|
2287
|
+
tool: {
|
|
2288
|
+
driver: {
|
|
2289
|
+
name: "Culprit CI",
|
|
2290
|
+
informationUri: "https://github.com/culpritsql/culprit-ci",
|
|
2291
|
+
version: report.version,
|
|
2292
|
+
rules
|
|
2293
|
+
}
|
|
2294
|
+
},
|
|
2295
|
+
results
|
|
2296
|
+
}
|
|
2297
|
+
]
|
|
2298
|
+
};
|
|
2299
|
+
return JSON.stringify(log, null, 2);
|
|
2300
|
+
}
|
|
2301
|
+
function escapeMdCell(text) {
|
|
2302
|
+
return sanitizeText(text).replace(/\|/g, "\\|").replace(/\r?\n/g, " ").trim();
|
|
2303
|
+
}
|
|
2304
|
+
function formatSeverityPill(severity) {
|
|
2305
|
+
if (severity === "high") return "**HIGH**";
|
|
2306
|
+
if (severity === "medium") return "MEDIUM";
|
|
2307
|
+
return "LOW";
|
|
2308
|
+
}
|
|
2309
|
+
function formatMarkdown(report) {
|
|
2310
|
+
const lines = [STICKY_PR_COMMENT_MARKER];
|
|
2311
|
+
const badgeUrl = report.passed ? "https://img.shields.io/badge/Culprit_CI-Passed-2ea043?style=flat-square" : "https://img.shields.io/badge/Culprit_CI-Failed-da3633?style=flat-square";
|
|
2312
|
+
const statusWord = report.passed ? "Passed" : "Failed";
|
|
2313
|
+
lines.push(`## Culprit SQL CI: ${statusWord}`);
|
|
2314
|
+
lines.push("");
|
|
2315
|
+
lines.push(
|
|
2316
|
+
` **High:** ${report.summary.high} | **Medium:** ${report.summary.medium} | **Low:** ${report.summary.low} | **Files Checked:** ${report.summary.filesChecked} | **Fail Threshold:** \`${report.failOn}\``
|
|
2317
|
+
);
|
|
2318
|
+
lines.push("");
|
|
2319
|
+
if (report.compareResult) {
|
|
2320
|
+
const cmp = report.compareResult;
|
|
2321
|
+
const verdictLabel = cmp.regressed ? "Regression Detected" : "Verified";
|
|
2322
|
+
lines.push(`### Execution Plan Diff (${verdictLabel})`);
|
|
2323
|
+
lines.push("");
|
|
2324
|
+
lines.push(
|
|
2325
|
+
`- **Comparison:** \`${escapeMdCell(cmp.beforeName)}\` -> \`${escapeMdCell(cmp.afterName)}\` (\`${cmp.engine}\`)`
|
|
2326
|
+
);
|
|
2327
|
+
lines.push(`- **Verdict:** **${sanitizeText(cmp.verdictSummary)}**`);
|
|
2328
|
+
if (cmp.diff.headlines.length > 0) {
|
|
2329
|
+
for (const hl of cmp.diff.headlines) {
|
|
2330
|
+
lines.push(`- ${sanitizeText(hl)}`);
|
|
2331
|
+
}
|
|
2332
|
+
}
|
|
2333
|
+
if (cmp.regressionReasons.length > 0) {
|
|
2334
|
+
for (const reason of cmp.regressionReasons) {
|
|
2335
|
+
lines.push(`- **Gate Failure:** ${sanitizeText(reason)}`);
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
if (cmp.explainUrl) {
|
|
2339
|
+
lines.push("");
|
|
2340
|
+
lines.push(`[Open Interactive Diff in Culprit Explain](${cmp.explainUrl})`);
|
|
2341
|
+
}
|
|
2342
|
+
lines.push("");
|
|
2343
|
+
}
|
|
2344
|
+
if (report.planResults.length > 0) {
|
|
2345
|
+
lines.push("### Execution Plan Gate");
|
|
2346
|
+
lines.push("");
|
|
2347
|
+
for (const pr of report.planResults) {
|
|
2348
|
+
const dur = pr.elapsedMs != null ? `, elapsed ${pr.elapsedMs.toFixed(2)} ms` : "";
|
|
2349
|
+
lines.push(
|
|
2350
|
+
`- \`${escapeMdCell(pr.file)}\` (\`${pr.engine}\`): ${pr.nodeCount} operators, cost ${pr.totalCost.toFixed(2)}${dur}, ${pr.fullTableScans.length} full scan(s), ${pr.diskSpills.length} spill(s)` + (pr.explainUrl ? ` ([Open Interactive Plan in Culprit Explain](${pr.explainUrl}))` : "")
|
|
2351
|
+
);
|
|
2352
|
+
}
|
|
2353
|
+
lines.push("");
|
|
2354
|
+
}
|
|
2355
|
+
if (report.findings.length === 0) {
|
|
2356
|
+
lines.push("No SQL migration, query, or execution plan issues found.");
|
|
2357
|
+
lines.push("");
|
|
2358
|
+
} else {
|
|
2359
|
+
lines.push("### Findings");
|
|
2360
|
+
lines.push("");
|
|
2361
|
+
lines.push("| File:Line | Rule | Severity | Issue & Fix |");
|
|
2362
|
+
lines.push("| :--- | :--- | :--- | :--- |");
|
|
2363
|
+
for (const f of report.findings) {
|
|
2364
|
+
const loc = `\`${escapeMdCell(f.file)}:${f.line}:${f.column}\``;
|
|
2365
|
+
const fixSqlPart = f.fixSql ? ` Suggested SQL: \`${escapeMdCell(f.fixSql)}\`` : "";
|
|
2366
|
+
const desc = `${escapeMdCell(f.message)} **Fix:** ${escapeMdCell(f.suggestion)}${fixSqlPart}`;
|
|
2367
|
+
lines.push(`| ${loc} | \`${f.ruleId}\` | ${formatSeverityPill(f.severity)} | ${desc} |`);
|
|
2368
|
+
}
|
|
2369
|
+
lines.push("");
|
|
2370
|
+
}
|
|
2371
|
+
lines.push(
|
|
2372
|
+
"_Generated locally by [`@culpritsql/ci`](https://github.com/culpritsql/culprit-ci) with zero telemetry or query uploads._"
|
|
2373
|
+
);
|
|
2374
|
+
return `${lines.join("\n")}
|
|
2375
|
+
`;
|
|
2376
|
+
}
|
|
2377
|
+
function formatText(report) {
|
|
2378
|
+
const lines = [];
|
|
2379
|
+
const headerStatus = report.passed ? "PASSED" : "FAILED";
|
|
2380
|
+
lines.push(
|
|
2381
|
+
`Culprit CI v${report.version}: ${headerStatus} (high: ${report.summary.high}, medium: ${report.summary.medium}, low: ${report.summary.low}, fail-on: ${report.failOn})`
|
|
2382
|
+
);
|
|
2383
|
+
if (report.compareResult) {
|
|
2384
|
+
const cmp = report.compareResult;
|
|
2385
|
+
lines.push(
|
|
2386
|
+
`Plan Diff [${cmp.beforeName} -> ${cmp.afterName}]: ${sanitizeText(cmp.verdictSummary)}` + (cmp.regressed ? " [REGRESSED]" : " [OK]")
|
|
2387
|
+
);
|
|
2388
|
+
if (cmp.explainUrl) {
|
|
2389
|
+
lines.push(` Interactive Diff: ${cmp.explainUrl}`);
|
|
2390
|
+
}
|
|
2391
|
+
}
|
|
2392
|
+
for (const pr of report.planResults) {
|
|
2393
|
+
lines.push(
|
|
2394
|
+
`Plan [${pr.file}]: engine=${pr.engine} steps=${pr.nodeCount} cost=${pr.totalCost.toFixed(2)} scans=${pr.fullTableScans.length} spills=${pr.diskSpills.length}`
|
|
2395
|
+
);
|
|
2396
|
+
if (pr.explainUrl) {
|
|
2397
|
+
lines.push(` Interactive Plan: ${pr.explainUrl}`);
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
if (report.findings.length > 0) {
|
|
2401
|
+
lines.push("");
|
|
2402
|
+
for (const f of report.findings) {
|
|
2403
|
+
lines.push(
|
|
2404
|
+
`${f.file}:${f.line}:${f.column} [${f.severity.toUpperCase()}] ${f.ruleId}: ${sanitizeText(f.message)}`
|
|
2405
|
+
);
|
|
2406
|
+
lines.push(` Fix: ${sanitizeText(f.suggestion)}`);
|
|
2407
|
+
if (f.fixSql) {
|
|
2408
|
+
lines.push(` SQL: ${sanitizeText(f.fixSql)}`);
|
|
2409
|
+
}
|
|
2410
|
+
}
|
|
2411
|
+
}
|
|
2412
|
+
return `${lines.join("\n")}
|
|
2413
|
+
`;
|
|
2414
|
+
}
|
|
2415
|
+
function formatJson(report) {
|
|
2416
|
+
const serializable = {
|
|
2417
|
+
version: report.version,
|
|
2418
|
+
passed: report.passed,
|
|
2419
|
+
failOn: report.failOn,
|
|
2420
|
+
engine: report.engine,
|
|
2421
|
+
summary: report.summary,
|
|
2422
|
+
findings: report.findings,
|
|
2423
|
+
planResults: report.planResults.map(({ plan: _plan, ...rest }) => rest),
|
|
2424
|
+
compareResult: report.compareResult ? (() => {
|
|
2425
|
+
const { beforePlan: _a, afterPlan: _b, ...rest } = report.compareResult;
|
|
2426
|
+
return rest;
|
|
2427
|
+
})() : null
|
|
2428
|
+
};
|
|
2429
|
+
return `${JSON.stringify(serializable, null, 2)}
|
|
2430
|
+
`;
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
// src/index.ts
|
|
2434
|
+
var VERSION = "0.5.6";
|
|
2435
|
+
var SEVERITY_RANK = {
|
|
2436
|
+
low: 1,
|
|
2437
|
+
medium: 2,
|
|
2438
|
+
high: 3
|
|
2439
|
+
};
|
|
2440
|
+
function exceedsFailOnThreshold(severity, failOn) {
|
|
2441
|
+
if (failOn === "none") return false;
|
|
2442
|
+
return SEVERITY_RANK[severity] >= SEVERITY_RANK[failOn];
|
|
2443
|
+
}
|
|
2444
|
+
function toPlanEngineHint(engine) {
|
|
2445
|
+
if (engine === "auto") return "auto";
|
|
2446
|
+
return engine;
|
|
2447
|
+
}
|
|
2448
|
+
async function runCiGate(opts = {}) {
|
|
2449
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
2450
|
+
const engine = opts.engine ?? "auto";
|
|
2451
|
+
const failOn = opts.failOn ?? "high";
|
|
2452
|
+
const redactShare = opts.redactShare !== false;
|
|
2453
|
+
let schemaSql;
|
|
2454
|
+
if (opts.schemaFile) {
|
|
2455
|
+
const schemaAbs = path2.resolve(cwd, opts.schemaFile);
|
|
2456
|
+
schemaSql = await readFile2(schemaAbs, "utf8");
|
|
2457
|
+
}
|
|
2458
|
+
const findings = [];
|
|
2459
|
+
const checkedFiles = /* @__PURE__ */ new Set();
|
|
2460
|
+
if (opts.sqlPatterns && opts.sqlPatterns.length > 0) {
|
|
2461
|
+
const resolvedMigrations = await resolveSqlInputs(opts.sqlPatterns, cwd);
|
|
2462
|
+
for (const item of resolvedMigrations) {
|
|
2463
|
+
checkedFiles.add(item.displayPath);
|
|
2464
|
+
const content = await readFile2(item.absPath, "utf8");
|
|
2465
|
+
const fileFindings = lintSql(content, {
|
|
2466
|
+
file: item.displayPath,
|
|
2467
|
+
engine,
|
|
2468
|
+
mode: "migration",
|
|
2469
|
+
schemaSql,
|
|
2470
|
+
disabledRules: opts.disabledRules
|
|
2471
|
+
});
|
|
2472
|
+
findings.push(...fileFindings);
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
if (opts.queryPatterns && opts.queryPatterns.length > 0) {
|
|
2476
|
+
const resolvedQueries = await resolveSqlInputs(opts.queryPatterns, cwd);
|
|
2477
|
+
for (const item of resolvedQueries) {
|
|
2478
|
+
checkedFiles.add(item.displayPath);
|
|
2479
|
+
const content = await readFile2(item.absPath, "utf8");
|
|
2480
|
+
const fileFindings = lintSql(content, {
|
|
2481
|
+
file: item.displayPath,
|
|
2482
|
+
engine,
|
|
2483
|
+
mode: "query",
|
|
2484
|
+
schemaSql,
|
|
2485
|
+
disabledRules: opts.disabledRules
|
|
2486
|
+
});
|
|
2487
|
+
findings.push(...fileFindings);
|
|
2488
|
+
}
|
|
2489
|
+
}
|
|
2490
|
+
const planResults = [];
|
|
2491
|
+
if (opts.planFiles && opts.planFiles.length > 0) {
|
|
2492
|
+
for (const planPath of opts.planFiles) {
|
|
2493
|
+
const abs = path2.resolve(cwd, planPath);
|
|
2494
|
+
const displayPath = toRelativeDisplayPath(abs, cwd);
|
|
2495
|
+
checkedFiles.add(displayPath);
|
|
2496
|
+
const rawPlan = await readFile2(abs, "utf8");
|
|
2497
|
+
const res = await analyzePlanGate(rawPlan, {
|
|
2498
|
+
file: displayPath,
|
|
2499
|
+
engine: toPlanEngineHint(engine),
|
|
2500
|
+
allowSeqScan: opts.allowSeqScan,
|
|
2501
|
+
maxCost: opts.maxCost,
|
|
2502
|
+
redactShare
|
|
2503
|
+
});
|
|
2504
|
+
planResults.push(res);
|
|
2505
|
+
findings.push(...res.findings);
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
let compareResult = null;
|
|
2509
|
+
if (opts.comparePlans) {
|
|
2510
|
+
const beforeAbs = path2.resolve(cwd, opts.comparePlans.beforeFile);
|
|
2511
|
+
const afterAbs = path2.resolve(cwd, opts.comparePlans.afterFile);
|
|
2512
|
+
const beforeDisplay = toRelativeDisplayPath(beforeAbs, cwd);
|
|
2513
|
+
const afterDisplay = toRelativeDisplayPath(afterAbs, cwd);
|
|
2514
|
+
checkedFiles.add(beforeDisplay);
|
|
2515
|
+
checkedFiles.add(afterDisplay);
|
|
2516
|
+
const [beforeText, afterText] = await Promise.all([
|
|
2517
|
+
readFile2(beforeAbs, "utf8"),
|
|
2518
|
+
readFile2(afterAbs, "utf8")
|
|
2519
|
+
]);
|
|
2520
|
+
compareResult = await comparePlanGate(beforeText, afterText, {
|
|
2521
|
+
beforeFile: beforeDisplay,
|
|
2522
|
+
afterFile: afterDisplay,
|
|
2523
|
+
beforeName: path2.basename(beforeDisplay),
|
|
2524
|
+
afterName: path2.basename(afterDisplay),
|
|
2525
|
+
engine: toPlanEngineHint(engine),
|
|
2526
|
+
redactShare
|
|
2527
|
+
});
|
|
2528
|
+
findings.push(...compareResult.findings);
|
|
2529
|
+
}
|
|
2530
|
+
let high = 0;
|
|
2531
|
+
let medium = 0;
|
|
2532
|
+
let low = 0;
|
|
2533
|
+
for (const f of findings) {
|
|
2534
|
+
if (f.severity === "high") high += 1;
|
|
2535
|
+
else if (f.severity === "medium") medium += 1;
|
|
2536
|
+
else low += 1;
|
|
2537
|
+
}
|
|
2538
|
+
const thresholdTriggered = findings.some((f) => exceedsFailOnThreshold(f.severity, failOn));
|
|
2539
|
+
const planRegressed = Boolean(compareResult?.regressed);
|
|
2540
|
+
const passed = !thresholdTriggered && !(failOn !== "none" && planRegressed);
|
|
2541
|
+
return {
|
|
2542
|
+
version: VERSION,
|
|
2543
|
+
passed,
|
|
2544
|
+
failOn,
|
|
2545
|
+
engine,
|
|
2546
|
+
summary: {
|
|
2547
|
+
high,
|
|
2548
|
+
medium,
|
|
2549
|
+
low,
|
|
2550
|
+
totalFindings: findings.length,
|
|
2551
|
+
filesChecked: checkedFiles.size,
|
|
2552
|
+
plansChecked: planResults.length + (compareResult ? 2 : 0),
|
|
2553
|
+
planRegressed
|
|
2554
|
+
},
|
|
2555
|
+
findings,
|
|
2556
|
+
planResults,
|
|
2557
|
+
compareResult
|
|
2558
|
+
};
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
// src/cli.ts
|
|
2562
|
+
var VALID_ENGINES = /* @__PURE__ */ new Set([
|
|
2563
|
+
"auto",
|
|
2564
|
+
"postgres",
|
|
2565
|
+
"mssql",
|
|
2566
|
+
"mysql",
|
|
2567
|
+
"sqlite",
|
|
2568
|
+
"yugabyte"
|
|
2569
|
+
]);
|
|
2570
|
+
var VALID_FAIL_ON = /* @__PURE__ */ new Set(["high", "medium", "low", "none"]);
|
|
2571
|
+
var VALID_FORMATS = /* @__PURE__ */ new Set(["text", "markdown", "json", "sarif"]);
|
|
2572
|
+
function formatHelpText() {
|
|
2573
|
+
return [
|
|
2574
|
+
`culprit-ci v${VERSION} - SQL migration linter, query analyzer, and execution plan gate`,
|
|
2575
|
+
"",
|
|
2576
|
+
"Usage:",
|
|
2577
|
+
" culprit-ci [options]",
|
|
2578
|
+
"",
|
|
2579
|
+
"Options:",
|
|
2580
|
+
' --sql <glob...> SQL migration files or globs (e.g. "migrations/*.sql")',
|
|
2581
|
+
' --queries <glob...> Application query files or globs (e.g. "src/**/*.sql")',
|
|
2582
|
+
" --schema <file> Optional schema SQL snapshot for foreign-key index checks",
|
|
2583
|
+
" --engine <name> SQL dialect: auto | postgres | mssql | mysql | sqlite | yugabyte (default: auto)",
|
|
2584
|
+
" --plan <file> Analyze and gate a single execution plan (.json, .txt, .sqlplan)",
|
|
2585
|
+
" --compare <before> <after> Compare baseline and candidate execution plans structurally",
|
|
2586
|
+
" --fail-on <level> Gate failure threshold: high | medium | low | none (default: high)",
|
|
2587
|
+
" --format <fmt> Stdout output format: text | markdown | json | sarif (default: text)",
|
|
2588
|
+
" --sarif <file> Write SARIF 2.1.0 report to file (for GitHub Code Scanning)",
|
|
2589
|
+
" --markdown-out <file> Write GitHub PR Markdown report to file",
|
|
2590
|
+
" --json-out <file> Write JSON report to file",
|
|
2591
|
+
" --max-cost <number> Fail plan gate when total optimizer cost exceeds budget",
|
|
2592
|
+
" --allow-seq-scan Allow full table scans in single-plan analysis",
|
|
2593
|
+
" --disable-rule <ID> Disable specific rule ID (repeatable or comma-separated)",
|
|
2594
|
+
" -h, --help Show help and exit",
|
|
2595
|
+
" -v, --version Show version and exit",
|
|
2596
|
+
"",
|
|
2597
|
+
"Exit Codes:",
|
|
2598
|
+
" 0 Gate passed",
|
|
2599
|
+
" 1 Gate failed (findings met --fail-on threshold or execution plan regressed)",
|
|
2600
|
+
" 2 Invalid CLI arguments or unreadable input",
|
|
2601
|
+
""
|
|
2602
|
+
].join("\n");
|
|
2603
|
+
}
|
|
2604
|
+
function parseCliArgs(argv) {
|
|
2605
|
+
const parsed = {
|
|
2606
|
+
help: false,
|
|
2607
|
+
version: false,
|
|
2608
|
+
sqlPatterns: [],
|
|
2609
|
+
queryPatterns: [],
|
|
2610
|
+
engine: "auto",
|
|
2611
|
+
planFiles: [],
|
|
2612
|
+
comparePlans: null,
|
|
2613
|
+
failOn: "high",
|
|
2614
|
+
format: "text",
|
|
2615
|
+
allowSeqScan: false,
|
|
2616
|
+
disabledRules: []
|
|
2617
|
+
};
|
|
2618
|
+
let beforePlanFlag;
|
|
2619
|
+
let afterPlanFlag;
|
|
2620
|
+
const consumeOneOrMoreValues = (startIdx, flagName) => {
|
|
2621
|
+
const values = [];
|
|
2622
|
+
let idx = startIdx;
|
|
2623
|
+
while (idx < argv.length && !argv[idx].startsWith("-")) {
|
|
2624
|
+
values.push(argv[idx]);
|
|
2625
|
+
idx += 1;
|
|
2626
|
+
}
|
|
2627
|
+
if (values.length === 0) {
|
|
2628
|
+
throw new Error(`Missing value for ${flagName}`);
|
|
2629
|
+
}
|
|
2630
|
+
return { values, nextIdx: idx };
|
|
2631
|
+
};
|
|
2632
|
+
let i = 0;
|
|
2633
|
+
while (i < argv.length) {
|
|
2634
|
+
const arg = argv[i];
|
|
2635
|
+
if (arg === "-h" || arg === "--help") {
|
|
2636
|
+
parsed.help = true;
|
|
2637
|
+
i += 1;
|
|
2638
|
+
continue;
|
|
2639
|
+
}
|
|
2640
|
+
if (arg === "-v" || arg === "--version") {
|
|
2641
|
+
parsed.version = true;
|
|
2642
|
+
i += 1;
|
|
2643
|
+
continue;
|
|
2644
|
+
}
|
|
2645
|
+
if (arg === "--allow-seq-scan") {
|
|
2646
|
+
parsed.allowSeqScan = true;
|
|
2647
|
+
i += 1;
|
|
2648
|
+
continue;
|
|
2649
|
+
}
|
|
2650
|
+
if (arg === "--sql") {
|
|
2651
|
+
const { values, nextIdx } = consumeOneOrMoreValues(i + 1, "--sql");
|
|
2652
|
+
parsed.sqlPatterns.push(...values);
|
|
2653
|
+
i = nextIdx;
|
|
2654
|
+
continue;
|
|
2655
|
+
}
|
|
2656
|
+
if (arg === "--queries") {
|
|
2657
|
+
const { values, nextIdx } = consumeOneOrMoreValues(i + 1, "--queries");
|
|
2658
|
+
parsed.queryPatterns.push(...values);
|
|
2659
|
+
i = nextIdx;
|
|
2660
|
+
continue;
|
|
2661
|
+
}
|
|
2662
|
+
if (arg === "--schema") {
|
|
2663
|
+
const val = argv[i + 1];
|
|
2664
|
+
if (!val || val.startsWith("-")) throw new Error("Missing file path for --schema");
|
|
2665
|
+
parsed.schemaFile = val;
|
|
2666
|
+
i += 2;
|
|
2667
|
+
continue;
|
|
2668
|
+
}
|
|
2669
|
+
if (arg === "--engine") {
|
|
2670
|
+
const val = argv[i + 1]?.toLowerCase();
|
|
2671
|
+
if (!val || !VALID_ENGINES.has(val)) {
|
|
2672
|
+
throw new Error(
|
|
2673
|
+
`Invalid --engine '${argv[i + 1] ?? ""}'. Expected one of: auto, postgres, mssql, mysql, sqlite, yugabyte`
|
|
2674
|
+
);
|
|
2675
|
+
}
|
|
2676
|
+
parsed.engine = val;
|
|
2677
|
+
i += 2;
|
|
2678
|
+
continue;
|
|
2679
|
+
}
|
|
2680
|
+
if (arg === "--plan") {
|
|
2681
|
+
const val = argv[i + 1];
|
|
2682
|
+
if (!val || val.startsWith("-")) throw new Error("Missing file path for --plan");
|
|
2683
|
+
parsed.planFiles.push(val);
|
|
2684
|
+
i += 2;
|
|
2685
|
+
continue;
|
|
2686
|
+
}
|
|
2687
|
+
if (arg === "--compare") {
|
|
2688
|
+
const before = argv[i + 1];
|
|
2689
|
+
const after = argv[i + 2];
|
|
2690
|
+
if (!before || before.startsWith("-") || !after || after.startsWith("-")) {
|
|
2691
|
+
throw new Error("--compare requires two file arguments: <before-plan> <after-plan>");
|
|
2692
|
+
}
|
|
2693
|
+
parsed.comparePlans = { beforeFile: before, afterFile: after };
|
|
2694
|
+
i += 3;
|
|
2695
|
+
continue;
|
|
2696
|
+
}
|
|
2697
|
+
if (arg === "--before-plan") {
|
|
2698
|
+
const val = argv[i + 1];
|
|
2699
|
+
if (!val || val.startsWith("-")) throw new Error("Missing file path for --before-plan");
|
|
2700
|
+
beforePlanFlag = val;
|
|
2701
|
+
i += 2;
|
|
2702
|
+
continue;
|
|
2703
|
+
}
|
|
2704
|
+
if (arg === "--after-plan") {
|
|
2705
|
+
const val = argv[i + 1];
|
|
2706
|
+
if (!val || val.startsWith("-")) throw new Error("Missing file path for --after-plan");
|
|
2707
|
+
afterPlanFlag = val;
|
|
2708
|
+
i += 2;
|
|
2709
|
+
continue;
|
|
2710
|
+
}
|
|
2711
|
+
if (arg === "--fail-on") {
|
|
2712
|
+
const val = argv[i + 1]?.toLowerCase();
|
|
2713
|
+
if (!val || !VALID_FAIL_ON.has(val)) {
|
|
2714
|
+
throw new Error(
|
|
2715
|
+
`Invalid --fail-on '${argv[i + 1] ?? ""}'. Expected one of: high, medium, low, none`
|
|
2716
|
+
);
|
|
2717
|
+
}
|
|
2718
|
+
parsed.failOn = val;
|
|
2719
|
+
i += 2;
|
|
2720
|
+
continue;
|
|
2721
|
+
}
|
|
2722
|
+
if (arg === "--format") {
|
|
2723
|
+
const val = argv[i + 1]?.toLowerCase();
|
|
2724
|
+
if (!val || !VALID_FORMATS.has(val)) {
|
|
2725
|
+
throw new Error(
|
|
2726
|
+
`Invalid --format '${argv[i + 1] ?? ""}'. Expected one of: text, markdown, json, sarif`
|
|
2727
|
+
);
|
|
2728
|
+
}
|
|
2729
|
+
parsed.format = val;
|
|
2730
|
+
i += 2;
|
|
2731
|
+
continue;
|
|
2732
|
+
}
|
|
2733
|
+
if (arg === "--sarif") {
|
|
2734
|
+
const val = argv[i + 1];
|
|
2735
|
+
if (!val || val.startsWith("-")) throw new Error("Missing output file path for --sarif");
|
|
2736
|
+
parsed.sarifOut = val;
|
|
2737
|
+
i += 2;
|
|
2738
|
+
continue;
|
|
2739
|
+
}
|
|
2740
|
+
if (arg === "--markdown-out") {
|
|
2741
|
+
const val = argv[i + 1];
|
|
2742
|
+
if (!val || val.startsWith("-")) throw new Error("Missing output file path for --markdown-out");
|
|
2743
|
+
parsed.markdownOut = val;
|
|
2744
|
+
i += 2;
|
|
2745
|
+
continue;
|
|
2746
|
+
}
|
|
2747
|
+
if (arg === "--json-out") {
|
|
2748
|
+
const val = argv[i + 1];
|
|
2749
|
+
if (!val || val.startsWith("-")) throw new Error("Missing output file path for --json-out");
|
|
2750
|
+
parsed.jsonOut = val;
|
|
2751
|
+
i += 2;
|
|
2752
|
+
continue;
|
|
2753
|
+
}
|
|
2754
|
+
if (arg === "--max-cost") {
|
|
2755
|
+
const rawNum = argv[i + 1];
|
|
2756
|
+
const num = Number(rawNum);
|
|
2757
|
+
if (!rawNum || !Number.isFinite(num) || num < 0) {
|
|
2758
|
+
throw new Error(`Invalid --max-cost '${rawNum ?? ""}'. Expected a non-negative number.`);
|
|
2759
|
+
}
|
|
2760
|
+
parsed.maxCost = num;
|
|
2761
|
+
i += 2;
|
|
2762
|
+
continue;
|
|
2763
|
+
}
|
|
2764
|
+
if (arg === "--disable-rule") {
|
|
2765
|
+
const val = argv[i + 1];
|
|
2766
|
+
if (!val || val.startsWith("-")) throw new Error("Missing rule ID for --disable-rule");
|
|
2767
|
+
for (const id of val.split(",")) {
|
|
2768
|
+
const trimmed = id.trim().toUpperCase();
|
|
2769
|
+
if (trimmed) parsed.disabledRules.push(trimmed);
|
|
2770
|
+
}
|
|
2771
|
+
i += 2;
|
|
2772
|
+
continue;
|
|
2773
|
+
}
|
|
2774
|
+
throw new Error(`Unknown option '${arg}'. Run 'culprit-ci --help' for usage.`);
|
|
2775
|
+
}
|
|
2776
|
+
if (beforePlanFlag || afterPlanFlag) {
|
|
2777
|
+
if (!beforePlanFlag || !afterPlanFlag) {
|
|
2778
|
+
throw new Error("Both --before-plan and --after-plan must be provided together.");
|
|
2779
|
+
}
|
|
2780
|
+
parsed.comparePlans = { beforeFile: beforePlanFlag, afterFile: afterPlanFlag };
|
|
2781
|
+
}
|
|
2782
|
+
return parsed;
|
|
2783
|
+
}
|
|
2784
|
+
async function writeOutputFile(filePath, content, cwd) {
|
|
2785
|
+
const abs = path3.resolve(cwd, filePath);
|
|
2786
|
+
await mkdir(path3.dirname(abs), { recursive: true });
|
|
2787
|
+
await writeFile(abs, content, "utf8");
|
|
2788
|
+
}
|
|
2789
|
+
async function runCli(argv, io = {}) {
|
|
2790
|
+
const cwd = io.cwd ?? process.cwd();
|
|
2791
|
+
const writeStdout = io.stdout ?? ((text) => process.stdout.write(text));
|
|
2792
|
+
const writeStderr = io.stderr ?? ((text) => process.stderr.write(text));
|
|
2793
|
+
let args;
|
|
2794
|
+
try {
|
|
2795
|
+
args = parseCliArgs(argv);
|
|
2796
|
+
} catch (err) {
|
|
2797
|
+
writeStderr(`Error: ${err instanceof Error ? err.message : String(err)}
|
|
2798
|
+
`);
|
|
2799
|
+
return 2;
|
|
2800
|
+
}
|
|
2801
|
+
if (args.help) {
|
|
2802
|
+
writeStdout(`${formatHelpText()}
|
|
2803
|
+
`);
|
|
2804
|
+
return 0;
|
|
2805
|
+
}
|
|
2806
|
+
if (args.version) {
|
|
2807
|
+
writeStdout(`${VERSION}
|
|
2808
|
+
`);
|
|
2809
|
+
return 0;
|
|
2810
|
+
}
|
|
2811
|
+
const hasInputs = args.sqlPatterns.length > 0 || args.queryPatterns.length > 0 || args.planFiles.length > 0 || args.comparePlans !== null;
|
|
2812
|
+
if (!hasInputs) {
|
|
2813
|
+
writeStderr(
|
|
2814
|
+
"Error: No inputs provided. Pass --sql, --queries, --plan, or --compare (see --help).\n"
|
|
2815
|
+
);
|
|
2816
|
+
return 2;
|
|
2817
|
+
}
|
|
2818
|
+
try {
|
|
2819
|
+
const report = await runCiGate({
|
|
2820
|
+
cwd,
|
|
2821
|
+
sqlPatterns: args.sqlPatterns,
|
|
2822
|
+
queryPatterns: args.queryPatterns,
|
|
2823
|
+
schemaFile: args.schemaFile,
|
|
2824
|
+
engine: args.engine,
|
|
2825
|
+
planFiles: args.planFiles,
|
|
2826
|
+
comparePlans: args.comparePlans,
|
|
2827
|
+
failOn: args.failOn,
|
|
2828
|
+
allowSeqScan: args.allowSeqScan,
|
|
2829
|
+
maxCost: args.maxCost,
|
|
2830
|
+
disabledRules: args.disabledRules
|
|
2831
|
+
});
|
|
2832
|
+
if (args.sarifOut) {
|
|
2833
|
+
await writeOutputFile(args.sarifOut, `${formatSarif(report)}
|
|
2834
|
+
`, cwd);
|
|
2835
|
+
}
|
|
2836
|
+
if (args.markdownOut) {
|
|
2837
|
+
await writeOutputFile(args.markdownOut, formatMarkdown(report), cwd);
|
|
2838
|
+
}
|
|
2839
|
+
if (args.jsonOut) {
|
|
2840
|
+
await writeOutputFile(args.jsonOut, formatJson(report), cwd);
|
|
2841
|
+
}
|
|
2842
|
+
if (args.format === "markdown") {
|
|
2843
|
+
writeStdout(formatMarkdown(report));
|
|
2844
|
+
} else if (args.format === "json") {
|
|
2845
|
+
writeStdout(formatJson(report));
|
|
2846
|
+
} else if (args.format === "sarif") {
|
|
2847
|
+
writeStdout(`${formatSarif(report)}
|
|
2848
|
+
`);
|
|
2849
|
+
} else {
|
|
2850
|
+
writeStdout(formatText(report));
|
|
2851
|
+
}
|
|
2852
|
+
return report.passed ? 0 : 1;
|
|
2853
|
+
} catch (err) {
|
|
2854
|
+
writeStderr(`Error: ${err instanceof Error ? err.message : String(err)}
|
|
2855
|
+
`);
|
|
2856
|
+
return 2;
|
|
2857
|
+
}
|
|
2858
|
+
}
|
|
2859
|
+
var isMainModule = (() => {
|
|
2860
|
+
if (!process.argv[1]) return false;
|
|
2861
|
+
const resolvedArg = path3.resolve(process.argv[1]);
|
|
2862
|
+
return resolvedArg.endsWith("cli.js") || resolvedArg.endsWith("cli.ts");
|
|
2863
|
+
})();
|
|
2864
|
+
if (isMainModule) {
|
|
2865
|
+
runCli(process.argv.slice(2)).then(
|
|
2866
|
+
(code) => {
|
|
2867
|
+
process.exitCode = code;
|
|
2868
|
+
},
|
|
2869
|
+
(err) => {
|
|
2870
|
+
process.stderr.write(`Fatal error: ${err instanceof Error ? err.message : String(err)}
|
|
2871
|
+
`);
|
|
2872
|
+
process.exitCode = 2;
|
|
2873
|
+
}
|
|
2874
|
+
);
|
|
2875
|
+
}
|
|
2876
|
+
export {
|
|
2877
|
+
formatHelpText,
|
|
2878
|
+
parseCliArgs,
|
|
2879
|
+
runCli
|
|
2880
|
+
};
|