@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/dist/linter.js ADDED
@@ -0,0 +1,1317 @@
1
+ import { splitSqlStatements, unquoteSqlString, } from "./lexer.js";
2
+ const DOCS_BASE = "https://github.com/culpritsql/culprit-ci#rule-reference";
3
+ export const RULES = {
4
+ MIG001: {
5
+ id: "MIG001",
6
+ severity: "high",
7
+ category: "migration",
8
+ title: "Index creation blocks writes on existing table",
9
+ description: "CREATE INDEX without an online build clause holds locks that block concurrent INSERT, UPDATE, and DELETE traffic on existing tables.",
10
+ helpUri: `${DOCS_BASE}`,
11
+ },
12
+ MIG002: {
13
+ id: "MIG002",
14
+ severity: "high",
15
+ category: "migration",
16
+ title: "CREATE INDEX CONCURRENTLY inside transaction block",
17
+ description: "PostgreSQL forbids running CREATE INDEX CONCURRENTLY or DROP INDEX CONCURRENTLY inside an explicit BEGIN / START TRANSACTION block.",
18
+ helpUri: `${DOCS_BASE}`,
19
+ },
20
+ MIG003: {
21
+ id: "MIG003",
22
+ severity: "high",
23
+ category: "migration",
24
+ title: "Hazardous column type rewrite or volatile NOT NULL addition",
25
+ 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.",
26
+ helpUri: `${DOCS_BASE}`,
27
+ },
28
+ MIG004: {
29
+ id: "MIG004",
30
+ severity: "medium",
31
+ category: "migration",
32
+ title: "Unindexed foreign key constraint",
33
+ description: "Adding a FOREIGN KEY without an index on its referencing column(s) causes sequential scans during parent-row UPDATE/DELETE cascades and joins.",
34
+ helpUri: `${DOCS_BASE}`,
35
+ },
36
+ MIG005: {
37
+ id: "MIG005",
38
+ severity: "high",
39
+ category: "migration",
40
+ title: "Destructive DROP or TRUNCATE without explicit ignore pragma",
41
+ description: "DROP TABLE, DROP COLUMN, and TRUNCATE permanently destroy data and break backward-compatible rolling deployments unless explicitly acknowledged.",
42
+ helpUri: `${DOCS_BASE}`,
43
+ },
44
+ MIG006: {
45
+ id: "MIG006",
46
+ severity: "low",
47
+ category: "migration",
48
+ title: "DDL on existing table without lock_timeout guard",
49
+ 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.",
50
+ helpUri: `${DOCS_BASE}`,
51
+ },
52
+ QRY001: {
53
+ id: "QRY001",
54
+ severity: "high",
55
+ category: "query",
56
+ title: "UPDATE or DELETE without WHERE clause",
57
+ description: "Executing an UPDATE or DELETE statement with no top-level WHERE predicate mutates or deletes every row in the target table.",
58
+ helpUri: `${DOCS_BASE}`,
59
+ },
60
+ QRY002: {
61
+ id: "QRY002",
62
+ severity: "medium",
63
+ category: "query",
64
+ title: "Non-sargable function wrapping column in WHERE",
65
+ description: "Wrapping an indexed column in LOWER(), UPPER(), DATE(), YEAR(), or CAST() inside WHERE prevents standard B-tree index seeks.",
66
+ helpUri: `${DOCS_BASE}`,
67
+ },
68
+ QRY003: {
69
+ id: "QRY003",
70
+ severity: "low",
71
+ category: "query",
72
+ title: "Leading wildcard LIKE / ILIKE predicate",
73
+ description: "A pattern starting with '%' (such as LIKE '%term') cannot use a standard B-tree index for range seeks and forces a scan.",
74
+ helpUri: `${DOCS_BASE}`,
75
+ },
76
+ PLAN001: {
77
+ id: "PLAN001",
78
+ severity: "medium",
79
+ category: "plan",
80
+ title: "Full table scan detected in execution plan",
81
+ description: "An execution plan operator scans an entire table without an index seek.",
82
+ helpUri: `${DOCS_BASE}`,
83
+ },
84
+ PLAN002: {
85
+ id: "PLAN002",
86
+ severity: "high",
87
+ category: "plan",
88
+ title: "Operator spilled intermediate data to disk",
89
+ description: "Sort, Hash, or Exchange operator exceeded memory allocation and spilled temporary pages to disk.",
90
+ helpUri: `${DOCS_BASE}`,
91
+ },
92
+ PLAN003: {
93
+ id: "PLAN003",
94
+ severity: "high",
95
+ category: "plan",
96
+ title: "Execution plan bottleneck insight",
97
+ description: "Culprit's WebAssembly plan analyzer surfaced a high-impact execution bottleneck.",
98
+ helpUri: `${DOCS_BASE}`,
99
+ },
100
+ PLAN004: {
101
+ id: "PLAN004",
102
+ severity: "high",
103
+ category: "plan",
104
+ title: "Execution plan exceeded maximum cost threshold",
105
+ description: "Total optimizer subtree cost exceeded the configured CI budget.",
106
+ helpUri: `${DOCS_BASE}`,
107
+ },
108
+ PLAN005: {
109
+ id: "PLAN005",
110
+ severity: "high",
111
+ category: "plan",
112
+ title: "Execution plan regression between baseline and candidate",
113
+ description: "Candidate execution plan regressed in runtime, optimizer cost, access path, or spill warnings compared to the baseline plan.",
114
+ helpUri: `${DOCS_BASE}`,
115
+ },
116
+ };
117
+ const NON_SARGABLE_FUNCTIONS = new Set([
118
+ "LOWER",
119
+ "UPPER",
120
+ "DATE",
121
+ "YEAR",
122
+ "MONTH",
123
+ "DAY",
124
+ "TRIM",
125
+ "LTRIM",
126
+ "RTRIM",
127
+ "BTRIM",
128
+ "SUBSTRING",
129
+ "SUBSTR",
130
+ "LEFT",
131
+ "COALESCE",
132
+ ]);
133
+ const VOLATILE_DEFAULT_FUNCTIONS = new Set([
134
+ "RANDOM",
135
+ "GEN_RANDOM_UUID",
136
+ "UUID_GENERATE_V4",
137
+ "UUID_GENERATE_V1",
138
+ "CLOCK_TIMESTAMP",
139
+ "TIMEofday",
140
+ "TIMEOFDAY",
141
+ "NEWID",
142
+ "UUID",
143
+ "RAND",
144
+ ]);
145
+ const COMPARISON_OPS = new Set(["=", "!=", "<>", "<", ">", "<=", ">="]);
146
+ function isIdentifierToken(tok) {
147
+ if (!tok)
148
+ return false;
149
+ return tok.kind === "word" || tok.kind === "quoted_ident";
150
+ }
151
+ /**
152
+ * Reads an optional `schema.object` or `db.schema.object` identifier chain starting at `startIdx`.
153
+ */
154
+ function readQualifiedName(tokens, startIdx) {
155
+ let idx = startIdx;
156
+ if (tokens[idx]?.upper === "ONLY") {
157
+ idx += 1;
158
+ }
159
+ const parts = [];
160
+ const rawParts = [];
161
+ if (!isIdentifierToken(tokens[idx])) {
162
+ return null;
163
+ }
164
+ parts.push(tokens[idx].ident);
165
+ rawParts.push(tokens[idx].raw);
166
+ idx += 1;
167
+ while (idx + 1 < tokens.length && tokens[idx].raw === "." && isIdentifierToken(tokens[idx + 1])) {
168
+ parts.push(tokens[idx + 1].ident);
169
+ rawParts.push(tokens[idx + 1].raw);
170
+ idx += 2;
171
+ }
172
+ const bare = parts[parts.length - 1];
173
+ const full = parts.length >= 2 ? `${parts[parts.length - 2]}.${bare}` : bare;
174
+ return {
175
+ full,
176
+ bare,
177
+ rawDisplay: rawParts.join("."),
178
+ nextIndex: idx,
179
+ };
180
+ }
181
+ class TableSet {
182
+ names = new Set();
183
+ add(name) {
184
+ this.names.add(name.full);
185
+ this.names.add(name.bare);
186
+ }
187
+ has(name) {
188
+ return this.names.has(name.full) || this.names.has(name.bare);
189
+ }
190
+ }
191
+ class TableIndexRegistry {
192
+ byTable = new Map();
193
+ add(tableKey, cols) {
194
+ if (cols.length === 0)
195
+ return;
196
+ const normalizedCols = cols.map((c) => c.toLowerCase());
197
+ const keys = new Set([tableKey.toLowerCase()]);
198
+ const dot = tableKey.lastIndexOf(".");
199
+ if (dot >= 0) {
200
+ keys.add(tableKey.slice(dot + 1).toLowerCase());
201
+ }
202
+ for (const k of keys) {
203
+ const list = this.byTable.get(k) ?? [];
204
+ list.push(normalizedCols);
205
+ this.byTable.set(k, list);
206
+ }
207
+ }
208
+ coversForeignKey(table, fkCols) {
209
+ if (fkCols.length === 0)
210
+ return true;
211
+ const target = fkCols.map((c) => c.toLowerCase());
212
+ const candidates = [
213
+ ...(this.byTable.get(table.full) ?? []),
214
+ ...(this.byTable.get(table.bare) ?? []),
215
+ ];
216
+ for (const idxCols of candidates) {
217
+ if (idxCols.length < target.length)
218
+ continue;
219
+ let prefixMatch = true;
220
+ for (let i = 0; i < target.length; i++) {
221
+ if (idxCols[i] !== target[i]) {
222
+ prefixMatch = false;
223
+ break;
224
+ }
225
+ }
226
+ if (prefixMatch)
227
+ return true;
228
+ }
229
+ return false;
230
+ }
231
+ }
232
+ /**
233
+ * Extracts a parenthesized list of column identifiers starting at `openParenIdx`.
234
+ * Handles `(col1, col2 DESC, LOWER(col3))` by extracting leading column names.
235
+ */
236
+ function parseParenColumnList(tokens, openParenIdx) {
237
+ if (tokens[openParenIdx]?.raw !== "(")
238
+ return null;
239
+ const columns = [];
240
+ let depth = 1;
241
+ let i = openParenIdx + 1;
242
+ let segTokens = [];
243
+ const flushSegment = () => {
244
+ if (segTokens.length === 0)
245
+ return;
246
+ // Simple column: `col` or `col ASC` or `col DESC`
247
+ if (isIdentifierToken(segTokens[0]) && segTokens[1]?.raw !== "(") {
248
+ columns.push(segTokens[0].ident);
249
+ }
250
+ else if (segTokens.length >= 4 &&
251
+ isIdentifierToken(segTokens[0]) &&
252
+ segTokens[1]?.raw === "(" &&
253
+ isIdentifierToken(segTokens[2])) {
254
+ // Expression index e.g. LOWER(email)
255
+ columns.push(segTokens[2].ident);
256
+ }
257
+ segTokens = [];
258
+ };
259
+ while (i < tokens.length && depth > 0) {
260
+ const tok = tokens[i];
261
+ if (tok.raw === "(") {
262
+ if (depth === 1)
263
+ segTokens.push(tok);
264
+ depth += 1;
265
+ }
266
+ else if (tok.raw === ")") {
267
+ depth -= 1;
268
+ if (depth === 0) {
269
+ flushSegment();
270
+ return { columns, closeParenIdx: i };
271
+ }
272
+ if (depth === 1)
273
+ segTokens.push(tok);
274
+ }
275
+ else if (tok.raw === "," && depth === 1) {
276
+ flushSegment();
277
+ }
278
+ else if (depth === 1) {
279
+ segTokens.push(tok);
280
+ }
281
+ else if (depth === 2 && segTokens.length > 0) {
282
+ segTokens.push(tok);
283
+ }
284
+ i += 1;
285
+ }
286
+ return null;
287
+ }
288
+ export function detectSqlEngine(tokens, configured = "auto") {
289
+ if (configured === "postgres" || configured === "yugabyte")
290
+ return "postgres";
291
+ if (configured === "mssql")
292
+ return "mssql";
293
+ if (configured === "mysql")
294
+ return "mysql";
295
+ if (configured === "sqlite")
296
+ return "sqlite";
297
+ for (let i = 0; i < tokens.length; i++) {
298
+ const t = tokens[i];
299
+ if (t.kind === "quoted_ident") {
300
+ if (t.raw.startsWith("["))
301
+ return "mssql";
302
+ if (t.raw.startsWith("`"))
303
+ return "mysql";
304
+ }
305
+ if (t.kind === "punct" && t.raw === "::")
306
+ return "postgres";
307
+ if (t.kind === "string" && t.raw.startsWith("$"))
308
+ return "postgres";
309
+ if (t.kind === "word") {
310
+ if (t.upper === "CONCURRENTLY" ||
311
+ t.upper === "TIMESTAMPTZ" ||
312
+ t.upper === "JSONB" ||
313
+ t.upper === "BIGSERIAL" ||
314
+ t.upper === "ILIKE") {
315
+ return "postgres";
316
+ }
317
+ if (t.upper === "NONCLUSTERED" ||
318
+ t.upper === "CLUSTERED" ||
319
+ t.upper === "NVARCHAR" ||
320
+ (t.upper === "GO" && (i === 0 || tokens[i - 1].endLine < t.line))) {
321
+ return "mssql";
322
+ }
323
+ if (t.upper === "AUTO_INCREMENT" || t.upper === "INPLACE") {
324
+ return "mysql";
325
+ }
326
+ if (t.upper === "AUTOINCREMENT" || t.upper === "PRAGMA") {
327
+ return "sqlite";
328
+ }
329
+ }
330
+ }
331
+ return "postgres";
332
+ }
333
+ function collectSchemaFactsFromStatements(statements, indexRegistry) {
334
+ const foreignKeys = [];
335
+ for (const stmt of statements) {
336
+ const toks = stmt.tokens;
337
+ if (toks.length === 0)
338
+ continue;
339
+ // 1. CREATE [UNIQUE] [CLUSTERED|NONCLUSTERED] INDEX ... ON table (cols)
340
+ if (toks[0].upper === "CREATE") {
341
+ let idx = 1;
342
+ if (toks[idx]?.upper === "UNIQUE")
343
+ idx += 1;
344
+ if (toks[idx]?.upper === "CLUSTERED" ||
345
+ toks[idx]?.upper === "NONCLUSTERED" ||
346
+ toks[idx]?.upper === "FULLTEXT" ||
347
+ toks[idx]?.upper === "SPATIAL") {
348
+ idx += 1;
349
+ }
350
+ if (toks[idx]?.upper === "INDEX") {
351
+ // Scan for ON <tableName> [USING <method>] (<cols>)
352
+ for (let j = idx + 1; j < toks.length; j++) {
353
+ if (toks[j].upper === "ON") {
354
+ const tbl = readQualifiedName(toks, j + 1);
355
+ if (tbl) {
356
+ let afterTbl = tbl.nextIndex;
357
+ if (toks[afterTbl]?.upper === "USING" && isIdentifierToken(toks[afterTbl + 1])) {
358
+ afterTbl += 2;
359
+ }
360
+ const colList = parseParenColumnList(toks, afterTbl);
361
+ if (colList && colList.columns.length > 0) {
362
+ indexRegistry.add(tbl.full, colList.columns);
363
+ }
364
+ }
365
+ break;
366
+ }
367
+ }
368
+ }
369
+ }
370
+ // 2. CREATE [TEMP|TEMPORARY|UNLOGGED] TABLE [IF NOT EXISTS] <table> (...)
371
+ if (toks[0].upper === "CREATE") {
372
+ let idx = 1;
373
+ if (toks[idx]?.upper === "TEMP" ||
374
+ toks[idx]?.upper === "TEMPORARY" ||
375
+ toks[idx]?.upper === "UNLOGGED") {
376
+ idx += 1;
377
+ }
378
+ if (toks[idx]?.upper === "TABLE") {
379
+ idx += 1;
380
+ if (toks[idx]?.upper === "IF" &&
381
+ toks[idx + 1]?.upper === "NOT" &&
382
+ toks[idx + 2]?.upper === "EXISTS") {
383
+ idx += 3;
384
+ }
385
+ const tbl = readQualifiedName(toks, idx);
386
+ if (tbl && toks[tbl.nextIndex]?.raw === "(") {
387
+ scanCreateTableElements(toks, tbl.nextIndex, tbl, indexRegistry, foreignKeys);
388
+ }
389
+ }
390
+ }
391
+ // 3. ALTER TABLE [IF EXISTS] [ONLY] <table> ...
392
+ if (toks[0].upper === "ALTER" && toks[1]?.upper === "TABLE") {
393
+ let idx = 2;
394
+ if (toks[idx]?.upper === "IF" && toks[idx + 1]?.upper === "EXISTS") {
395
+ idx += 2;
396
+ }
397
+ const tbl = readQualifiedName(toks, idx);
398
+ if (tbl) {
399
+ scanAlterTableConstraints(toks, tbl.nextIndex, tbl, indexRegistry, foreignKeys);
400
+ }
401
+ }
402
+ }
403
+ return foreignKeys;
404
+ }
405
+ function splitTopLevelParenClauses(tokens, openParenIdx) {
406
+ if (tokens[openParenIdx]?.raw !== "(")
407
+ return [];
408
+ const clauses = [];
409
+ let current = [];
410
+ let depth = 1;
411
+ let i = openParenIdx + 1;
412
+ while (i < tokens.length && depth > 0) {
413
+ const tok = tokens[i];
414
+ if (tok.raw === "(") {
415
+ depth += 1;
416
+ current.push(tok);
417
+ }
418
+ else if (tok.raw === ")") {
419
+ depth -= 1;
420
+ if (depth === 0) {
421
+ if (current.length > 0)
422
+ clauses.push(current);
423
+ break;
424
+ }
425
+ current.push(tok);
426
+ }
427
+ else if (tok.raw === "," && depth === 1) {
428
+ if (current.length > 0)
429
+ clauses.push(current);
430
+ current = [];
431
+ }
432
+ else {
433
+ current.push(tok);
434
+ }
435
+ i += 1;
436
+ }
437
+ return clauses;
438
+ }
439
+ function scanCreateTableElements(tokens, openParenIdx, table, indexRegistry, foreignKeys) {
440
+ const elements = splitTopLevelParenClauses(tokens, openParenIdx);
441
+ for (const elem of elements) {
442
+ if (elem.length === 0)
443
+ continue;
444
+ let start = 0;
445
+ if (elem[0].upper === "CONSTRAINT" && isIdentifierToken(elem[1])) {
446
+ start = 2;
447
+ }
448
+ // Table-level PRIMARY KEY (cols) or UNIQUE (cols) or INDEX idx (cols)
449
+ if (elem[start]?.upper === "PRIMARY" && elem[start + 1]?.upper === "KEY") {
450
+ let pIdx = start + 2;
451
+ if (elem[pIdx]?.upper === "CLUSTERED" || elem[pIdx]?.upper === "NONCLUSTERED")
452
+ pIdx += 1;
453
+ const cols = parseParenColumnList(elem, pIdx);
454
+ if (cols)
455
+ indexRegistry.add(table.full, cols.columns);
456
+ continue;
457
+ }
458
+ if (elem[start]?.upper === "UNIQUE") {
459
+ let uIdx = start + 1;
460
+ if (elem[uIdx]?.upper === "INDEX" || elem[uIdx]?.upper === "KEY")
461
+ uIdx += 1;
462
+ if (isIdentifierToken(elem[uIdx]) && elem[uIdx + 1]?.raw === "(")
463
+ uIdx += 1;
464
+ const cols = parseParenColumnList(elem, uIdx);
465
+ if (cols)
466
+ indexRegistry.add(table.full, cols.columns);
467
+ continue;
468
+ }
469
+ if ((elem[start]?.upper === "INDEX" || elem[start]?.upper === "KEY") && elem.length >= start + 2) {
470
+ let kIdx = start + 1;
471
+ if (isIdentifierToken(elem[kIdx]))
472
+ kIdx += 1;
473
+ const cols = parseParenColumnList(elem, kIdx);
474
+ if (cols)
475
+ indexRegistry.add(table.full, cols.columns);
476
+ continue;
477
+ }
478
+ // Table-level FOREIGN KEY (cols) REFERENCES ...
479
+ if (elem[start]?.upper === "FOREIGN" && elem[start + 1]?.upper === "KEY") {
480
+ const cols = parseParenColumnList(elem, start + 2);
481
+ if (cols && cols.columns.length > 0) {
482
+ foreignKeys.push({
483
+ table,
484
+ columns: cols.columns,
485
+ token: elem[0],
486
+ endToken: elem[elem.length - 1],
487
+ });
488
+ }
489
+ continue;
490
+ }
491
+ // Column-level definition: `<col_name> <type> ...`
492
+ if (isIdentifierToken(elem[0]) &&
493
+ elem[0].upper !== "CHECK" &&
494
+ elem[0].upper !== "EXCLUDE" &&
495
+ elem[0].upper !== "PERIOD") {
496
+ const colName = elem[0].ident;
497
+ for (let k = 1; k < elem.length; k++) {
498
+ if (elem[k].upper === "PRIMARY" && elem[k + 1]?.upper === "KEY") {
499
+ indexRegistry.add(table.full, [colName]);
500
+ }
501
+ else if (elem[k].upper === "UNIQUE") {
502
+ indexRegistry.add(table.full, [colName]);
503
+ }
504
+ else if (elem[k].upper === "REFERENCES") {
505
+ foreignKeys.push({
506
+ table,
507
+ columns: [colName],
508
+ token: elem[0],
509
+ endToken: elem[elem.length - 1],
510
+ });
511
+ }
512
+ }
513
+ }
514
+ }
515
+ }
516
+ function scanAlterTableConstraints(tokens, startIdx, table, indexRegistry, foreignKeys) {
517
+ for (let i = startIdx; i < tokens.length; i++) {
518
+ if (tokens[i].upper === "PRIMARY" && tokens[i + 1]?.upper === "KEY") {
519
+ let pIdx = i + 2;
520
+ if (tokens[pIdx]?.upper === "CLUSTERED" || tokens[pIdx]?.upper === "NONCLUSTERED")
521
+ pIdx += 1;
522
+ const cols = parseParenColumnList(tokens, pIdx);
523
+ if (cols)
524
+ indexRegistry.add(table.full, cols.columns);
525
+ }
526
+ else if (tokens[i].upper === "UNIQUE") {
527
+ let uIdx = i + 1;
528
+ if (tokens[uIdx]?.upper === "INDEX" || tokens[uIdx]?.upper === "KEY")
529
+ uIdx += 1;
530
+ if (isIdentifierToken(tokens[uIdx]) && tokens[uIdx + 1]?.raw === "(")
531
+ uIdx += 1;
532
+ const cols = parseParenColumnList(tokens, uIdx);
533
+ if (cols)
534
+ indexRegistry.add(table.full, cols.columns);
535
+ }
536
+ else if (tokens[i].upper === "FOREIGN" && tokens[i + 1]?.upper === "KEY") {
537
+ const cols = parseParenColumnList(tokens, i + 2);
538
+ if (cols && cols.columns.length > 0) {
539
+ foreignKeys.push({
540
+ table,
541
+ columns: cols.columns,
542
+ token: tokens[i],
543
+ endToken: tokens[tokens.length - 1],
544
+ });
545
+ }
546
+ }
547
+ else if (tokens[i].upper === "ADD") {
548
+ let aIdx = i + 1;
549
+ if (tokens[aIdx]?.upper === "COLUMN")
550
+ aIdx += 1;
551
+ if (tokens[aIdx]?.upper === "IF" &&
552
+ tokens[aIdx + 1]?.upper === "NOT" &&
553
+ tokens[aIdx + 2]?.upper === "EXISTS") {
554
+ aIdx += 3;
555
+ }
556
+ if (isIdentifierToken(tokens[aIdx]) &&
557
+ tokens[aIdx].upper !== "CONSTRAINT" &&
558
+ tokens[aIdx].upper !== "FOREIGN" &&
559
+ tokens[aIdx].upper !== "PRIMARY" &&
560
+ tokens[aIdx].upper !== "UNIQUE" &&
561
+ tokens[aIdx].upper !== "CHECK" &&
562
+ tokens[aIdx].upper !== "INDEX") {
563
+ const colName = tokens[aIdx].ident;
564
+ // Scan until top-level comma or end of statement for inline REFERENCES / PRIMARY KEY / UNIQUE
565
+ let depth = 0;
566
+ for (let k = aIdx + 1; k < tokens.length; k++) {
567
+ if (tokens[k].raw === "(")
568
+ depth += 1;
569
+ else if (tokens[k].raw === ")")
570
+ depth = Math.max(0, depth - 1);
571
+ else if (tokens[k].raw === "," && depth === 0)
572
+ break;
573
+ if (depth === 0) {
574
+ if (tokens[k].upper === "PRIMARY" && tokens[k + 1]?.upper === "KEY") {
575
+ indexRegistry.add(table.full, [colName]);
576
+ }
577
+ else if (tokens[k].upper === "UNIQUE") {
578
+ indexRegistry.add(table.full, [colName]);
579
+ }
580
+ else if (tokens[k].upper === "REFERENCES") {
581
+ foreignKeys.push({
582
+ table,
583
+ columns: [colName],
584
+ token: tokens[i],
585
+ endToken: tokens[k + 1] ?? tokens[k],
586
+ });
587
+ break;
588
+ }
589
+ }
590
+ }
591
+ }
592
+ }
593
+ }
594
+ }
595
+ function hasOnlineIndexOption(tokens, engine, autoMode) {
596
+ const hasConcurrently = tokens.some((t) => t.upper === "CONCURRENTLY");
597
+ const hasMssqlOnline = tokens.some((t, i) => t.upper === "ONLINE" && tokens[i + 1]?.raw === "=" && tokens[i + 2]?.upper === "ON");
598
+ const hasMysqlOnline = tokens.some((t, i) => (t.upper === "LOCK" &&
599
+ ((tokens[i + 1]?.raw === "=" && tokens[i + 2]?.upper === "NONE") ||
600
+ tokens[i + 1]?.upper === "NONE")) ||
601
+ (t.upper === "ALGORITHM" &&
602
+ ((tokens[i + 1]?.raw === "=" &&
603
+ (tokens[i + 2]?.upper === "INPLACE" || tokens[i + 2]?.upper === "INSTANT")) ||
604
+ tokens[i + 1]?.upper === "INPLACE" ||
605
+ tokens[i + 1]?.upper === "INSTANT")));
606
+ if (autoMode) {
607
+ return hasConcurrently || hasMssqlOnline || hasMysqlOnline;
608
+ }
609
+ if (engine === "postgres")
610
+ return hasConcurrently;
611
+ if (engine === "mssql")
612
+ return hasMssqlOnline;
613
+ if (engine === "mysql")
614
+ return hasMysqlOnline;
615
+ return true;
616
+ }
617
+ function buildOnlineIndexFixSql(stmt, engine) {
618
+ const trimmed = stmt.rawSql.trim().replace(/;\s*$/, "");
619
+ if (engine === "postgres") {
620
+ return `${trimmed.replace(/^(\s*CREATE\s+(?:UNIQUE\s+)?INDEX)\b/i, "$1 CONCURRENTLY")};`;
621
+ }
622
+ if (engine === "mssql") {
623
+ if (/\bWITH\s*\(/i.test(trimmed)) {
624
+ return `${trimmed.replace(/\bWITH\s*\(/i, "WITH (ONLINE = ON, ")};`;
625
+ }
626
+ return `${trimmed} WITH (ONLINE = ON);`;
627
+ }
628
+ if (engine === "mysql") {
629
+ return `${trimmed} ALGORITHM=INPLACE, LOCK=NONE;`;
630
+ }
631
+ return `${trimmed};`;
632
+ }
633
+ function isLockTimeoutStatement(tokens) {
634
+ if (tokens[0]?.upper !== "SET")
635
+ return false;
636
+ let idx = 1;
637
+ if (tokens[idx]?.upper === "LOCAL" || tokens[idx]?.upper === "SESSION") {
638
+ idx += 1;
639
+ }
640
+ return tokens[idx]?.upper === "LOCK_TIMEOUT";
641
+ }
642
+ function checkMigrationStatement(stmt, engine, autoMode, file, createdTables, state, isRuleEnabled, findings) {
643
+ const toks = stmt.tokens;
644
+ if (toks.length === 0)
645
+ return;
646
+ // Track explicit transaction state
647
+ if ((toks[0].upper === "BEGIN" && toks[1]?.upper !== "ATOMIC") ||
648
+ (toks[0].upper === "START" && toks[1]?.upper === "TRANSACTION")) {
649
+ state.inTransaction = true;
650
+ return;
651
+ }
652
+ if (toks[0].upper === "COMMIT" ||
653
+ toks[0].upper === "ROLLBACK" ||
654
+ toks[0].upper === "ABORT" ||
655
+ (toks[0].upper === "END" && toks.length <= 3)) {
656
+ state.inTransaction = false;
657
+ return;
658
+ }
659
+ // Track SET lock_timeout / SET LOCK_TIMEOUT
660
+ if (isLockTimeoutStatement(toks)) {
661
+ state.hasLockTimeout = true;
662
+ return;
663
+ }
664
+ // Track CREATE TABLE so subsequent indexes/alters on the brand-new table do not false-positive
665
+ if (toks[0].upper === "CREATE") {
666
+ let cIdx = 1;
667
+ if (toks[cIdx]?.upper === "TEMP" ||
668
+ toks[cIdx]?.upper === "TEMPORARY" ||
669
+ toks[cIdx]?.upper === "UNLOGGED") {
670
+ cIdx += 1;
671
+ }
672
+ if (toks[cIdx]?.upper === "TABLE") {
673
+ cIdx += 1;
674
+ if (toks[cIdx]?.upper === "IF" &&
675
+ toks[cIdx + 1]?.upper === "NOT" &&
676
+ toks[cIdx + 2]?.upper === "EXISTS") {
677
+ cIdx += 3;
678
+ }
679
+ const tbl = readQualifiedName(toks, cIdx);
680
+ if (tbl) {
681
+ createdTables.add(tbl);
682
+ }
683
+ return;
684
+ }
685
+ }
686
+ const emitLockTimeoutIfNeeded = (targetTable) => {
687
+ if (state.hasLockTimeout || state.emittedLockTimeoutWarning)
688
+ return;
689
+ if (engine !== "postgres" && engine !== "mssql")
690
+ return;
691
+ if (targetTable && createdTables.has(targetTable))
692
+ return;
693
+ if (!isRuleEnabled("MIG006", stmt))
694
+ return;
695
+ state.emittedLockTimeoutWarning = true;
696
+ const fixSql = engine === "mssql" ? "SET LOCK_TIMEOUT 3000;" : "SET lock_timeout = '3s';";
697
+ const settingName = engine === "mssql" ? "SET LOCK_TIMEOUT" : "SET lock_timeout";
698
+ findings.push({
699
+ ruleId: "MIG006",
700
+ severity: "low",
701
+ file,
702
+ line: stmt.startLine,
703
+ column: stmt.startColumn,
704
+ endLine: stmt.endLine,
705
+ endColumn: stmt.endColumn,
706
+ title: RULES.MIG006.title,
707
+ message: `DDL modifies an existing table without setting ${settingName} first. Waiting behind an active query can stall all queued traffic on the table.`,
708
+ suggestion: `Prepend ${fixSql} at the top of the migration and retry safely if lock acquisition times out.`,
709
+ fixSql,
710
+ });
711
+ };
712
+ // MIG001 & MIG002: CREATE [UNIQUE] INDEX / DROP INDEX CONCURRENTLY
713
+ if (toks[0].upper === "CREATE" || toks[0].upper === "DROP") {
714
+ const hasConcurrently = toks.some((t) => t.upper === "CONCURRENTLY");
715
+ const hasIndexKeyword = toks.some((t, idx) => idx <= 4 && t.upper === "INDEX");
716
+ if (hasIndexKeyword && hasConcurrently && state.inTransaction) {
717
+ if (isRuleEnabled("MIG002", stmt)) {
718
+ const concTok = toks.find((t) => t.upper === "CONCURRENTLY") ?? toks[0];
719
+ findings.push({
720
+ ruleId: "MIG002",
721
+ severity: "high",
722
+ file,
723
+ line: concTok.line,
724
+ column: concTok.column,
725
+ endLine: stmt.endLine,
726
+ endColumn: stmt.endColumn,
727
+ title: RULES.MIG002.title,
728
+ message: "CREATE/DROP INDEX CONCURRENTLY is placed inside an explicit BEGIN / START TRANSACTION block and will fail at runtime in PostgreSQL.",
729
+ suggestion: "Remove BEGIN / COMMIT around CONCURRENTLY index builds and configure your migration runner to execute this file outside a transaction.",
730
+ });
731
+ }
732
+ }
733
+ if (toks[0].upper === "CREATE" && hasIndexKeyword) {
734
+ let targetTable = null;
735
+ for (let j = 1; j < toks.length; j++) {
736
+ if (toks[j].upper === "ON") {
737
+ targetTable = readQualifiedName(toks, j + 1);
738
+ break;
739
+ }
740
+ }
741
+ if (targetTable && !createdTables.has(targetTable)) {
742
+ emitLockTimeoutIfNeeded(targetTable);
743
+ if (engine !== "sqlite" &&
744
+ !hasOnlineIndexOption(toks, engine, autoMode) &&
745
+ isRuleEnabled("MIG001", stmt)) {
746
+ const clauseHint = engine === "mssql"
747
+ ? "WITH (ONLINE = ON)"
748
+ : engine === "mysql"
749
+ ? "ALGORITHM=INPLACE, LOCK=NONE"
750
+ : "CONCURRENTLY";
751
+ findings.push({
752
+ ruleId: "MIG001",
753
+ severity: "high",
754
+ file,
755
+ line: stmt.startLine,
756
+ column: stmt.startColumn,
757
+ endLine: stmt.endLine,
758
+ endColumn: stmt.endColumn,
759
+ title: RULES.MIG001.title,
760
+ message: `Creating index on existing table '${targetTable.rawDisplay}' without ${clauseHint} blocks concurrent writes until the index build finishes.`,
761
+ suggestion: `Add ${clauseHint} so concurrent DML can continue while the index builds.`,
762
+ fixSql: buildOnlineIndexFixSql(stmt, engine),
763
+ });
764
+ }
765
+ }
766
+ return;
767
+ }
768
+ if (toks[0].upper === "DROP" && toks[1]?.upper === "TABLE") {
769
+ let dIdx = 2;
770
+ if (toks[dIdx]?.upper === "IF" && toks[dIdx + 1]?.upper === "EXISTS")
771
+ dIdx += 2;
772
+ const droppedTbl = readQualifiedName(toks, dIdx);
773
+ emitLockTimeoutIfNeeded(droppedTbl ?? undefined);
774
+ if (isRuleEnabled("MIG005", stmt)) {
775
+ const tblLabel = droppedTbl?.rawDisplay ?? "table";
776
+ findings.push({
777
+ ruleId: "MIG005",
778
+ severity: "high",
779
+ file,
780
+ line: stmt.startLine,
781
+ column: stmt.startColumn,
782
+ endLine: stmt.endLine,
783
+ endColumn: stmt.endColumn,
784
+ title: RULES.MIG005.title,
785
+ message: `DROP TABLE '${tblLabel}' permanently deletes table data and breaks running application instances that still reference it.`,
786
+ suggestion: "Stop reading/writing the table in an earlier release first, then annotate intentional cleanup with '-- culprit-ignore: MIG005'.",
787
+ });
788
+ }
789
+ return;
790
+ }
791
+ }
792
+ // MIG005: TRUNCATE [TABLE] ...
793
+ if (toks[0].upper === "TRUNCATE") {
794
+ let tIdx = 1;
795
+ if (toks[tIdx]?.upper === "TABLE")
796
+ tIdx += 1;
797
+ const truncTbl = readQualifiedName(toks, tIdx);
798
+ emitLockTimeoutIfNeeded(truncTbl ?? undefined);
799
+ if (isRuleEnabled("MIG005", stmt)) {
800
+ findings.push({
801
+ ruleId: "MIG005",
802
+ severity: "high",
803
+ file,
804
+ line: stmt.startLine,
805
+ column: stmt.startColumn,
806
+ endLine: stmt.endLine,
807
+ endColumn: stmt.endColumn,
808
+ title: RULES.MIG005.title,
809
+ message: `TRUNCATE on '${truncTbl?.rawDisplay ?? "table"}' acquires an exclusive lock and permanently removes all rows.`,
810
+ suggestion: "If purging data in production is intentional, acknowledge with '-- culprit-ignore: MIG005'.",
811
+ });
812
+ }
813
+ return;
814
+ }
815
+ // ALTER TABLE checks: MIG003, MIG005 (DROP COLUMN), MIG006
816
+ if (toks[0].upper === "ALTER" && toks[1]?.upper === "TABLE") {
817
+ let idx = 2;
818
+ if (toks[idx]?.upper === "IF" && toks[idx + 1]?.upper === "EXISTS") {
819
+ idx += 2;
820
+ }
821
+ const targetTable = readQualifiedName(toks, idx);
822
+ if (!targetTable)
823
+ return;
824
+ const isBrandNewTable = createdTables.has(targetTable);
825
+ if (!isBrandNewTable) {
826
+ emitLockTimeoutIfNeeded(targetTable);
827
+ }
828
+ // Split top-level comma actions after table name (e.g. ALTER TABLE t DROP COLUMN a, ALTER COLUMN b TYPE text)
829
+ const actionSlices = [];
830
+ let currentAction = [];
831
+ let depth = 0;
832
+ for (let k = targetTable.nextIndex; k < toks.length; k++) {
833
+ const t = toks[k];
834
+ if (t.raw === "(")
835
+ depth += 1;
836
+ else if (t.raw === ")")
837
+ depth = Math.max(0, depth - 1);
838
+ if (t.raw === "," && depth === 0) {
839
+ if (currentAction.length > 0)
840
+ actionSlices.push(currentAction);
841
+ currentAction = [];
842
+ }
843
+ else {
844
+ currentAction.push(t);
845
+ }
846
+ }
847
+ if (currentAction.length > 0)
848
+ actionSlices.push(currentAction);
849
+ for (const action of actionSlices) {
850
+ if (action.length === 0)
851
+ continue;
852
+ const first = action[0];
853
+ const last = action[action.length - 1];
854
+ // 1. DROP [COLUMN] <col> -> MIG005 (skip DROP CONSTRAINT, DROP INDEX, DROP PRIMARY/FOREIGN KEY)
855
+ if (first.upper === "DROP") {
856
+ const second = action[1]?.upper;
857
+ const isConstraintOrIndex = second === "CONSTRAINT" ||
858
+ second === "INDEX" ||
859
+ second === "KEY" ||
860
+ second === "PRIMARY" ||
861
+ second === "FOREIGN" ||
862
+ second === "CHECK" ||
863
+ second === "PARTITION";
864
+ if (!isConstraintOrIndex && isRuleEnabled("MIG005", stmt)) {
865
+ let colIdx = second === "COLUMN" ? 2 : 1;
866
+ if (action[colIdx]?.upper === "IF" && action[colIdx + 1]?.upper === "EXISTS") {
867
+ colIdx += 2;
868
+ }
869
+ const colName = action[colIdx]?.raw ?? "column";
870
+ findings.push({
871
+ ruleId: "MIG005",
872
+ severity: "high",
873
+ file,
874
+ line: first.line,
875
+ column: first.column,
876
+ endLine: last.endLine,
877
+ endColumn: last.endColumn,
878
+ title: RULES.MIG005.title,
879
+ message: `Dropping column '${colName}' from '${targetTable.rawDisplay}' breaks in-flight queries that still select or insert that column during a rolling deploy.`,
880
+ suggestion: "Stop referencing the column in application code first, deploy, then add '-- culprit-ignore: MIG005' when dropping the unused column.",
881
+ });
882
+ }
883
+ continue;
884
+ }
885
+ if (isBrandNewTable)
886
+ continue;
887
+ // 2. ALTER [COLUMN] <col> [SET DATA] TYPE ... (Postgres) or ALTER COLUMN <col> <type> (MSSQL)
888
+ // or MODIFY [COLUMN] / CHANGE [COLUMN] (MySQL) -> MIG003
889
+ if (first.upper === "ALTER") {
890
+ let aIdx = 1;
891
+ if (action[aIdx]?.upper === "COLUMN")
892
+ aIdx += 1;
893
+ const colTok = action[aIdx];
894
+ const afterCol = action[aIdx + 1]?.upper;
895
+ const isPgSetType = afterCol === "TYPE" ||
896
+ (afterCol === "SET" && action[aIdx + 2]?.upper === "DATA" && action[aIdx + 3]?.upper === "TYPE");
897
+ const isMssqlAlterType = engine === "mssql" &&
898
+ isIdentifierToken(colTok) &&
899
+ isIdentifierToken(action[aIdx + 1]) &&
900
+ afterCol !== "ADD" &&
901
+ afterCol !== "DROP";
902
+ if ((isPgSetType || isMssqlAlterType) && isRuleEnabled("MIG003", stmt)) {
903
+ findings.push({
904
+ ruleId: "MIG003",
905
+ severity: "high",
906
+ file,
907
+ line: first.line,
908
+ column: first.column,
909
+ endLine: last.endLine,
910
+ endColumn: last.endColumn,
911
+ title: RULES.MIG003.title,
912
+ message: `Changing type of column '${colTok?.raw ?? "column"}' on '${targetTable.rawDisplay}' acquires an exclusive table lock and can rewrite every row on disk.`,
913
+ suggestion: "Use expand-and-contract instead: add a new nullable column, backfill in small batches, dual-write, and swap.",
914
+ });
915
+ }
916
+ continue;
917
+ }
918
+ if ((first.upper === "MODIFY" || first.upper === "CHANGE") &&
919
+ isRuleEnabled("MIG003", stmt)) {
920
+ const colIdx = action[1]?.upper === "COLUMN" ? 2 : 1;
921
+ findings.push({
922
+ ruleId: "MIG003",
923
+ severity: "high",
924
+ file,
925
+ line: first.line,
926
+ column: first.column,
927
+ endLine: last.endLine,
928
+ endColumn: last.endColumn,
929
+ title: RULES.MIG003.title,
930
+ message: `Modifying column '${action[colIdx]?.raw ?? "column"}' on '${targetTable.rawDisplay}' can trigger a full table copy and block concurrent writes.`,
931
+ suggestion: "Verify instant/in-place DDL compatibility or migrate via expand-and-contract with a new column.",
932
+ });
933
+ continue;
934
+ }
935
+ // 3. ADD [COLUMN] <col> <type> ... NOT NULL without constant DEFAULT or with volatile DEFAULT -> MIG003
936
+ if (first.upper === "ADD") {
937
+ let aIdx = 1;
938
+ if (action[aIdx]?.upper === "COLUMN")
939
+ aIdx += 1;
940
+ if (action[aIdx]?.upper === "IF" &&
941
+ action[aIdx + 1]?.upper === "NOT" &&
942
+ action[aIdx + 2]?.upper === "EXISTS") {
943
+ aIdx += 3;
944
+ }
945
+ const colTok = action[aIdx];
946
+ const isConstraintKeyword = colTok?.upper === "CONSTRAINT" ||
947
+ colTok?.upper === "FOREIGN" ||
948
+ colTok?.upper === "PRIMARY" ||
949
+ colTok?.upper === "UNIQUE" ||
950
+ colTok?.upper === "CHECK" ||
951
+ colTok?.upper === "INDEX";
952
+ if (isIdentifierToken(colTok) && !isConstraintKeyword) {
953
+ const hasNotNull = action.some((t, idx2) => t.upper === "NOT" && action[idx2 + 1]?.upper === "NULL");
954
+ if (hasNotNull && isRuleEnabled("MIG003", stmt)) {
955
+ const defaultIdx = action.findIndex((t) => t.upper === "DEFAULT");
956
+ let volatileFunc = null;
957
+ if (defaultIdx !== -1) {
958
+ for (let d = defaultIdx + 1; d < action.length; d++) {
959
+ const dt = action[d];
960
+ if (dt.upper === "NOT" ||
961
+ dt.upper === "NULL" ||
962
+ dt.upper === "CONSTRAINT" ||
963
+ dt.upper === "REFERENCES" ||
964
+ dt.upper === "CHECK") {
965
+ break;
966
+ }
967
+ if (dt.kind === "word" &&
968
+ action[d + 1]?.raw === "(" &&
969
+ VOLATILE_DEFAULT_FUNCTIONS.has(dt.upper)) {
970
+ volatileFunc = `${dt.raw}()`;
971
+ break;
972
+ }
973
+ }
974
+ }
975
+ if (defaultIdx === -1) {
976
+ findings.push({
977
+ ruleId: "MIG003",
978
+ severity: "high",
979
+ file,
980
+ line: first.line,
981
+ column: first.column,
982
+ endLine: last.endLine,
983
+ endColumn: last.endColumn,
984
+ title: RULES.MIG003.title,
985
+ 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.`,
986
+ suggestion: "Add the column as nullable first, backfill existing rows in batches, and enforce NOT NULL with a NOT VALID check constraint before validating.",
987
+ });
988
+ }
989
+ else if (volatileFunc) {
990
+ findings.push({
991
+ ruleId: "MIG003",
992
+ severity: "high",
993
+ file,
994
+ line: first.line,
995
+ column: first.column,
996
+ endLine: last.endLine,
997
+ endColumn: last.endColumn,
998
+ title: RULES.MIG003.title,
999
+ message: `Adding NOT NULL column '${colTok.raw}' on '${targetTable.rawDisplay}' with volatile default ${volatileFunc} rewrites every row under an ACCESS EXCLUSIVE lock.`,
1000
+ suggestion: "Add the column as nullable with the default for new rows, backfill existing rows in batches, then validate NOT NULL.",
1001
+ });
1002
+ }
1003
+ }
1004
+ }
1005
+ }
1006
+ }
1007
+ }
1008
+ }
1009
+ function findMainStatementStartAfterWith(tokens) {
1010
+ if (tokens[0]?.upper !== "WITH")
1011
+ return 0;
1012
+ let idx = 1;
1013
+ if (tokens[idx]?.upper === "RECURSIVE")
1014
+ idx += 1;
1015
+ let depth = 0;
1016
+ while (idx < tokens.length) {
1017
+ const t = tokens[idx];
1018
+ if (t.raw === "(") {
1019
+ depth += 1;
1020
+ }
1021
+ else if (t.raw === ")") {
1022
+ depth = Math.max(0, depth - 1);
1023
+ if (depth === 0) {
1024
+ if (tokens[idx + 1]?.raw === ",") {
1025
+ idx += 2;
1026
+ continue;
1027
+ }
1028
+ return idx + 1;
1029
+ }
1030
+ }
1031
+ idx += 1;
1032
+ }
1033
+ return 0;
1034
+ }
1035
+ function checkQueryStatement(stmt, engine, file, isRuleEnabled, findings) {
1036
+ const toks = stmt.tokens;
1037
+ if (toks.length === 0)
1038
+ return;
1039
+ // 1. QRY001: UPDATE or DELETE with no top-level WHERE clause
1040
+ const mainStart = findMainStatementStartAfterWith(toks);
1041
+ const mainVerb = toks[mainStart]?.upper;
1042
+ if ((mainVerb === "UPDATE" || mainVerb === "DELETE") && isRuleEnabled("QRY001", stmt)) {
1043
+ let depth = 0;
1044
+ let hasTopLevelWhere = false;
1045
+ for (let i = mainStart + 1; i < toks.length; i++) {
1046
+ if (toks[i].raw === "(")
1047
+ depth += 1;
1048
+ else if (toks[i].raw === ")")
1049
+ depth = Math.max(0, depth - 1);
1050
+ else if (depth === 0 && toks[i].upper === "WHERE") {
1051
+ hasTopLevelWhere = true;
1052
+ break;
1053
+ }
1054
+ }
1055
+ if (!hasTopLevelWhere) {
1056
+ const verbTok = toks[mainStart];
1057
+ findings.push({
1058
+ ruleId: "QRY001",
1059
+ severity: "high",
1060
+ file,
1061
+ line: verbTok.line,
1062
+ column: verbTok.column,
1063
+ endLine: stmt.endLine,
1064
+ endColumn: stmt.endColumn,
1065
+ title: RULES.QRY001.title,
1066
+ message: `${mainVerb} statement has no top-level WHERE clause and will modify or delete every row in the target table.`,
1067
+ suggestion: `Add an explicit WHERE predicate (or '-- culprit-ignore: QRY001' if full-table ${mainVerb} is intentional).`,
1068
+ });
1069
+ }
1070
+ }
1071
+ // 2. QRY002: Non-sargable function wrapping a column inside a WHERE clause
1072
+ if (isRuleEnabled("QRY002", stmt)) {
1073
+ let inWhere = false;
1074
+ let whereParenDepth = 0;
1075
+ for (let i = 0; i < toks.length; i++) {
1076
+ const tok = toks[i];
1077
+ if (tok.raw === "(") {
1078
+ if (inWhere)
1079
+ whereParenDepth += 1;
1080
+ }
1081
+ else if (tok.raw === ")") {
1082
+ if (inWhere) {
1083
+ if (whereParenDepth === 0) {
1084
+ inWhere = false;
1085
+ }
1086
+ else {
1087
+ whereParenDepth -= 1;
1088
+ }
1089
+ }
1090
+ }
1091
+ else if (tok.upper === "WHERE") {
1092
+ inWhere = true;
1093
+ whereParenDepth = 0;
1094
+ continue;
1095
+ }
1096
+ else if (inWhere &&
1097
+ whereParenDepth === 0 &&
1098
+ (tok.upper === "GROUP" ||
1099
+ tok.upper === "ORDER" ||
1100
+ tok.upper === "LIMIT" ||
1101
+ tok.upper === "HAVING" ||
1102
+ tok.upper === "RETURNING" ||
1103
+ tok.upper === "UNION" ||
1104
+ tok.upper === "INTERSECT" ||
1105
+ tok.upper === "EXCEPT")) {
1106
+ inWhere = false;
1107
+ continue;
1108
+ }
1109
+ if (!inWhere)
1110
+ continue;
1111
+ const isCast = tok.kind === "word" && tok.upper === "CAST" && toks[i + 1]?.raw === "(";
1112
+ const isFunc = tok.kind === "word" &&
1113
+ NON_SARGABLE_FUNCTIONS.has(tok.upper) &&
1114
+ toks[i + 1]?.raw === "(";
1115
+ if (!isCast && !isFunc)
1116
+ continue;
1117
+ // Locate matching closing ')' of the function call
1118
+ let depth = 1;
1119
+ let closeIdx = -1;
1120
+ for (let k = i + 2; k < toks.length; k++) {
1121
+ if (toks[k].raw === "(")
1122
+ depth += 1;
1123
+ else if (toks[k].raw === ")") {
1124
+ depth -= 1;
1125
+ if (depth === 0) {
1126
+ closeIdx = k;
1127
+ break;
1128
+ }
1129
+ }
1130
+ }
1131
+ if (closeIdx === -1)
1132
+ continue;
1133
+ // Verify first argument inside (...) is a column reference (and not a literal/parameter)
1134
+ const argStart = i + 2;
1135
+ const colRef = readQualifiedName(toks, argStart);
1136
+ if (!colRef)
1137
+ continue;
1138
+ // Ignore SQL keyword literals like NULL, TRUE, FALSE, CURRENT_DATE, CURRENT_TIMESTAMP, NOW
1139
+ const firstArgUpper = toks[argStart]?.upper ?? "";
1140
+ if (firstArgUpper === "NULL" ||
1141
+ firstArgUpper === "TRUE" ||
1142
+ firstArgUpper === "FALSE" ||
1143
+ firstArgUpper === "CURRENT_DATE" ||
1144
+ firstArgUpper === "CURRENT_TIMESTAMP" ||
1145
+ firstArgUpper === "NOW" ||
1146
+ toks[argStart]?.raw.startsWith("@")) {
1147
+ continue;
1148
+ }
1149
+ // Check that this function call participates in a comparison predicate (either `FUNC(col) = ...` or `... = FUNC(col)`)
1150
+ const nextTok = toks[closeIdx + 1];
1151
+ const prevTok = toks[i - 1];
1152
+ const comparedOnRight = nextTok !== undefined &&
1153
+ (COMPARISON_OPS.has(nextTok.raw) ||
1154
+ nextTok.upper === "IN" ||
1155
+ nextTok.upper === "BETWEEN" ||
1156
+ nextTok.upper === "LIKE" ||
1157
+ nextTok.upper === "ILIKE");
1158
+ const comparedOnLeft = prevTok !== undefined && COMPARISON_OPS.has(prevTok.raw);
1159
+ if (!comparedOnRight && !comparedOnLeft)
1160
+ continue;
1161
+ const fnUpper = tok.upper;
1162
+ const colDisplay = colRef.rawDisplay;
1163
+ let suggestion;
1164
+ let fixSql;
1165
+ if (fnUpper === "LOWER" || fnUpper === "UPPER") {
1166
+ const indexClause = engine === "postgres" ? "CONCURRENTLY " : "";
1167
+ suggestion = `Add a functional index on ${fnUpper}(${colDisplay}) or store normalized/case-insensitive values so the planner can seek directly.`;
1168
+ fixSql = `CREATE INDEX ${indexClause}idx_expr_${fnUpper.toLowerCase()}_${colRef.bare} ON <table> (${fnUpper}(${colRef.bare}));`;
1169
+ }
1170
+ else if (fnUpper === "DATE" || fnUpper === "YEAR" || fnUpper === "MONTH" || fnUpper === "DAY") {
1171
+ 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.`;
1172
+ }
1173
+ else if (fnUpper === "CAST") {
1174
+ suggestion = `Cast the parameter or literal on the other side of the comparison instead of wrapping column '${colDisplay}' in CAST(...).`;
1175
+ }
1176
+ else {
1177
+ suggestion = `Avoid wrapping indexed column '${colDisplay}' in ${fnUpper}(...) inside WHERE, or create a matching expression index.`;
1178
+ }
1179
+ const endTok = comparedOnRight && toks[closeIdx + 2] ? toks[closeIdx + 2] : toks[closeIdx];
1180
+ findings.push({
1181
+ ruleId: "QRY002",
1182
+ severity: "medium",
1183
+ file,
1184
+ line: tok.line,
1185
+ column: tok.column,
1186
+ endLine: endTok.endLine,
1187
+ endColumn: endTok.endColumn,
1188
+ title: RULES.QRY002.title,
1189
+ message: `Non-sargable predicate wraps column '${colDisplay}' in ${fnUpper}(...), preventing standard B-tree index seeks.`,
1190
+ suggestion,
1191
+ ...(fixSql ? { fixSql } : {}),
1192
+ });
1193
+ }
1194
+ }
1195
+ // 3. QRY003: Leading wildcard LIKE '%...' or ILIKE '%...'
1196
+ if (isRuleEnabled("QRY003", stmt)) {
1197
+ for (let i = 0; i < toks.length - 1; i++) {
1198
+ const tok = toks[i];
1199
+ if (tok.kind !== "word" || (tok.upper !== "LIKE" && tok.upper !== "ILIKE")) {
1200
+ continue;
1201
+ }
1202
+ const patTok = toks[i + 1];
1203
+ if (patTok?.kind !== "string")
1204
+ continue;
1205
+ // Ignore dollar-quoted strings unless single-quoted literal
1206
+ if (!patTok.raw.includes("'"))
1207
+ continue;
1208
+ const patternVal = unquoteSqlString(patTok.raw);
1209
+ if (patternVal.startsWith("%")) {
1210
+ const suggestion = engine === "postgres"
1211
+ ? "Add a pg_trgm GIN index (USING gin (col gin_trgm_ops)), use full-text search (tsvector), or anchor the prefix without a leading '%'."
1212
+ : "Use full-text search, an inverted/n-gram index, or a reversed-column prefix index for suffix lookups.";
1213
+ findings.push({
1214
+ ruleId: "QRY003",
1215
+ severity: "low",
1216
+ file,
1217
+ line: tok.line,
1218
+ column: tok.column,
1219
+ endLine: patTok.endLine,
1220
+ endColumn: patTok.endColumn,
1221
+ title: RULES.QRY003.title,
1222
+ message: `Leading wildcard pattern ${tok.upper} ${patTok.raw} prevents B-tree index range seeks and forces a full index or table scan.`,
1223
+ suggestion,
1224
+ });
1225
+ }
1226
+ }
1227
+ }
1228
+ }
1229
+ /**
1230
+ * Lints a SQL string (migration or query file) and returns exact 1-based findings.
1231
+ */
1232
+ export function lintSql(sql, options = {}) {
1233
+ const file = options.file ?? "input.sql";
1234
+ const configuredEngine = options.engine ?? "auto";
1235
+ const mode = options.mode ?? "migration";
1236
+ const disabledSet = new Set((options.disabledRules ?? []).map((r) => r.toUpperCase()));
1237
+ const lexed = splitSqlStatements(sql);
1238
+ const resolvedEngine = detectSqlEngine(lexed.tokens, configuredEngine);
1239
+ const autoMode = configuredEngine === "auto";
1240
+ const isRuleEnabled = (ruleId, stmt) => {
1241
+ const upper = ruleId.toUpperCase();
1242
+ if (disabledSet.has(upper))
1243
+ return false;
1244
+ if (lexed.fileIgnoredRules.has("*") || lexed.fileIgnoredRules.has(upper))
1245
+ return false;
1246
+ if (stmt && (stmt.ignoredRules.has("*") || stmt.ignoredRules.has(upper)))
1247
+ return false;
1248
+ return true;
1249
+ };
1250
+ const indexRegistry = new TableIndexRegistry();
1251
+ // Seed existing indexes from optional programmatic configuration
1252
+ if (options.existingIndexes) {
1253
+ for (const [tbl, colLists] of Object.entries(options.existingIndexes)) {
1254
+ for (const cols of colLists) {
1255
+ indexRegistry.add(tbl, cols);
1256
+ }
1257
+ }
1258
+ }
1259
+ // Seed existing indexes from optional schema SQL snapshot
1260
+ if (options.schemaSql) {
1261
+ const schemaLexed = splitSqlStatements(options.schemaSql);
1262
+ collectSchemaFactsFromStatements(schemaLexed.statements, indexRegistry);
1263
+ }
1264
+ // Pass 1: Collect all indexes & foreign keys declared anywhere in this SQL file
1265
+ const fileForeignKeys = collectSchemaFactsFromStatements(lexed.statements, indexRegistry);
1266
+ const findings = [];
1267
+ const createdTables = new TableSet();
1268
+ const migrationState = {
1269
+ inTransaction: false,
1270
+ hasLockTimeout: false,
1271
+ emittedLockTimeoutWarning: false,
1272
+ };
1273
+ const runMigrationRules = mode === "migration" || mode === "all";
1274
+ const runQueryRules = mode === "query" || mode === "migration" || mode === "all";
1275
+ // Pass 2: Evaluate statement-by-statement migration & query rules
1276
+ for (const stmt of lexed.statements) {
1277
+ if (runMigrationRules) {
1278
+ checkMigrationStatement(stmt, resolvedEngine, autoMode, file, createdTables, migrationState, isRuleEnabled, findings);
1279
+ }
1280
+ if (runQueryRules) {
1281
+ checkQueryStatement(stmt, resolvedEngine, file, isRuleEnabled, findings);
1282
+ }
1283
+ }
1284
+ // Pass 3: Evaluate MIG004 across collected foreign keys once all file-wide indexes are registered
1285
+ if (runMigrationRules) {
1286
+ for (const fk of fileForeignKeys) {
1287
+ // Locate owning statement for ignore pragma support
1288
+ const ownerStmt = lexed.statements.find((s) => fk.token.offset >= s.tokens[0].offset && fk.token.offset <= s.tokens[s.tokens.length - 1].endOffset);
1289
+ if (!isRuleEnabled("MIG004", ownerStmt))
1290
+ continue;
1291
+ if (!indexRegistry.coversForeignKey(fk.table, fk.columns)) {
1292
+ const colsJoined = fk.columns.join(", ");
1293
+ const colsSlug = fk.columns.join("_");
1294
+ const onlineKw = resolvedEngine === "postgres" && !createdTables.has(fk.table) ? "CONCURRENTLY " : "";
1295
+ const onlineSuffix = resolvedEngine === "mssql" && !createdTables.has(fk.table) ? " WITH (ONLINE = ON)" : "";
1296
+ const fixSql = `CREATE INDEX ${onlineKw}idx_${fk.table.bare}_${colsSlug} ON ${fk.table.rawDisplay} (${colsJoined})${onlineSuffix};`;
1297
+ findings.push({
1298
+ ruleId: "MIG004",
1299
+ severity: "medium",
1300
+ file,
1301
+ line: fk.token.line,
1302
+ column: fk.token.column,
1303
+ endLine: fk.endToken.endLine,
1304
+ endColumn: fk.endToken.endColumn,
1305
+ title: RULES.MIG004.title,
1306
+ message: `Foreign key on '${fk.table.rawDisplay} (${colsJoined})' has no covering index in this migration or schema snapshot.`,
1307
+ suggestion: `Create an index with leading column(s) (${colsJoined}) on '${fk.table.rawDisplay}' to avoid lock amplification and full scans on parent updates/deletes.`,
1308
+ fixSql,
1309
+ });
1310
+ }
1311
+ }
1312
+ }
1313
+ // Sort deterministically by line, column, ruleId
1314
+ findings.sort((a, b) => a.line - b.line || a.column - b.column || a.ruleId.localeCompare(b.ruleId));
1315
+ return findings;
1316
+ }
1317
+ //# sourceMappingURL=linter.js.map