| 330 | |
| 331 | /** Lint a single migration's SQL. Returns only actionable findings. */ |
| 332 | export function lintSql(content: string): Finding[] { |
| 333 | const lines = content.split('\n') |
| 334 | const statements = parseStatements(content) |
| 335 | const createdTables = new Set<string>() |
| 336 | for (const { sql } of statements) { |
| 337 | const m = sql.match(/^CREATE TABLE (?:IF NOT EXISTS )?("?[.\w]+"?)/i) |
| 338 | if (m) createdTables.add(bareName(m[1])) |
| 339 | } |
| 340 | |
| 341 | const findings: Finding[] = [] |
| 342 | let sawCommit = false |
| 343 | for (const { sql, startLine } of statements) { |
| 344 | for (const match of classify(sql, createdTables, sawCommit)) { |
| 345 | if (match.kind === 'error') { |
| 346 | findings.push({ |
| 347 | line: startLine, |
| 348 | statement: sql, |
| 349 | tier: 'error', |
| 350 | rule: match.rule, |
| 351 | message: match.message, |
| 352 | }) |
| 353 | } else if (match.kind === 'warn') { |
| 354 | findings.push({ |
| 355 | line: startLine, |
| 356 | statement: sql, |
| 357 | tier: 'warn', |
| 358 | rule: match.rule, |
| 359 | message: match.message, |
| 360 | }) |
| 361 | } else { |
| 362 | const ann = readAnnotation(lines, startLine) |
| 363 | if (ann.allowed) continue |
| 364 | findings.push({ |
| 365 | line: startLine, |
| 366 | statement: sql, |
| 367 | tier: 'error', |
| 368 | rule: match.rule, |
| 369 | message: ann.missingReason |
| 370 | ? `${match.message}: \`-- migration-safe:\` annotation has no reason. Give it a real justification.` |
| 371 | : `${match.message} ${ANNOTATE_GUIDANCE}`, |
| 372 | }) |
| 373 | } |
| 374 | } |
| 375 | if (/^COMMIT\b/i.test(sql.trim())) sawCommit = true |
| 376 | } |
| 377 | return findings |
| 378 | } |
| 379 | |
| 380 | function git(args: string[]): string | null { |
| 381 | try { |