fix(sqlite): normalize database context routing

This commit is contained in:
Guoyu Su authored and GitHub committed 2026-07-30 03:12:02 +08:00
1 parent 545c2c9e00
commit d0a55b1b07
23 files changed
+499 -69

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { buildAiContext } from "@/lib/ai/ai";
import type { ConnectionConfig, QueryTab } from "@/types/database";
const apiMock = vi.hoisted(() => ({
listTables: vi.fn(),
getColumns: vi.fn(),
listIndexes: vi.fn(),
listForeignKeys: vi.fn(),
}));
vi.mock("@/lib/backend/api", () => apiMock);
function sqliteConnection(database?: string): ConnectionConfig {
return {
id: "sqlite-1",
name: "SQLite",
db_type: "sqlite",
host: "/tmp/real.sqlite",
port: 0,
username: "",
password: "",
database,
};
}
function queryTab(database: string): QueryTab {
return {
id: "tab-1",
title: "Query",
connectionId: "sqlite-1",
database,
sql: "",
isExecuting: false,
isCancelling: false,
isExplaining: false,
mode: "query",
};
}
describe("SQLite AI context routing", () => {
beforeEach(() => {
vi.clearAllMocks();
apiMock.listTables.mockResolvedValue([]);
apiMock.getColumns.mockResolvedValue([]);
apiMock.listIndexes.mockResolvedValue([]);
apiMock.listForeignKeys.mockResolvedValue([]);
});
it("uses main for a stale path-shaped SQLite database value", async () => {
const context = await buildAiContext(queryTab("/tmp/stale.sqlite"), sqliteConnection("/tmp/legacy.sqlite"));
expect(context.database).toBe("main");
expect(apiMock.listTables).toHaveBeenCalledWith("sqlite-1", "main", "main");
});
it("preserves an attached SQLite database alias", async () => {
const context = await buildAiContext(queryTab("analytics"), sqliteConnection());
expect(context.database).toBe("analytics");
expect(apiMock.listTables).toHaveBeenCalledWith("sqlite-1", "analytics", "analytics");
});
});
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { decodeSelectableDatabaseValue, EMPTY_DATABASE_SELECT_VALUE, encodeSelectableDatabaseValue, TREE_SCHEMA_DEFAULT_DATABASE_SELECT_VALUE } from "@/lib/database/defaultDatabase";
import { decodeSelectableDatabaseValue, EMPTY_DATABASE_SELECT_VALUE, encodeSelectableDatabaseValue, isDefaultDatabase, resolveDefaultDatabase, TREE_SCHEMA_DEFAULT_DATABASE_SELECT_VALUE } from "@/lib/database/defaultDatabase";
describe("defaultDatabase selectable values", () => {
it("encodes empty tree-schema databases with the default database sentinel", () => {
@@ -16,4 +16,20 @@ describe("defaultDatabase selectable values", () => {
expect(encodeSelectableDatabaseValue("access", "653128SXB.mdb")).toBe("653128SXB.mdb");
expect(decodeSelectableDatabaseValue("access", "653128SXB.mdb")).toBe("653128SXB.mdb");
});
it("uses main for SQLite connections with stale file paths", () => {
expect(resolveDefaultDatabase({ db_type: "sqlite", database: "/tmp/stale.sqlite" }, [])).toBe("main");
expect(resolveDefaultDatabase({ db_type: "sqlite", database: "C:\\data\\stale.db" }, [])).toBe("main");
expect(resolveDefaultDatabase({ db_type: "sqlite", database: "file:/tmp/stale.sqlite" }, [])).toBe("main");
expect(resolveDefaultDatabase({ db_type: "sqlite", database: ":memory:" }, [])).toBe("main");
expect(isDefaultDatabase({ db_type: "sqlite", database: "/tmp/stale.sqlite" }, "main")).toBe(true);
expect(resolveDefaultDatabase({ db_type: "sqlite", host: "relative.sqlite", database: undefined }, ["relative.sqlite"])).toBe("main");
expect(resolveDefaultDatabase({ db_type: "sqlite", host: "legacyfile", database: undefined }, ["legacyfile"])).toBe("main");
});
it("preserves a SQLite attached database alias", () => {
expect(resolveDefaultDatabase({ db_type: "sqlite", database: "analytics" }, ["main", "analytics"])).toBe("analytics");
expect(isDefaultDatabase({ db_type: "sqlite", database: "analytics" }, "analytics")).toBe(true);
expect(resolveDefaultDatabase({ db_type: "sqlite", host: "primary.db", database: undefined }, ["analytics.db"])).toBe("analytics.db");
});
});
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { isSqliteFileNamespace, normalizeSqliteNamespace, normalizeStoredConnectionDatabase } from "@/lib/database/sqliteNamespace";
describe("SQLite namespace normalization", () => {
it("recognizes physical SQLite locations across platforms", () => {
for (const value of ["/tmp/app.sqlite", "C:\\data\\app.db", "./relative.db3", "file:/tmp/app.sqlite", "sqlite:/tmp/app.sqlite", ":memory:"]) {
expect(isSqliteFileNamespace(value)).toBe(true);
expect(normalizeSqliteNamespace(value)).toBe("main");
}
});
it("preserves logical attached database aliases", () => {
expect(isSqliteFileNamespace("analytics")).toBe(false);
expect(normalizeSqliteNamespace("analytics")).toBe("analytics");
expect(isSqliteFileNamespace("analytics.db")).toBe(false);
expect(normalizeSqliteNamespace("analytics.db", { database: "analytics.db" })).toBe("analytics.db");
expect(normalizeSqliteNamespace(undefined)).toBe("main");
});
it("recognizes ambiguous file names only from the connection context", () => {
expect(normalizeSqliteNamespace("primary.db", { host: "primary.db" })).toBe("main");
expect(normalizeSqliteNamespace("legacyfile", { host: "legacyfile" })).toBe("main");
});
it("removes the hidden database field only for stored SQLite connections", () => {
expect(normalizeStoredConnectionDatabase("sqlite", "/tmp/stale.sqlite")).toBeUndefined();
expect(normalizeStoredConnectionDatabase("postgres", "app")).toBe("app");
});
});
@@ -15,6 +15,28 @@ function layoutLabels(layout: SidebarLayout, connectionNames: Map<string, string
}
describe("DataGrip connection import", () => {
it("imports a SQLite file path without treating it as a schema", () => {
const [connection] = parseDataGripConnections(
payload(`
<project>
<component name="DataSourceManagerImpl">
<data-source name="Local SQLite" uuid="sqlite-1">
<driver-ref>sqlite.xerial</driver-ref>
<jdbc-url>jdbc:sqlite:/tmp/app.sqlite</jdbc-url>
</data-source>
</component>
</project>
`),
);
expect(connection).toMatchObject({
name: "Local SQLite",
db_type: "sqlite",
host: "/tmp/app.sqlite",
});
expect(connection?.database).toBeUndefined();
});
it("recognizes Kingbase custom JDBC drivers", () => {
const connections = parseDataGripConnections(
payload(`
@@ -24,6 +24,32 @@ function layoutLabels(layout: SidebarLayout, connectionNames: Map<string, string
}
describe("DBeaver folder import", () => {
it("imports a SQLite file path without treating it as a schema", async () => {
const [connection] = await parseDbeaverConnections(
payload({
connections: {
sqlite: {
id: "sqlite",
name: "Local SQLite",
provider: "sqlite",
driver: "sqlite_jdbc",
configuration: {
url: "jdbc:sqlite:/tmp/app.sqlite",
database: "/tmp/app.sqlite",
},
},
},
}),
);
expect(connection).toMatchObject({
name: "Local SQLite",
db_type: "sqlite",
host: "/tmp/app.sqlite",
});
expect(connection?.database).toBeUndefined();
});
it("keeps parseDbeaverConnections compatible when no folders exist", async () => {
const connections = await parseDbeaverConnections(payload({ connections: { root: mysqlConnection("root", "Root") } }));
@@ -76,14 +76,14 @@ if (!globalThis.DOMParser) {
}
describe("parseNavicatConnections", () => {
it("imports SQLite DatabaseFile as both host and database", async () => {
it("imports SQLite DatabaseFile as the host without treating it as a schema", async () => {
const [connection] = await parseNavicatConnections(`<Connections>
<Connection ConnType="SQLite" Name="local-sqlite" DatabaseFile="C:\\Users\\Yang\\demo.db" />
</Connections>`);
expect(connection?.db_type).toBe("sqlite");
expect(connection?.host).toBe("C:\\Users\\Yang\\demo.db");
expect(connection?.database).toBe("C:\\Users\\Yang\\demo.db");
expect(connection?.database).toBeUndefined();
expect(connection?.port).toBe(0);
});
@@ -94,6 +94,7 @@ describe("parseNavicatConnections", () => {
expect(connection?.db_type).toBe("sqlite");
expect(connection?.host).toBe("/home/yang/demo.sqlite");
expect(connection?.database).toBeUndefined();
});
it("uses SQLite Database field as the file path", async () => {
@@ -103,7 +104,7 @@ describe("parseNavicatConnections", () => {
expect(connection?.db_type).toBe("sqlite");
expect(connection?.host).toBe("/tmp/app.data");
expect(connection?.database).toBe("/tmp/app.data");
expect(connection?.database).toBeUndefined();
});
it("keeps non-SQLite host and database mapping unchanged", async () => {
+32 -2
View File
@@ -28,7 +28,7 @@ describe("resolveNewQueryTarget", () => {
database: "bi",
objectBrowser: { catalog: "paimon_catalog" },
},
connections: [{ id: "conn-1", database: "" }],
connections: [{ id: "conn-1", host: "localhost", database: "", db_type: "starrocks" }],
preferredSource: "tab",
}),
).toEqual({
@@ -53,10 +53,40 @@ describe("resolveNewQueryTarget", () => {
primaryKeys: [],
},
},
connections: [{ id: "conn-1", database: "" }],
connections: [{ id: "conn-1", host: "localhost", database: "", db_type: "starrocks" }],
})?.catalog,
).toBe("paimon_catalog");
});
it("repairs a stale SQLite file path inherited from an active tab", () => {
expect(
resolveNewQueryTarget({
activeTab: {
connectionId: "conn-sqlite",
database: "/tmp/stale.sqlite",
},
connections: [{ id: "conn-sqlite", host: "/tmp/stale.sqlite", database: "/tmp/stale.sqlite", db_type: "sqlite" }],
}),
).toEqual({
connectionId: "conn-sqlite",
database: "main",
schema: undefined,
catalog: undefined,
shouldRefreshDefaultDatabase: false,
});
});
it("preserves an attached SQLite database alias inherited from an active tab", () => {
expect(
resolveNewQueryTarget({
activeTab: {
connectionId: "conn-sqlite",
database: "analytics.db",
},
connections: [{ id: "conn-sqlite", host: "primary.db", database: undefined, db_type: "sqlite" }],
})?.database,
).toBe("analytics.db");
});
});
describe("resolveNewQueryTable", () => {
+36 -28
View File
@@ -8,6 +8,7 @@ import { aiTableMentionKey, type AiTableMention } from "@/lib/ai/aiTableMentions
import { aiSkillForAction } from "@/lib/ai/aiSkills";
import { isSchemaAware } from "@/lib/database/databaseCapabilities";
import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
import { normalizeSqliteNamespace } from "@/lib/database/sqliteNamespace";
import type { AgentEvent } from "@/lib/backend/tauri";
@@ -434,6 +435,7 @@ export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig
const maxIndexesPerTable = options.maxIndexesPerTable ?? 10;
const maxFksPerTable = options.maxFksPerTable ?? 10;
const databaseType = aiDatabaseTypeForConnection(connection);
const database = aiDatabaseNamespace(tab, connection);
const tables: AiSchemaTable[] = [];
const tableKeys = new Set<string>();
let truncated = false;
@@ -444,8 +446,8 @@ export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig
schemaScope = "focused_table";
const s = tab.tableMeta.schema ?? "";
const tName = tab.tableMeta.tableName;
const [indexes, foreignKeys] = await Promise.all([api.listIndexes(tab.connectionId, tab.database, s, tName).catch(() => [] as IndexInfo[]), api.listForeignKeys(tab.connectionId, tab.database, s, tName).catch(() => [] as ForeignKeyInfo[])]);
const tableComment = await loadTableComment(tab.connectionId, tab.database, s, tName).catch(() => undefined);
const [indexes, foreignKeys] = await Promise.all([api.listIndexes(tab.connectionId, database, s, tName).catch(() => [] as IndexInfo[]), api.listForeignKeys(tab.connectionId, database, s, tName).catch(() => [] as ForeignKeyInfo[])]);
const tableComment = await loadTableComment(tab.connectionId, database, s, tName).catch(() => undefined);
tables.push({
schema: tab.tableMeta.schema,
name: tName,
@@ -471,7 +473,7 @@ export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig
// Vector databases: load collections instead of SQL tables
if (isVectorDbType(databaseType)) {
try {
const collections = await api.vectorListCollections(tab.connectionId, tab.database);
const collections = await api.vectorListCollections(tab.connectionId, database);
// Find the currently opened collection (tab.sql is UUID for ChromaDB, name for others)
const currentCollection = collections.find((c) => c.id === tab.sql || c.name === tab.sql);
@@ -508,26 +510,24 @@ export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig
try {
const schemas = await loadCandidateSchemas(tab, connection);
for (const schema of schemas) {
const tableList = await api.listTables(tab.connectionId, tab.database, schema);
const tableList = await api.listTables(tab.connectionId, database, schema);
const candidates = tableList.slice(0, maxTables - tables.length);
if (candidates.length < tableList.length) truncated = true;
const metaResults = await Promise.all(
candidates.map((table) =>
Promise.all([
api.getColumns(tab.connectionId, tab.database, schema, table.name),
api.listIndexes(tab.connectionId, tab.database, schema, table.name).catch(() => [] as IndexInfo[]),
api.listForeignKeys(tab.connectionId, tab.database, schema, table.name).catch(() => [] as ForeignKeyInfo[]),
]).then(([columns, indexes, foreignKeys]) => ({
schema: schema === tab.database && !isSchemaAware(databaseType) ? undefined : schema,
name: table.name,
tableType: table.table_type,
comment: table.comment,
columns: columns.slice(0, maxColumnsPerTable),
indexes: indexes.slice(0, maxIndexesPerTable),
foreignKeys: foreignKeys.slice(0, maxFksPerTable),
_truncatedCols: columns.length > maxColumnsPerTable,
})),
Promise.all([api.getColumns(tab.connectionId, database, schema, table.name), api.listIndexes(tab.connectionId, database, schema, table.name).catch(() => [] as IndexInfo[]), api.listForeignKeys(tab.connectionId, database, schema, table.name).catch(() => [] as ForeignKeyInfo[])]).then(
([columns, indexes, foreignKeys]) => ({
schema: schema === database && !isSchemaAware(databaseType) ? undefined : schema,
name: table.name,
tableType: table.table_type,
comment: table.comment,
columns: columns.slice(0, maxColumnsPerTable),
indexes: indexes.slice(0, maxIndexesPerTable),
foreignKeys: foreignKeys.slice(0, maxFksPerTable),
_truncatedCols: columns.length > maxColumnsPerTable,
}),
),
),
);
@@ -550,7 +550,7 @@ export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig
connectionId: tab.connectionId,
connectionName: connection.name,
databaseType,
database: tab.database,
database,
currentSql: currentCollectionName ?? tab.sql,
lastError: extractLastError(tab.result),
lastResultPreview: formatResultPreview(tab.result),
@@ -563,15 +563,16 @@ export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig
async function loadMentionedTableContext(tab: QueryTab, connection: ConnectionConfig, mention: AiTableMention, maxColumnsPerTable: number, maxIndexesPerTable: number, maxFksPerTable: number): Promise<AiSchemaTable | undefined> {
const databaseType = aiDatabaseTypeForConnection(connection);
const database = aiDatabaseNamespace(tab, connection);
const schema = await resolveMentionedTableSchema(tab, connection, mention);
const [columns, indexes, foreignKeys, tableComment] = await Promise.all([
api.getColumns(tab.connectionId, tab.database, schema, mention.table),
api.listIndexes(tab.connectionId, tab.database, schema, mention.table).catch(() => [] as IndexInfo[]),
api.listForeignKeys(tab.connectionId, tab.database, schema, mention.table).catch(() => [] as ForeignKeyInfo[]),
loadTableComment(tab.connectionId, tab.database, schema, mention.table).catch(() => undefined),
api.getColumns(tab.connectionId, database, schema, mention.table),
api.listIndexes(tab.connectionId, database, schema, mention.table).catch(() => [] as IndexInfo[]),
api.listForeignKeys(tab.connectionId, database, schema, mention.table).catch(() => [] as ForeignKeyInfo[]),
loadTableComment(tab.connectionId, database, schema, mention.table).catch(() => undefined),
]);
return {
schema: schema === tab.database && !isSchemaAware(databaseType) ? undefined : schema,
schema: schema === database && !isSchemaAware(databaseType) ? undefined : schema,
name: mention.table,
tableType: "TABLE",
comment: tableComment,
@@ -592,27 +593,34 @@ async function resolveMentionedTableSchema(tab: QueryTab, connection: Connection
return tab.tableMeta.schema;
}
if (isSchemaAware(aiDatabaseTypeForConnection(connection))) {
const database = aiDatabaseNamespace(tab, connection);
const schemas = await loadCandidateSchemas(tab, connection);
for (const schema of schemas) {
const tables = await api.listTables(tab.connectionId, tab.database, schema, mention.table, 10).catch(() => []);
const tables = await api.listTables(tab.connectionId, database, schema, mention.table, 10).catch(() => []);
if (tables.some((table) => table.name.toLowerCase() === mention.table.toLowerCase())) return schema;
}
}
return tab.database || connection.database || "main";
return aiDatabaseNamespace(tab, connection);
}
async function loadCandidateSchemas(tab: QueryTab, connection: ConnectionConfig): Promise<string[]> {
const database = aiDatabaseNamespace(tab, connection);
if (isSchemaAware(aiDatabaseTypeForConnection(connection))) {
const schemas = await api.listSchemas(tab.connectionId, tab.database);
const schemas = await api.listSchemas(tab.connectionId, database);
return prioritizeSchemas(schemas);
}
return [tab.database || connection.database || "main"];
return [database];
}
function aiDatabaseTypeForConnection(connection: ConnectionConfig): DatabaseType {
return effectiveDatabaseTypeForConnection(connection) ?? connection.db_type;
}
function aiDatabaseNamespace(tab: QueryTab, connection: ConnectionConfig): string {
const database = tab.database || connection.database || "main";
return connection.db_type === "sqlite" ? normalizeSqliteNamespace(database, connection) : database;
}
function prioritizeSchemas(schemas: string[]): string[] {
const preferred = ["public", "dbo", "main"];
return [...schemas].sort((a, b) => {
@@ -1,11 +1,13 @@
import type { ConnectionConfig, DatabaseType } from "@/types/database";
import { usesTreeSchemaMode } from "@/lib/database/databaseCapabilities";
import { normalizeSqliteNamespace } from "@/lib/database/sqliteNamespace";
export const TREE_SCHEMA_DEFAULT_DATABASE_SELECT_VALUE = "__dbx_tree_schema_default_database__";
export const EMPTY_DATABASE_SELECT_VALUE = "__dbx_empty_database__";
export function resolveDefaultDatabase(connection: Pick<ConnectionConfig, "database"> & Partial<Pick<ConnectionConfig, "db_type">>, options: string[]): string {
export function resolveDefaultDatabase(connection: Pick<ConnectionConfig, "database"> & Partial<Pick<ConnectionConfig, "db_type" | "host">>, options: string[]): string {
if (connection.db_type === "cloudflare-d1") return "main";
if (connection.db_type === "sqlite") return normalizeSqliteNamespace(connection.database || options[0], connection);
return connection.database || options[0] || "";
}
@@ -30,7 +32,8 @@ export function formatDatabaseLabel(connection: Pick<ConnectionConfig, "db_type"
return database || labels.noDatabase;
}
export function isDefaultDatabase(connection: (Pick<ConnectionConfig, "database"> & Partial<Pick<ConnectionConfig, "db_type">>) | undefined, database: string): boolean {
export function isDefaultDatabase(connection: (Pick<ConnectionConfig, "database"> & Partial<Pick<ConnectionConfig, "db_type" | "host">>) | undefined, database: string): boolean {
if (connection?.db_type === "cloudflare-d1") return database === "main";
if (connection?.db_type === "sqlite") return database === normalizeSqliteNamespace(connection.database, connection);
return !!connection?.database && !!database && connection.database === database;
}
@@ -0,0 +1,36 @@
import type { ConnectionConfig } from "@/types/database";
const WINDOWS_DRIVE_PATH_RE = /^[a-z]:[\\/]/i;
type SqliteNamespaceConnection = Partial<Pick<ConnectionConfig, "host" | "database">>;
export function isSqliteFileNamespace(value: string | undefined, connection?: SqliteNamespaceConnection): boolean {
const normalized = value?.trim() || "";
if (!normalized) return false;
const lower = normalized.toLowerCase();
const connectionHost = connection?.host?.trim() || "";
return (
lower === ":memory:" ||
lower.startsWith("file:") ||
lower.startsWith("sqlite:") ||
WINDOWS_DRIVE_PATH_RE.test(normalized) ||
normalized.startsWith("/") ||
normalized.startsWith("\\") ||
normalized.startsWith("~/") ||
normalized.startsWith("./") ||
normalized.startsWith("../") ||
normalized.includes("/") ||
normalized.includes("\\") ||
normalized === connectionHost
);
}
export function normalizeSqliteNamespace(value: string | undefined, connection?: SqliteNamespaceConnection): string {
const normalized = value?.trim() || "";
return !normalized || isSqliteFileNamespace(normalized, connection) ? "main" : normalized;
}
export function normalizeStoredConnectionDatabase(dbType: ConnectionConfig["db_type"], database: string | undefined): string | undefined {
return dbType === "sqlite" ? undefined : database;
}
@@ -1,5 +1,6 @@
import type { HistoryEntry } from "@/lib/backend/api";
import { resolveDefaultDatabase } from "@/lib/database/defaultDatabase";
import { normalizeSqliteNamespace } from "@/lib/database/sqliteNamespace";
import type { ConnectionConfig, QueryTab } from "@/types/database";
export interface HistorySqlRestoreTarget {
@@ -13,7 +14,8 @@ export function resolveHistorySqlRestoreTarget(options: { entry: HistoryEntry; a
const connectionId = entry.connection_id || activeTab?.connectionId || firstConnectionId;
if (!connectionId) return null;
const config = getConfig(connectionId);
const database = entry.database || activeTab?.database || (config ? resolveDefaultDatabase(config, []) : "");
const storedDatabase = entry.database || activeTab?.database || (config ? resolveDefaultDatabase(config, []) : "");
const database = config?.db_type === "sqlite" ? normalizeSqliteNamespace(storedDatabase, config) : storedDatabase;
const schema = activeTab?.connectionId === connectionId && activeTab.database === database ? activeTab.schema : undefined;
return { connectionId, database: database || "", schema };
}
@@ -177,7 +177,9 @@ function parseJdbcUrl(jdbcUrl: string): {
const fileMatch = url.match(/^(sqlite|duckdb):(.+)$/i);
if (fileMatch) {
result.host = expandPathMacros(fileMatch[2].split("?")[0]);
result.database = result.host;
if (fileMatch[1].toLowerCase() !== "sqlite") {
result.database = result.host;
}
return result;
}
@@ -171,7 +171,6 @@ function parseJdbcUrl(url: string, profile: ConnectionProfile) {
const sqliteMatch = withoutJdbc.match(/^sqlite:(.+)$/i);
if (sqliteMatch) {
result.host = sqliteMatch[1];
result.database = sqliteMatch[1];
return result;
}
@@ -221,8 +220,9 @@ function buildConnection(entry: DbeaverConnectionEntry, credentials: ReturnType<
const config = entry.configuration || {};
const url = getString(config.url);
const parsedUrl = parseJdbcUrl(url, profile);
const host = getString(config.host || config["host-name"] || parsedUrl.host || (profile.dbType === "sqlite" ? "" : "127.0.0.1"));
const database = getString(config.database || config["database-name"] || config.schema || parsedUrl.database);
const configuredDatabase = getString(config.database || config["database-name"] || config.schema || parsedUrl.database);
const host = getString(config.host || config["host-name"] || parsedUrl.host || (profile.dbType === "sqlite" ? configuredDatabase : "127.0.0.1"));
const database = profile.dbType === "sqlite" ? "" : configuredDatabase;
const name = getString(entry.name || database || host || profile.label);
if (!entry.id || !name) return null;
@@ -300,7 +300,7 @@ async function parseConnection(node: ParsedNode): Promise<ConnectionConfig | nul
const name = getAny(node.values, ["name", "connectionName", "connName", "caption", "title"]) || getAny(node.values, ["host", "server", "hostname"]) || sqlitePath || effectiveProfile.label;
const host = sqlitePath || getAny(node.values, ["host", "server", "hostname", "serverHost", "address"]) || (effectiveProfile.dbType === "sqlite" ? "" : "127.0.0.1");
// Navicat exports OceanBase Oracle connections with Database="ORCL", but OceanBase resolves the target from the username.
const database = effectiveProfile.dbType === "sqlite" ? sqlitePath : effectiveProfile.dbType === "oceanbase-oracle" ? "" : getAny(node.values, ["database", "databaseName", "initialDatabase", "serviceName", "sid", "schema"]);
const database = effectiveProfile.dbType === "sqlite" ? "" : effectiveProfile.dbType === "oceanbase-oracle" ? "" : getAny(node.values, ["database", "databaseName", "initialDatabase", "serviceName", "sid", "schema"]);
const isOracleLike = effectiveProfile.dbType === "oracle" || effectiveProfile.dbType === "oceanbase-oracle";
const oracleConnectionType = isOracleLike && getAny(node.values, ["sid"]) ? "sid" : isOracleLike ? "service_name" : undefined;
const username = getAny(node.values, ["user", "username", "userName", "uid"]) || profile.user;
+8 -3
View File
@@ -1,4 +1,5 @@
import { resolveDefaultDatabase } from "@/lib/database/defaultDatabase";
import { normalizeSqliteNamespace } from "@/lib/database/sqliteNamespace";
import { qualifiedTableName } from "@/lib/table/tableSelectSql";
import type { ConnectionConfig, DatabaseType, QueryTab, TreeNode } from "@/types/database";
@@ -16,7 +17,7 @@ interface ResolveNewQueryTargetInput {
activeTab?: Pick<QueryTab, "connectionId" | "database" | "schema" | "catalog" | "objectBrowser" | "tableMeta">;
selectedTreeNode?: Pick<TreeNode, "connectionId" | "database" | "schema" | "catalog"> | null;
activeConnectionId?: string | null;
connections: Pick<ConnectionConfig, "id" | "database">[];
connections: Pick<ConnectionConfig, "id" | "host" | "database" | "db_type">[];
preferredSource?: NewQueryContextSource;
}
@@ -49,11 +50,15 @@ export function resolveNewQueryTarget(input: ResolveNewQueryTargetInput): NewQue
: null;
}
function targetFromContext(context: Pick<QueryTab, "connectionId" | "database" | "schema" | "catalog" | "objectBrowser" | "tableMeta"> | Pick<TreeNode, "connectionId" | "database" | "schema" | "catalog"> | undefined, connections: Pick<ConnectionConfig, "id" | "database">[]): NewQueryTarget | null {
function targetFromContext(
context: Pick<QueryTab, "connectionId" | "database" | "schema" | "catalog" | "objectBrowser" | "tableMeta"> | Pick<TreeNode, "connectionId" | "database" | "schema" | "catalog"> | undefined,
connections: Pick<ConnectionConfig, "id" | "host" | "database" | "db_type">[],
): NewQueryTarget | null {
if (!context?.connectionId) return null;
const connection = connections.find((item) => item.id === context.connectionId);
if (!connection) return null;
const database = context.database || resolveDefaultDatabase(connection, []);
const contextDatabase = context.database || resolveDefaultDatabase(connection, []);
const database = connection.db_type === "sqlite" ? normalizeSqliteNamespace(contextDatabase, connection) : contextDatabase;
const objectBrowser = "objectBrowser" in context ? context.objectBrowser : undefined;
const tableMeta = "tableMeta" in context ? context.tableMeta : undefined;
return {