#!/usr/bin/env node /** Scan DELETE ... USING / FROM with JOIN ON referencing target alias */ const fs = require('fs'); const path = require('path'); function walk(d, acc = []) { for (const e of fs.readdirSync(d, { withFileTypes: true })) { const p = path.join(d, e.name); if (e.isDirectory()) { if (['node_modules', 'dist', '.git'].includes(e.name)) continue; walk(p, acc); } else if (/\.(ts|js|sql|cjs|mjs)$/.test(e.name)) acc.push(p); } return acc; } function chunks(file, text) { if (file.endsWith('.sql')) return [{ text, start: 0 }]; const out = []; const re = /`([\s\S]*?)`/g; let m; while ((m = re.exec(text))) out.push({ text: m[1], start: m.index }); return out; } const files = ['server/src', 'server/scripts', 'scripts', 'migrations'].flatMap((r) => fs.existsSync(r) ? walk(r) : [] ); const findings = []; for (const file of files) { // skip historical migrations for "runtime risk" report but still collect const text = fs.readFileSync(file, 'utf8'); for (const chunk of chunks(file, text)) { const sql = chunk.text; // DELETE FROM table alias USING ... JOIN ... ON alias. // DELETE FROM table alias WHERE ... JOIN unlikely const re = /DELETE\s+FROM\s+([a-zA-Z_][\w.]*)\s+([a-zA-Z_]\w*)\s+([\s\S]*?)(?=;|$)/gi; let m; while ((m = re.exec(sql))) { const target = m[1]; const alias = m[2]; const body = m[3]; if (!/\bUSING\b/i.test(body) && !/\bJOIN\b/i.test(body)) continue; const usingMatch = body.match(/\bUSING\b([\s\S]*?)(?=\bWHERE\b|\bRETURNING\b|$)/i); const scope = usingMatch ? usingMatch[1] : body; if (!/\bJOIN\b/i.test(scope)) continue; const onParts = [ ...scope.matchAll( /\bON\b([\s\S]*?)(?=\b(?:INNER|LEFT|RIGHT|FULL|CROSS)?\s*JOIN\b|\bWHERE\b|$)/gi ), ]; const aliasDot = new RegExp(`\\b${alias}\\.`, 'i'); const bad = onParts.map((x) => x[1]).filter((on) => aliasDot.test(on)); if (!bad.length) continue; const line = text.slice(0, chunk.start + m.index).split(/\n/).length; findings.push({ file: file.replace(/\\/g, '/'), line, kind: 'DELETE', target, alias, sample: bad[0].trim().replace(/\s+/g, ' ').slice(0, 160), runtime: !file.includes('migrations') && !file.includes('scripts'), }); } } } console.log(JSON.stringify(findings, null, 2)); console.log('count', findings.length); console.log( 'runtime', findings.filter((f) => f.runtime).length );