fix(mysql): switch tab database label after USE statements

This commit is contained in:
zipg authored and GitHub committed 2026-09-22 11:48:36 +08:00
1 parent 713ce06aea
commit 8b3d7fc9e6
7 files changed
+174 -16

No files matched your search

@@ -12,6 +12,8 @@ import {
sqlServerLeadingUseScript,
sqlServerUseCompletionDatabaseNames,
sqlServerUseDatabaseFromStatement,
switchesDatabaseWithUseStatement,
useDatabaseFromStatement,
} from "@/lib/sql/sqlCompletionLookupTarget";
describe("sqlCompletionLookupTarget", () => {
@@ -290,6 +292,35 @@ describe("sqlCompletionLookupTarget", () => {
expect(sqlServerLeadingUseScript("USE FooDB; INSERT INTO audit_log VALUES (1); SELECT * FROM Users;")).toBeUndefined();
});
it("parses the USE target of MySQL-family dialects in all three identifier forms", () => {
expect(useDatabaseFromStatement("USE hd_ods", "mysql")).toBe("hd_ods");
expect(useDatabaseFromStatement("use hd_ods;", "mysql")).toBe("hd_ods");
expect(useDatabaseFromStatement(" USE `hd-ods`; ", "doris")).toBe("hd-ods");
expect(useDatabaseFromStatement('USE "报告库";', "starrocks")).toBe("报告库");
expect(useDatabaseFromStatement("-- switch\n/* c */ USE goldendb_db;", "goldendb")).toBe("goldendb_db");
expect(useDatabaseFromStatement("USE `a``b`;", "gbase")).toBe("a`b");
});
it("does not turn other statements or dialects into a database switch", () => {
expect(useDatabaseFromStatement("SELECT 1 FROM dual;", "mysql")).toBeUndefined();
expect(useDatabaseFromStatement("USE hd_ods; SELECT 1;", "mysql")).toBeUndefined();
expect(useDatabaseFromStatement("USE hd_ods;", "postgres")).toBeUndefined();
expect(useDatabaseFromStatement("USE other_ods;", "oracle")).toBeUndefined();
// SQL Server keeps its own bracket-aware parser.
expect(useDatabaseFromStatement("USE [Bar]]DB];", "sqlserver")).toBe("Bar]DB");
expect(useDatabaseFromStatement("USE hd_ods;", undefined)).toBeUndefined();
});
it("reports which dialects treat USE as a database switch", () => {
for (const databaseType of ["mysql", "doris", "starrocks", "goldendb", "gbase"] as const) {
expect(switchesDatabaseWithUseStatement(databaseType)).toBe(true);
}
for (const databaseType of ["postgres", "oracle", "clickhouse", "hive"] as const) {
expect(switchesDatabaseWithUseStatement(databaseType)).toBe(false);
}
expect(switchesDatabaseWithUseStatement(undefined)).toBe(false);
});
it("ignores commented, quoted, current, later, and non-SQL Server USE text", () => {
const sql = "-- USE [CommentDB]\nSELECT 'USE [StringDB]';\nSELECT * FROM T;\nUSE [LaterDB];";
const cursor = sql.indexOf("T;") + 1;