Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

fix(oracle): handle separated dblinks and q-literals in param scan

efeire8ad26fd0aeec
diff --git a/apps/desktop/src/lib/__tests__/sql/semantic/tokens.spec.ts b/apps/desktop/src/lib/__tests__/sql/semantic/tokens.spec.ts
index dcec531aec..92a4b79fbb 100644
--- a/apps/desktop/src/lib/__tests__/sql/semantic/tokens.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/semantic/tokens.spec.ts
@@ -35,6 +35,37 @@ describe("sqlSemanticTokens", () => {
expect(incomplete?.closed).toBe(false);
});
+ it("preserves Oracle alternative-quoted token boundaries and following parameters", () => {
+ for (const prefix of ["q", "Q", "nq", "NQ", "Nq", "nQ"]) {
+ for (const [opener, closer] of [
+ ["[", "]"],
+ ["'", "'"],
+ ["😀", "😀"],
+ ]) {
+ const literal = `${prefix}'${opener}O'Reilly :hidden${closer}'`;
+ const sql = `SELECT ${literal}, :id`;
+ const tokens = tokenizeSqlSemantic(sql, "oracle");
+ expect(tokens.filter((token) => token.kind === "string")).toMatchObject([{ text: literal, quote: `${prefix.toLowerCase()}'`, span: { start: 7, end: 7 + literal.length }, closed: true }]);
+ expect(tokens.filter((token) => token.kind === "parameter")).toMatchObject([{ text: ":id", span: { start: 9 + literal.length, end: 12 + literal.length } }]);
+ }
+ }
+ });
+
+ it("marks an unterminated Oracle national alternative-quoted token as incomplete", () => {
+ const sql = "SELECT nq'[O'Reilly :hidden";
+ const tokens = tokenizeSqlSemantic(sql, "oracle");
+ expect(tokens.filter((token) => token.kind === "string")).toMatchObject([{ text: "nq'[O'Reilly :hidden", span: { start: 7, end: sql.length }, closed: false }]);
+ expect(tokens.filter((token) => token.kind === "parameter")).toEqual([]);
+ });
+
+ it("keeps national alternative-quote recognition specific to Oracle", () => {
+ for (const dialect of ["mysql", "postgres", "sqlserver"]) {
+ const tokens = tokenizeSqlSemantic("SELECT nq'[O' AS label, :id", dialect);
+ expect(tokens.filter((token) => token.kind === "string").map((token) => token.text)).toEqual(["'[O'"]);
+ expect(tokens.filter((token) => token.kind === "parameter").map((token) => token.text)).toEqual([":id"]);
+ }
+ });
+
it("handles hash tokens according to the SQL dialect", () => {
const sqlServerSql = "SELECT * FROM #temp; SELECT * FROM ##global_temp; SELECT * FROM tempdb..#temp";
const sqlServerTokens = tokenizeSqlSemantic(sqlServerSql, "sqlserver");
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
index 89b746b07e..c874e8d6a5 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
@@ -89,6 +89,79 @@ describe("extractSqlParameters", () => {
expect(extractSqlParameters(sql)).toEqual(["real_param"]);
});
+ it.each(["oracle", "oceanbase-oracle"] as const)("preserves alternative-quoted strings and following parameters for %s", (databaseType) => {
+ for (const literal of [
+ "q'[O'Reilly :hidden]'",
+ "nq'{O'Reilly :hidden}'",
+ "Q'<O'Reilly :hidden>'",
+ "NQ'(O'Reilly :hidden)'",
+ "q'!O'Reilly :hidden!'",
+ "q'[O'Reilly [nested] :hidden]'",
+ "q'[O'Reilly /* :inside */ @LINK ${shell} #{mybatis} ? :hidden]'",
+ "q''O'Reilly :hidden''",
+ "nq'😀O'Reilly :hidden😀'",
+ ]) {
+ const sql = `UPDATE t SET name = ${literal} WHERE id = :id`;
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { id: { kind: "number", value: "7" }, hidden: { kind: "string", value: "WRONG" } }, { databaseType })).toBe(`UPDATE t SET name = ${literal} WHERE id = 7`);
+ }
+ });
+
+ it.each(["oracle", "oceanbase-oracle"] as const)("ignores parameters inside unterminated alternative-quoted strings for %s", (databaseType) => {
+ for (const literal of ["q'[O'Reilly :hidden", "nq'{O'Reilly :hidden]"]) {
+ const sql = `SELECT :id, ${literal}`;
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { id: { kind: "number", value: "7" } }, { databaseType })).toBe(`SELECT 7, ${literal}`);
+ }
+ });
+
+ it.each(["oracle", "oceanbase-oracle"] as const)("preserves separated database links after alternative-quoted strings for %s", (databaseType) => {
+ for (const literal of ["q'[O'Reilly :hidden]'", "nq'{O'Reilly :hidden}'", "q''O'Reilly :hidden''", "nq'😀O'Reilly :hidden😀'"]) {
+ const sql = `SELECT ${literal} FROM employees /* separator */ @LINK WHERE id = :id`;
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { id: { kind: "number", value: "7" }, LINK: { kind: "string", value: "WRONG" } }, { databaseType })).toBe(`SELECT ${literal} FROM employees /* separator */ @LINK WHERE id = 7`);
+ }
+ });
+
+ it.each(["postgres", "mysql", "sqlserver", "dameng"] as const)("does not apply alternative-quote rules to %s", (databaseType) => {
+ const sql = "SELECT q'[O' AS label, :id";
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { id: { kind: "number", value: "7" } }, { databaseType })).toBe("SELECT q'[O' AS label, 7");
+ });
+
+ it.each(["oracle", "oceanbase-oracle"] as const)("requires a complete alternative-quote prefix for %s", (databaseType) => {
+ for (const prefix of ["myq", "mynq", "my$q"]) {
+ const sql = `SELECT ${prefix}'[O' AS label, :id`;
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ }
+ });
+
+ it.each(["oracle", "oceanbase-oracle"] as const)("keeps alternative-quoted content during MyBatis substitution for %s", (databaseType) => {
+ const sql = "SELECT q'[O'Reilly &lt; :hidden]' FROM t WHERE id &gt; #{id}";
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { id: { kind: "number", value: "7" } }, { databaseType })).toBe("SELECT q'[O'Reilly &lt; :hidden]' FROM t WHERE id > 7");
+ });
+
+ it.each(["oracle", "oceanbase-oracle"] as const)("ignores MyBatis closing tags inside alternative-quoted strings for %s", (databaseType) => {
+ const sql = "SELECT * FROM t <where> name = q'[O'Reilly </where> :hidden]' AND id = #{id} </where>";
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { id: { kind: "number", value: "7" } }, { databaseType })).toBe("SELECT * FROM t WHERE name = q'[O'Reilly </where> :hidden]' AND id = 7");
+ });
+
+ it.each(["oracle", "oceanbase-oracle"] as const)("preserves trigger pseudo-records after alternative-quoted strings for %s", (databaseType) => {
+ const sql = "CREATE TRIGGER trg BEFORE UPDATE ON t FOR EACH ROW BEGIN :new.name := nq'[O'Reilly :hidden]'; :new.id := :id; END;";
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { id: { kind: "number", value: "7" } }, { databaseType })).toBe("CREATE TRIGGER trg BEFORE UPDATE ON t FOR EACH ROW BEGIN :new.name := nq'[O'Reilly :hidden]'; :new.id := 7; END;");
+ });
+
+ it.each(["oracle", "oceanbase-oracle"] as const)("keeps parameters after ordinary strings ending in a literal backslash for %s", (databaseType) => {
+ const sql = "UPDATE t SET name = 'a\\' WHERE id = :id";
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { id: { kind: "number", value: "7" } }, { databaseType })).toBe("UPDATE t SET name = 'a\\' WHERE id = 7");
+ expect(extractSqlParameters(sql, { databaseType: "mysql" })).toEqual([]);
+ expect(substituteSqlParameters("SELECT 'a\\' FROM t WHERE id &gt; #{id}", { id: { kind: "number", value: "7" } }, { databaseType })).toBe("SELECT 'a\\' FROM t WHERE id > 7");
+ });
+
it("extracts supported placeholder syntaxes in order", () => {
const sql = "select ? as a, :named as b, ${shell_name} as c, #{mybatis_name} as d, @sql_server_name as e";
expect(extractSqlParameters(sql)).toEqual(["?1", "named", "shell_name", "mybatis_name", "sql_server_name"]);
@@ -237,14 +310,143 @@ describe("extractSqlParameters", () => {
expect(extractSqlParameters("select @amount/2, @total / 4")).toEqual(["amount", "total"]);
});
- it("ignores Oracle database links while preserving standalone at-sign placeholders", () => {
+ it.each(["oracle", "oceanbase-oracle"] as const)("ignores %s database links while preserving standalone at-sign placeholders", (databaseType) => {
const sql = 'SELECT * FROM HR.EMPLOYEES@REMOTE_DB, "AUDIT_LOG"@ARCHIVE_DB WHERE tenant_id = @tenant_id';
- expect(extractSqlParameters("SELECT 1 FROM DUAL@WDHIS160;", { databaseType: "oracle" })).toEqual([]);
- expect(extractSqlParameters(sql, { databaseType: "oracle" })).toEqual(["tenant_id"]);
- expect(substituteSqlParameters(sql, { tenant_id: { kind: "number", value: "7" } }, { databaseType: "oracle" })).toBe('SELECT * FROM HR.EMPLOYEES@REMOTE_DB, "AUDIT_LOG"@ARCHIVE_DB WHERE tenant_id = 7');
+ expect(extractSqlParameters("SELECT 1 FROM DUAL@WDHIS160;", { databaseType })).toEqual([]);
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["tenant_id"]);
+ expect(substituteSqlParameters(sql, { tenant_id: { kind: "number", value: "7" } }, { databaseType })).toBe('SELECT * FROM HR.EMPLOYEES@REMOTE_DB, "AUDIT_LOG"@ARCHIVE_DB WHERE tenant_id = 7');
expect(extractSqlParameters("SELECT * FROM EMPLOYEES@REMOTE_DB", { databaseType: "postgres" })).toEqual(["REMOTE_DB"]);
});
+ it.each(["oracle", "oceanbase-oracle"] as const)("preserves %s links, quoted names, strings and comments during substitution", (databaseType) => {
+ const sql = `SELECT '@literal' FROM "Hr"."Audit Log"@ARCHIVE_DB /* @comment */ WHERE "Id" = :id AND tenant_id = @tenant_id -- @tail`;
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id", "tenant_id"]);
+ expect(
+ substituteSqlParameters(
+ sql,
+ {
+ id: { kind: "number", value: "3" },
+ tenant_id: { kind: "number", value: "7" },
+ ARCHIVE_DB: { kind: "number", value: "99" },
+ literal: { kind: "number", value: "99" },
+ comment: { kind: "number", value: "99" },
+ tail: { kind: "number", value: "99" },
+ },
+ { databaseType },
+ ),
+ ).toBe(`SELECT '@literal' FROM "Hr"."Audit Log"@ARCHIVE_DB /* @comment */ WHERE "Id" = 3 AND tenant_id = 7 -- @tail`);
+ });
+
+ it.each(["oracle", "oceanbase-oracle"] as const)("extracts only real %s parameters around separated database links", (databaseType) => {
+ const sql = `SELECT @projection FROM SYS.ALL_TABLES @LINK
+ JOIN "Hr"."Audit Log"/* comment */@ARCHIVE_DB ON 1 = 1
+ JOIN employees -- comment with /* and @ignored
+ @REMOTE_DB ON 1 = 1
+ WHERE owner = :owner AND tenant_id = @tenant_id`;
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["projection", "owner", "tenant_id"]);
+ });
+
+ describe.each(["oracle", "oceanbase-oracle"] as const)("%s database link separators", (databaseType) => {
+ it.each(["", " ", "\t\r\n", "/* comment with -- and @ignored */", " /* first */ \n /* second */ ", "-- comment with /* and @ignored\n"])("preserves database links separated by %j during replacement", (separator) => {
+ const sql = `SELECT '@literal', @projection FROM "Hr"."Audit Log"${separator}@LINK WHERE id = :id -- @tail`;
+ expect(
+ substituteSqlParameters(
+ sql,
+ {
+ LINK: { kind: "string", value: "WRONG" },
+ projection: { kind: "number", value: "3" },
+ id: { kind: "number", value: "7" },
+ },
+ { databaseType },
+ ),
+ ).toBe(`SELECT '@literal', 3 FROM "Hr"."Audit Log"${separator}@LINK WHERE id = 7 -- @tail`);
+ });
+
+ it("keeps parameters following SQL and PL/SQL keywords", () => {
+ const sql = `SELECT CASE WHEN/* table_name */@condition THEN @yes ELSE @no END FROM DUAL;
+ BEGIN IF @condition THEN NULL; END IF; RETURN @result; END;`;
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["condition", "yes", "no", "result"]);
+ expect(
+ substituteSqlParameters(
+ sql,
+ {
+ condition: { kind: "raw", value: "1 = 1" },
+ yes: { kind: "number", value: "1" },
+ no: { kind: "number", value: "0" },
+ result: { kind: "number", value: "7" },
+ },
+ { databaseType },
+ ),
+ ).toBe(`SELECT CASE WHEN/* table_name */1 = 1 THEN 1 ELSE 0 END FROM DUAL;
+ BEGIN IF 1 = 1 THEN NULL; END IF; RETURN 7; END;`);
+ });
+
+ it("preserves quoted keywords and Unicode object names before links", () => {
+ const sql = `SELECT @value FROM "SELECT" /* separator */ @LINK, 订单 @中文链接 WHERE id = :id`;
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["value", "id"]);
+ expect(substituteSqlParameters(sql, { value: { kind: "number", value: "1" }, id: { kind: "number", value: "7" } }, { databaseType })).toBe(`SELECT 1 FROM "SELECT" /* separator */ @LINK, 订单 @中文链接 WHERE id = 7`);
+ });
+
+ it("keeps standalone parameters in joins, pagination and dynamic SQL", () => {
+ const sql = `SELECT @value FROM @source JOIN @target USING (@column)
+ OFFSET @offset ROWS FETCH NEXT @count ROWS ONLY;
+ BEGIN EXECUTE IMMEDIATE @sql USING @input; END;`;
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["value", "source", "target", "column", "offset", "count", "sql", "input"]);
+ });
+
+ it.each(["HR.NEXT", "HR.OFFSET", "HR.FIRST", "FIRST", "-- comment\nFIRST", "employees, FIRST", "(SELECT id FROM employees) e, FIRST"])("preserves database links on the non-reserved object %s", (objectName) => {
+ const sql = `SELECT * FROM ${objectName} /* separator */ @LINK WHERE id = :id`;
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { LINK: { kind: "string", value: "WRONG" }, id: { kind: "number", value: "7" } }, { databaseType })).toBe(`SELECT * FROM ${objectName} /* separator */ @LINK WHERE id = 7`);
+ });
+
+ it("keeps lock wait, null ordering and cursor parameters", () => {
+ const sql = `SELECT * FROM HR.EMPLOYEES ORDER BY id NULLS @position FOR UPDATE WAIT @seconds;
+ BEGIN OPEN @cursor FOR SELECT * FROM HR.EMPLOYEES; END;`;
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["position", "seconds", "cursor"]);
+ expect(substituteSqlParameters(sql, { position: { kind: "raw", value: "FIRST" }, seconds: { kind: "number", value: "5" }, cursor: { kind: "raw", value: "c" } }, { databaseType })).toBe(`SELECT * FROM HR.EMPLOYEES ORDER BY id NULLS FIRST FOR UPDATE WAIT 5;
+ BEGIN OPEN c FOR SELECT * FROM HR.EMPLOYEES; END;`);
+ });
+
+ it.each([
+ ["SELECT * FROM HR.EMPLOYEES AS OF SCN @value", "7", "SELECT * FROM HR.EMPLOYEES AS OF SCN 7"],
+ ["SELECT * FROM HR.EMPLOYEES AS OF TIMESTAMP @value", "SYSTIMESTAMP", "SELECT * FROM HR.EMPLOYEES AS OF TIMESTAMP SYSTIMESTAMP"],
+ ["BEGIN CLOSE @value; END;", "c", "BEGIN CLOSE c; END;"],
+ ["SELECT * FROM employees WHERE name LIKE 'x' ESCAPE @value", "'!'", "SELECT * FROM employees WHERE name LIKE 'x' ESCAPE '!'"],
+ ["SELECT CURRENT_TIMESTAMP AT TIME ZONE @value FROM DUAL", "'UTC'", "SELECT CURRENT_TIMESTAMP AT TIME ZONE 'UTC' FROM DUAL"],
+ ["SELECT INTERVAL @value DAY FROM DUAL", "'1'", "SELECT INTERVAL '1' DAY FROM DUAL"],
+ ["SELECT JSON_OBJECT(KEY @value VALUE 'x') FROM DUAL", "'k'", "SELECT JSON_OBJECT(KEY 'k' VALUE 'x') FROM DUAL"],
+ ["SELECT JSON_OBJECT(KEY 'k' VALUE @value) FROM DUAL", "'x'", "SELECT JSON_OBJECT(KEY 'k' VALUE 'x') FROM DUAL"],
+ ["SELECT XMLQUERY('/a' PASSING @value RETURNING CONTENT) FROM DUAL", "XMLTYPE('<a/>')", "SELECT XMLQUERY('/a' PASSING XMLTYPE('<a/>') RETURNING CONTENT) FROM DUAL"],
+ ["SELECT SUM(salary) OVER (ORDER BY salary RANGE @value PRECEDING) FROM employees", "100", "SELECT SUM(salary) OVER (ORDER BY salary RANGE 100 PRECEDING) FROM employees"],
+ ["SELECT id FROM employees CONNECT BY NOCYCLE @value", "PRIOR id = manager_id", "SELECT id FROM employees CONNECT BY NOCYCLE PRIOR id = manager_id"],
+ ["SELECT LISTAGG(name, ',' ON OVERFLOW TRUNCATE @value) WITHIN GROUP (ORDER BY name) FROM employees", "'...'", "SELECT LISTAGG(name, ',' ON OVERFLOW TRUNCATE '...') WITHIN GROUP (ORDER BY name) FROM employees"],
+ ["SELECT name COLLATE @value FROM employees", "BINARY_CI", "SELECT name COLLATE BINARY_CI FROM employees"],
+ ["SET TRANSACTION NAME @value", "'test'", "SET TRANSACTION NAME 'test'"],
+ ["DECLARE v NUMBER; BEGIN EXECUTE IMMEDIATE 'BEGIN :x := 1; END;' USING OUT @value; END;", "v", "DECLARE v NUMBER; BEGIN EXECUTE IMMEDIATE 'BEGIN :x := 1; END;' USING OUT v; END;"],
+ ["BEGIN FOR i IN REVERSE @value .. 10 LOOP NULL; END LOOP; END;", "1", "BEGIN FOR i IN REVERSE 1 .. 10 LOOP NULL; END LOOP; END;"],
+ ["SAVEPOINT @value", "sp1", "SAVEPOINT sp1"],
+ ["DECLARE e EXCEPTION; BEGIN RAISE @value; END;", "e", "DECLARE e EXCEPTION; BEGIN RAISE e; END;"],
+ ["BEGIN GOTO @value; <<finish>> NULL; END;", "finish", "BEGIN GOTO finish; <<finish>> NULL; END;"],
+ ["BEGIN <<outer_loop>> LOOP EXIT @value; END LOOP; END;", "outer_loop", "BEGIN <<outer_loop>> LOOP EXIT outer_loop; END LOOP; END;"],
+ ["BEGIN <<outer_loop>> FOR i IN 1..2 LOOP CONTINUE @value WHEN i = 1; END LOOP; END;", "outer_loop", "BEGIN <<outer_loop>> FOR i IN 1..2 LOOP CONTINUE outer_loop WHEN i = 1; END LOOP; END;"],
+ ["SELECT 1, INTERVAL @value DAY FROM DUAL", "'1'", "SELECT 1, INTERVAL '1' DAY FROM DUAL"],
+ ["SELECT 1, CASE @value WHEN 1 THEN 2 ELSE 3 END FROM DUAL", "1", "SELECT 1, CASE 1 WHEN 1 THEN 2 ELSE 3 END FROM DUAL"],
+ ["SELECT 1, TIMESTAMP @value FROM DUAL", "'2026-10-09 00:00:00'", "SELECT 1, TIMESTAMP '2026-10-09 00:00:00' FROM DUAL"],
+ ["SELECT JSON_OBJECT('first' VALUE 1, KEY @value VALUE 2) FROM DUAL", "'k'", "SELECT JSON_OBJECT('first' VALUE 1, KEY 'k' VALUE 2) FROM DUAL"],
+ ["DECLARE v NUMBER; BEGIN EXECUTE IMMEDIATE 'BEGIN :x := 1; :y := 2; END;' USING OUT v, OUT @value; END;", "v", "DECLARE v NUMBER; BEGIN EXECUTE IMMEDIATE 'BEGIN :x := 1; :y := 2; END;' USING OUT v, OUT v; END;"],
+ ])("keeps expression parameters in %s", (sql, value, expected) => {
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["value"]);
+ expect(substituteSqlParameters(sql, { value: { kind: "raw", value } }, { databaseType })).toBe(expected);
+ });
+ });
+
+ it.each(["postgres", "sqlserver", "dameng"] as const)("keeps separated at-sign parameters unchanged for %s", (databaseType) => {
+ const sql = "SELECT * FROM employees /* comment */ @LINK WHERE id = :id";
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["LINK", "id"]);
+ expect(substituteSqlParameters(sql, { LINK: { kind: "number", value: "9" }, id: { kind: "number", value: "7" } }, { databaseType })).toBe("SELECT * FROM employees /* comment */ 9 WHERE id = 7");
+ });
+
it("describes each placeholder syntax for the parameter dialog", () => {
const sql = "select ? as a, :named as b, ${shell_name} as c, #{mybatis_name} as d, @sql_server_name as e";
expect(extractSqlParameterDescriptors(sql)).toEqual([
@@ -659,8 +861,8 @@ describe("extractSqlParameters", () => {
});
});
-describe("Oracle and Dameng trigger pseudo-records", () => {
- it("ignores Oracle default pseudo-record fields while keeping ordinary parameters", () => {
+describe("Oracle, OceanBase Oracle and Dameng trigger pseudo-records", () => {
+ it.each(["oracle", "oceanbase-oracle"] as const)("ignores %s default pseudo-record fields while keeping ordinary parameters", (databaseType) => {
const sql = `
CREATE OR REPLACE TRIGGER audit_orders
BEFORE UPDATE ON orders
@@ -671,7 +873,7 @@ describe("Oracle and Dameng trigger pseudo-records", () => {
END;
`;
- expect(extractSqlParameters(sql, { databaseType: "oracle" })).toEqual(["tenant_id"]);
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["tenant_id"]);
});
it("ignores Dameng default pseudo-record fields case-insensitively", () => {
@@ -686,7 +888,7 @@ describe("Oracle and Dameng trigger pseudo-records", () => {
expect(extractSqlParameters(sql, { databaseType: "dameng" })).toEqual(["actor_id"]);
});
- it("parses REFERENCING aliases without disabling default pseudo-records", () => {
+ it.each(["oracle", "oceanbase-oracle"] as const)("parses %s REFERENCING aliases without disabling default pseudo-records", (databaseType) => {
const sql = `
create or replace trigger audit_orders
before update on orders
@@ -697,10 +899,10 @@ describe("Oracle and Dameng trigger pseudo-records", () => {
end;
`;
- expect(extractSqlParameters(sql, { databaseType: "oracle" })).toEqual(["reason"]);
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["reason"]);
});
- it("replaces ordinary trigger parameters but preserves pseudo-record fields", () => {
+ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("replaces ordinary %s trigger parameters but preserves pseudo-record fields", (databaseType) => {
const sql = `create trigger audit_orders before update on orders
referencing new as inserted old as deleted
for each row begin
@@ -715,7 +917,7 @@ describe("Oracle and Dameng trigger pseudo-records", () => {
user_id: { kind: "number", value: "42" },
note: { kind: "string", value: "manual" },
},
- { databaseType: "dameng" },
+ { databaseType },
),
).toBe(`create trigger audit_orders before update on orders
referencing new as inserted old as deleted
@@ -732,11 +934,12 @@ describe("Oracle and Dameng trigger pseudo-records", () => {
select :new, :outside_value from dual;`;
expect(extractSqlParameters(oracleScript, { databaseType: "oracle" })).toEqual(["value", "new", "outside_value"]);
+ expect(extractSqlParameters(oracleScript, { databaseType: "oceanbase-oracle" })).toEqual(["value", "new", "outside_value"]);
expect(extractSqlParameters("create trigger t before update on x begin :NEW.id := :value; end;", { databaseType: "postgres" })).toEqual(["NEW", "value"]);
expect(extractSqlParameters("create trigger t before update on x begin NEW.id := :value; end;", { databaseType: "postgres" })).toEqual(["value"]);
});
- it("keeps assignment, casts, comments, strings, and non-field pseudo-record tokens unchanged", () => {
+ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("keeps %s assignment, casts, comments, strings, and non-field pseudo-record tokens unchanged", (databaseType) => {
const sql = `create trigger audit_orders before update on orders
for each row begin
:new := :actual_value;
@@ -746,7 +949,7 @@ describe("Oracle and Dameng trigger pseudo-records", () => {
note := ':EVENTINFO.string_field';
end;`;
- expect(extractSqlParameters(sql, { databaseType: "dameng" })).toEqual(["new", "actual_value", "target_value"]);
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["new", "actual_value", "target_value"]);
});
});
diff --git a/apps/desktop/src/lib/sql/semantic/tokens.ts b/apps/desktop/src/lib/sql/semantic/tokens.ts
index 1ee871bdee..624ee552e2 100644
--- a/apps/desktop/src/lib/sql/semantic/tokens.ts
+++ b/apps/desktop/src/lib/sql/semantic/tokens.ts
@@ -149,12 +149,13 @@ export function tokenizeSqlSemantic(input: string, dialectId = "mysql", options?
continue;
}
- if (dialectId === "oracle" && (ch === "q" || ch === "Q") && next === "'" && input[index + 2]) {
- const opener = input[index + 2]!;
+ const oracleQuoteStart = (ch === "n" || ch === "N") && (next === "q" || next === "Q") ? index + 1 : index;
+ if (dialectId === "oracle" && (input[oracleQuoteStart] === "q" || input[oracleQuoteStart] === "Q") && input[oracleQuoteStart + 1] === "'" && input[oracleQuoteStart + 2]) {
+ const opener = characterAt(input, oracleQuoteStart + 2);
const closer = ({ "[": "]", "{": "}", "(": ")", "<": ">" } as Record<string, string>)[opener] ?? opener;
- const end = input.indexOf(closer + "'", index + 3);
- index = end < 0 ? input.length : end + 2;
- tokens.push(token("string", input.slice(start, index), start, index, depth, "q'", end >= 0));
+ const end = input.indexOf(closer + "'", oracleQuoteStart + 2 + opener.length);
+ index = end < 0 ? input.length : end + closer.length + 1;
+ tokens.push(token("string", input.slice(start, index), start, index, depth, oracleQuoteStart === start ? "q'" : "nq'", end >= 0));
continue;
}
diff --git a/apps/desktop/src/lib/sql/sqlIdentifier.ts b/apps/desktop/src/lib/sql/sqlIdentifier.ts
index 9df82fd4aa..39cbcd58ad 100644
--- a/apps/desktop/src/lib/sql/sqlIdentifier.ts
+++ b/apps/desktop/src/lib/sql/sqlIdentifier.ts
@@ -550,7 +550,11 @@ export function requiresMysqlIdentifierQuote(identifier: string, additionalKeywo
}
export function requiresOracleIdentifierQuote(identifier: string): boolean {
- return !SIMPLE_ORACLE_IDENTIFIER.test(identifier) || ORACLE_RESERVED_IDENTIFIER_KEYWORDS.has(identifier);
+ return !SIMPLE_ORACLE_IDENTIFIER.test(identifier) || isOracleReservedKeyword(identifier);
+}
+
+export function isOracleReservedKeyword(identifier: string): boolean {
+ return ORACLE_RESERVED_IDENTIFIER_KEYWORDS.has(identifier.toUpperCase());
}
export function requiresDamengIdentifierQuote(identifier: string): boolean {
diff --git a/apps/desktop/src/lib/sql/sqlParameters.ts b/apps/desktop/src/lib/sql/sqlParameters.ts
index 0fc9f70791..871e8f49b2 100644
--- a/apps/desktop/src/lib/sql/sqlParameters.ts
+++ b/apps/desktop/src/lib/sql/sqlParameters.ts
@@ -1,4 +1,7 @@
import type { DatabaseType } from "@/types/database";
+import { supportsOracleDatabaseLinks } from "@/lib/database/oracleDatabaseLinks";
+import { isOracleReservedKeyword } from "@/lib/sql/sqlIdentifier";
+import { tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";
export type SqlParameterValueKind = "string" | "number" | "boolean" | "null" | "raw";
@@ -64,6 +67,50 @@ export interface SqlParameterOptions {
const PARAMETER_NAME_RE = /^[\p{L}_][\p{L}\p{N}_]*(?:\.[\p{L}_][\p{L}\p{N}_]*)*$/u;
const PARAMETER_NAME_START_RE = /[\p{L}_]/u;
const PARAMETER_NAME_CHAR_RE = /[\p{L}\p{N}_]/u;
+const ORACLE_PARAMETER_PREFIX_KEYWORDS = new Set([
+ "begin",
+ "case",
+ "close",
+ "collate",
+ "continue",
+ "elsif",
+ "escape",
+ "exit",
+ "fetch",
+ "first",
+ "goto",
+ "if",
+ "interval",
+ "join",
+ "key",
+ "limit",
+ "loop",
+ "name",
+ "next",
+ "nocycle",
+ "nulls",
+ "offset",
+ "open",
+ "out",
+ "passing",
+ "raise",
+ "range",
+ "return",
+ "returning",
+ "reverse",
+ "savepoint",
+ "scn",
+ "timestamp",
+ "truncate",
+ "using",
+ "value",
+ "wait",
+ "when",
+ "while",
+ "zone",
+]);
+const ORACLE_OBJECT_PREFIX_KEYWORDS = new Set(["from", "join", "update", "into", "table", "delete"]);
+const ORACLE_TABLE_LIST_BOUNDARIES = new Set(["select", "from", "where", "group", "having", "order", "connect", "start", "union", "intersect", "minus", "for", "returning", "set", "values"]);
const SQL_SERVER_TEMP_TABLE_CONTEXT_KEYWORDS = new Set(["table", "from", "join", "into", "update", "truncate"]);
const MYSQL_ROUTINE_LABEL_STATEMENTS = new Set(["begin", "loop", "while", "repeat"]);
const MYSQL_ROUTINE_LABEL_CONTEXTS = new Set(["begin", "then", "else", "do", "loop", "repeat"]);
@@ -324,7 +371,7 @@ function decodeMyBatisXmlComparisonEntities(sql: string, databaseType?: Database
const next = sql[i + 1];
if (ch === "'" || ch === '"' || ch === "`") {
- i = skipQuoted(sql, i, ch);
+ i = skipQuoted(sql, i, ch, databaseType);
continue;
}
if (ch === "[") {
@@ -381,6 +428,7 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions)
const supportsNamedParameters = databaseType !== "saphana" && databaseType !== "neo4j" && databaseType !== "nebula";
const enabledSyntaxes = options?.enabledSyntaxes ? new Set(options.enabledSyntaxes) : null;
const isSyntaxEnabled = (syntax: SqlParameterSyntax) => !enabledSyntaxes || enabledSyntaxes.has(syntax);
+ const separatedOracleDatabaseLinks = isSyntaxEnabled("sqlserver") ? collectSeparatedOracleDatabaseLinks(sql, databaseType) : new Set<number>();
const complexTypeFieldSeparators = supportsNamedParameters && isSyntaxEnabled("named") ? collectComplexTypeFieldSeparators(sql, databaseType) : new Set<number>();
const duckDbStructFieldSeparators = supportsNamedParameters && isSyntaxEnabled("named") && databaseType === "duckdb" ? collectDuckDbStructFieldSeparators(sql) : new Set<number>();
const triggerPseudoRecordFieldStarts = supportsNamedParameters && isSyntaxEnabled("named") ? collectTriggerPseudoRecordFieldStarts(sql, databaseType) : new Set<number>();
@@ -419,7 +467,7 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions)
i = foreach.end;
continue;
}
- const where = readMyBatisWhereAt(sql, i);
+ const where = readMyBatisWhereAt(sql, i, databaseType);
if (where) {
occurrences.push({
key: "",
@@ -443,7 +491,7 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions)
i = quoted.end;
continue;
}
- const quotedEnd = skipQuoted(sql, i, ch);
+ const quotedEnd = skipQuoted(sql, i, ch, databaseType);
// Double quotes can delimit identifiers, so only ordinary single-quoted
// values opt into embedded interpolation.
if (ch === "'" && !hasSqlStringLiteralPrefix(sql, i)) {
@@ -541,7 +589,16 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions)
}
if (ch === "@" && isSyntaxEnabled("sqlserver")) {
const name = readParameterName(sql, i + 1);
- if (name && next !== "@" && sql[i - 1] !== "@" && !isOracleDatabaseLinkMarker(sql, i, options?.databaseType) && !isJdbcxMcpScopedPackage(sql, i, i + 1 + name.length) && !nativeSqlServerParameters.declared.has(name.toLowerCase()) && !nativeSqlServerParameters.ignoredStarts.has(i)) {
+ if (
+ name &&
+ next !== "@" &&
+ sql[i - 1] !== "@" &&
+ !separatedOracleDatabaseLinks.has(i) &&
+ !isOracleDatabaseLinkMarker(sql, i, databaseType) &&
+ !isJdbcxMcpScopedPackage(sql, i, i + 1 + name.length) &&
+ !nativeSqlServerParameters.declared.has(name.toLowerCase()) &&
+ !nativeSqlServerParameters.ignoredStarts.has(i)
+ ) {
occurrences.push({
key: name,
name,
@@ -606,12 +663,12 @@ function readMyBatisForeachAt(sql: string, start: number, databaseType?: Databas
};
}
-function readMyBatisWhereAt(sql: string, start: number): { body: string; end: number } | null {
+function readMyBatisWhereAt(sql: string, start: number, databaseType?: DatabaseType): { body: string; end: number } | null {
if (!/^<where(?:\s|>)/i.test(sql.slice(start))) return null;
const openingEnd = findXmlTagEnd(sql, start);
if (openingEnd === -1) return null;
- const close = findMatchingXmlTagClose(sql, openingEnd + 1, "where");
+ const close = findMatchingXmlTagClose(sql, openingEnd + 1, "where", databaseType);
if (!close) return null;
return { body: sql.slice(openingEnd + 1, close.start), end: close.end };
}
@@ -667,7 +724,7 @@ function findMatchingXmlTagClose(sql: string, start: number, tagName: string, da
const next = sql[i + 1];
if (ch === "'" || ch === '"' || ch === "`") {
- i = skipQuoted(sql, i, ch);
+ i = skipQuoted(sql, i, ch, databaseType);
continue;
}
if (ch === "[") {
@@ -725,11 +782,45 @@ function isDuckDbCompactPrefixAliasSeparator(sql: string, index: number, databas
}
function isOracleDatabaseLinkMarker(sql: string, index: number, databaseType: DatabaseType | undefined): boolean {
- if (databaseType !== "oracle" || index === 0) return false;
+ if (!supportsOracleDatabaseLinks(databaseType) || index === 0) return false;
const previous = sql[index - 1];
return PARAMETER_NAME_CHAR_RE.test(previous) || previous === "$" || previous === "#" || previous === '"';
}
+function collectSeparatedOracleDatabaseLinks(sql: string, databaseType: DatabaseType | undefined): Set<number> {
+ const links = new Set<number>();
+ if (!supportsOracleDatabaseLinks(databaseType) || !sql.includes("@")) return links;
+ const tokens = tokenizeSqlSemantic(sql, "oracle").filter((token) => token.kind !== "comment");
+ for (let i = 1; i < tokens.length; i += 1) {
+ const token = tokens[i];
+ if (token.kind !== "word" || !token.text.startsWith("@")) continue;
+ const object = tokens[i - 1];
+ if (object.kind === "quoted_identifier" && object.quote === '"') {
+ links.add(token.span.start);
+ continue;
+ }
+ if (object.kind !== "word" || !/^[\p{L}_][\p{L}\p{N}_$#]*$/u.test(object.text) || isOracleReservedKeyword(object.text)) continue;
+ const prefix = tokens[i - 2]?.normalized ?? "";
+ // Non-reserved words can name objects (FROM first@link), while expression
+ // keywords still introduce parameters (FETCH FIRST @count, UPDATE WAIT @n).
+ let objectContext = prefix === "." || (ORACLE_OBJECT_PREFIX_KEYWORDS.has(prefix) && !(prefix === "update" && tokens[i - 3]?.normalized === "for"));
+ // A comma can separate tables or expressions. Only a FROM list makes the
+ // following non-reserved keyword an object name, including after subqueries.
+ if (prefix === "," && ORACLE_PARAMETER_PREFIX_KEYWORDS.has(object.normalized)) {
+ for (let j = i - 3; j >= 0; j -= 1) {
+ const before = tokens[j];
+ if (before.depth < token.depth || before.text === ";") break;
+ if (before.depth === token.depth && before.kind === "word" && ORACLE_TABLE_LIST_BOUNDARIES.has(before.normalized)) {
+ objectContext = before.normalized === "from";
+ break;
+ }
+ }
+ }
+ if (objectContext || !ORACLE_PARAMETER_PREFIX_KEYWORDS.has(object.normalized)) links.add(token.span.start);
+ }
+ return links;
+}
+
function isPostgresQuestionMarkOperator(sql: string, index: number, databaseType: DatabaseType | undefined): boolean {
if (databaseType !== "postgres") return false;
if (sql[index - 1] === "@" || sql[index + 1] === "|" || sql[index + 1] === "&") return true;
@@ -872,7 +963,7 @@ function readDuckDbStructFieldSeparator(sql: string, start: number): number | nu
return sql[separator] === ":" ? separator : null;
}
-// Oracle and Dameng expose trigger rows through colon-prefixed pseudo-records,
+// Oracle, OceanBase Oracle and Dameng expose trigger rows through colon-prefixed pseudo-records,
// unlike PostgreSQL's unprefixed NEW/OLD records. Keep ordinary :name binds enabled.
function collectTriggerPseudoRecordFieldStarts(sql: string, databaseType?: DatabaseType): Set<number> {
const starts = new Set<number>();
@@ -895,7 +986,7 @@ function collectTriggerPseudoRecordFieldStarts(sql: string, databaseType?: Datab
const ch = sql[i];
const next = sql[i + 1];
if (ch === "'" || ch === '"' || ch === "`") {
- i = skipQuoted(sql, i, ch);
+ i = skipQuoted(sql, i, ch, databaseType);
continue;
}
if (ch === "[") {
@@ -955,7 +1046,7 @@ function collectTriggerPseudoRecordFieldStarts(sql: string, databaseType?: Datab
}
function triggerPseudoRecordDefaults(databaseType?: DatabaseType): readonly TriggerPseudoRecordName[] | null {
- if (databaseType === "oracle") return ["new", "old", "parent"];
+ if (databaseType === "oracle" || databaseType === "oceanbase-oracle") return ["new", "old", "parent"];
if (databaseType === "dameng") return ["new", "old", "eventinfo"];
return null;
}
@@ -1702,10 +1793,29 @@ function hasSqlStringLiteralPrefix(sql: string, quoteStart: number): boolean {
return PARAMETER_NAME_CHAR_RE.test(sql[quoteStart - 1]);
}
-function skipQuoted(sql: string, start: number, quote: string): number {
+function skipOracleAlternativeQuoted(sql: string, quoteStart: number): number | null {
+ if (sql[quoteStart - 1]?.toLowerCase() !== "q") return null;
+ const prefixStart = sql[quoteStart - 2]?.toLowerCase() === "n" ? quoteStart - 2 : quoteStart - 1;
+ const previous = sql[prefixStart - 1] ?? "";
+ if (PARAMETER_NAME_CHAR_RE.test(previous) || previous === "$" || previous === "#") return null;
+
+ const openerCodePoint = sql.codePointAt(quoteStart + 1);
+ if (openerCodePoint === undefined) return null;
+ const opener = String.fromCodePoint(openerCodePoint);
+ if (/\s/.test(opener)) return null;
+ const closer = ({ "[": "]", "{": "}", "(": ")", "<": ">" } as Record<string, string>)[opener] ?? opener;
+ const end = sql.indexOf(closer + "'", quoteStart + 1 + opener.length);
+ return end === -1 ? sql.length : end + closer.length + 1;
+}
+
+function skipQuoted(sql: string, start: number, quote: string, databaseType?: DatabaseType): number {
+ if (quote === "'" && (databaseType === "oracle" || databaseType === "oceanbase-oracle")) {
+ const end = skipOracleAlternativeQuoted(sql, start);
+ if (end !== null) return end;
+ }
let i = start + 1;
while (i < sql.length) {
- if (sql[i] === "\\" && quote === "'" && i + 1 < sql.length) {
+ if (sql[i] === "\\" && quote === "'" && databaseType !== "oracle" && databaseType !== "oceanbase-oracle" && i + 1 < sql.length) {
i += 2;
continue;
}