25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(sql): 补全 PostgreSQL MERGE 子句,修复格式化逐词换行
zipg5e52b722cdfb
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.tsindex c976e545cf..2cf6f49f10 100644--- a/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts+++ b/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts@@ -840,3 +840,48 @@ describe("classic layout style (v0.6.15 reproduction)", () => {expect(await formatSqlText("select * from t", "mysql", { ...classic, fromClauseLayout: "sameLine" })).toBe(lines("SELECT", " *", "FROM t"));});});++describe("PostgreSQL MERGE formatting (#12592)", () => {+ // sql-formatter 15's postgresql grammar predates PG15 MERGE, so the DBX+ // layout printer used to emit one token per line for these statements.+ const merge = "MERGE INTO target t USING source s ON t.id = s.id WHEN MATCHED THEN UPDATE SET name = s.name WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);";++ it("lays out the UPDATE and INSERT actions as clauses", async () => {+ const formatted = await formatSqlText(merge, "postgres");++ expect(formatted).toBe(["MERGE INTO target t USING source s ON t.id = s.id", "WHEN MATCHED THEN", "UPDATE SET name = s.name", "WHEN NOT MATCHED THEN", "INSERT (id, name)", "VALUES (s.id, s.name);"].join("\n"));+ // Formatting is idempotent: the clause keywords stay clause boundaries.+ await expect(formatSqlText(formatted, "postgres")).resolves.toBe(formatted);+ });++ it("keeps conditions, DELETE actions and RETURNING intact", async () => {+ const sql = "MERGE INTO products p USING new_products np ON p.product_id = np.product_id WHEN MATCHED AND np.price > p.price THEN UPDATE SET price = np.price WHEN NOT MATCHED THEN INSERT (product_id, product_name, price) VALUES (np.product_id, np.product_name, np.price) RETURNING p.*;";++ await expect(formatSqlText(sql, "postgres")).resolves.toBe(+ [+ "MERGE INTO products p USING new_products np ON p.product_id = np.product_id",+ "WHEN MATCHED AND np.price > p.price THEN",+ "UPDATE SET price = np.price",+ "WHEN NOT MATCHED THEN",+ "INSERT (product_id, product_name, price)",+ "VALUES (np.product_id, np.product_name, np.price)",+ "RETURNING p.*;",+ ].join("\n"),+ );++ const deleteAction = "MERGE INTO t USING s ON t.id = s.id WHEN MATCHED THEN DELETE WHEN NOT MATCHED THEN INSERT (id) VALUES (s.id);";+ await expect(formatSqlText(deleteAction, "postgres")).resolves.toBe(["MERGE INTO t USING s ON t.id = s.id", "WHEN MATCHED THEN DELETE", "WHEN NOT MATCHED THEN", "INSERT (id)", "VALUES (s.id);"].join("\n"));+ });++ it("does not change regular INSERT, UPDATE or JOIN formatting", async () => {+ await expect(formatSqlText("insert into t (a, b) values (1, 2) on conflict (a) do update set b = excluded.b;", "postgres")).resolves.toBe("INSERT INTO t (a, b)\nVALUES (1, 2)\nON CONFLICT (a) DO UPDATE\nSET b = excluded.b;");+ await expect(formatSqlText("update t set a = 1, b = 2 where id = 3;", "postgres")).resolves.toBe("UPDATE t SET a = 1, b = 2 WHERE id = 3;");+ await expect(formatSqlText("select a.id, b.name from a join b on a.id = b.id where a.x = 1;", "postgres")).resolves.toBe("SELECT a.id,\n b.name\nFROM a\n JOIN b ON a.id = b.id\nWHERE a.x = 1;");+ });++ it("applies to PostgreSQL-compatible connections too", async () => {+ // GaussDB / Kingbase / HighGo / openGauss reuse the postgres grammar.+ expect(sqlFormatDialectForDbType("gaussdb")).toBe("postgres");+ await expect(formatSqlText(merge, sqlFormatDialectForDbType("kingbase"))).resolves.toContain("WHEN MATCHED THEN\nUPDATE SET name = s.name");+ });+});diff --git a/apps/desktop/src/lib/sql/sqlFormatter.ts b/apps/desktop/src/lib/sql/sqlFormatter.tsindex 8255fea4c6..b8d05d6990 100644--- a/apps/desktop/src/lib/sql/sqlFormatter.ts+++ b/apps/desktop/src/lib/sql/sqlFormatter.ts@@ -81,6 +81,34 @@ function resolveOracleExtendedDialect(sqlFormatter: SqlFormatterModule): SqlFormreturn oracleExtendedDialect;}+// sql-formatter 15's PostgreSQL grammar predates PostgreSQL 15's MERGE+// statement: MERGE / MATCHED are plain identifiers to it, so the DBX layout+// printer — which splits a statement at its clauses — receives a flat child+// list it cannot recognise and puts every token on its own line. Register+// PostgreSQL's MERGE clauses (and the bare `INSERT` action, which has no+// `INTO`) so MERGE keeps the same one-clause-per-line shape as INSERT/UPDATE.+// The statement itself is untouched: the words are only recognized as clause+// boundaries. `WHEN MATCHED` / `WHEN NOT MATCHED` are registered without the+// trailing `THEN` so the optional `AND <condition>` form still splits here.+const POSTGRES_MERGE_CLAUSES = ["MERGE INTO", "WHEN MATCHED", "WHEN NOT MATCHED", "UPDATE SET", "INSERT"];+let postgresMergeDialect: SqlFormatterModule["postgresql"] | null = null;++function resolvePostgresMergeDialect(sqlFormatter: SqlFormatterModule): SqlFormatterModule["postgresql"] {+ if (postgresMergeDialect) return postgresMergeDialect;++ const clauses = sqlFormatter.postgresql.tokenizerOptions.reservedClauses;+ const extraClauses = POSTGRES_MERGE_CLAUSES.filter((clause) => !clauses.includes(clause));++ postgresMergeDialect = {+ ...sqlFormatter.postgresql,+ tokenizerOptions: {+ ...sqlFormatter.postgresql.tokenizerOptions,+ reservedClauses: [...clauses, ...extraClauses],+ },+ };+ return postgresMergeDialect;+}+export function canFormatSqlForDatabaseType(dbType: string | null | undefined): boolean {return dbType !== "redis" && dbType !== "victoriametrics";}@@ -432,7 +460,16 @@ export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "ge},}: options;- const resolvedDialect = dialect === "mysql" ? resolveMysqlFunctionSafeDialect(sqlFormatter) : dialect === "clickhouse" ? resolveClickHouseIdentifierSafeDialect(sqlFormatter) : dialect === "oracle" ? resolveOracleExtendedDialect(sqlFormatter) : undefined;+ const resolvedDialect =+ dialect === "mysql"+ ? resolveMysqlFunctionSafeDialect(sqlFormatter)+ : dialect === "clickhouse"+ ? resolveClickHouseIdentifierSafeDialect(sqlFormatter)+ : dialect === "oracle"+ ? resolveOracleExtendedDialect(sqlFormatter)+ : dialect === "postgres"+ ? resolvePostgresMergeDialect(sqlFormatter)+ : undefined;const formatWithFallback = (input: string): string => {try {if (resolvedDialect) {