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): restrict DBLink detection to object references

efeire7653e860dd8c
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
index c874e8d6a5..cff633f360 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
@@ -347,6 +347,33 @@ describe("extractSqlParameters", () => {
});
describe.each(["oracle", "oceanbase-oracle"] as const)("%s database link separators", (databaseType) => {
+ it.each([
+ ["SELECT XMLSERIALIZE(CONTENT @value AS CLOB) FROM DUAL", "XMLTYPE('<a/>')"],
+ ["SELECT XMLSERIALIZE(CONTENT@value AS CLOB) FROM DUAL", "XMLTYPE('<a/>')"],
+ ["SELECT XMLSERIALIZE(DOCUMENT @value AS CLOB) FROM DUAL", "XMLTYPE('<a/>')"],
+ ["CREATE OR REPLACE PACKAGE BODY @value AS PROCEDURE p IS BEGIN NULL; END; END;", "test_package"],
+ ["DROP DATABASE LINK @value", "remote_db"],
+ ["CREATE DATABASE LINK @value CONNECT TO remote_user IDENTIFIED BY password USING 'remote'", "remote_db"],
+ ['SELECT "xml_column" @value FROM DUAL', "AS xml_alias"],
+ ])("keeps raw template parameters outside object references in %s", (sql, value) => {
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["value"]);
+ expect(substituteSqlParameters(sql, { value: { kind: "raw", value } }, { databaseType })).toBe(sql.replace("@value", value));
+ });
+
+ it("preserves remote routine links in expressions and PL/SQL calls", () => {
+ const sql = "SELECT HR.get_value@LINK(:id) FROM DUAL; BEGIN HR.run_job /* link */ @LINK(:id); END;";
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { id: { kind: "number", value: "7" }, LINK: { kind: "raw", value: "WRONG" } }, { databaseType })).toBe("SELECT HR.get_value@LINK(7) FROM DUAL; BEGIN HR.run_job /* link */ @LINK(7); END;");
+ });
+
+ it.each(["employees", "HR.EMPLOYEES", '"Hr"."Employees"', "DUAL"])("preserves compact and separated links on %s", (objectName) => {
+ for (const separator of ["", " /* object link */ "]) {
+ const sql = `SELECT @value FROM ${objectName}${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" }, LINK: { kind: "raw", value: "WRONG" } }, { databaseType })).toBe(`SELECT 1 FROM ${objectName}${separator}@LINK WHERE id = 7`);
+ }
+ });
+
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(
@@ -394,6 +421,17 @@ describe("extractSqlParameters", () => {
expect(extractSqlParameters(sql, { databaseType })).toEqual(["value", "source", "target", "column", "offset", "count", "sql", "input"]);
});
+ it.each(["DELETE FROM @table WHERE id = :id", "INSERT INTO @table VALUES (:id)"])("keeps parameters after reserved keywords in %s", (sql) => {
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["table", "id"]);
+ expect(substituteSqlParameters(sql, { table: { kind: "raw", value: "employees" }, id: { kind: "number", value: "7" } }, { databaseType })).toBe(sql.replace("@table", "employees").replace(":id", "7"));
+ });
+
+ it("preserves remote routine links in comma-separated select lists", () => {
+ const sql = "SELECT ename, HR.get_sal@LINK(empno) FROM emp WHERE id = :id";
+ expect(extractSqlParameters(sql, { databaseType })).toEqual(["id"]);
+ expect(substituteSqlParameters(sql, { LINK: { kind: "raw", value: "WRONG" }, id: { kind: "number", value: "7" } }, { databaseType })).toBe("SELECT ename, HR.get_sal@LINK(empno) FROM emp WHERE id = 7");
+ });
+
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"]);
diff --git a/apps/desktop/src/lib/sql/sqlParameters.ts b/apps/desktop/src/lib/sql/sqlParameters.ts
index 871e8f49b2..a2732f80c8 100644
--- a/apps/desktop/src/lib/sql/sqlParameters.ts
+++ b/apps/desktop/src/lib/sql/sqlParameters.ts
@@ -67,48 +67,6 @@ 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"]);
@@ -589,16 +547,7 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions)
}
if (ch === "@" && isSyntaxEnabled("sqlserver")) {
const name = readParameterName(sql, i + 1);
- 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)
- ) {
+ if (name && next !== "@" && sql[i - 1] !== "@" && !separatedOracleDatabaseLinks.has(i) && !isJdbcxMcpScopedPackage(sql, i, i + 1 + name.length) && !nativeSqlServerParameters.declared.has(name.toLowerCase()) && !nativeSqlServerParameters.ignoredStarts.has(i)) {
occurrences.push({
key: name,
name,
@@ -781,42 +730,50 @@ function isDuckDbCompactPrefixAliasSeparator(sql: string, index: number, databas
return PARAMETER_NAME_CHAR_RE.test(previous) || previous === '"';
}
-function isOracleDatabaseLinkMarker(sql: string, index: number, databaseType: DatabaseType | undefined): boolean {
- 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");
+ const tokens = tokenizeSqlSemantic(sql, "oracle")
+ .filter((token) => token.kind !== "comment")
+ .flatMap((token) => {
+ const marker = token.kind === "word" ? token.text.indexOf("@") : -1;
+ if (marker <= 0) return [token];
+ // The semantic tokenizer keeps an unquoted compact object@link in one word.
+ // Split it without changing source offsets so it uses the same context check.
+ return [
+ { ...token, text: token.text.slice(0, marker), normalized: token.normalized.slice(0, marker), span: { ...token.span, end: token.span.start + marker } },
+ { ...token, text: token.text.slice(marker), normalized: token.normalized.slice(marker), span: { ...token.span, start: token.span.start + marker } },
+ ];
+ });
for (let i = 1; i < tokens.length; i += 1) {
const token = tokens[i];
if (token.kind !== "word" || !token.text.startsWith("@")) continue;
+ const isObjectIdentifier = (position: number) => {
+ const candidate = tokens[position];
+ return candidate && ((candidate.kind === "quoted_identifier" && candidate.quote === '"') || (candidate.kind === "word" && /^[\p{L}_][\p{L}\p{N}_$#]*$/u.test(candidate.text) && !isOracleReservedKeyword(candidate.text)));
+ };
+ if (!isObjectIdentifier(i - 1)) continue;
+ let objectStart = i - 1;
+ while (tokens[objectStart - 1]?.text === "." && isObjectIdentifier(objectStart - 2)) objectStart -= 2;
+ const prefix = tokens[objectStart - 1]?.normalized ?? "";
+ // Require a table reference or a remote routine call. Unknown expression
+ // keywords (CONTENT, BODY, LINK) must not hide template parameters.
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"));
+ const routineCall = tokens[i + 1]?.text === "(" && (object.kind === "quoted_identifier" || !isOracleReservedKeyword(object.text));
+ let objectContext = (ORACLE_OBJECT_PREFIX_KEYWORDS.has(prefix) && !(prefix === "update" && tokens[objectStart - 2]?.normalized === "for")) || routineCall;
// 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) {
+ if (prefix === ",") {
+ for (let j = objectStart - 2; 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";
+ objectContext = before.normalized === "from" || routineCall;
break;
}
}
}
- if (objectContext || !ORACLE_PARAMETER_PREFIX_KEYWORDS.has(object.normalized)) links.add(token.span.start);
+ if (objectContext) links.add(token.span.start);
}
return links;
}