feat(editor): 支持 SELECT * 展开为字段列表

* ✨ feat(editor): 支持将 SELECT * 展开为字段列表

- 新增右键菜单及 `Mod+Shift+X` 快捷键,可展开 `*` 和 `别名.*`
- 基于语义分析识别单表来源、别名及原始引用符,并按数据库方言处理字段名转义
- 优先读取本地或远程表字段元数据,单表纯星号查询可回退使用执行结果字段
- 增加字段加载失败提示及多语言文案
- 补充星号展开、结果匹配和快捷键注册测试

* fix(editor): selectStar 回退加词边界检查并记录加载失败

---------

Co-authored-by: t8y2 <t8y2@users.noreply.github.com>
Co-authored-by: skyler <1156263951@qq.com>
This commit is contained in:
authored and GitHub committed 2026-08-06 00:55:36 +08:00
1 parent fa6540b739
commit 5c281b1653
18 files changed
+473 -17

No files matched your search

@@ -42,6 +42,14 @@ describe("shortcutRegistry editor actions", () => {
expect(findShortcutConflict("executeSqlInNewResultTab", DEFAULT_SHORTCUT_SETTINGS.executeSqlInNewResultTab, DEFAULT_SHORTCUT_SETTINGS)).toBeNull();
});
it("registers a conflict-free shortcut for expanding SELECT stars", () => {
const definition = SHORTCUT_DEFINITIONS.find((item) => item.id === "expandSelectStar");
expect(definition).toMatchObject({ scope: "editor", defaultShortcut: "Mod+Shift+X" });
expect(shortcutToCodeMirrorKey(DEFAULT_SHORTCUT_SETTINGS.expandSelectStar)).toBe("Mod-Shift-x");
expect(findShortcutConflict("expandSelectStar", DEFAULT_SHORTCUT_SETTINGS.expandSelectStar, DEFAULT_SHORTCUT_SETTINGS)).toBeNull();
});
it("resolves the close-other-tabs default per platform and heals cross-platform synced defaults", () => {
// 本测试环境(darwin):默认应为 macOS 组合
expect(DEFAULT_SHORTCUT_SETTINGS.closeOtherTabs).toBe(closeOtherTabsDefaultShortcut());
+41 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { sqlSemanticCompletionScope, sqlSemanticLocalColumnsByTable, sqlSemanticProjectionAliasColumns } from "@/lib/sql/semantic/completion";
import { sqlSemanticCompletionScope, sqlSemanticLocalColumnsByTable, sqlSemanticProjectionAliasColumns, sqlSemanticSelectStarIsOnlyProjection, sqlSemanticSelectStarQualifierSql, sqlSemanticSelectStarTableSource } from "@/lib/sql/semantic/completion";
import { SQL_SEMANTIC_BASELINE_FIXTURES, sqlFixtureCursor } from "@/lib/sql/semantic/fixtures";
import { buildSqlSemanticModel, sqlSemanticTableNameSpans } from "@/lib/sql/semantic/model";
@@ -29,6 +29,46 @@ describe("sqlSemanticModel baseline fixtures", () => {
});
}
it("does not treat SELECT as the qualifier of an unqualified star", () => {
const { sql, cursor } = sqlFixtureCursor("select *| from apis as ap");
const model = buildSqlSemanticModel(sql, cursor);
expect(model.cursorIntent).toEqual(expect.objectContaining({ kind: "star", qualifierParts: [] }));
});
it("retains the qualifier of a qualified star", () => {
const { sql, cursor } = sqlFixtureCursor("select ap.*| from apis as ap");
const model = buildSqlSemanticModel(sql, cursor);
expect(model.cursorIntent).toEqual(expect.objectContaining({ kind: "star", qualifierParts: ["ap"], targetSourceId: model.rowSources[0]?.id }));
});
it("does not resolve an unqualified star to the only physical table among multiple row sources", () => {
const { sql, cursor } = sqlFixtureCursor("select *| from users u join (select 1 as x) s on 1 = 1");
const model = buildSqlSemanticModel(sql, cursor);
expect(model.rowSources.map((source) => source.kind)).toEqual(["table", "subquery"]);
expect(sqlSemanticSelectStarTableSource(model)).toBeUndefined();
});
it.each([
["select *| from apis", true],
["select distinct *| from apis", true],
["select ap.*| from apis ap", true],
["select *, 1 as extra| from apis", false],
["select ap.*, 1 as extra| from apis ap", false],
] as const)("detects whether the star is the only projection in %s", (markedSql, expected) => {
const { sql, cursor } = sqlFixtureCursor(markedSql);
expect(sqlSemanticSelectStarIsOnlyProjection(buildSqlSemanticModel(sql, cursor))).toBe(expected);
});
it("retains the original quoting of a star qualifier", () => {
const { sql, cursor } = sqlFixtureCursor('select "Order Alias".*| from orders as "Order Alias"');
expect(sqlSemanticSelectStarQualifierSql(buildSqlSemanticModel(sql, cursor, { databaseType: "postgres", dialect: "postgres" }))).toBe('"Order Alias"');
});
it("does not mix row sources from inactive statements", () => {
const { sql, cursor } = sqlFixtureCursor("select * from users u; select * from orders o where o.|");
const model = buildSqlSemanticModel(sql, cursor);
@@ -1,5 +1,7 @@
import { describe, expect, it } from "vitest";
import { buildSqlCompletionItems, getSqlCompletionContext, shouldAutoOpenSqlCompletion } from "@/lib/sql/sqlCompletion";
import { buildSelectStarExpansion, buildSqlCompletionItems, getSqlCompletionContext, selectStarResultColumnsMatch, shouldAutoOpenSqlCompletion } from "@/lib/sql/sqlCompletion";
import { sqlCompletionContextFromSemantic } from "@/lib/sql/semantic/completion";
import { buildSqlSemanticModel } from "@/lib/sql/semantic/model";
describe("sqlCompletion keyword snippets", () => {
it("auto-opens and suggests SELECT when typing sel", () => {
@@ -14,6 +16,118 @@ describe("sqlCompletion keyword snippets", () => {
});
});
describe("SELECT star expansion", () => {
it("reuses completion column ordering for an unqualified star", () => {
const sql = "SELECT * FROM apis";
const context = getSqlCompletionContext(sql, "SELECT *".length);
expect(
buildSelectStarExpansion(
context,
new Map([
[
"apis",
[
{ name: "id", table: "apis" },
{ name: "created_at", table: "apis" },
{ name: "method", table: "apis" },
],
],
]),
),
).toBe("id, created_at, method");
});
it("preserves an alias while replacing only the star", () => {
const sql = "SELECT ap.* FROM apis AS ap";
const cursor = "SELECT ap.*".length;
const context = sqlCompletionContextFromSemantic(buildSqlSemanticModel(sql, cursor), getSqlCompletionContext(sql, cursor));
expect(
buildSelectStarExpansion(
context,
new Map([
[
"apis",
[
{ name: "id", table: "apis" },
{ name: "created_at", table: "apis" },
],
],
]),
),
).toBe("id, ap.created_at");
});
it.each([
["postgres", "postgres", '"Order Alias"', '"created at"'],
["mysql", "mysql", "`Order Alias`", "`created at`"],
["sqlserver", "sqlserver", "[Order Alias]", "[created at]"],
["oracle", "mysql", '"Order Alias"', '"created at"'],
] as const)("preserves a quoted %s alias for every expanded column", (databaseType, dialect, qualifierSql, quotedColumn) => {
const sql = `SELECT ${qualifierSql}.* FROM orders AS ${qualifierSql}`;
const cursor = sql.indexOf("*") + 1;
const context = sqlCompletionContextFromSemantic(buildSqlSemanticModel(sql, cursor, { databaseType, dialect }), getSqlCompletionContext(sql, cursor, { databaseType, dialect }));
expect(
buildSelectStarExpansion(
context,
new Map([
[
"orders",
[
{ name: "id", table: "orders" },
{ name: "created at", table: "orders" },
],
],
]),
dialect,
qualifierSql,
databaseType,
),
).toBe(`id, ${qualifierSql}.${quotedColumn}`);
});
it("expands an unqualified star from result columns when the table has an alias", () => {
const sql = "select *\nfrom apis as ap\nlimit 100;";
const cursor = "select *".length;
const context = sqlCompletionContextFromSemantic(buildSqlSemanticModel(sql, cursor), getSqlCompletionContext(sql, cursor));
expect(
buildSelectStarExpansion(
context,
new Map([
[
"apis",
[
{ name: "id", table: "apis" },
{ name: "created_at", table: "apis" },
{ name: "updated_at", table: "apis" },
{ name: "deleted_at", table: "apis" },
{ name: "method", table: "apis" },
],
],
]),
),
).toBe("id, created_at, updated_at, deleted_at, method");
});
it("accepts result columns only when their source still contains the target star", () => {
const currentSql = "select * from apis;\nselect * from users;";
const sourceStatement = "select * from users";
const sourceFrom = currentSql.lastIndexOf("select");
const targetFrom = currentSql.lastIndexOf("*");
expect(selectStarResultColumnsMatch({ currentSql, targetFrom, targetTo: targetFrom + 1, statementSql: sourceStatement, sourceStatement, sourceFrom, sourceTo: sourceFrom + sourceStatement.length })).toBe(true);
expect(selectStarResultColumnsMatch({ currentSql, targetFrom: currentSql.indexOf("*"), targetTo: currentSql.indexOf("*") + 1, statementSql: "select * from apis", sourceStatement, sourceFrom, sourceTo: sourceFrom + sourceStatement.length })).toBe(false);
});
it("rejects stale and incomplete result source metadata", () => {
expect(selectStarResultColumnsMatch({ currentSql: "select * from users", targetFrom: 7, targetTo: 8, statementSql: "select * from users", sourceStatement: "select * from apis" })).toBe(false);
expect(selectStarResultColumnsMatch({ currentSql: "select * from users", targetFrom: 7, targetTo: 8, statementSql: "select * from users", sourceStatement: "select * from users", sourceFrom: 0 })).toBe(false);
});
});
describe("sqlCompletion database functions", () => {
it("suggests ClickHouse functions with canonical casing and preferred placeholders", () => {
const sql = "SELECT tostart";
@@ -4,6 +4,7 @@ export type ShortcutActionId =
| "executeSql"
| "executeSqlInNewResultTab"
| "formatSql"
| "expandSelectStar"
| "toggleLineComment"
| "saveSql"
| "acceptCompletion"
@@ -103,6 +104,12 @@ export const SHORTCUT_DEFINITIONS: ShortcutDefinition[] = [
scope: "editor",
defaultShortcut: "Shift+Mod+F",
},
{
id: "expandSelectStar",
labelKey: "settings.shortcutExpandSelectStar",
scope: "editor",
defaultShortcut: "Mod+Shift+X",
},
{
id: "toggleLineComment",
labelKey: "settings.shortcutToggleLineComment",
@@ -1,6 +1,6 @@
import type { SqlCompletionColumn, SqlCompletionContext, SqlCompletionReferencedTable } from "@/lib/sql/sqlCompletion";
import { SQL_SEMANTIC_DIALECTS } from "@/lib/sql/semantic/dialect";
import type { SqlSemanticModel, SqlSemanticRowSource } from "@/lib/sql/semantic/types";
import type { SqlSemanticModel, SqlSemanticRowSource, SqlSemanticToken } from "@/lib/sql/semantic/types";
export type SqlSemanticCompletionScopeKind = "keyword" | "table" | "schema" | "catalog" | "routine" | "columns" | "local";
@@ -13,6 +13,61 @@ export interface SqlSemanticCompletionScope {
fallbackReason?: string;
}
function isSemanticIdentifier(token: SqlSemanticToken | undefined): boolean {
return token?.kind === "word" || token?.kind === "quoted_identifier";
}
function selectStarToken(model: SqlSemanticModel): SqlSemanticToken | undefined {
const range = model.cursorIntent.replacementRange;
if (model.cursorIntent.kind !== "star") return undefined;
return model.tokens.find((token) => token.text === "*" && token.span.start === range.start && token.span.end === range.end);
}
export function sqlSemanticSelectStarTableSource(model: SqlSemanticModel): SqlSemanticRowSource | undefined {
if (model.cursorIntent.kind !== "star") return undefined;
const source = model.cursorIntent.targetSourceId ? model.rowSources.find((candidate) => candidate.id === model.cursorIntent.targetSourceId) : model.rowSources.length === 1 ? model.rowSources[0] : undefined;
return source?.kind === "table" ? source : undefined;
}
export function sqlSemanticSelectStarQualifierSql(model: SqlSemanticModel): string | undefined {
const star = selectStarToken(model);
if (!star) return undefined;
const starIndex = model.tokens.indexOf(star);
let index = starIndex - 1;
if (model.tokens[index]?.text !== ".") return undefined;
const qualifierEnd = model.tokens[index]!.span.start;
index -= 1;
if (!isSemanticIdentifier(model.tokens[index])) return undefined;
let qualifierStart = model.tokens[index]!.span.start;
while (index >= 2 && model.tokens[index - 1]?.text === "." && isSemanticIdentifier(model.tokens[index - 2])) {
index -= 2;
qualifierStart = model.tokens[index]!.span.start;
}
return model.sql.slice(qualifierStart, qualifierEnd).trim() || undefined;
}
export function sqlSemanticSelectStarIsOnlyProjection(model: SqlSemanticModel): boolean {
const star = selectStarToken(model);
if (!star) return false;
let selectIndex = -1;
for (let index = model.tokens.length - 1; index >= 0; index -= 1) {
const token = model.tokens[index];
if (!token || token.span.end > star.span.start || token.depth !== star.depth) continue;
if (token.kind === "word" && token.normalized === "select") {
selectIndex = index;
break;
}
}
if (selectIndex < 0) return false;
const fromIndex = model.tokens.findIndex((token, index) => index > selectIndex && token.span.start >= star.span.end && token.depth === star.depth && token.kind === "word" && token.normalized === "from");
const projectionEnd = fromIndex >= 0 ? model.tokens[fromIndex]!.span.start : model.statement.span.end;
const projectionTokens = model.tokens.filter((token) => token.span.start >= model.tokens[selectIndex]!.span.end && token.span.end <= projectionEnd && token.kind !== "comment");
if (projectionTokens[0]?.kind === "word" && (projectionTokens[0].normalized === "all" || projectionTokens[0].normalized === "distinct")) projectionTokens.shift();
if (projectionTokens.pop() !== star) return false;
if (projectionTokens.length === 0) return true;
return projectionTokens.length % 2 === 0 && projectionTokens.every((token, index) => (index % 2 === 0 ? isSemanticIdentifier(token) : token.text === "."));
}
export function sqlSemanticReferencedTables(model: SqlSemanticModel): SqlCompletionReferencedTable[] {
return model.rowSources
.filter((source) => source.kind !== "unknown")
+2 -1
View File
@@ -675,7 +675,8 @@ function sourceForQualifier(sources: readonly SqlSemanticRowSource[], qualifierP
function starQualifierParts(before: readonly SqlSemanticToken[], starIndex: number, dialect: SqlSemanticDialectAdapter): string[] {
let index = starIndex - 1;
if (before[index]?.text === ".") index -= 1;
if (before[index]?.text !== ".") return [];
index -= 1;
const qualifierParts: string[] = [];
while (index >= 0) {
const identifier = before[index];
+38 -7
View File
@@ -11,6 +11,7 @@ import type { SqlSemanticBuildOptions, SqlSemanticSpan } from "@/lib/sql/semanti
import { DEFAULT_SQL_SNIPPETS, MANTICORESEARCH_SQL_SNIPPETS, resolveSqlSnippetBodyForDatabase } from "@/lib/sql/sqlSnippetTemplates";
import { requiresPostgresIdentifierQuote } from "@/lib/sql/sqlIdentifier";
import { containsHan, orderedSubsequenceSpan, pinyinFirstLetters } from "@/lib/common/pinyin";
import { quoteTableIdentifier } from "@/lib/table/tableSelectSql";
export { DEFAULT_SQL_SNIPPETS, resolveSqlSnippetBodyForDatabase } from "@/lib/sql/sqlSnippetTemplates";
@@ -2861,6 +2862,14 @@ export function quoteSqlIdentifier(identifier: string, dialect?: "mysql" | "post
const POSTGRES_IDENTIFIER_KEYWORDS = new Set(SQL_KEYWORDS.map((keyword) => keyword.toLowerCase()));
function quoteSelectStarColumnIdentifier(identifier: string, dialect?: "mysql" | "postgres" | "sqlserver", databaseType?: DatabaseType): string {
if (!requiresPostgresIdentifierQuote(identifier, POSTGRES_IDENTIFIER_KEYWORDS)) return identifier;
if (databaseType) return quoteTableIdentifier(databaseType, identifier);
if (dialect === "mysql") return `\`${identifier.replaceAll("`", "``")}\``;
if (dialect === "sqlserver") return `[${identifier.replaceAll("]", "]]")}]`;
return quoteSqlIdentifier(identifier, dialect);
}
function buildTableItems(
context: Pick<SqlCompletionContext, "prefix" | "qualifier">,
tables: SqlCompletionTable[],
@@ -3167,16 +3176,38 @@ function buildPreferredKeywordItems(prefix: string, keywords: string[], keywordC
}));
}
function buildStarExpansionItem(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>, t?: SqlCompletionTranslations, dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem | null {
function selectStarExpansionColumns(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>): SqlCompletionColumn[] {
const columns = context.qualifier ? referencedTablesForSelectAllColumns(context).flatMap((ref) => columnsForSelectAllReferencedTable(ref, columnsByTable)) : [...columnsByTable.values()].flat();
const uniqueColumns = uniqueColumnsByName(columns);
if (uniqueColumns.length === 0) return null;
return uniqueColumnsByName(columns);
}
export function selectStarResultColumnsMatch(options: { currentSql: string; targetFrom: number; targetTo: number; statementSql: string; sourceStatement?: string; sourceFrom?: number; sourceTo?: number }): boolean {
if (!options.sourceStatement) return false;
const hasSourceFrom = typeof options.sourceFrom === "number";
const hasSourceTo = typeof options.sourceTo === "number";
if (hasSourceFrom !== hasSourceTo) return false;
if (!hasSourceFrom || !hasSourceTo) return options.statementSql === options.sourceStatement;
// 词边界检查:已执行语句可能是当前内容的真前缀(如 `FROM users` → `FROM users_backup`),
// 此时 slice 仍与 sourceStatement 相等,会用旧表列回退到新表。要求 sourceTo 落在标识符边界。
const sourceToAtBoundary = !/[\w$]/.test(options.currentSql[options.sourceTo!] ?? "");
return options.targetFrom >= options.sourceFrom! && options.targetTo <= options.sourceTo! && sourceToAtBoundary && options.currentSql.slice(options.sourceFrom, options.sourceTo) === options.sourceStatement;
}
export function buildSelectStarExpansion(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>, dialect?: "mysql" | "postgres" | "sqlserver", qualifierSql = context.qualifier, databaseType?: DatabaseType): string | null {
const columns = selectStarExpansionColumns(context, columnsByTable);
if (columns.length === 0) return null;
// `alias.*` replaces only the `*`, so the first column must continue the already typed `alias.`.
const expansion = context.qualifier ? buildSelectAllColumnExpansion(uniqueColumns, context.qualifier, true, dialect) : uniqueColumns.map((column) => quoteSqlIdentifier(column.name, dialect)).join(", ");
return qualifierSql ? buildSelectAllColumnExpansion(columns, qualifierSql, true, dialect, databaseType) : columns.map((column) => quoteSelectStarColumnIdentifier(column.name, dialect, databaseType)).join(", ");
}
function buildStarExpansionItem(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>, t?: SqlCompletionTranslations, dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem | null {
const expansion = buildSelectStarExpansion(context, columnsByTable, dialect);
if (!expansion) return null;
const columnCount = selectStarExpansionColumns(context, columnsByTable).length;
return {
label: "* → columns",
type: "snippet" as const,
detail: `${(t?.starExpansionColumns ?? "{count} columns").replace("{count}", String(uniqueColumns.length))}: ${expansion.length > 60 ? expansion.slice(0, 57) + "..." : expansion}`,
detail: `${(t?.starExpansionColumns ?? "{count} columns").replace("{count}", String(columnCount))}: ${expansion.length > 60 ? expansion.slice(0, 57) + "..." : expansion}`,
apply: expansion,
boost: 1900,
};
@@ -3248,10 +3279,10 @@ function referencedTablesForSelectAllColumns(context: SqlCompletionContext): Sql
return context.referencedTables.filter((table) => referencedTableMatchesColumnQualifier(table, qualifier, qualifierLower, qualifiedTarget));
}
function buildSelectAllColumnExpansion(columns: SqlCompletionColumn[], qualifier: string | undefined, qualifierAlreadyTyped: boolean, dialect?: "mysql" | "postgres" | "sqlserver"): string {
function buildSelectAllColumnExpansion(columns: SqlCompletionColumn[], qualifier: string | undefined, qualifierAlreadyTyped: boolean, dialect?: "mysql" | "postgres" | "sqlserver", databaseType?: DatabaseType): string {
return columns
.map((column, index) => {
const columnName = quoteSqlIdentifier(column.name, dialect);
const columnName = quoteSelectStarColumnIdentifier(column.name, dialect, databaseType);
if (!qualifier || (qualifierAlreadyTyped && index === 0)) return columnName;
return `${qualifier}.${columnName}`;
})