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(safety): scan Oracle alternative-quoted strings in all safety scanners
ordinary being36aa8425e6fc
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlRisk.dialect.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlRisk.dialect.spec.tsindex f504f29a0b..42593dd3cd 100644--- a/apps/desktop/src/lib/__tests__/sql/sqlRisk.dialect.spec.ts+++ b/apps/desktop/src/lib/__tests__/sql/sqlRisk.dialect.spec.ts@@ -29,6 +29,16 @@ const postgresConnection: ConnectionConfig = {password: "",};+const oracleConnection: ConnectionConfig = {+ id: "conn-oracle",+ name: "Reporting",+ db_type: "oracle",+ host: "db.internal",+ port: 1521,+ username: "app",+ password: "",+};+describe("SQL risk dialect lexer rules", () => {it("keeps the SQL Server DELETE after a #temp reference", () => {const sql = "SELECT * FROM #tmp; DELETE FROM #tmp;";@@ -99,6 +109,50 @@ describe("SQL risk dialect lexer rules", () => {expect(sqlSafetyText(sql, "postgres")).not.toContain("DELETE FROM users");});+ it("scans Oracle alternative-quoted strings by the dialect lexer rules", () => {+ for (const literal of ["q'[O'Reilly]'", "nq'{O'Reilly}'", "Q'<O'Reilly>'", "q'!O'Reilly!'"]) {+ const sql = `SELECT ${literal} FROM dual; DELETE FROM users;`;++ // The quote inside q'...' is literal, so the DELETE after the literal is+ // real code and must be classified.+ expect(sqlSafetyText(sql, "oracle")).toContain("DELETE FROM users");+ expect(classifySqlRisk(sql, { dialect: "oracle" }).risk).toBe("write");+ expect(classifySqlRisk(sql, { dialect: "oceanbase-oracle" }).risk).toBe("write");+ }++ // SQL-looking text inside the literal stays literal data.+ const inside = "SELECT q'[it's; DELETE FROM users;]' FROM dual;";++ expect(sqlSafetyText(inside, "oracle")).not.toContain("DELETE FROM users");+ expect(classifySqlRisk(inside, { dialect: "oracle" }).risk).toBe("read");+ });++ it("does not auto-execute an Oracle write hidden behind an alternative-quoted string", () => {+ const sql = "SELECT q'[it's]' FROM dual; DELETE FROM users;";++ expect(classifyAiSqlExecution(sql, oracleConnection)).toMatchObject({+ action: "confirm",+ category: "write",+ });+ });++ it("keeps alternative quoting specific to the Oracle family", () => {+ const sql = "SELECT q'[O' AS label FROM dual;";++ // Oracle reads the whole `q'[O' AS label FROM dual;` as an unterminated+ // alternative-quoted literal; PostgreSQL has no `q'...'` introducer.+ expect(sqlSafetyText(sql, "oracle")).not.toContain("AS label");+ expect(sqlSafetyText(sql, "postgres")).toContain("AS label");+ });++ it("keeps an identifier character before q out of the alternative-quote rules", () => {+ const sql = "SELECT aq'[x]' FROM dual; DELETE FROM users;";++ // `aq` is one identifier, so the following literal is ordinary.+ expect(sqlSafetyText(sql, "oracle")).toContain("DELETE FROM users");+ expect(classifySqlRisk(sql, { dialect: "oracle" }).risk).toBe("write");+ });+it("still reads # as a line comment on MySQL", () => {const sql = "SELECT * FROM #tmp; DELETE FROM #tmp;";diff --git a/apps/desktop/src/lib/database/__tests__/productionSafety.spec.ts b/apps/desktop/src/lib/database/__tests__/productionSafety.spec.tsindex 32046077e8..e18b4a5769 100644--- a/apps/desktop/src/lib/database/__tests__/productionSafety.spec.ts+++ b/apps/desktop/src/lib/database/__tests__/productionSafety.spec.ts@@ -71,6 +71,21 @@ describe("production SQL safety", () => {expect(assessProductionSql("SELECT E'a\\''; DROP DATABASE prod_app;", pg, "staging")).toMatchObject({ active: true, reason: "sql_target", isMutation: true, databases: ["prod_app"] });});+ it("keeps production DDL visible after Oracle alternative-quoted strings", () => {+ const oracle = connection({ db_type: "oracle" });++ // The quote inside q'...' is literal, so the DDL after the literal is real.+ expect(assessProductionSql("SELECT q'[it's]' FROM dual; DROP DATABASE prod_app;", oracle, "staging")).toMatchObject({+ active: true,+ reason: "sql_target",+ isMutation: true,+ databases: ["prod_app"],+ });++ // ...and DDL-looking text inside the literal stays literal data.+ expect(assessProductionSql("SELECT q'[it's; DROP DATABASE prod_app;]' FROM dual;", oracle, "staging")).toMatchObject({ active: false });+ });+it("matches the shared SQL target safety corpus", () => {for (const corpusCase of productionSafetyCorpus) {const assessment = assessProductionSql(diff --git a/apps/desktop/src/lib/database/productionSafety.ts b/apps/desktop/src/lib/database/productionSafety.tsindex 91a83828cb..58fa8400f9 100644--- a/apps/desktop/src/lib/database/productionSafety.ts+++ b/apps/desktop/src/lib/database/productionSafety.ts@@ -1,6 +1,6 @@import type { ConnectionConfig, DatabaseType } from "@/types/database";import { nacosNamespaceIdentity } from "@/lib/nacos/nacosNamespaceVisibility";-import { classifySqlRisk, endsWithEscapeStringPrefix, isSqlRiskMutation, usesMysqlLexerRules, usesPostgresEscapeStrings } from "@/lib/sql/sqlRisk";+import { classifySqlRisk, endsWithEscapeStringPrefix, isSqlRiskMutation, readOracleAlternativeQuoteEnd, usesMysqlLexerRules, usesOracleAlternativeQuotes, usesPostgresEscapeStrings } from "@/lib/sql/sqlRisk";export type ProductionContextReason = "connection" | "database" | "sql_target";@@ -273,6 +273,7 @@ function splitTargetStatements(sql: string): string[] {function sqlTargetSafetyText(sql: string, dialect?: DatabaseType | string, quotedIdentifiers = new Map<string, string>()): SqlTargetSafetyText {const mysqlLexer = usesMysqlLexerRules(dialect);const postgresEscapeStrings = usesPostgresEscapeStrings(dialect);+ const oracleAlternativeQuotes = usesOracleAlternativeQuotes(dialect);let output = "";let index = 0;@@ -316,6 +317,15 @@ function sqlTargetSafetyText(sql: string, dialect?: DatabaseType | string, quotecontinue;}+ if (oracleAlternativeQuotes && (char === "q" || char === "Q" || char === "n" || char === "N")) {+ const alternativeQuoteEnd = readOracleAlternativeQuoteEnd(sql, index);+ if (alternativeQuoteEnd !== undefined) {+ index = alternativeQuoteEnd;+ output += " ";+ continue;+ }+ }+if (char === "'") {const backslashEscapes = mysqlLexer || (postgresEscapeStrings && endsWithEscapeStringPrefix(sql, index));index = readQuotedEnd(sql, index, "'", "'", backslashEscapes);diff --git a/apps/desktop/src/lib/sql/sqlRisk.ts b/apps/desktop/src/lib/sql/sqlRisk.tsindex df462e0553..e82430f0c8 100644--- a/apps/desktop/src/lib/sql/sqlRisk.ts+++ b/apps/desktop/src/lib/sql/sqlRisk.ts@@ -81,6 +81,47 @@ export function endsWithEscapeStringPrefix(sql: string, quoteIndex: number): booreturn before === undefined || !/[\p{L}\p{N}_$]/u.test(before);}+/**+ * Oracle alternative quoting: `q'...'` / `nq'...'` literals delimited by+ * `[`/`]`, `{`/`}`, `(`/`)`, `<`/`>` or a self-delimiting character, where the+ * quote character may appear inside the literal unchanged. Mirrors+ * `skipOracleAlternativeQuoted` in `apps/desktop/src/lib/sql/sqlParameters.ts`+ * and the Oracle branch of `tokenizeSqlSemantic`.+ */+const ORACLE_ALTERNATIVE_QUOTE_DATABASE_TYPES = new Set<string>(["oracle", "oceanbase-oracle"]);++export function usesOracleAlternativeQuotes(dialect?: DatabaseType | string): boolean {+ return typeof dialect === "string" && ORACLE_ALTERNATIVE_QUOTE_DATABASE_TYPES.has(dialect.trim().toLowerCase());+}++/**+ * Returns the index past the closing quote of the alternative-quoted literal+ * starting at `index` (the `q`/`n` of `q'...'` / `nq'...'`), or `undefined`+ * when this is not such a literal. The introducer must start its own token, so+ * `aq'...'` and `q '...'` stay ordinary strings.+ */+export function readOracleAlternativeQuoteEnd(sql: string, index: number): number | undefined {+ let quoteIndex = index;+ const first = sql[quoteIndex]?.toLowerCase();+ if (first === "n") {+ if (sql[quoteIndex + 1]?.toLowerCase() !== "q") return undefined;+ quoteIndex += 1;+ } else if (first !== "q") {+ return undefined;+ }+ if (sql[quoteIndex + 1] !== "'") return undefined;+ const previous = sql[index - 1];+ if (previous !== undefined && /[\p{L}\p{N}_$#]/u.test(previous)) return undefined;++ const openerCodePoint = sql.codePointAt(quoteIndex + 2);+ if (openerCodePoint === undefined) return undefined;+ const opener = String.fromCodePoint(openerCodePoint);+ if (/\s/.test(opener)) return undefined;+ const closer = ({ "[": "]", "{": "}", "(": ")", "<": ">" } as Record<string, string>)[opener] ?? opener;+ const end = sql.indexOf(closer + "'", quoteIndex + 2 + opener.length);+ return end === -1 ? sql.length : end + closer.length + 1;+}+const RISK_ORDER: Record<SqlRiskLevel, number> = {read: 0,write: 1,@@ -211,6 +252,7 @@ export function isSqlRiskMutation(risk: SqlRiskLevel): boolean {export function sqlSafetyText(sql: string, dialect?: DatabaseType | string): string {const mysqlLexer = usesMysqlLexerRules(dialect);const postgresEscapeStrings = usesPostgresEscapeStrings(dialect);+ const oracleAlternativeQuotes = usesOracleAlternativeQuotes(dialect);let output = "";let index = 0;@@ -254,6 +296,15 @@ export function sqlSafetyText(sql: string, dialect?: DatabaseType | string): strcontinue;}+ if (oracleAlternativeQuotes && (char === "q" || char === "Q" || char === "n" || char === "N")) {+ const alternativeQuoteEnd = readOracleAlternativeQuoteEnd(sql, index);+ if (alternativeQuoteEnd !== undefined) {+ index = alternativeQuoteEnd;+ output += " ";+ continue;+ }+ }+if (char === "'") {const backslashEscapes = mysqlLexer || (postgresEscapeStrings && endsWithEscapeStringPrefix(sql, index));index = readQuotedEnd(sql, index, "'", "'", backslashEscapes);diff --git a/crates/dbx-core/src/safety/production_safety.rs b/crates/dbx-core/src/safety/production_safety.rsindex c29de9fed1..e1c52149a2 100644--- a/crates/dbx-core/src/safety/production_safety.rs+++ b/crates/dbx-core/src/safety/production_safety.rs@@ -589,6 +589,8 @@ struct SqlScanLexerRules {backslash_escaped_quotes: bool,/// `E'...'` literals escape with a backslash (PostgreSQL family).postgres_escape_strings: bool,+ /// `q'...'` / `nq'...'` alternative-quoted literals (Oracle family).+ oracle_alternative_quotes: bool,}impl SqlScanLexerRules {@@ -612,6 +614,7 @@ impl SqlScanLexerRules {| DatabaseType::Uxdb| DatabaseType::Kwdb);+ let oracle_family = matches!(db_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle);Self {hash_line_comments: mysql_family,// Only claim the escape where the engine has it: MySQL, and@@ -621,6 +624,7 @@ impl SqlScanLexerRules {// so they may ask once too often — the safe direction here.)backslash_escaped_quotes: mysql_family,postgres_escape_strings: postgres_family,+ oracle_alternative_quotes: oracle_family,}}}@@ -635,6 +639,53 @@ fn ends_with_escape_string_prefix(prefix: &[char]) -> bool {!chars.next().is_some_and(|ch| ch.is_alphanumeric() || *ch == '_' || *ch == '$')}+/// Oracle alternative quoting: `q'...'` / `nq'...'` literals delimited by+/// `[`/`]`, `{`/`}`, `(`/`)`, `<`/`>` or a self-delimiting character, where the+/// quote character may appear inside the literal unchanged. The literal ends at+/// the first `closer + '` — Oracle has no escape or nesting inside these+/// literals. Mirrors `readOracleAlternativeQuoteEnd` in+/// `apps/desktop/src/lib/sql/sqlRisk.ts`.+fn read_oracle_alternative_quote_end(chars: &[char], index: usize) -> Option<usize> {+ let mut quote_index = index;+ match chars.get(index)? {+ 'n' | 'N' => {+ if !matches!(chars.get(index + 1), Some('q' | 'Q')) {+ return None;+ }+ quote_index += 1;+ }+ 'q' | 'Q' => {}+ _ => return None,+ }+ if chars.get(quote_index + 1) != Some(&'\'') {+ return None;+ }+ // The introducer must start its own token, so `aq'...'` and `q '...'` stay+ // ordinary strings. Oracle identifiers may contain `$` and `#`.+ if chars[..index].last().is_some_and(|ch| ch.is_alphanumeric() || *ch == '_' || *ch == '$' || *ch == '#') {+ return None;+ }+ let opener = *chars.get(quote_index + 2)?;+ if opener.is_whitespace() {+ return None;+ }+ let closer = match opener {+ '[' => ']',+ '{' => '}',+ '(' => ')',+ '<' => '>',+ other => other,+ };+ let mut scan = quote_index + 3;+ while scan + 1 < chars.len() {+ if chars[scan] == closer && chars[scan + 1] == '\'' {+ return Some(scan + 2);+ }+ scan += 1;+ }+ Some(chars.len())+}+fn append_sql_target_safety_text(chars: &[char], rules: SqlScanLexerRules, result: &mut SqlTargetSafetyText) {let mut index = 0usize;@@ -684,6 +735,13 @@ fn append_sql_target_safety_text(chars: &[char], rules: SqlScanLexerRules, resulresult.text.push(' ');continue;}+ if rules.oracle_alternative_quotes && matches!(ch, 'q' | 'Q' | 'n' | 'N') {+ if let Some(end) = read_oracle_alternative_quote_end(chars, index) {+ index = end;+ result.text.push(' ');+ continue;+ }+ }if ch == '\'' {index = skip_string_literal(chars, index, '\'', '\'', rules);result.text.push(' ');@@ -961,6 +1019,41 @@ mod tests {assert!(!escape_string.text.contains("DELETE FROM users"), "{}", escape_string.text);}+ #[test]+ fn scans_oracle_alternative_quoted_strings_by_the_dialect_lexer_rules() {+ for literal in ["q'[O'Reilly]'", "nq'{O'Reilly}'", "Q'<O'Reilly>'", "q'!O'Reilly!'"] {+ let sql = format!("SELECT {literal} FROM dual; DELETE FROM users;");+ // The quote inside q'...' is literal, so the DELETE after the+ // literal is real code and must stay visible to the gate.+ let scanned = sql_target_safety_text(&sql, &DatabaseType::Oracle);+ assert!(scanned.text.contains("DELETE FROM users"), "{literal}: {}", scanned.text);+ let scanned = sql_target_safety_text(&sql, &DatabaseType::OceanbaseOracle);+ assert!(scanned.text.contains("DELETE FROM users"), "{literal}: {}", scanned.text);+ }++ // SQL-looking text inside the literal stays literal data.+ let inside =+ sql_target_safety_text(r#"SELECT q'[it's; DELETE FROM users;]' FROM dual;"#, &DatabaseType::Oracle);+ assert!(!inside.text.contains("DELETE FROM users"), "{}", inside.text);+ }++ #[test]+ fn keeps_alternative_quoting_specific_to_the_oracle_family() {+ // Oracle reads the whole `q'[O' AS label FROM dual;` as an unterminated+ // alternative-quoted literal; PostgreSQL has no `q'...'` introducer.+ let oracle = sql_target_safety_text("SELECT q'[O' AS label FROM dual;", &DatabaseType::Oracle);+ assert!(!oracle.text.contains("AS label"), "{}", oracle.text);+ let postgres = sql_target_safety_text("SELECT q'[O' AS label FROM dual;", &DatabaseType::Postgres);+ assert!(postgres.text.contains("AS label"), "{}", postgres.text);+ }++ #[test]+ fn keeps_an_identifier_character_before_q_out_of_the_alternative_quote_rules() {+ // `aq` is one identifier, so the following literal is ordinary.+ let scanned = sql_target_safety_text(r#"SELECT aq'[x]' FROM dual; DELETE FROM users;"#, &DatabaseType::Oracle);+ assert!(scanned.text.contains("DELETE FROM users"), "{}", scanned.text);+ }+#[test]fn detects_cross_database_references_for_mcp_database_scope() {let allowed = vec!["reporting".to_string()];diff --git a/crates/dbx-sql-core/src/query_execution_sql.rs b/crates/dbx-sql-core/src/query_execution_sql.rsindex 5b0693ca71..edbee10f5b 100644--- a/crates/dbx-sql-core/src/query_execution_sql.rs+++ b/crates/dbx-sql-core/src/query_execution_sql.rs@@ -1335,6 +1335,16 @@ fn strip_sql_comments_and_literals_with_metadata(sql: &str, detect_mysql_executain_block_comment = true;continue;}+ if matches!(ch, 'q' | 'Q' | 'n' | 'N') && !previous_code_char.is_some_and(is_oracle_identifier_char) {+ if let Some(length) = oracle_alternative_quote_len(ch, &chars) {+ for _ in 0..length {+ chars.next();+ }+ output.push_str(&" ".repeat(length));+ previous_code_char = Some(' ');+ continue;+ }+ }if ch == '\'' {in_single_quote = true;output.push(' ');@@ -1387,6 +1397,57 @@ fn is_identifier_char(character: char) -> bool {character.is_ascii_alphanumeric() || character == '_' || character == '$'}+/// Oracle identifiers may also contain `#` (and `$` above), so an introducer+/// directly after one of those characters does not start its own token.+fn is_oracle_identifier_char(character: char) -> bool {+ character.is_alphanumeric() || character == '_' || character == '$' || character == '#'+}++/// Length of an Oracle alternative-quoted literal — `q'#...#'`, `q'[...]'`,+/// `nq'{...}'` — where the delimiter may contain the quote character+/// unchanged. The literal ends at the first `closer + '`; Oracle has no escape+/// or nesting inside these literals. `ch` is the already-read `q`/`Q`/`n`/`N`+/// introducer and the returned length includes it. An unterminated literal+/// returns `None` so the text stays visible to the keyword scan and malformed+/// input still fails closed, matching the dollar-quote policy here. Mirrors+/// `readOracleAlternativeQuoteEnd` in `apps/desktop/src/lib/sql/sqlRisk.ts`.+fn oracle_alternative_quote_len(ch: char, chars: &std::iter::Peekable<std::str::Chars<'_>>) -> Option<usize> {+ let mut probe = chars.clone();+ let mut length = 1usize;+ if matches!(ch, 'n' | 'N') {+ match probe.next() {+ Some('q' | 'Q') => length += 1,+ _ => return None,+ }+ }+ match probe.next() {+ Some('\'') => length += 1,+ _ => return None,+ }+ let opener = probe.next()?;+ length += 1;+ // A whitespace opener means `q '...'` — an identifier then an ordinary+ // string, not an alternative-quoted literal.+ if opener.is_whitespace() {+ return None;+ }+ let closer = match opener {+ '[' => ']',+ '{' => '}',+ '(' => ')',+ '<' => '>',+ other => other,+ };+ loop {+ let scan = probe.next()?;+ length += 1;+ if scan == closer && probe.peek() == Some(&'\'') {+ probe.next();+ return Some(length + 1);+ }+ }+}+/// Read a PostgreSQL dollar-quote delimiter — `$$` or `$tag$` — from the/// characters that follow an opening `$`, and return it only when the literal is/// actually closed later in the statement.@@ -2340,6 +2401,38 @@ mod tests {assert_eq!(strip_sql_comments_and_literals("# comment\nSELECT 1"), " SELECT 1");}+ #[test]+ fn strip_sql_comments_and_literals_oracle_alternative_quoted() {+ // The quote inside q'...' is literal data, so the rest of the statement+ // stays visible to the keyword scan instead of being swallowed by the+ // mis-paired ordinary string.+ let visible = strip_sql_comments_and_literals("SELECT q'[O'Reilly]' FROM t; DELETE FROM users;");+ assert!(visible.contains("DELETE FROM users"), "{visible}");+ let visible = strip_sql_comments_and_literals("SELECT nq'{O'Reilly}' FROM t; DELETE FROM users;");+ assert!(visible.contains("DELETE FROM users"), "{visible}");+ // SQL-looking text inside the literal stays literal data.+ let hidden = strip_sql_comments_and_literals("SELECT q'[it's; DELETE FROM users;]' FROM t;");+ assert!(!hidden.contains("DELETE"), "{hidden}");+ // The introducer must start its own token: `aq` is one identifier, so+ // the following literal is ordinary.+ let visible = strip_sql_comments_and_literals("SELECT aq'[x]' FROM t; DELETE FROM users;");+ assert!(visible.contains("DELETE FROM users"), "{visible}");+ // An unterminated q-literal is malformed input and stays visible, so+ // the keyword scan fails closed.+ let visible = strip_sql_comments_and_literals("SELECT q'[O'Reilly FROM t; DELETE FROM users;");+ assert!(visible.contains("DELETE FROM users"), "{visible}");+ }++ #[test]+ fn oracle_proven_read_only_statement_alternative_quoted() {+ // The mis-paired quotes previously reduced this to `SELECT q`, proving+ // the statement read-only even though real code follows the literal.+ assert!(!is_oracle_proven_read_only_statement("SELECT q'[O'Reilly]' FROM users; DELETE FROM users;"));+ assert!(is_oracle_proven_read_only_statement("SELECT * FROM users WHERE name = q'[O''Reilly]'"));+ // SQL-looking text inside the literal is data, not a forbidden keyword.+ assert!(is_oracle_proven_read_only_statement("SELECT * FROM users WHERE note = q'[drop table]'"));+ }+#[test]fn strip_sql_comments_and_literals_nested() {// String literals containing comments should be stripped