Repository navigation
fix: read SQL text with escape strings, Unicode and quoted names #1856
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -79,10 +79,15 @@ export function stripAggFilter(sql: string): string { | |||||||||||||||||||||||||||||||
| */ | ||||||||||||||||||||||||||||||||
| export function stripSql(sql: string): string { | ||||||||||||||||||||||||||||||||
| // A quoted name ("a--b", `c/*d`, [e--f]) is kept whole, so comment marks inside it start no comment. | ||||||||||||||||||||||||||||||||
| // Postgres's escape string (E'it\'s') ends at an unescaped quote, not at a backslash-escaped one. | ||||||||||||||||||||||||||||||||
| return sql.replace( | ||||||||||||||||||||||||||||||||
| /"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[(?:[^\]]|\]\])*\]|'(?:[^']|'')*'|\$([A-Za-z_]\w*)?\$[\s\S]*?\$\1\$|--[^\r\n]*|\/\*[\s\S]*?\*\//g, | ||||||||||||||||||||||||||||||||
| /"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[(?:[^\]]|\]\])*\]|(?<![\w$])[eE]'(?:[^'\\]|\\[\s\S]|'')*'|'(?:[^']|'')*'|\$([A-Za-z_]\w*)?\$[\s\S]*?\$\1\$|--[^\r\n]*|\/\*[\s\S]*?\*\//g, | ||||||||||||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: Keep escape-string mode active for newline-concatenated segments after an Prompt for AI agents
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Leaving this one, as on CodeRabbit's thread here. A continued |
||||||||||||||||||||||||||||||||
| (match) => | ||||||||||||||||||||||||||||||||
|
Comment on lines
83
to
85
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [🟠 MEDIUM] The regular expression for Using Suggested change:
Suggested change
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Leaving this one; it's R5 in the review log. The dollar-quote tag pattern is as on main, and C2 keeps every other literal as on main. The |
||||||||||||||||||||||||||||||||
| match.startsWith('"') || match.startsWith("`") || match.startsWith("[") ? match : match.startsWith("'") || match.startsWith("$") ? "''" : " ", | ||||||||||||||||||||||||||||||||
| match.startsWith('"') || match.startsWith("`") || match.startsWith("[") | ||||||||||||||||||||||||||||||||
| ? match | ||||||||||||||||||||||||||||||||
| : /^(?:[eE]?'|\$)/.test(match) | ||||||||||||||||||||||||||||||||
| ? "''" | ||||||||||||||||||||||||||||||||
| : " ", | ||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
|
|
@@ -92,14 +97,15 @@ export function hasNestedWith(sql: string): boolean { | |||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| const ENGINE_NAME = /^_(?:col_)?\d+$/i | ||||||||||||||||||||||||||||||||
| const COLUMNS_CALL = /(?<![\w$])columns\s*\(/i | ||||||||||||||||||||||||||||||||
| const COLUMNS_CALL = /(?<![\p{L}\p{N}_$])columns\s*\(/iu | ||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| /** | ||||||||||||||||||||||||||||||||
| * The engine's own name for an unaliased expression in a SELECT list (`_1`, `_col_1`): not the warehouse's | ||||||||||||||||||||||||||||||||
| * name for it. A name the SQL itself writes (`amount as _1`) is a real alias. | ||||||||||||||||||||||||||||||||
| */ | ||||||||||||||||||||||||||||||||
| export function engineMade(name: string, stripped: string): boolean { | ||||||||||||||||||||||||||||||||
| return ENGINE_NAME.test(name) && !new RegExp(`(?<![\\w$])${name}(?![\\w$])`, "i").test(stripped) | ||||||||||||||||||||||||||||||||
| // A whole name only, in any script: `é_1` is a name of its own, so it writes no `_1`. | ||||||||||||||||||||||||||||||||
| return ENGINE_NAME.test(name) && !new RegExp(`(?<!${NAME})${name}(?!${NAME})`, "iu").test(stripped) | ||||||||||||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION:
Adding
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Leaving this one, recorded as R5 in the review log. It's the same shape as the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Include combining marks in the name boundary.
Include
|
||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| /** | ||||||||||||||||||||||||||||||||
|
|
@@ -112,8 +118,24 @@ function namesItsOutputs(outputs: string[]): boolean { | |||||||||||||||||||||||||||||||
| return names.length > 0 && new Set(names).size === names.length | ||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| const QUOTED = '"(?:[^"]|"")*"|`[^`]*`|\\[[^\\]]*\\]' | ||||||||||||||||||||||||||||||||
| const unquoteName = (name: string) => name.replace(/^["`[]|["`\]]$/g, "").toLowerCase() | ||||||||||||||||||||||||||||||||
| const QUOTED = '"(?:[^"]|"")*"|`(?:[^`]|``)*`|\\[(?:[^\\]]|\\]\\])*\\]' | ||||||||||||||||||||||||||||||||
| /** A name's text, lower-cased; a quoted one loses its quotes and unescapes only its own doubled quote (`"a""b"` is a"b). */ | ||||||||||||||||||||||||||||||||
| function unquoteName(name: string): string { | ||||||||||||||||||||||||||||||||
| const q = name[0] | ||||||||||||||||||||||||||||||||
| if (q === '"' || q === "`") return name.slice(1, -1).replaceAll(q + q, q).toLowerCase() | ||||||||||||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION: the new helper duplicates the unescape
return at - start === 1 && ENDS_EXPRESSION.test(last.text) ? null : unquoteName(last.text)(
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done in f92232a: the cast reader hands every name to |
||||||||||||||||||||||||||||||||
| if (q === "[") return name.slice(1, -1).replaceAll("]]", "]").toLowerCase() | ||||||||||||||||||||||||||||||||
| return name.toLowerCase() | ||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||
| /** A name's characters, unquoted: letters and digits in any script, `_` and `$`. */ | ||||||||||||||||||||||||||||||||
| const NAME = "[\\p{L}\\p{N}_$]" | ||||||||||||||||||||||||||||||||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
|
||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| /** The character before index `i`, a whole code point even outside the BMP (`𐐨` is two UTF-16 units); "" at the start. */ | ||||||||||||||||||||||||||||||||
| function charBefore(text: string, i: number): string { | ||||||||||||||||||||||||||||||||
| if (i <= 0) return "" | ||||||||||||||||||||||||||||||||
| const unit = text.charCodeAt(i - 1) | ||||||||||||||||||||||||||||||||
| if (unit >= 0xdc00 && unit <= 0xdfff && i >= 2) return String.fromCodePoint(text.codePointAt(i - 2)!) | ||||||||||||||||||||||||||||||||
| return text[i - 1]! | ||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||
|
Comment on lines
+133
to
+138
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [🟠 MEDIUM] If the character at It is recommended to explicitly check if Suggested change:
Suggested change
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Leaving this one: a lone low surrogate can't reach |
||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| /** | ||||||||||||||||||||||||||||||||
| * The items of the SQL's outermost SELECT list (the first one outside parentheses, so after any WITH), split at | ||||||||||||||||||||||||||||||||
|
|
@@ -131,8 +153,9 @@ export function selectItems(stripped: string): string[] { | |||||||||||||||||||||||||||||||
| if (ch === "(") depth++ | ||||||||||||||||||||||||||||||||
| else if (ch === ")") depth-- | ||||||||||||||||||||||||||||||||
| if (depth !== 0) continue | ||||||||||||||||||||||||||||||||
| const word = /^[a-z_]+/i.exec(text.slice(i))?.[0]?.toLowerCase() | ||||||||||||||||||||||||||||||||
| const boundary = i === 0 || !/[\w$]/.test(text[i - 1]!) | ||||||||||||||||||||||||||||||||
| // A keyword is a whole name: `from` inside `éfrom` or `fromage` ends no list. | ||||||||||||||||||||||||||||||||
| const word = /^[\p{L}\p{N}_$]+/u.exec(text.slice(i))?.[0]?.toLowerCase() | ||||||||||||||||||||||||||||||||
| const boundary = !/[\p{L}\p{N}_$]/u.test(charBefore(text, i)) | ||||||||||||||||||||||||||||||||
| if (start < 0) { | ||||||||||||||||||||||||||||||||
| if (boundary && word === "select") { | ||||||||||||||||||||||||||||||||
| start = i + 6 | ||||||||||||||||||||||||||||||||
|
|
@@ -154,27 +177,45 @@ export function selectItems(stripped: string): string[] { | |||||||||||||||||||||||||||||||
| return items.filter((one) => one !== "") | ||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| /** Words that end an expression (`x is null`, `case … end`) rather than alias it. */ | ||||||||||||||||||||||||||||||||
| const ENDS_EXPRESSION = /^(?:null|true|false|end)$/i | ||||||||||||||||||||||||||||||||
| /** Words after which the next word is an operand (`a and b`, `sum(x) over w`), not an alias. */ | ||||||||||||||||||||||||||||||||
| const TAKES_OPERAND = /^(?:and|or|not|is|in|like|ilike|rlike|regexp|similar|to|between|case|when|then|else|over|collate|escape|interval|distinct|by|as|at|zone|any|all|some|exists|div|mod|xor)$/i | ||||||||||||||||||||||||||||||||
| /** Words that join, compare or qualify operands (`a and b`, `x is null`, `sum(x) over w`): never an alias, never a type. */ | ||||||||||||||||||||||||||||||||
| const OPERATOR_WORDS = ["and", "or", "not", "is", "isnull", "notnull", "in", "like", "ilike", "rlike", "regexp", "similar", | ||||||||||||||||||||||||||||||||
| "between", "case", "when", "then", "else", "over", "filter", "collate", "escape", "div", "mod", "xor", "any", "all", "some", "exists"] | ||||||||||||||||||||||||||||||||
| /** Literal words: they end an expression (`x is null`, `case … end`), and a bare one is no column. */ | ||||||||||||||||||||||||||||||||
| const LITERAL_WORDS = ["null", "true", "false", "end"] | ||||||||||||||||||||||||||||||||
| const wordList = (list: string[]) => new RegExp(`^(?:${list.join("|")})$`, "i") | ||||||||||||||||||||||||||||||||
| /** Words that end an expression rather than alias it. */ | ||||||||||||||||||||||||||||||||
| const ENDS_EXPRESSION = wordList(LITERAL_WORDS) | ||||||||||||||||||||||||||||||||
| /** | ||||||||||||||||||||||||||||||||
| * Words after which the next word is an operand, not an alias: the operators, and words that take one (`interval`, | ||||||||||||||||||||||||||||||||
| * `at time zone`). `isnull` and `notnull` end an expression, so the word after them is an alias (`x isnull flag`). | ||||||||||||||||||||||||||||||||
| */ | ||||||||||||||||||||||||||||||||
| const TAKES_OPERAND = wordList([...OPERATOR_WORDS.filter((word) => word !== "isnull" && word !== "notnull"), "to", "interval", "distinct", "by", "as", "at", "zone"]) | ||||||||||||||||||||||||||||||||
| /** Words a type name never holds: an item with one after `::` is more than a cast (`amount::numeric is not null`). */ | ||||||||||||||||||||||||||||||||
| const NOT_TYPE = wordList([...OPERATOR_WORDS, ...LITERAL_WORDS, "as", "at"]) | ||||||||||||||||||||||||||||||||
| /** An interval's fields: after a complete interval literal (`interval '1' day`) the word is part of it, not an alias. */ | ||||||||||||||||||||||||||||||||
| const INTERVAL_FIELD = /^(?:year|month|week|day|hour|minute|second|millisecond|microsecond|quarter|decade|century|millennium)s?$/i | ||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| /** | ||||||||||||||||||||||||||||||||
| * A SELECT item's output name when the SQL gives one (`x as name`, `x name`, a bare `t.col`), `*` for a star, | ||||||||||||||||||||||||||||||||
| * else null. | ||||||||||||||||||||||||||||||||
| */ | ||||||||||||||||||||||||||||||||
| export function itemName(item: string): string | null { | ||||||||||||||||||||||||||||||||
| if (/^(?:[\w$]+\.)*\*(?:\s|$)/.test(item)) return "*" | ||||||||||||||||||||||||||||||||
| const as = new RegExp(`\\s+as\\s+(${QUOTED}|[\\w$]+)$`, "i").exec(item) | ||||||||||||||||||||||||||||||||
| const part = `(?:${QUOTED}|${NAME}+)` | ||||||||||||||||||||||||||||||||
| if (new RegExp(`^(?:${part}\\.)*\\*(?:\\s|$)`, "u").test(item)) return "*" | ||||||||||||||||||||||||||||||||
| const as = new RegExp(`\\s+as\\s+(${part})$`, "iu").exec(item) | ||||||||||||||||||||||||||||||||
| if (as) return unquoteName(as[1]!) | ||||||||||||||||||||||||||||||||
| const bare = new RegExp(`^(?:(?:${QUOTED}|[\\w$]+)\\.)*(${QUOTED}|[\\w$]+)$`).exec(item) | ||||||||||||||||||||||||||||||||
| const bare = new RegExp(`^(?:${part}\\.)*(${part})$`, "u").exec(item) | ||||||||||||||||||||||||||||||||
| if (bare) return unquoteName(bare[1]!) | ||||||||||||||||||||||||||||||||
| // An alias without AS: the last word, after an expression that ends in a name, a `)`, a quote or a literal. | ||||||||||||||||||||||||||||||||
| const plain = new RegExp(`^([\\s\\S]*?[\\w$)"\`\\]'])\\s+(${QUOTED}|[\\w$]+)$`).exec(item) | ||||||||||||||||||||||||||||||||
| const plain = new RegExp(`^([\\s\\S]*?(?:${NAME}|[)"\`\\]']))\\s+(${part})$`, "u").exec(item) | ||||||||||||||||||||||||||||||||
| if (!plain) return null | ||||||||||||||||||||||||||||||||
| const before = /([\w$]+)\s*$/.exec(plain[1]!)?.[1] | ||||||||||||||||||||||||||||||||
| if ((before && TAKES_OPERAND.test(before)) || /(?<![\w$])interval\s+(?:''|[\d.]+)$/i.test(plain[1]!)) return null | ||||||||||||||||||||||||||||||||
| return ENDS_EXPRESSION.test(plain[2]!) ? null : unquoteName(plain[2]!) | ||||||||||||||||||||||||||||||||
| const [, expression, alias] = plain as unknown as [string, string, string] | ||||||||||||||||||||||||||||||||
| // The word before: an operator takes the next word as its operand, unless it is a column after a dot (`t.mod id`). | ||||||||||||||||||||||||||||||||
| const before = new RegExp(`(\\.)?(${NAME}+)\\s*$`, "u").exec(expression) | ||||||||||||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Recognize whitespace after a qualifier dot. SQL permits whitespace between tokens. (postgresql.org) However, The suffix match loses the qualifier dot when whitespace precedes
|
||||||||||||||||||||||||||||||||
| const before = new RegExp(`(\\.)?(${NAME}+)\\s*$`, "u").exec(expression) | |
| const before = new RegExp(`(\\.\\s*)?(${NAME}+)\\s*$`, "u").exec(expression) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Leaving this one, as on CodeRabbit's thread here. Whitespace after a qualifier's dot (t. mod id) is R4 in the review log, reading SELECT items from text, and it breaks no claim.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Preserve escape mode across continued E strings.
PostgreSQL permits an E string to continue after a newline without another
Eprefix. (postgresql.org)The continuation uses the plain-string branch, which stops at
\'. This exposes(b)::intand shifts subsequent SELECT-item positions. Keep escape mode across continuation segments without changing unrelated plain strings.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Leaving this one. A continued
E''string, a second segment after a newline, is R1 in the review log: backslash escapes are read only inside theE''segment itself. It takes an escaped quote, then a comma and a cast inside the continuation, to shift an item. That breaks no claim, and this PR is now fixing only what does.