* Split SQL into statements with their 1-based start line, respecting line * comments (`--`), block comments, and single-quoted strings so a `;` inside * any of them does not terminate a statement.
(content: string)
| 60 | * any of them does not terminate a statement. |
| 61 | */ |
| 62 | function parseStatements(content: string): Statement[] { |
| 63 | const statements: Statement[] = [] |
| 64 | let buf = '' |
| 65 | let startOffset = -1 |
| 66 | let inLine = false |
| 67 | let inBlock = false |
| 68 | let inStr = false |
| 69 | let dollarTag: string | null = null |
| 70 | |
| 71 | const lineAt = (offset: number): number => { |
| 72 | let line = 1 |
| 73 | for (let i = 0; i < offset; i++) if (content[i] === '\n') line++ |
| 74 | return line |
| 75 | } |
| 76 | const flush = () => { |
| 77 | const sql = buf.trim() |
| 78 | if (sql.length > 0 && startOffset >= 0) statements.push({ sql, startLine: lineAt(startOffset) }) |
| 79 | buf = '' |
| 80 | startOffset = -1 |
| 81 | } |
| 82 | |
| 83 | for (let i = 0; i < content.length; i++) { |
| 84 | const c = content[i] |
| 85 | const next = content[i + 1] |
| 86 | |
| 87 | if (inLine) { |
| 88 | if (c === '\n') inLine = false |
| 89 | continue |
| 90 | } |
| 91 | if (inBlock) { |
| 92 | if (c === '*' && next === '/') { |
| 93 | inBlock = false |
| 94 | i++ |
| 95 | } |
| 96 | continue |
| 97 | } |
| 98 | if (inStr) { |
| 99 | buf += c |
| 100 | if (c === "'") { |
| 101 | if (next === "'") { |
| 102 | buf += "'" |
| 103 | i++ |
| 104 | } else { |
| 105 | inStr = false |
| 106 | } |
| 107 | } |
| 108 | continue |
| 109 | } |
| 110 | if (dollarTag) { |
| 111 | if (c === '$' && content.startsWith(dollarTag, i)) { |
| 112 | buf += dollarTag |
| 113 | i += dollarTag.length - 1 |
| 114 | dollarTag = null |
| 115 | } else { |
| 116 | buf += c |
| 117 | } |
| 118 | continue |
| 119 | } |