fix(database): keep a script's statements whole around each dialect's literals and comments (#7846)

The console's statement splitter cut some literals and comments, so part of one could run as a statement of its own (PostgreSQL /* outer /* inner */ ; DELETE FROM b; */ ran the DELETE). It now knows PostgreSQL and SQL Server nested comments, PostgreSQL E'...' strings and $ inside names, MySQL backslash escapes in double-quoted strings and its rule that -- needs a blank after it, SQL Server [a]]b] and SQLite [a;b] and backtick names. The TypeScript lexer behind the unsafe-statement warning reads the same literals alike.

Co-authored-by: ntbang0901 <[email protected]>
Цей коміт міститься в:
ntbang0901 authored and GitHub committed 2026-12-04 00:37:25 +08:00
1 джерело 61418e9cb5
коміт 5de7b0964e
5 files changed
+215 -28

No files matched your search

+116 -11
Переглянути файл
@@ -1,5 +1,7 @@
//! Splitting SQL scripts into statements (`;`-terminated), aware of string
//! literals, quoted identifiers, comments and PostgreSQL dollar quoting.
//! MySQL strings take backslash escapes (no `NO_BACKSLASH_ESCAPES`) and double
//! quotes (no `ANSI_QUOTES`), its defaults; the console's lexer.ts reads them alike.
//! Offsets are UTF-16 code units, like everything on the IPC boundary.
use crate::DbDriver;
@@ -22,12 +24,13 @@ enum State {
Single,
Double,
Backtick,
Bracket,
LineComment,
BlockComment,
}
// Starts just after the opening `/*`. ClickHouse supports nested block comments.
fn after_clickhouse_block_comment(mut text: &str) -> &str {
// Starts just after the opening `/*`.
fn after_nested_block_comment(mut text: &str) -> &str {
let mut depth = 1usize;
while let Some(at) = text.find(['/', '*']) {
text = &text[at..];
@@ -55,7 +58,7 @@ pub(super) fn clickhouse_keyword<'a>(sql: &mut &'a str) -> Option<&'a str> {
if let Some(comment) = text.strip_prefix('#').or_else(|| text.strip_prefix("--")) {
text = comment.split_once('\n').map_or("", |(_, rest)| rest);
} else if let Some(comment) = text.strip_prefix("/*") {
text = after_clickhouse_block_comment(comment);
text = after_nested_block_comment(comment);
} else {
break;
}
@@ -76,6 +79,10 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
// PL/SQL: `;` inside BEGIN…END / DECLARE…END blocks does not terminate a statement.
let plsql = driver == DbDriver::Oracle;
let snowflake = driver == DbDriver::Snowflake;
let postgres = driver == DbDriver::Postgres;
let sqlite = driver == DbDriver::Sqlite;
let sql_server = driver == DbDriver::SqlServer;
let nested_comments = clickhouse || postgres || sql_server;
let chars: Vec<(usize, char)> = text.char_indices().collect();
// UTF-16 offset of each char index (plus the end).
let mut u16_at = Vec::with_capacity(chars.len() + 1);
@@ -105,6 +112,8 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
let mut script = false;
// The segment may carry a Scripting block as its body (`CREATE TASK … AS BEGIN … END`).
let mut defines = false;
// The open string is PostgreSQL's `E'…'`.
let mut escape_string = false;
let push = |out: &mut Vec<SqlStatement>, s: usize, e: usize, has_code: bool| {
if !has_code {
return;
@@ -164,6 +173,18 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
defines = false;
}
';' => has_code = true,
// Words are read whole: the `E` of `E'…'` starts one, and a `$` inside one quotes nothing.
_ if postgres && (c.is_alphabetic() || c == '_') => {
has_code = true;
if matches!(c, 'E' | 'e') && next == Some('\'') {
(state, escape_string) = (State::Single, true);
i += 1;
} else {
while chars.get(i + 1).is_some_and(|&(_, c)| c.is_alphanumeric() || matches!(c, '_' | '$')) {
i += 1;
}
}
}
'\'' => {
state = State::Single;
has_code = true;
@@ -172,13 +193,17 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
state = State::Double;
has_code = true;
}
'`' if mysql || clickhouse => {
'`' if mysql || clickhouse || sqlite => {
state = State::Backtick;
has_code = true;
}
'[' if sqlite || sql_server => {
state = State::Bracket;
has_code = true;
}
'/' if next == Some('*') => {
if clickhouse {
let rest = after_clickhouse_block_comment(&text[byte_at(i + 2)..]);
if nested_comments {
let rest = after_nested_block_comment(&text[byte_at(i + 2)..]);
let end = text.len() - rest.len();
i = chars.partition_point(|&(offset, _)| offset < end);
continue;
@@ -199,7 +224,10 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
block = false;
package = false;
}
'-' if next == Some('-') => {
// MySQL reads `5--1` as a subtraction.
'-' if next == Some('-')
&& (!mysql || chars.get(i + 2).is_none_or(|&(_, c)| c == ' ' || c.is_ascii_control())) =>
{
state = State::LineComment;
i += 1;
}
@@ -213,7 +241,7 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
state = State::LineComment;
i += 1;
}
'$' if driver == DbDriver::Postgres || snowflake => {
'$' if postgres || snowflake => {
// `$tag$ … $tag$` (tag may be empty); `$1` parameters are not quotes.
let rest = &text[byte_at(i)..];
let tag_len = rest[1..].find('$').filter(|&n| {
@@ -289,18 +317,18 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
_ => {}
},
State::Single => {
if (mysql || clickhouse || snowflake) && c == '\\' {
if (mysql || clickhouse || snowflake || escape_string) && c == '\\' {
i += 1;
} else if c == '\'' {
if next == Some('\'') {
i += 1;
} else {
state = State::Code;
(state, escape_string) = (State::Code, false);
}
}
}
State::Double => {
if clickhouse && c == '\\' {
if (mysql || clickhouse) && c == '\\' {
i += 1;
} else if c == '"' {
if next == Some('"') {
@@ -317,6 +345,13 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
state = State::Code;
}
}
State::Bracket => {
if sql_server && c == ']' && next == Some(']') {
i += 1;
} else if c == ']' {
state = State::Code;
}
}
State::LineComment => {
if c == '\n' {
state = State::Code;
@@ -510,6 +545,76 @@ mod tests {
);
}
#[test]
fn postgres_and_sql_server_nest_block_comments() {
let sql = "/* outer /* inner */ ; DELETE FROM b; */ SELECT 1";
for driver in [DbDriver::Postgres, DbDriver::SqlServer] {
assert_eq!(texts(&format!("{sql}; SELECT 2"), driver), vec![sql, "SELECT 2"]);
assert_eq!(statement_at(sql, 25, driver).map(|s| s.text).as_deref(), Some(sql));
assert_eq!(texts("/* open /* ; */ ; DELETE FROM b", driver), Vec::<String>::new());
}
for driver in [DbDriver::Mysql, DbDriver::Sqlite, DbDriver::Oracle, DbDriver::Snowflake] {
assert_eq!(texts("/* a /* b */ SELECT 1; SELECT 2", driver), vec!["/* a /* b */ SELECT 1", "SELECT 2"]);
}
}
#[test]
fn postgres_escape_strings_and_dollars_in_names() {
for sql in [r"SELECT E'it\'s; DELETE FROM b; --'", r"SELECT e'a\\', E'it''s; \';'"] {
assert_eq!(texts(&format!("{sql}; SELECT 2"), DbDriver::Postgres), vec![sql, "SELECT 2"]);
assert_eq!(statement_at(sql, 22, DbDriver::Postgres).map(|s| s.text).as_deref(), Some(sql));
}
// A backslash is plain in other strings, also after a word that ends in `e`.
for sql in [r"SELECT 'a\'", r"SELECT date'\'", r"SELECT U&'\'", r#"SELECT "a\""#] {
assert_eq!(texts(&format!("{sql}; SELECT 2"), DbDriver::Postgres), vec![sql, "SELECT 2"]);
}
// A `$` inside a name opens no dollar quote.
assert_eq!(
texts("SELECT a$b$ FROM t; SELECT b$b$ FROM t", DbDriver::Postgres),
vec!["SELECT a$b$ FROM t", "SELECT b$b$ FROM t"]
);
}
#[test]
fn mysql_double_quoted_strings_and_dashes() {
let sql = r#"SELECT "say \"hi; DELETE FROM b; \"", 'a''b;', "c"";", `d``;`"#;
assert_eq!(texts(&format!("{sql}; SELECT 2"), DbDriver::Mysql), vec![sql, "SELECT 2"]);
assert_eq!(statement_at(sql, 24, DbDriver::Mysql).map(|s| s.text).as_deref(), Some(sql));
// `--` starts a comment only before whitespace, a control character or the end.
assert_eq!(texts("SELECT 5--1; SELECT 2", DbDriver::Mysql), vec!["SELECT 5--1", "SELECT 2"]);
for comment in ["-- a;", "--\ta;", "--"] {
assert_eq!(texts(&format!("SELECT 5 {comment}\n+ 1; SELECT 2"), DbDriver::Mysql).len(), 2);
assert_eq!(texts(&format!("SELECT 1; {comment}"), DbDriver::Mysql), vec!["SELECT 1"]);
}
for driver in [DbDriver::Postgres, DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Oracle] {
assert_eq!(texts("SELECT 5--1; SELECT 2", driver), vec!["SELECT 5--1; SELECT 2"]);
}
}
#[test]
fn bracketed_and_backtick_names() {
for (sql, driver) in [
("SELECT * FROM [a;b]", DbDriver::SqlServer),
("SELECT * FROM [a]];'b]", DbDriver::SqlServer),
("SELECT * FROM `a;b`, `c``;'d`", DbDriver::Sqlite),
("SELECT * FROM [c;d], [it's]", DbDriver::Sqlite),
("SELECT * FROM [e[;]", DbDriver::Sqlite),
] {
assert_eq!(texts(&format!("{sql}; SELECT 2"), driver), vec![sql, "SELECT 2"]);
assert_eq!(statement_at(sql, 16, driver).map(|s| s.text).as_deref(), Some(sql));
}
// Array subscripts and literals elsewhere.
assert_eq!(texts("SELECT a[1; SELECT 2", DbDriver::Postgres), vec!["SELECT a[1", "SELECT 2"]);
assert_eq!(texts("SELECT [1; SELECT 2", DbDriver::Clickhouse), vec!["SELECT [1", "SELECT 2"]);
}
#[test]
fn a_selection_keeps_literals_whole() {
let sql = "SELECT 0; SELECT E'\\';'; SELECT 2";
let s = statements_in(sql, 10, sql.len() as u32, DbDriver::Postgres);
assert_eq!(s.iter().map(|s| s.text.as_str()).collect::<Vec<_>>(), vec!["SELECT E'\\';'", "SELECT 2"]);
}
#[test]
fn utf16_offsets() {
let sql = "select '😀';\nselect 2;";
+31 -10
Переглянути файл
@@ -2,8 +2,10 @@
* SQL tokens for completion and resolution: words, quoted identifiers, string
* literals, numbers and punctuation, with comments and whitespace dropped.
* Dialect-aware (MySQL backticks / `#` comments / backslash escapes,
* PostgreSQL dollar quoting / nested comments, Snowflake `$$` strings / `//` comments / stages /
* variant paths). Offsets are UTF-16, like the editor's.
* PostgreSQL dollar quoting / `E''` strings / nested comments, SQL Server and SQLite `[names]`,
* Snowflake `$$` strings / `//` comments / stages / variant paths). Offsets are UTF-16, like the
* editor's. Literals and comments end where `split.rs` of ide-db ends them: the unsafe-statement
* check reads the statements it cuts.
*/
import { sqlWordUpper, type SqlDriver } from "./dialect";
@@ -52,11 +54,17 @@ function blockCommentEnd(text: string, from: number, nested: boolean): number {
return -1;
}
/** What must follow `--` for MySQL to read a comment. */
const blankOrControl = (c: string | undefined) => c === undefined || c <= " " || c === "\x7f";
export function lex(text: string, driver: SqlDriver = "sqlite"): Lexed {
const mysql = driver === "mysql";
const clickhouse = driver === "clickhouse";
const snowflake = driver === "snowflake";
const duckdb = driver === "duckdb";
const postgres = driver === "postgres";
const sqlite = driver === "sqlite";
const sqlServer = driver === "sqlServer";
const tokens: Token[] = [];
const comments: Lexed["comments"] = [];
const n = text.length;
@@ -92,17 +100,21 @@ export function lex(text: string, driver: SqlDriver = "sqlite"): Lexed {
const next = text[i + 1];
if (c === " " || c === "\t" || c === "\n" || c === "\r") {
i++;
} else if ((c === "-" && next === "-") || (c === "#" && mysql) || (c === "/" && next === "/" && snowflake)) {
} else if (
(c === "-" && next === "-" && (!mysql || blankOrControl(text[i + 2]))) ||
(c === "#" && mysql) ||
(c === "/" && next === "/" && snowflake)
) {
const end = text.indexOf("\n", i);
const to = end < 0 ? n : end;
comments.push({ from: i, to, open: true });
i = to;
} else if (c === "/" && next === "*") {
const end = blockCommentEnd(text, i + 2, driver === "postgres" || duckdb);
const end = blockCommentEnd(text, i + 2, postgres || sqlServer || duckdb);
const to = end < 0 ? n : end + 2;
comments.push({ from: i, to, open: end < 0 });
i = to;
} else if (duckdb && (c === "E" || c === "e") && next === "'") {
} else if ((postgres || duckdb) && (c === "E" || c === "e") && next === "'") {
const to = quoted(i + 1, "'", true);
push("string", i, to);
i = to;
@@ -111,14 +123,19 @@ export function lex(text: string, driver: SqlDriver = "sqlite"): Lexed {
push("string", i, to);
i = to;
} else if (c === '"') {
const to = quoted(i, '"', clickhouse);
const to = quoted(i, '"', mysql || clickhouse);
push(mysql ? "string" : "quoted", i, to);
i = to;
} else if (c === "`" && (mysql || clickhouse)) {
} else if (c === "`" && (mysql || clickhouse || sqlite)) {
const to = quoted(i, "`", clickhouse);
push("quoted", i, to);
i = to;
} else if (c === "$" && (driver === "postgres" || duckdb)) {
} else if (c === "[" && (sqlite || sqlServer) && text.includes("]", i)) {
// An unclosed bracket (a name being typed) must not swallow the rest of the text.
const to = sqlServer ? quoted(i, "]", false) : text.indexOf("]", i) + 1;
push("quoted", i, to);
i = to;
} else if (c === "$" && (postgres || duckdb)) {
const m = /^\$([\p{L}_][\p{L}\p{N}_]*)?\$/u.exec(text.slice(i, i + 64));
if (m) {
const tag = m[0];
@@ -187,11 +204,15 @@ export function lex(text: string, driver: SqlDriver = "sqlite"): Lexed {
return { tokens, comments };
}
/** Whether `pos` lies inside a string literal, quoted identifier or comment (not at its edge). */
/**
* Whether `pos` lies inside a string literal, quoted identifier or comment (not at its edge).
* Not inside `[name]`: names are completed there.
*/
export function inLiteral(lexed: Lexed, pos: number): "string" | "quoted" | "comment" | null {
for (const c of lexed.comments) if (pos > c.from && (pos < c.to || (c.open && pos === c.to))) return "comment";
for (const t of lexed.tokens) {
if (t.from >= pos) break;
if (t.text[0] === "[") continue;
if ((t.kind === "string" || t.kind === "quoted") && pos > t.from && (pos < t.to || !closed(t))) return t.kind;
}
return null;
@@ -213,7 +234,7 @@ function closed(t: Token): boolean {
export function identName(t: Token): string {
if (t.kind !== "quoted") return t.text;
if (t.value !== undefined) return t.value;
const q = t.text[0]!;
const q = t.text[0] === "[" ? "]" : t.text[0]!;
const body = t.text.endsWith(q) && t.text.length > 1 ? t.text.slice(1, -1) : t.text.slice(1);
return body.split(q + q).join(q);
}
+45
Переглянути файл
@@ -245,6 +245,51 @@ describe("lexer", () => {
expect(inLiteral(lex("select 'abc"), 11)).toBe("string");
});
it.each([
["postgres", String.raw`E'it\'s; --'`, "string"],
["postgres", String.raw`e'a\\'`, "string"],
["mysql", String.raw`"say \"hi; -- \""`, "string"],
["sqlServer", "[a]];'b]", "quoted"],
["sqlite", "[it's; --]", "quoted"],
["sqlite", "`a``;'b`", "quoted"],
] as const)("reads %s %s as one %s", (driver, text, kind) => {
const tokens = lex(`select ${text}, x`, driver).tokens;
expect(tokens.map((t) => t.text)).toEqual(["select", text, ",", "x"]);
expect(tokens[1]!.kind).toBe(kind);
});
it("names bracketed and backtick identifiers", () => {
const names = (sql: string, driver: "sqlServer" | "sqlite") => lex(sql, driver).tokens.map(identName);
expect(names("[Order]] Id]", "sqlServer")).toEqual(["Order] Id"]);
expect(names("[a[b] `c``d`", "sqlite")).toEqual(["a[b", "c`d"]);
});
it("reads brackets as punctuation where they quote nothing", () => {
expect(lex("a[1]", "postgres").tokens.map((t) => t.text)).toEqual(["a", "[", "1", "]"]);
expect(lex("select [na from t", "sqlServer").tokens.map((t) => t.text)).toEqual(["select", "[", "na", "from", "t"]);
});
it("nests block comments in SQL Server", () => {
const l = lex("/* a /* b */ c */ select 1", "sqlServer");
expect(l.tokens.map((t) => t.text)).toEqual(["select", "1"]);
expect(l.comments).toHaveLength(1);
});
it("reads a MySQL `--` as a comment only before whitespace or the end", () => {
expect(lex("select 5--1", "mysql").tokens.map((t) => t.text)).toEqual(["select", "5", "-", "-", "1"]);
for (const comment of ["-- a", "--\ta", "--\n", "--"])
expect(
lex(`select 5 ${comment}`, "mysql").tokens.map((t) => t.text),
comment,
).toEqual(["select", "5"]);
expect(lex("select 5--1", "postgres").comments).toHaveLength(1);
});
it("still completes inside brackets", () => {
expect(at("select [na|] from t", "sqlServer").context.kind).toBe("column");
expect(at("select * from [us|]", "sqlServer").context.kind).toBe("table");
});
it("reads Snowflake dollar strings, comments, escapes, variant paths and stages", () => {
const texts = (sql: string) => lex(sql, "snowflake").tokens.map((t) => t.text);
const l = lex("select $$ it's; -- $$ // c ' \n, 'a\\'b' /* d */ -- e", "snowflake");
+16
Переглянути файл
@@ -14,6 +14,22 @@ describe("unsafeStatement", () => {
});
});
it.each([
["postgres", String.raw`UPDATE t SET a = E'it\'s WHERE x'`],
["postgres", String.raw`UPDATE t SET a = E'\' WHERE id = 1 --'`],
["mysql", String.raw`UPDATE t SET a = "say \"hi\" WHERE x"`],
["sqlServer", "UPDATE t SET [where] = 1"],
["sqlServer", "/* a /* b */ c */ DELETE FROM t"],
["sqlite", "UPDATE [it's] SET [where] = 1"],
["sqlite", "UPDATE t SET `where` = 1"],
] as const)("reads %s literals and comments as the statement splitter does: %s", (driver, text) => {
expect(unsafeStatement(text, driver)).toMatchObject({ reason: "no-where" });
});
it("keeps a MySQL WHERE that follows two minus signs", () => {
expect(unsafeStatement("UPDATE t SET a = 5--1 WHERE id = 3", "mysql")).toBeNull();
});
it("flags a WHERE that is always true", () => {
expect(check("DELETE FROM t_digital_tachometer_file WHERE 1=1")).toMatchObject({
kind: "delete",
+7 -7
Переглянути файл
@@ -464,17 +464,17 @@ function nullSafeEqual(a: Value, b: Value): Truth {
function value(tokens: readonly Token[]): Value {
if (!tokens.length) return undefined;
if (wrapped(tokens)) return value(tokens.slice(1, -1));
// `N'a'` (national), `E'a'` (escapes: only without any).
// `N'a'` (national).
const [prefix, literal] = tokens;
if (tokens.length === 2 && prefix!.kind === "word" && literal!.kind === "string" && prefix!.to === literal!.from) {
const plain = prefix!.upper === "N" || (prefix!.upper === "E" && !literal!.text.includes("\\"));
return plain ? value([literal!]) : undefined;
}
if (tokens.length === 2 && prefix!.kind === "word" && literal!.kind === "string" && prefix!.to === literal!.from)
return prefix!.upper === "N" ? value([literal!]) : undefined;
if (tokens.length === 1) {
const t = tokens[0]!;
if (t.kind === "number") return numberLiteral(t.text);
if (t.kind === "string" && t.text.startsWith("'") && t.text.endsWith("'") && t.text.length > 1)
return t.text.slice(1, -1).replaceAll("''", "'");
// `E'a'` (escapes: only without any).
const text = t.kind === "string" && !t.text.includes("\\") ? t.text.replace(/^[eE]'/, "'") : t.text;
if (t.kind === "string" && text.startsWith("'") && text.endsWith("'") && text.length > 1)
return text.slice(1, -1).replaceAll("''", "'");
if (t.kind === "word") {
if (t.upper === "NULL") return null;
if (t.upper === "TRUE") return true;