25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(sql): keep MyBatis XML entity semicolons from splitting statements
弈秋0453ac83e54b
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlStatementRanges.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlStatementRanges.spec.tsindex 18092b7bdf..88bf3b5cb4 100644--- a/apps/desktop/src/lib/__tests__/sql/sqlStatementRanges.spec.ts+++ b/apps/desktop/src/lib/__tests__/sql/sqlStatementRanges.spec.ts@@ -1712,6 +1712,28 @@ DISTRIBUTED BY HASH(product_id) BUCKETS 1`;expect(rangeSqlTexts(executableStatementRanges(`${first};\n\n${second};`, databaseType))).toEqual([first, second]);});++ // Issue #11699: MyBatis XML comparison entities (`>=`, `<=`) end with a+ // `;` that must not be read as a statement terminator, otherwise one query is+ // split into fragments, its run buttons multiply, and parameters living in+ // later fragments are lost from the execute dialog.+ it("keeps MyBatis comparison entities from splitting a statement (issue #11699)", () => {+ const sql = ["select * from course_user cu", "where cu.is_delete = 0", "and cu.create_time >= #{param.startDateTime}", "and cu.create_time <= #{param.endDateTime}", "group by cu.dept_id"].join("\n");+ expect(rangeSqlTexts(splitSqlStatementRanges(sql, "mysql"))).toEqual([sql]);+ expect(rangeSqlTexts(executableStatementRanges(sql, "mysql"))).toEqual([sql]);+ expect(hasMultipleExecutionTargets(sql, "mysql")).toBe(false);+ expect(currentExecutableStatementRange(sql, sql.indexOf("group by"), "mysql")?.sql).toBe(sql);+ });++ it("still splits real statements after an entity and after a bitwise AND (issue #11699)", () => {+ expect(rangeSqlTexts(splitSqlStatementRanges("SELECT a FROM t WHERE b >= 1;\nSELECT 2;", "mysql"))).toEqual(["SELECT a FROM t WHERE b >= 1", "SELECT 2"]);+ expect(rangeSqlTexts(splitSqlStatementRanges("SELECT a FROM t WHERE a&b;", "mysql"))).toEqual(["SELECT a FROM t WHERE a&b"]);+ expect(rangeSqlTexts(splitSqlStatementRanges("SELECT 'Tom & Jerry';\nSELECT 2;", "mysql"))).toEqual(["SELECT 'Tom & Jerry'", "SELECT 2"]);+ // Numeric refs: MySQL-family dialects (and, in this splitter, Postgres) read a+ // bare `#` as a line comment, so use sqlserver where `#` is an identifier marker.+ expect(rangeSqlTexts(splitSqlStatementRanges("SELECT ' AS q;\nSELECT 2;", "sqlserver"))).toEqual(["SELECT ' AS q", "SELECT 2"]);+ });+it("returns statement ranges starting only at statement starts", () => {const sql = "SELECT *\nFROM users\nWHERE active = 1;\nSELECT 2;";const ranges = executableStatementRanges(sql);diff --git a/apps/desktop/src/lib/sql/sqlStatementRanges.ts b/apps/desktop/src/lib/sql/sqlStatementRanges.tsindex 8c10065dc2..235c34a80b 100644--- a/apps/desktop/src/lib/sql/sqlStatementRanges.ts+++ b/apps/desktop/src/lib/sql/sqlStatementRanges.ts@@ -322,6 +322,31 @@ const ORACLE_PL_SQL_CREATE_OBJECT_TYPES = new Set(["FUNCTION", "PROCEDURE", "TRIconst ORACLE_PL_SQL_TERMINATORS = new Set(["IF", "LOOP", "CASE"]);const SAP_HANA_SCRIPT_BLOCK_TERMINATORS = new Set(["IF", "FOR", "WHILE"]);+/**+ * XML/HTML character references (`<`, `>`, `&`, `"`, `'`,+ * `'`, `'`) end with `;`. MyBatis XML writes comparison operators+ * this way (`>= #{param}`), so that `;` must not be read as a statement+ * terminator — otherwise one query is split into fragments, its run buttons+ * multiply, and parameters in later fragments vanish (#11699). Only the five+ * predefined XML names plus numeric references are recognized, so a plain+ * bitwise `a&b;` still splits at its real terminator.+ */+const XML_ENTITY_REFERENCE_NAMES = new Set(["lt", "gt", "amp", "quot", "apos"]);++function isXmlEntityReferenceSemicolon(sql: string, semicolonIndex: number): boolean {+ let start = semicolonIndex;+ while (start > 0 && isAsciiAlphanumeric(sql[start - 1] ?? "")) start -= 1;+ if (start > 0 && sql[start - 1] === "#") start -= 1;+ if (start === 0 || sql[start - 1] !== "&") return false;+ const name = sql.slice(start, semicolonIndex);+ if (name.startsWith("#")) return /^#(?:[xX][0-9A-Fa-f]+|[0-9]+)$/.test(name);+ return XML_ENTITY_REFERENCE_NAMES.has(name);+}++function isAsciiAlphanumeric(ch: string): boolean {+ return (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") || (ch >= "0" && ch <= "9");+}+/*** Parse the SQL document into top-level statement ranges delimited by `;`.*@@ -613,7 +638,7 @@ export function splitSqlStatementRanges(sql: string, databaseType?: DatabaseTypestatementHitStart = i;continue;}- } else if (ch === ";") {+ } else if (ch === ";" && !isXmlEntityReferenceSemicolon(sql, i)) {const routineTokensBeforeSemicolon = isMysqlRoutineBlockDatabase(databaseType) && statementStart !== -1 ? mysqlRoutineTokensUpTo(i) : null;const isMysqlRoutineBlock = routineTokensBeforeSemicolon !== null && isMysqlRoutineDdlStartFromWords(mysqlRoutineDdlStartWords(routineTokensBeforeSemicolon)) && mysqlRoutineTokensContainBegin(routineTokensBeforeSemicolon);if (isMysqlRoutineBlock) {diff --git a/crates/dbx-sql-core/src/sql.rs b/crates/dbx-sql-core/src/sql.rsindex 19faaf252b..41d2574b72 100644--- a/crates/dbx-sql-core/src/sql.rs+++ b/crates/dbx-sql-core/src/sql.rs@@ -533,6 +533,36 @@ fn dash_dash_starts_line_comment(profile: SqlDialectProfile, char_after_dashes:char_after_dashes.is_none_or(|ch| ch.is_whitespace() || ch.is_control())}+/// Whether the text ends with an XML/HTML character reference whose closing `;`+/// is about to be scanned. MyBatis XML writes comparison operators as `>=`+/// / `<=`, and that `;` must not be read as a statement terminator (#11699).+/// Only the five predefined XML names (`lt`, `gt`, `amp`, `quot`, `apos`) plus+/// numeric references (`'`, `'`) are recognized, so a plain bitwise+/// `a&b;` still splits at its real terminator. Mirrors+/// `isXmlEntityReferenceSemicolon` in the editor splitter+/// (`apps/desktop/src/lib/sql/sqlStatementRanges.ts`); keep both in sync.+fn ends_with_xml_entity_reference(buffer: &str) -> bool {+ let bytes = buffer.as_bytes();+ let mut start = bytes.len();+ while start > 0 && bytes[start - 1].is_ascii_alphanumeric() {+ start -= 1;+ }+ if start > 0 && bytes[start - 1] == b'#' {+ start -= 1;+ }+ if start == 0 || bytes[start - 1] != b'&' {+ return false;+ }+ let name = &buffer[start..];+ if let Some(hex) = name.strip_prefix("#x").or_else(|| name.strip_prefix("#X")) {+ return !hex.is_empty() && hex.bytes().all(|byte| byte.is_ascii_hexdigit());+ }+ if let Some(digits) = name.strip_prefix('#') {+ return !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit());+ }+ matches!(name, "lt" | "gt" | "amp" | "quot" | "apos")+}+/// Tracks an Oracle `q'...'` literal across characters, so a semicolon inside its/// text never splits the statement.#[derive(Default, Clone, Copy)]@@ -799,7 +829,11 @@ impl SqlStatementSplitter {self.buffer.push(ch);}';' if !self.in_single_quote && !self.in_double_quote && !self.in_backtick => {- if (self.options.profile.supports_custom_delimiter_commands && self.on_delimiter_line())+ if ends_with_xml_entity_reference(&self.buffer) {+ // The `;` closes an XML/MyBatis entity (`>`, `<`,+ // `'`, ...), not the statement (#11699).+ self.buffer.push(ch);+ } else if (self.options.profile.supports_custom_delimiter_commands && self.on_delimiter_line())|| self.custom_delimiter.is_some(){self.buffer.push(ch);@@ -3500,6 +3534,36 @@ mod tests {);}+ #[test]+ fn keeps_mybatis_comparison_entity_semicolons_inside_one_statement() {+ // Issue #11699: the `;` of `>`/`<`/`'` closes an XML entity,+ // not the statement.+ let sql = "select * from course_user cu\nwhere cu.is_delete = 0\nand cu.create_time >= #{param.startDateTime}\nand cu.create_time <= #{param.endDateTime}\ngroup by cu.dept_id";++ assert_eq!(split_sql_statements_for_database(sql, DatabaseType::Mysql), vec![sql.to_string()]);+ assert_eq!(+ split_sql_statements_for_database("SELECT a FROM t WHERE b >= 1;\nSELECT 2;", DatabaseType::Mysql),+ vec!["SELECT a FROM t WHERE b >= 1".to_string(), "SELECT 2".to_string()]+ );+ // A bitwise AND before a real terminator must still split.+ assert_eq!(+ split_sql_statements_for_database("SELECT a FROM t WHERE a&b;", DatabaseType::Mysql),+ vec!["SELECT a FROM t WHERE a&b".to_string()]+ );+ // Numeric character references and quoted entities stay intact too.+ assert_eq!(+ split_sql_statements_for_database("SELECT 'Tom & Jerry' AS n;\nSELECT 2;", DatabaseType::Mysql),+ vec!["SELECT 'Tom & Jerry' AS n".to_string(), "SELECT 2".to_string()]+ );+ // Numeric character references: MySQL-family dialects read a bare `#` as a+ // line comment, so exercise this on SQL Server (whose `#` is an identifier+ // marker) where `'` reaches the splitter as code.+ assert_eq!(+ split_sql_statements_for_database("SELECT ' AS q;\nSELECT 2;", DatabaseType::SqlServer),+ vec!["SELECT ' AS q".to_string(), "SELECT 2".to_string()]+ );+ }+#[test]fn keeps_postgres_e_string_newlines_inside_batch_statement() {let sql = "SELECT version();\n\nCREATE TABLE dbx_test (\n delimiter VARCHAR(32) DEFAULT E'\\n\\n'\n);";