feat(sql): add schema qualification completion setting

Closes #9219
This commit is contained in:
t8y2 authored and t8y2 committed 2026-09-27 12:04:10 +08:00
1 parent 4a7b8f0f27
commit 627a8498d0
27 files changed
+339 -15

No files matched your search

@@ -30,6 +30,7 @@ function semanticCompletion(markedSql: string, input: Partial<SqlCompletionProvi
databaseType: options.databaseType,
keywordCase: input.keywordCase,
autoAliasTables: input.autoAliasTables,
tableCompletionSchemaQualification: input.tableCompletionSchemaQualification,
});
return { sql, cursor, model, context, items };
}
@@ -1365,7 +1365,7 @@ describe("sqlCompletion scoped metadata ranking", () => {
expect(items.findIndex((item) => item.label === "ORDERS_10K")).toBeLessThan(items.findIndex((item) => item.label === "TABLE"));
});
it("qualifies same-name PostgreSQL tables from different schemas", () => {
it("uses on-collision qualification by default for same-name PostgreSQL tables", () => {
const sql = "SELECT * FROM shared";
const items = buildSqlCompletionItems(sql, sql.length, {
databaseType: "postgres",
@@ -1381,6 +1381,86 @@ describe("sqlCompletion scoped metadata ranking", () => {
expect(items.map((item) => item.apply).sort()).toEqual(["public.shared", "reporting.shared"]);
});
it("never qualifies table names while keeping colliding candidates distinct", () => {
const sql = "SELECT * FROM shared";
const items = buildSqlCompletionItems(sql, sql.length, {
databaseType: "postgres",
dialect: "postgres",
tables: [
{ name: "shared", schema: "public", type: "table", applyName: "public.shared" },
{ name: "shared", schema: "reporting", type: "view", applyName: "reporting.shared" },
],
columnsByTable: new Map(),
tableCompletionSchemaQualification: "never",
}).filter((item) => item.type === "table");
expect(items).toHaveLength(2);
expect(items.map((item) => item.apply)).toEqual(["shared", "shared"]);
expect(items.map((item) => item.detail).sort()).toEqual(["public.shared", "reporting.shared"]);
});
it("always qualifies tables and views when schema metadata is available", () => {
const sql = "SELECT * FROM ";
const items = buildSqlCompletionItems(sql, sql.length, {
databaseType: "postgres",
dialect: "postgres",
tables: [
{ name: "Order Details", schema: "Sales Data", type: "view" },
{ name: "scratch", type: "table" },
],
columnsByTable: new Map(),
tableCompletionSchemaQualification: "always",
}).filter((item) => item.type === "table");
expect(items.find((item) => item.label === "Order Details")?.apply).toBe('"Sales Data"."Order Details"');
expect(items.find((item) => item.label === "scratch")?.apply).toBe("scratch");
});
it.each([
["never", "customers"],
["always", "sales.customers"],
] as const)("applies the %s policy to foreign-key table suggestions", (tableCompletionSchemaQualification, expectedApply) => {
const sql = "SELECT * FROM sales.orders o JOIN cus";
const items = buildSqlCompletionItems(sql, sql.length, {
databaseType: "postgres",
dialect: "postgres",
tables: [
{ name: "orders", schema: "sales", type: "table" },
{ name: "customers", schema: "sales", type: "table" },
],
columnsByTable: new Map(),
foreignKeysByTable: new Map([["sales.orders", [{ name: "orders_customer_id_fkey", column: "customer_id", ref_table: "customers", ref_schema: "sales", ref_column: "id" }]]]),
tableCompletionSchemaQualification,
});
const customers = items.filter((item) => item.type === "table" && item.label === "customers");
expect(customers).toHaveLength(1);
expect(customers[0]?.apply).toBe(expectedApply);
expect(customers[0]?.detail).toContain("related by");
});
it("does not repeat an already typed quoted schema or SQL Server database/schema qualifier", () => {
const postgresSql = 'SELECT * FROM "Sales Data".Ord';
const postgresItems = buildSqlCompletionItems(postgresSql, postgresSql.length, {
databaseType: "postgres",
dialect: "postgres",
tables: [{ name: "Order Details", schema: "Sales Data", type: "table" }],
columnsByTable: new Map(),
tableCompletionSchemaQualification: "always",
});
const sqlServerSql = "SELECT * FROM Reporting.dbo.Ord";
const sqlServerItems = buildSqlCompletionItems(sqlServerSql, sqlServerSql.length, {
databaseType: "sqlserver",
dialect: "sqlserver",
tables: [{ name: "Order Details", database: "Reporting", schema: "dbo", type: "table" }],
columnsByTable: new Map(),
tableCompletionSchemaQualification: "always",
});
expect(postgresItems.find((item) => item.label === "Order Details")?.apply).toBe('"Order Details"');
expect(sqlServerItems.find((item) => item.label === "Order Details")?.apply).toBe("[Order Details]");
});
it("qualifies same-name tables for generic metadata providers", () => {
const sql = "SELECT * FROM orders";
const items = buildSqlCompletionItems(sql, sql.length, {
@@ -136,6 +136,10 @@ describe("EDITOR_SETTINGS_DRAFT_KEYS", () => {
expect(EDITOR_SETTINGS_DRAFT_KEYS).toContain("completionTriggerMode");
});
it("includes tableCompletionSchemaQualification", () => {
expect(EDITOR_SETTINGS_DRAFT_KEYS).toContain("tableCompletionSchemaQualification");
});
it("includes tableHoverLookupMode", () => {
expect(EDITOR_SETTINGS_DRAFT_KEYS).toContain("tableHoverLookupMode");
});
@@ -231,6 +235,11 @@ describe("editorSettingsDraftFromSettings", () => {
const draft = editorSettingsDraftFromSettings(makeSettings({ completionTriggerMode: "always" as unknown } as Partial<EditorSettings>));
expect(draft.completionTriggerMode).toBe("positional");
});
it("maps and normalizes tableCompletionSchemaQualification", () => {
expect(editorSettingsDraftFromSettings(makeSettings({ tableCompletionSchemaQualification: "always" })).tableCompletionSchemaQualification).toBe("always");
expect(editorSettingsDraftFromSettings(makeSettings({ tableCompletionSchemaQualification: "invalid" } as any)).tableCompletionSchemaQualification).toBe("collision");
});
});
describe("normalizeTableOpenPageSizeDraft", () => {
@@ -406,6 +415,16 @@ describe("editorSettingsPatchFromDraft", () => {
const patch = editorSettingsPatchFromDraft(draft, base);
expect(patch.completionTriggerMode).toBeUndefined();
});
it("includes tableCompletionSchemaQualification only when changed", () => {
const settings = makeSettings({ tableCompletionSchemaQualification: "collision" });
const draft = editorSettingsDraftFromSettings(settings);
const base = editorSettingsDraftFromSettings(settings);
expect(editorSettingsPatchFromDraft(draft, base).tableCompletionSchemaQualification).toBeUndefined();
draft.tableCompletionSchemaQualification = "never";
expect(editorSettingsPatchFromDraft(draft, base).tableCompletionSchemaQualification).toBe("never");
});
});
describe("EDITOR_SETTINGS_DRAFT_KEYS - tabLayout", () => {
@@ -295,6 +295,7 @@ describe("settings search", () => {
{ titleKey: "settings.sidebarObjectInfoMode", category: "navigation", targetId: "navigation" },
{ titleKey: "settings.insertSpaceAfterCompletion", category: "editor", targetId: "editor" },
{ titleKey: "settings.completionTriggerMode", category: "editor", targetId: "editor" },
{ titleKey: "settings.tableCompletionSchemaQualification", category: "editor", targetId: "editor" },
{ titleKey: "settings.autoAliasTables", category: "editor", targetId: "editor" },
{ titleKey: "settings.clickTableNavigationTarget", category: "navigation", targetId: "navigation" },
{ titleKey: "settings.prefillNewQueryWithSelect", category: "navigation", targetId: "navigation" },
@@ -68,6 +68,18 @@ describe("settingsTransfer", () => {
expect(result.error.detail).toContain("updateDownloadSource");
});
it("round-trips table completion schema qualification as an editor setting", () => {
const result = parseSettingsTransferFile(fileWith({ tableCompletionSchemaQualification: "always" }));
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.editorSettings.tableCompletionSchemaQualification).toBe("always");
expect(result.value.categories).toEqual(["editor"]);
const invalid = parseSettingsTransferFile(fileWith({ tableCompletionSchemaQualification: "sometimes" }));
expect(invalid.ok).toBe(false);
if (!invalid.ok) expect(invalid.error.detail).toContain("tableCompletionSchemaQualification");
});
it("rejects out-of-range numbers that the normalizer clamps", () => {
const result = parseSettingsTransferFile(fileWith({ sidebarIndent: 99999 }));
expect(result.ok).toBe(false);
@@ -4,6 +4,7 @@ import { normalizeResultPageSize } from "@/lib/dataGrid/paginationPageSize";
import { normalizeQueryResultMaxRows } from "@/lib/dataGrid/queryResultRowLimit";
import { normalizeExternalSqlEditorMaxMb } from "@/lib/sql/sqlFileOpen";
import { normalizeCompletionTriggerMode } from "@/lib/sql/sqlCompletionTriggerPolicy";
import { normalizeSqlTableCompletionSchemaQualification } from "@/lib/sql/sqlCompletionSchemaQualification";
import { normalizeTableHoverLookupMode } from "@/lib/editor/hoverTableLookup";
import { normalizeRedisKeyTemplates } from "@/lib/redis/redisKeyTemplates";
@@ -25,6 +26,7 @@ export const EDITOR_SETTINGS_DRAFT_KEYS = [
"showCurrentStatementFrame",
"showInsertValueHints",
"autoAliasTables",
"tableCompletionSchemaQualification",
"insertSpaceAfterCompletion",
"sqlServerSpaceConfirmsCompletion",
"sortCompletionColumnsAlphabetically",
@@ -158,6 +160,7 @@ function normalizedDraftValue(key: EditorSettingsDraftKey, value: unknown): unkn
if (key === "queryResultMaxRows") return normalizeQueryResultMaxRowsDraft(value);
if (key === "externalSqlEditorMaxMb") return normalizeExternalSqlEditorMaxMb(value);
if (key === "completionTriggerMode") return normalizeCompletionTriggerMode(value);
if (key === "tableCompletionSchemaQualification") return normalizeSqlTableCompletionSchemaQualification(value);
if (key === "tableHoverLookupMode") return normalizeTableHoverLookupMode(value);
if (key === "redisKeyTemplates") return normalizeRedisKeyTemplates(value);
if (key === "backgroundImage") return normalizeBackgroundImageSettings(value);
@@ -145,6 +145,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
{ id: "editor-completion-spacing", category: "editor", titleKey: "settings.insertSpaceAfterCompletion", descriptionKey: "settings.insertSpaceAfterCompletionDescription", targetId: "editor" },
{ id: "editor-sqlserver-space-completion", category: "editor", titleKey: "settings.sqlServerSpaceConfirmsCompletion", descriptionKey: "settings.sqlServerSpaceConfirmsCompletionDescription", targetId: "editor", visible: sqlServerSpaceCompletionVisible },
{ id: "editor-completion-trigger-mode", category: "editor", titleKey: "settings.completionTriggerMode", descriptionKey: "settings.completionTriggerModeDescription", targetId: "editor" },
{ id: "editor-table-completion-schema-qualification", category: "editor", titleKey: "settings.tableCompletionSchemaQualification", descriptionKey: "settings.tableCompletionSchemaQualificationDescription", targetId: "editor" },
{ id: "editor-auto-alias", category: "editor", titleKey: "settings.autoAliasTables", descriptionKey: "settings.autoAliasTablesDescription", targetId: "editor" },
{ id: "editor-unsaved-close", category: "editor", titleKey: "settings.confirmUnsavedSqlClose", descriptionKey: "settings.confirmUnsavedSqlCloseDescription", targetId: "editor" },
{ id: "editor-app-close-unsaved-tabs", category: "editor", titleKey: "settings.appCloseUnsavedTabsMode", descriptionKey: "settings.appCloseUnsavedTabsModeDescription", targetId: "editor" },
@@ -83,6 +83,7 @@ const SETTINGS_TRANSFER_CATEGORY_KEYS: Record<SettingsTransferCategoryId, readon
"showCurrentStatementFrame",
"showInsertValueHints",
"autoAliasTables",
"tableCompletionSchemaQualification",
"insertSpaceAfterCompletion",
"sqlServerSpaceConfirmsCompletion",
"sortCompletionColumnsAlphabetically",
+31 -12
View File
@@ -21,6 +21,7 @@ import { driverProfileCompletionObjects, driverProfileCompletionTableMetadata, d
import { DORIS_FUNCTION_DOCS, DORIS_FUNCTION_SIGNATURES } from "@/lib/sql/doris/functions";
import { rejectsAliasReferenceInHaving } from "@/lib/database/databaseFeatureSupport";
import { isOracleCompletionDatabase } from "@/lib/sql/oracleCompletionSession";
import { normalizeSqlTableCompletionSchemaQualification, type SqlTableCompletionSchemaQualification } from "@/lib/sql/sqlCompletionSchemaQualification";
export { DEFAULT_SQL_SNIPPETS, resolveSqlSnippetBodyForDatabase } from "@/lib/sql/sqlSnippetTemplates";
@@ -1616,6 +1617,7 @@ export interface SqlCompletionProviderInput {
keywordCase?: SqlKeywordCase;
functionCase?: SqlKeywordCase;
autoAliasTables?: boolean;
tableCompletionSchemaQualification?: SqlTableCompletionSchemaQualification;
quoteIdentifiers?: boolean;
}
@@ -1636,6 +1638,7 @@ export function buildSqlCompletionItems(
keywordCase?: SqlKeywordCase;
functionCase?: SqlKeywordCase;
autoAliasTables?: boolean;
tableCompletionSchemaQualification?: SqlTableCompletionSchemaQualification;
quoteIdentifiers?: boolean;
},
): SqlCompletionItem[] {
@@ -1768,8 +1771,9 @@ class SqlCompletionProvider {
if (!context.exclusiveColumnSuggestions && context.suggestTables) {
const autoAliasTables = !!this.input.autoAliasTables && context.autoAliasTableCompletions && !context.tableCompletionTargetAliasUnsafe && supportsTableAliases(this.databaseType);
this.items.push(...buildForeignKeyRelatedTableItems(context, completionTables, this.input.foreignKeysByTable, this.dialect, autoAliasTables, this.databaseType, this.input.currentSchema));
this.items.push(...buildTableItems(context, completionTables, this.dialect, autoAliasTables, context.referencedTables, this.databaseType, this.input.currentSchema));
const schemaQualification = normalizeSqlTableCompletionSchemaQualification(this.input.tableCompletionSchemaQualification);
this.items.push(...buildForeignKeyRelatedTableItems(context, completionTables, this.input.foreignKeysByTable, this.dialect, autoAliasTables, this.databaseType, this.input.currentSchema, schemaQualification));
this.items.push(...buildTableItems(context, completionTables, this.dialect, autoAliasTables, context.referencedTables, this.databaseType, this.input.currentSchema, schemaQualification));
if (this.databaseType === "clickhouse") {
this.items.push(...buildClickHouseFunctionItems(context.prefix, context.openingParenAfterCursor, "table"));
}
@@ -3932,27 +3936,30 @@ function resolveTableSchemaQualification(
databaseType: DatabaseType | undefined,
currentSchema: string | undefined,
schemasByTableName: Map<string, Set<string>>,
schemaQualificationMode: SqlTableCompletionSchemaQualification,
): { ambiguousTableName: boolean; schemaQualification: boolean; defaultApplyName: string } {
const oracleSchemaQualification = isOracleCompletionDatabase(databaseType) && table.schema && table.schema.toUpperCase() !== "PUBLIC" && (!currentSchema || normalizeIdentifierPart(table.schema) !== normalizeIdentifierPart(currentSchema));
// A bare table name is ambiguous when metadata contains the same name in multiple schemas.
// Keep Oracle's current-schema behavior, but qualify the generic/PostgreSQL/SQL Server paths.
// Collision mode keeps Oracle's current-schema behavior and qualifies the
// generic/PostgreSQL/SQL Server paths only when metadata is ambiguous.
const ambiguousTableName = !isOracleCompletionDatabase(databaseType) && (schemasByTableName.get(normalizeIdentifierPart(table.name))?.size ?? 0) > 1;
const schemaQualification = !!table.schema && (oracleSchemaQualification || ambiguousTableName);
const schemaQualification = !!table.schema && (schemaQualificationMode === "always" || (schemaQualificationMode === "collision" && (oracleSchemaQualification || ambiguousTableName)));
const defaultApplyName = schemaQualification ? `${quoteCompletionApplyIdentifier(table.schema!, dialect)}.${quoteCompletionApplyIdentifier(table.name, dialect)}` : quoteCompletionApplyIdentifier(table.name, dialect);
return { ambiguousTableName, schemaQualification, defaultApplyName };
}
function buildTableItems(
context: Pick<SqlCompletionContext, "prefix" | "qualifier">,
context: Pick<SqlCompletionContext, "prefix" | "qualifier" | "qualifierParts">,
tables: SqlCompletionTable[],
dialect?: SqlCompletionApplyDialect,
autoAliasTables = false,
referencedTables: SqlCompletionReferencedTable[] = [],
databaseType?: DatabaseType,
currentSchema?: string,
schemaQualificationMode: SqlTableCompletionSchemaQualification = "collision",
): SqlCompletionItem[] {
const { prefix } = context;
const qualifierSchema = context.qualifier?.split(".").filter(Boolean).pop();
const qualifierSchema = context.qualifierParts?.[context.qualifierParts.length - 1] ?? context.qualifier?.split(".").filter(Boolean).pop();
const existingAliases = new Set(referencedTables.map((ref) => ref.alias?.toLowerCase()).filter((alias): alias is string => !!alias));
const matchingTables = tables.filter((table) => matchesPrefix(table.name, prefix));
// Ambiguity is decided among prefix-matching tables only, matching prior behavior.
@@ -3960,11 +3967,19 @@ function buildTableItems(
return matchingTables
.map((table) => {
const qualifiedByContext = !!qualifierSchema && !!table.schema && normalizeIdentifierPart(qualifierSchema) === normalizeIdentifierPart(table.schema);
const { ambiguousTableName, defaultApplyName } = resolveTableSchemaQualification(table, dialect, databaseType, currentSchema, schemasByTableName);
const { ambiguousTableName, defaultApplyName } = resolveTableSchemaQualification(table, dialect, databaseType, currentSchema, schemasByTableName, schemaQualificationMode);
const unqualifiedApplyName = quoteCompletionApplyIdentifier(table.name, dialect);
const rawSuppliedApplyName = table.applyName?.trim();
const suppliedApplyName = dialect === "sqlserver" && rawSuppliedApplyName ? quoteCompletionApplyName(rawSuppliedApplyName, dialect) : rawSuppliedApplyName;
const suppliedApplyNameIsQualified = suppliedApplyName?.includes(".") === true;
const applyName = qualifiedByContext ? quoteCompletionApplyIdentifier(table.name, dialect) : ambiguousTableName && !!table.schema && (!suppliedApplyName || !suppliedApplyNameIsQualified) ? defaultApplyName : (suppliedApplyName ?? defaultApplyName);
const applyName =
qualifiedByContext || schemaQualificationMode === "never"
? unqualifiedApplyName
: schemaQualificationMode === "always" && table.schema
? defaultApplyName
: ambiguousTableName && table.schema && (!suppliedApplyName || !suppliedApplyNameIsQualified)
? defaultApplyName
: (suppliedApplyName ?? defaultApplyName);
const alias = autoAliasTables ? generateTableCompletionAlias(table.name, existingAliases) : "";
const schemaDetail = ambiguousTableName && table.schema ? `${table.schema}.${table.name}` : undefined;
const detail = table.detail && schemaDetail ? `${schemaDetail} ${table.detail}` : (table.detail ?? schemaDetail ?? (table.type === "table" ? undefined : table.type));
@@ -3974,7 +3989,7 @@ function buildTableItems(
detail,
apply: formatTableAliasApply(applyName, alias),
boost: computeBoost(table.name, prefix) + 1000 + (table.boost ?? 0),
dedupeKey: table.applyName || ambiguousTableName || (isOracleCompletionDatabase(databaseType) && table.schema) ? applyName : undefined,
dedupeKey: schemaQualificationMode === "never" && table.schema ? `${quoteCompletionApplyIdentifier(table.schema, dialect)}.${unqualifiedApplyName}` : table.applyName || ambiguousTableName || (isOracleCompletionDatabase(databaseType) && table.schema) ? applyName : undefined,
};
})
.sort(compareCompletionItems)
@@ -3989,6 +4004,7 @@ function buildForeignKeyRelatedTableItems(
autoAliasTables = false,
databaseType?: DatabaseType,
currentSchema?: string,
schemaQualificationMode: SqlTableCompletionSchemaQualification = "collision",
): SqlCompletionItem[] {
if (!foreignKeysByTable || context.referencedTables.length === 0) return [];
const candidates = new Map<string, { table: SqlCompletionTable; detail: string }>();
@@ -4016,11 +4032,14 @@ function buildForeignKeyRelatedTableItems(
// `schema.table` exactly when regular candidates would. Built from the same
// prefix-matching table set buildTableItems uses, keeping the two in lockstep.
const schemasByTableName = collectSchemasByTableName(tables.filter((table) => matchesPrefix(table.name, context.prefix)));
const qualifierSchema = context.qualifierParts?.[context.qualifierParts.length - 1] ?? context.qualifier?.split(".").filter(Boolean).pop();
return [...candidates.values()]
.map(({ table, detail }) => {
const { ambiguousTableName, defaultApplyName } = resolveTableSchemaQualification(table, dialect, databaseType, currentSchema, schemasByTableName);
const applyName = defaultApplyName;
const qualifiedByContext = !!qualifierSchema && !!table.schema && normalizeIdentifierPart(qualifierSchema) === normalizeIdentifierPart(table.schema);
const { ambiguousTableName, defaultApplyName } = resolveTableSchemaQualification(table, dialect, databaseType, currentSchema, schemasByTableName, schemaQualificationMode);
const unqualifiedApplyName = quoteCompletionApplyIdentifier(table.name, dialect);
const applyName = qualifiedByContext || schemaQualificationMode === "never" ? unqualifiedApplyName : defaultApplyName;
const alias = autoAliasTables ? generateTableCompletionAlias(table.name, existingAliases) : "";
return {
label: table.name,
@@ -4030,7 +4049,7 @@ function buildForeignKeyRelatedTableItems(
boost: computeBoost(table.name, context.prefix) + 3600,
// Mirror buildTableItems' dedupeKey so an FK candidate and the regular
// candidate for the same schema-qualified table collapse to one entry.
dedupeKey: ambiguousTableName || (isOracleCompletionDatabase(databaseType) && table.schema) ? applyName : undefined,
dedupeKey: schemaQualificationMode === "never" && table.schema ? `${quoteCompletionApplyIdentifier(table.schema, dialect)}.${unqualifiedApplyName}` : ambiguousTableName || (isOracleCompletionDatabase(databaseType) && table.schema) ? applyName : undefined,
};
})
.sort(compareCompletionItems);
@@ -0,0 +1,8 @@
export type SqlTableCompletionSchemaQualification = "never" | "collision" | "always";
export const DEFAULT_SQL_TABLE_COMPLETION_SCHEMA_QUALIFICATION: SqlTableCompletionSchemaQualification = "collision";
export function normalizeSqlTableCompletionSchemaQualification(value: unknown): SqlTableCompletionSchemaQualification {
if (value === "never" || value === "collision" || value === "always") return value;
return DEFAULT_SQL_TABLE_COMPLETION_SCHEMA_QUALIFICATION;
}