feat(completion): fix SQL alias completion, star expansion, and formatter layout

This commit is contained in:
jinmo authored and GitHub committed 2026-08-10 01:11:25 +08:00
1 parent 0402fea37b
commit 868f7961e3
30 files changed
+758 -76

No files matched your search

@@ -281,6 +281,29 @@ describe("semantic SQL completion candidates", () => {
expect(columns.find((item) => item.label === "v.id")?.apply).toBe("v.id");
});
it("prioritizes matching table aliases over matching columns", () => {
const columnsByTable = new Map<string, SqlCompletionColumn[]>([["test_tb", ["title", "type"].map((name) => ({ name, table: "test_tb" }))]]);
const { items } = semanticCompletion("SELECT * FROM test_tb AS tt WHERE t|", { columnsByTable });
expect(items[0]).toMatchObject({ label: "tt", type: "text", apply: "tt" });
expect(items.filter((item) => item.type === "column").map((item) => item.label)).toEqual(expect.arrayContaining(["title", "type"]));
});
it("qualifies both unique and duplicate columns in multi-table queries", () => {
const columnsByTable = new Map<string, SqlCompletionColumn[]>([
["tVillage", ["villageId", "villageName"].map((name) => ({ name, table: "tVillage" }))],
["tland", ["villageId", "landName"].map((name) => ({ name, table: "tland" }))],
]);
const { items } = semanticCompletion("SELECT vill| FROM tVillage tV INNER JOIN tland tl ON tV.villageId = tl.villageId", { columnsByTable });
const columns = items.filter((item) => item.type === "column");
expect(columns.map((item) => item.label)).toEqual(expect.arrayContaining(["tV.villageId", "tV.villageName", "tl.villageId"]));
expect(columns.find((item) => item.label === "tV.villageName")).toMatchObject({ filterText: "villageName", apply: "tV.villageName" });
expect(columns.find((item) => item.label === "tl.villageId")).toMatchObject({ filterText: "villageId", apply: "tl.villageId" });
});
it("completes columns for aliases in comma-separated table lists", () => {
const columnsByTable = new Map<string, SqlCompletionColumn[]>([
["table_a", ["id", "name"].map((name) => ({ name, table: "table_a" }))],
+8 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { sqlSemanticCompletionScope, sqlSemanticLocalColumnsByTable, sqlSemanticProjectionAliasColumns, sqlSemanticSelectStarIsOnlyProjection, sqlSemanticSelectStarQualifierSql, sqlSemanticSelectStarTableSource } from "@/lib/sql/semantic/completion";
import { sqlSemanticCompletionScope, sqlSemanticLocalColumnsByTable, sqlSemanticProjectionAliasColumns, sqlSemanticSelectStarIsOnlyProjection, sqlSemanticSelectStarQualifierSql, sqlSemanticSelectStarTableSource, sqlSemanticSelectStarTableSources } from "@/lib/sql/semantic/completion";
import { SQL_SEMANTIC_BASELINE_FIXTURES, sqlFixtureCursor } from "@/lib/sql/semantic/fixtures";
import { buildSqlSemanticModel, sqlSemanticTableNameSpans } from "@/lib/sql/semantic/model";
@@ -51,6 +51,13 @@ describe("sqlSemanticModel baseline fixtures", () => {
expect(sqlSemanticSelectStarTableSource(model)).toBeUndefined();
});
it("returns every table source for an unqualified multi-table star", () => {
const { sql, cursor } = sqlFixtureCursor("select *| from tVillage tV inner join tland tl on tV.villageId = tl.villageId");
const model = buildSqlSemanticModel(sql, cursor);
expect(sqlSemanticSelectStarTableSources(model).map((source) => source.alias)).toEqual(["tV", "tl"]);
});
it.each([
["select *| from apis", true],
["select distinct *| from apis", true],
@@ -39,6 +39,62 @@ describe("SELECT star expansion", () => {
).toBe("id, created_at, method");
});
it("expands a multi-table star with aliases and preserves duplicate column names", () => {
const sql = "SELECT * FROM tVillage tV INNER JOIN tland tl ON tV.villageId = tl.villageId";
const cursor = "SELECT *".length;
const context = sqlCompletionContextFromSemantic(buildSqlSemanticModel(sql, cursor), getSqlCompletionContext(sql, cursor));
expect(
buildSelectStarExpansion(
context,
new Map([
[
"tVillage",
[
{ name: "villageId", table: "tVillage" },
{ name: "villageName", table: "tVillage" },
],
],
[
"tland",
[
{ name: "villageId", table: "tland" },
{ name: "landName", table: "tland" },
],
],
]),
),
).toBe("tV.villageId, tV.villageName, tl.villageId, tl.landName");
});
it("uses FROM/JOIN order even when the metadata map arrives in another order", () => {
const sql = "SELECT * FROM tVillage tv INNER JOIN tland tl ON tv.villageId = tl.villageId";
const cursor = "SELECT *".length;
const context = sqlCompletionContextFromSemantic(buildSqlSemanticModel(sql, cursor), getSqlCompletionContext(sql, cursor));
expect(
buildSelectStarExpansion(
context,
new Map([
[
"tland",
[
{ name: "landName", table: "tland" },
{ name: "villageId", table: "tland" },
],
],
[
"tVillage",
[
{ name: "villageName", table: "tVillage" },
{ name: "villageId", table: "tVillage" },
],
],
]),
),
).toBe("tv.villageName, tv.villageId, tl.landName, tl.villageId");
});
it("preserves an alias while replacing only the star", () => {
const sql = "SELECT ap.* FROM apis AS ap";
const cursor = "SELECT ap.*".length;
+63
View File
@@ -89,6 +89,69 @@ describe("sqlFormatter", () => {
await expect(formatSqlText(`< 10 AND score > 2`, "postgres")).resolves.toBe(`< 10\nAND score > 2`);
});
it("keeps logical conditions on one line when configured", async () => {
const formatted = await formatSqlText("SELECT * FROM t WHERE a = 1 AND b = 2", "mysql", { logicalOperatorNewline: "none" });
expect(formatted).toContain("a = 1 AND b = 2");
expect(formatted).not.toMatch(/\n\s*AND\b/i);
});
it("does not collapse AND/OR line breaks inside block comments (regression: comment reformatting)", async () => {
// sql-formatter preserves newlines inside /* ... */ verbatim, so the
// keepLogicalOperatorsOnSameLine post-pass used to fold the comment's
// internal `AND`/`OR` onto one line along with the real clause `AND`.
// The comment body must stay multi-line; only the clause-level AND gets
// pulled back onto the previous (comment-closing) line instead of sitting
// alone on its own line.
const sql = "SELECT * FROM t WHERE 1 = 1 /* note:\nAND is a keyword here\nOR also */ AND b = 2";
for (const dialect of ["mysql", "postgres", "generic"] as const) {
const formatted = await formatSqlText(sql, dialect, { logicalOperatorNewline: "none" });
// 注释内部多行结构必须保留
expect(formatted).toContain("/* note:");
expect(formatted).toContain("AND is a keyword here");
expect(formatted).toContain("OR also */");
// 注释内部 AND/OR 仍各自独占一行(前面是换行)
expect(formatted).toMatch(/note:\n\s*AND is a keyword here/);
expect(formatted).toMatch(/keyword here\n\s*OR also/);
// 真正子句间的 AND 换行应被折叠:AND b = 2 不再独占行首
expect(formatted).toContain("*/ AND b = 2");
expect(formatted).not.toMatch(/\n\s*AND b = 2/);
}
});
it("does not collapse AND/OR inside single-quoted string literals", async () => {
// 字符串字面量内的 AND/OR 也不应被当作逻辑算子折叠。这里用一个含换行的
// 字符串(虽然 sql-formatter 通常会把字符串单行化,但遮罩应防御性覆盖)。
const sql = "SELECT 'a\nAND b\nOR c' AS s WHERE x = 1 AND y = 2";
const formatted = await formatSqlText(sql, "postgres", { logicalOperatorNewline: "none" });
expect(formatted).toContain("'a\nAND b\nOR c'");
expect(formatted).toContain("x = 1 AND y = 2");
});
it("can keep FROM and the first table on the same line", async () => {
const formatted = await formatSqlText("SELECT * FROM tVillage AS tv INNER JOIN tLand AS tl ON tv.villageId = tl.villageId AND 1 = 1", "sqlserver", {
fromClauseLayout: "sameLine",
logicalOperatorNewline: "none",
useTabs: true,
tabWidth: 4,
});
expect(formatted).toContain("FROM\ttVillage AS tv");
expect(formatted).toContain("ON tv.villageId = tl.villageId AND 1 = 1");
});
it("keeps derived tables multiline with FROM same-line layout", async () => {
const formatted = await formatSqlText("SELECT * FROM (SELECT * FROM tVillage) AS tv", "sqlserver", { fromClauseLayout: "sameLine" });
expect(formatted).toContain("FROM\n");
expect(formatted).toContain("\n SELECT");
expect(formatted).toContain("FROM tVillage");
});
it("keeps display formatting lossless for XML/JSON-looking input", async () => {
const xml = `<root><item id="1">value</item></root>`;
const json = `{"a":1}`;
@@ -39,4 +39,20 @@ describe("sqlFormatterConfig shortcut storage", () => {
custom: [{ regex: String.raw`\{\{[^}]+\}\}` }, { regex: String.raw`\$\{[^}]+\}` }, { regex: String.raw`#\{[^}]+\}` }],
});
});
it("accepts the same-line logical operator mode", () => {
const result = parseSqlFormatterConfig(JSON.stringify({ version: 1, formatter: "sql-formatter", options: { logicalOperatorNewline: "none" } }));
expect(result).toEqual(expect.objectContaining({ ok: true }));
if (result.ok) expect(result.settings.logicalOperatorNewline).toBe("none");
expect(sqlFormatterOptions({ logicalOperatorNewline: "none" }).logicalOperatorNewline).toBe("before");
});
it("accepts and serializes the FROM clause layout", () => {
const result = parseSqlFormatterConfig(JSON.stringify({ version: 1, formatter: "sql-formatter", options: { fromClauseLayout: "sameLine" } }));
expect(result).toEqual(expect.objectContaining({ ok: true }));
if (result.ok) expect(result.settings.fromClauseLayout).toBe("sameLine");
expect(JSON.parse(serializeSqlFormatterConfig({ fromClauseLayout: "sameLine" })).options.fromClauseLayout).toBe("sameLine");
});
});