feat(formatter): add custom default SQL layout engine

This commit is contained in:
t8y2 authored and GitHub committed 2026-09-17 17:21:47 +08:00
1 parent 58200ce5a4
commit 455117b8c5
20 files changed
+1588 -175

No files matched your search

+80 -37
View File
@@ -34,10 +34,10 @@ describe("sqlFormatter", () => {
expect(defaultFormatted).toContain("-- tstt\nSELECT");
expect(preserved).toContain("-- tstt\n\nSELECT");
expect(preservedConsecutive).toContain("-- section\n\n\nSELECT");
expect(preservedQueriesNoSpacing).toBe("SELECT\n 1;\n\nSELECT\n 2;");
expect(preservedQueries).toBe("SELECT\n 1;\n\nSELECT\n 2;");
expect(preservedQueriesWideSpacing).toBe("SELECT\n 1;\n\n\nSELECT\n 2;");
expect(preservedQueriesWithTwoEmptyLines).toBe("SELECT\n 1;\n\n\nSELECT\n 2;");
expect(preservedQueriesNoSpacing).toBe("SELECT 1;\n\nSELECT 2;");
expect(preservedQueries).toBe("SELECT 1;\n\nSELECT 2;");
expect(preservedQueriesWideSpacing).toBe("SELECT 1;\n\n\nSELECT 2;");
expect(preservedQueriesWithTwoEmptyLines).toBe("SELECT 1;\n\n\nSELECT 2;");
expect(preserved).not.toContain("__DBX_PRESERVE_EMPTY_LINE_");
});
@@ -69,7 +69,7 @@ describe("sqlFormatter", () => {
});
it("formats an OceanBase Oracle single-line view DDL into readable multi-line SQL (issue #7540)", async () => {
const singleLine = `CREATE OR REPLACE VIEW "APP"."ACTIVE_USERS" AS SELECT ID, NAME FROM USERS WHERE STATUS = 'ACTIVE'`;
const singleLine = `create or replace view "APP"."ACTIVE_USERS" as select ID, NAME, EMAIL, CREATED_AT from USERS where STATUS = 'ACTIVE' and DELETED_AT is null order by CREATED_AT desc`;
const formatted = await formatSqlForDisplay(singleLine, sqlFormatDialectForDbType("oceanbase-oracle"));
expect(formatted).not.toBe(singleLine);
@@ -83,11 +83,23 @@ describe("sqlFormatter", () => {
expect(formatted).toContain('"ACTIVE_USERS"');
});
it("collapses a short OceanBase Oracle view DDL onto one line (issue #7540)", async () => {
// The default style joins a statement that fits the line width onto one
// line, so a short view body comes back with its keywords cased rather
// than spread over several.
const singleLine = `create or replace view "APP"."ACTIVE_USERS" as select ID, NAME from USERS where STATUS = 'ACTIVE'`;
const formatted = await formatSqlForDisplay(singleLine, sqlFormatDialectForDbType("oceanbase-oracle"));
expect(formatted).toBe(`CREATE OR REPLACE VIEW "APP"."ACTIVE_USERS" AS SELECT ID, NAME FROM USERS WHERE STATUS = 'ACTIVE'`);
expect(formatted).toContain("'ACTIVE'");
expect(formatted).toContain('"ACTIVE_USERS"');
});
it("formats a bare OceanBase Oracle view source wrapped as CREATE VIEW (issue #7540)", async () => {
// Mirrors the backend build_view_ddl_sql output for a fallback ALL_VIEWS.TEXT
// body: `CREATE VIEW <name> AS <single-line SELECT>`.
const wrapped = `CREATE VIEW "APP"."ACTIVE_USERS" AS
SELECT ID, NAME FROM USERS WHERE STATUS = 'ACTIVE';`;
const wrapped = `create view "APP"."ACTIVE_USERS" as
select ID, NAME, EMAIL, CREATED_AT from USERS where STATUS = 'ACTIVE' and DELETED_AT is null order by CREATED_AT desc;`;
const formatted = await formatSqlForDisplay(wrapped, sqlFormatDialectForDbType("oceanbase-oracle"));
expect(formatted.split("\n").length).toBeGreaterThan(2);
@@ -121,27 +133,40 @@ WHERE STATUS = 'ACTIVE';`;
});
it("keeps issue #7138 Oracle hierarchy clauses intact", async () => {
const sql = "SELECT ctt.u_dm, ctt.u_mc, ctt.parent_id, ctt.level_num, ctt.create_time FROM cte_test ctt WHERE ctt.status = 'A' AND ctt.deleted = 0 START WITH ctt.su_dm IN ('16','17','18') CONNECT BY PRIOR ctt.u_dm = ctt.su_dm;";
// `START WITH` and `CONNECT BY PRIOR` are clauses of their own, not part of
// the WHERE condition: each opens a line, and the hierarchy is never dropped.
await expect(formatSqlForEditing(sql, sqlFormatDialectForDbType("oracle"))).resolves.toBe(`SELECT ctt.u_dm,
ctt.u_mc,
ctt.parent_id,
ctt.level_num,
ctt.create_time
FROM cte_test ctt
WHERE ctt.status = 'A'
AND ctt.deleted = 0
START WITH ctt.su_dm IN ('16', '17', '18')
CONNECT BY PRIOR ctt.u_dm = ctt.su_dm;`);
});
it("collapses a short Oracle hierarchy query onto one line", async () => {
const sql = "SELECT ctt.U_DM FROM cte_test ctt START WITH ctt.SU_DM IN ('16','17','18','19') CONNECT BY PRIOR ctt.U_DM = HY.SU_DM;";
await expect(formatSqlForEditing(sql, sqlFormatDialectForDbType("oracle"))).resolves.toBe(`SELECT
ctt.U_DM
FROM
cte_test ctt
START WITH ctt.SU_DM IN ('16', '17', '18', '19')
CONNECT BY PRIOR ctt.U_DM = HY.SU_DM;`);
await expect(formatSqlForEditing(sql, sqlFormatDialectForDbType("oracle"))).resolves.toBe(`SELECT ctt.U_DM FROM cte_test ctt START WITH ctt.SU_DM IN ('16', '17', '18', '19') CONNECT BY PRIOR ctt.U_DM = HY.SU_DM;`);
});
it("formats valid Oracle hierarchy clauses with the same alias", async () => {
const sql = "SELECT ctt.U_DM FROM cte_test ctt START WITH ctt.SU_DM = '16' CONNECT BY PRIOR ctt.U_DM = ctt.SU_DM;";
const sql = "select ctt.u_dm, ctt.u_mc, ctt.parent_id, ctt.level_num, ctt.create_time from cte_test ctt where ctt.status = 'A' and ctt.deleted = 0 start with ctt.su_dm = '16' connect by prior ctt.u_dm = ctt.su_dm;";
const formatted = await formatSqlForEditing(sql, sqlFormatDialectForDbType("oracle"));
expect(formatted).toContain("FROM\n cte_test ctt\nSTART WITH ctt.SU_DM = '16'");
expect(formatted).toContain("\nCONNECT BY PRIOR ctt.U_DM = ctt.SU_DM;");
expect(formatted).toContain("FROM cte_test ctt");
expect(formatted).toContain("\nSTART WITH ctt.su_dm = '16'");
expect(formatted).toContain("\nCONNECT BY PRIOR ctt.u_dm = ctt.su_dm;");
});
it("formats ordinary Oracle SQL and anonymous PL/SQL", async () => {
await expect(formatSqlForEditing("select employee_id from employees where department_id = 10;", sqlFormatDialectForDbType("oracle"))).resolves.toBe("SELECT\n employee_id\nFROM\n employees\nWHERE\n department_id = 10;");
await expect(formatSqlForEditing("select employee_id from employees where department_id = 10;", sqlFormatDialectForDbType("oracle"))).resolves.toBe("SELECT employee_id FROM employees WHERE department_id = 10;");
await expect(formatSqlForEditing("declare v_count number := 1; begin v_count := v_count + 1; end;", sqlFormatDialectForDbType("oracle"))).resolves.toBe("DECLARE v_count number := 1;\n\nBEGIN v_count := v_count + 1;\n\nEND;");
});
@@ -243,14 +268,15 @@ OR inside$$ as note
it("preserves the ClickHouse table alias from issue #7079", async () => {
const formatted = await formatSqlText("SELECT *\nFROM MATERIAL m\nLIMIT 100;", sqlFormatDialectForDbType("clickhouse"));
expect(formatted).toBe("SELECT\n *\nFROM\n MATERIAL m\nLIMIT\n 100;");
expect(formatted).toBe("SELECT * FROM MATERIAL m LIMIT 100;");
});
it.each(["d", "dd", "h", "hh", "m", "mcs", "mi", "mm", "ms", "n", "ns", "q", "qq", "s", "ss", "wk", "ww", "yy", "yyyy"])("preserves ClickHouse identifier-like date part %s while formatting keywords", async (identifier) => {
const formatted = await formatSqlText(`select ${identifier}, t.${identifier} from material ${identifier} limit 100;`, sqlFormatDialectForDbType("clickhouse"));
expect(formatted).toContain(` ${identifier},`);
expect(formatted).toContain(`material ${identifier}`);
// Alias casing is the tokenizer's business, not the keyword casing's: the
// date part stays an identifier, so `keywordCase: "upper"` leaves it alone.
expect(formatted).toBe(`SELECT ${identifier}, t.${identifier} FROM material ${identifier} LIMIT 100;`);
expect(formatted).toContain("SELECT");
expect(formatted).toContain("FROM");
expect(formatted).toContain("LIMIT");
@@ -262,17 +288,15 @@ OR inside$$ as note
const lowerKeywords = await formatSqlText(sql, sqlFormatDialectForDbType("clickhouse"), { keywordCase: "lower", identifierCase: "preserve" });
const lowerIdentifiers = await formatSqlText(sql, sqlFormatDialectForDbType("clickhouse"), { keywordCase: "upper", identifierCase: "lower" });
expect(lowerKeywords).toContain("from\n MATERIAL M");
expect(lowerKeywords).toContain("limit\n 100");
expect(lowerIdentifiers).toContain("FROM\n material m");
expect(lowerIdentifiers).toContain("LIMIT\n 100");
expect(lowerKeywords).toBe("select * from MATERIAL M limit 100;");
expect(lowerIdentifiers).toBe("SELECT * FROM material m LIMIT 100;");
});
it("still formats unambiguous ClickHouse interval keywords", async () => {
const formatted = await formatSqlText("select now() + interval 1 minutes from source_table m;", sqlFormatDialectForDbType("clickhouse"));
expect(formatted).toContain("INTERVAL 1 MINUTES");
expect(formatted).toContain("FROM\n source_table m");
expect(formatted).toContain("FROM source_table m");
});
it("preserves DBX brace placeholders in generic and MySQL SQL", async () => {
@@ -344,19 +368,19 @@ OR inside$$ as note
it("formats complete backtick-quoted spans with the PostgreSQL dialect", async () => {
const formatted = await formatSqlText("select `schema`.`odd``name` from user;", "postgres");
expect(formatted).toBe("SELECT\n `schema`.`odd``name`\nFROM\n user;");
expect(formatted).toBe("SELECT `schema`.`odd``name` FROM user;");
});
it("keeps PostgreSQL double-quoted identifiers and casts unchanged", async () => {
const formatted = await formatSqlText('select "display""name" from records where payload::jsonb is not null;', "postgres");
expect(formatted).toBe('SELECT\n "display""name"\nFROM\n records\nWHERE\n payload::jsonb IS NOT NULL;');
expect(formatted).toBe('SELECT "display""name" FROM records WHERE payload::jsonb IS NOT NULL;');
});
it("keeps MySQL backtick formatting unchanged", async () => {
const formatted = await formatSqlText("select `schema`.`odd``name` from `user`;", "mysql");
expect(formatted).toBe("SELECT\n `schema`.`odd``name`\nFROM\n `user`;");
expect(formatted).toBe("SELECT `schema`.`odd``name` FROM `user`;");
});
it("keeps malformed PostgreSQL backtick input unchanged while editing", async () => {
@@ -372,7 +396,9 @@ OR inside$$ as note
const formatted = await formatSqlForEditing(sql, sqlFormatDialectForDbType("dameng"));
expect(formatted).toContain('JS1.REC_CREATOR AS "recCreator"');
expect(formatted).toContain("DECODE (");
// Known and unknown functions alike are written without a space before the
// parenthesis.
expect(formatted).toContain("DECODE(");
expect(formatted.endsWith("JS1.REC_CREATE_TIME DESC .")).toBe(true);
});
@@ -383,7 +409,7 @@ OR inside$$ as note
});
it("preserves whitespace after a recovered trailing dot", async () => {
await expect(formatSqlForEditing("SELECT 1 .\n", "dameng")).resolves.toBe("SELECT\n 1 .\n");
await expect(formatSqlForEditing("SELECT 1 .\n", "dameng")).resolves.toBe("SELECT 1 .\n");
});
it("preserves the newline before a trailing dot after a line comment", async () => {
@@ -438,7 +464,18 @@ OR inside$$ as note
it("still formats selected SQL comparison fragments", async () => {
await expect(formatSqlText(`< 10`, "postgres")).resolves.toBe(`< 10`);
await expect(formatSqlText(`< 10 AND score > 2`, "postgres")).resolves.toBe(`< 10\nAND score > 2`);
// A short fragment collapses like any other short statement.
await expect(formatSqlText(`< 10 AND score > 2`, "postgres")).resolves.toBe(`< 10 AND score > 2`);
// A wider one has no clause to lay out, so it falls back to sql-formatter's
// own operand-per-line rendering of a fragment rather than the clause rules.
await expect(formatSqlText(`< 10 AND score > 2 AND status = 'active' AND deleted_at IS NULL AND created_at > now() - interval '30 days' AND owner_id = 42`, "postgres")).resolves.toBe(
`< 10
AND score > 2
AND status = 'active'
AND deleted_at IS NULL
AND created_at > now() - interval '30 days'
AND owner_id = 42`,
);
});
it("keeps logical conditions on one line when configured", async () => {
@@ -492,16 +529,22 @@ OR inside$$ as note
tabWidth: 4,
});
expect(formatted).toContain("FROM\ttVillage AS tv");
expect(formatted).toContain("ON tv.villageId = tl.villageId AND 1 = 1");
// The join keeps `FROM` and its source together (the setting's whole point),
// indents by one tab width, and the `ON` condition stays on the join's line.
expect(formatted).toBe("SELECT *\nFROM tVillage AS tv\n\tINNER JOIN tLand AS tl 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" });
const sql = "SELECT * FROM (SELECT villageId, villageName, townshipId, createdAt, updatedAt, deletedAt FROM tVillage WHERE deletedAt IS NULL AND villageName LIKE '%x%') AS tv";
expect(formatted).toContain("FROM\n");
expect(formatted).toContain("\n SELECT");
expect(formatted).toContain("FROM tVillage");
const formatted = await formatSqlText(sql, "sqlserver", { fromClauseLayout: "sameLine" });
// The derived table still expands — `FROM (` stays on the line it opens and
// the subquery's clauses align under that parenthesis, so the same-line
// setting only decides whether the group starts on the keyword's line.
expect(formatted).toContain("FROM (SELECT villageId,");
expect(formatted).toContain("\n FROM tVillage");
expect(formatted.endsWith(") AS tv")).toBe(true);
});
it("keeps display formatting lossless for XML/JSON-looking input", async () => {
+235
View File
@@ -0,0 +1,235 @@
import { describe, expect, it } from "vitest";
import { formatSqlText } from "@/lib/sql/sqlFormatter";
import { DEFAULT_SQL_FORMATTER_SETTINGS, type SqlFormatterSettings } from "@/lib/sql/sqlFormatterConfig";
/**
* Golden tests for the layout engine behind DBX's default formatting style.
* The expectations for the queries in issues #827, #4850 and #5170 pin the
* real-world shapes those reports asked for; the rest pin the rules those
* examples exercise — the collapse of short statements, the wrap of long ones,
* element alignment, and column alignment in `CREATE TABLE`.
*/
type Dialect = Parameters<typeof formatSqlText>[1];
async function format(sql: string, overrides: Partial<SqlFormatterSettings> = {}, dialect: Dialect = "mysql") {
return formatSqlText(sql, dialect, { ...DEFAULT_SQL_FORMATTER_SETTINGS, ...overrides });
}
const lines = (...rows: string[]) => rows.join("\n");
describe("sql layout", () => {
it("formats a query with a derived table (#827)", async () => {
const sql = lines(
"SELECT loc_id, loc_name, loc_type, delivery_emp_num, update_time",
"FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY loc_id ORDER BY update_time DESC) AS rn",
" FROM responsible_area_info",
" WHERE DATE_FORMAT(update_time, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')) t",
"WHERE rn = 1;",
);
// The subquery's clauses align under the `(` that opens it, and the closing
// `)` stays on the last clause's line.
//
// The subquery's two select elements could be split; the screenshots in
// #827 and #4850 disagree on that point (both are two-element lists, one
// split, one not), so the keeping rule here is the one #4850's rendering
// matches.
expect(await format(sql)).toBe(
lines(
"SELECT loc_id,",
" loc_name,",
" loc_type,",
" delivery_emp_num,",
" update_time",
"FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY loc_id ORDER BY update_time DESC) AS rn",
" FROM responsible_area_info",
" WHERE DATE_FORMAT(update_time, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')) t",
"WHERE rn = 1;",
),
);
});
it("keeps a long statement's clauses apart (#4850)", async () => {
const sql = lines(
"SELECT HIMMS_XDSBDJ.HIMMS_XDSBDJ_ID, HIMMS_XDSBDJ.YNKE, himms_zwxsysj_sysj(V_HIMMS_XDSBDJ.HIMMS_XDSBDJ_ID) AS SJSYSJ",
"FROM HIMMS_XDSBDJ",
"LEFT JOIN (SELECT himms_xdsbdj_id, MAX(SJ) SJ FROM himms_zwxqdjc GROUP BY himms_xdsbdj_id) SUB_QDJC ON HIMMS_XDSBDJ.HIMMS_XDSBDJ_ID = SUB_QDJC.himms_xdsbdj_id",
"WHERE HIMMS_XDSBDJ.tybz IS NULL;",
);
// The user-defined function is written without a space, and the join's
// subquery expands rather than pushing `ON` onto a line of its own.
expect(await format(sql)).toBe(
lines(
"SELECT HIMMS_XDSBDJ.HIMMS_XDSBDJ_ID, HIMMS_XDSBDJ.YNKE, himms_zwxsysj_sysj(V_HIMMS_XDSBDJ.HIMMS_XDSBDJ_ID) AS SJSYSJ",
"FROM HIMMS_XDSBDJ",
" LEFT JOIN (SELECT himms_xdsbdj_id, MAX(SJ) SJ",
" FROM himms_zwxqdjc",
" GROUP BY himms_xdsbdj_id) SUB_QDJC ON HIMMS_XDSBDJ.HIMMS_XDSBDJ_ID = SUB_QDJC.himms_xdsbdj_id",
"WHERE HIMMS_XDSBDJ.tybz IS NULL;",
),
);
});
it("collapses a statement that fits on one line (#5170)", async () => {
const sql = lines("SELECT", " *", "FROM", " task", "ORDER BY", " created_at DESC;");
expect(await format(sql)).toBe("SELECT * FROM task ORDER BY created_at DESC;");
});
it("aligns CREATE TABLE columns", async () => {
const sql = lines(
"CREATE TABLE IF NOT EXISTS `delivery_emp_info`",
"(",
" `id` varchar(20) PRIMARY KEY NOT NULL COMMENT '主键',",
" `emp_id` varchar(20) NOT NULL COMMENT '员工id',",
" `delivery_type_ids` varchar(512) DEFAULT NULL COMMENT '负责的运送类型id集合',",
" `update_time` datetime NOT NULL COMMENT '更新时间',",
" CONSTRAINT idx_emp_phone UNIQUE (emp_id, emp_phone_num) COMMENT '运送员id电话唯一'",
") ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin COMMENT '运达员信息表';",
);
// Name, type and modifiers each get their own column, so the definitions'
// `COMMENT`s line up; the constraint's `(` keeps its space.
expect(await format(sql)).toBe(
lines(
"CREATE TABLE IF NOT EXISTS `delivery_emp_info`",
"(",
" `id` varchar(20) PRIMARY KEY NOT NULL COMMENT '主键',",
" `emp_id` varchar(20) NOT NULL COMMENT '员工id',",
" `delivery_type_ids` varchar(512) DEFAULT NULL COMMENT '负责的运送类型id集合',",
" `update_time` datetime NOT NULL COMMENT '更新时间',",
" CONSTRAINT idx_emp_phone UNIQUE (emp_id, emp_phone_num) COMMENT '运送员id电话唯一'",
") ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin COMMENT '运达员信息表';",
),
);
});
it("keeps a call shaped like a call at any nesting depth", async () => {
const sql = "INSERT INTO t (a, b) VALUES (f(x), g(y)) ON DUPLICATE KEY UPDATE b = f(g(b));";
// The insert target's column list is spaced; the calls inside the values,
// and inside another call's arguments, are not.
expect(await format(sql)).toBe("INSERT INTO t (a, b) VALUES (f(x), g(y)) ON DUPLICATE KEY UPDATE b = f(g(b));");
});
it("breaks a long condition before each logical operator", async () => {
const sql = "SELECT a, b FROM t WHERE alpha = 1 AND beta = 2 AND gamma = 3 AND delta = 4 AND epsilon = 5 AND zeta = 6 AND eta = 7 AND theta = 8;";
// The statement is too long to collapse, and the default
// `logicalOperatorNewline: "before"` starts each continuation line with the
// operator, aligned under the condition's first operand like any other
// clause item.
expect(await format(sql)).toBe(lines("SELECT a, b", "FROM t", "WHERE alpha = 1", " AND beta = 2", " AND gamma = 3", " AND delta = 4", " AND epsilon = 5", " AND zeta = 6", " AND eta = 7", " AND theta = 8;"));
});
it("puts a wrapped condition's operators where the setting asks", async () => {
const sql = "SELECT a, b FROM t WHERE alpha = 1 AND beta = 2 AND gamma = 3 AND delta = 4 AND epsilon = 5 AND zeta = 6 AND eta = 7 AND theta = 8;";
// `after` ends the previous line with the operator instead.
expect(await format(sql, { logicalOperatorNewline: "after" })).toContain("WHERE alpha = 1 AND\n beta = 2 AND");
// `none` keeps the condition on the clause's line, however long it gets.
expect(await format(sql, { logicalOperatorNewline: "none" })).toBe(lines("SELECT a, b", "FROM t", "WHERE alpha = 1 AND beta = 2 AND gamma = 3 AND delta = 4 AND epsilon = 5 AND zeta = 6 AND eta = 7 AND theta = 8;"));
});
it("expands a parenthesized list that does not fit, aligned under its first item", async () => {
const sql = `SELECT * FROM t WHERE id IN (${Array.from({ length: 16 }, (_, index) => 100000 + index).join(", ")});`;
expect(await format(sql)).toBe(
lines(
"SELECT *",
"FROM t",
"WHERE id IN (100000,",
" 100001,",
" 100002,",
" 100003,",
" 100004,",
" 100005,",
" 100006,",
" 100007,",
" 100008,",
" 100009,",
" 100010,",
" 100011,",
" 100012,",
" 100013,",
" 100014,",
" 100015);",
),
);
});
it("keeps a small subquery inline", async () => {
expect(await format("SELECT * FROM t WHERE id IN (SELECT id FROM u WHERE a = 1 AND b = 2);")).toBe("SELECT * FROM t WHERE id IN (SELECT id FROM u WHERE a = 1 AND b = 2);");
});
it("collapses each clause independently", async () => {
const sql = "SELECT (SELECT count(*) FROM orders o WHERE o.customer_id = c.id AND o.status = 'paid') AS order_count, c.name FROM customers c;";
// The scalar subquery fits, the select list does not: only the second one
// breaks.
expect(await format(sql)).toBe(lines("SELECT (SELECT count(*) FROM orders o WHERE o.customer_id = c.id AND o.status = 'paid') AS order_count, c.name", "FROM customers c;"));
});
it("never joins a CASE onto one line", async () => {
expect(await format("SELECT CASE WHEN a = 1 THEN 'one' WHEN a = 2 THEN 'two' ELSE 'other' END AS label FROM t;")).toBe(lines("SELECT CASE", " WHEN a = 1 THEN 'one'", " WHEN a = 2 THEN 'two'", " ELSE 'other'", " END AS label", "FROM t;"));
});
it("gives a set operation its own line", async () => {
expect(await format("SELECT a FROM t UNION ALL SELECT b FROM u;")).toBe(lines("SELECT a", "FROM t", "UNION ALL", "SELECT b", "FROM u;"));
});
it("keeps comments and does not fold them onto a line", async () => {
const sql = lines("-- heading", "SELECT a, -- why", " b", "FROM t; /* trailing */");
expect(await format(sql)).toBe(lines("-- heading", "SELECT a,", " -- why", " b", "FROM t;", "", "/* trailing */"));
});
it("keeps PostgreSQL casts tight", async () => {
expect(await format("select coalesce(a, b)::text, (x + y)::int from t;", {}, "postgres")).toBe("SELECT coalesce(a, b)::text, (x + y)::int FROM t;");
});
it("keeps the comma of a MySQL LIMIT offset", async () => {
expect(await format("SELECT a FROM t LIMIT 5, 10;", {}, "mysql")).toBe("SELECT a FROM t LIMIT 5, 10;");
});
it("indents with tabs when asked", async () => {
const sql = "SELECT alpha_column, beta_column, gamma_column, delta_column FROM some_really_long_table_name WHERE first_condition = 1 AND second_condition = 2 AND third_condition = 3;";
// Only the leading indentation becomes a tab; the alignment padding stays
// spaces so a continuation column lands where it was measured.
expect(await format(sql, { useTabs: true, tabWidth: 4 })).toBe(["SELECT alpha_column,", "\t beta_column,", "\t gamma_column,", "\t delta_column", "FROM some_really_long_table_name", "WHERE first_condition = 1", "\t AND second_condition = 2", "\t AND third_condition = 3;"].join("\n"));
});
it("moves a FROM source to its own line when configured", async () => {
const sql = "SELECT alpha_column, beta_column, gamma_column, delta_column FROM some_really_long_table_name WHERE first_condition = 1 AND second_condition = 2 AND third_condition = 3;";
expect(await format(sql, { fromClauseLayout: "newLine" })).toBe(
lines("SELECT alpha_column,", " beta_column,", " gamma_column,", " delta_column", "FROM", " some_really_long_table_name", "WHERE first_condition = 1", " AND second_condition = 2", " AND third_condition = 3;"),
);
});
it("honours the blank lines between queries", async () => {
const sql = "SELECT 1;\nSELECT 2;";
expect(await format(sql, { linesBetweenQueries: 0 })).toBe(lines("SELECT 1;", "SELECT 2;"));
expect(await format(sql, { linesBetweenQueries: 1 })).toBe(lines("SELECT 1;", "", "SELECT 2;"));
expect(await format(sql, { linesBetweenQueries: 2 })).toBe(lines("SELECT 1;", "", "", "SELECT 2;"));
});
it("keeps a blank source line when the setting is on", async () => {
expect(await format(lines("-- heading", "", "SELECT a FROM t;"), { preserveEmptyLines: true })).toBe(lines("-- heading", "", "SELECT a", "FROM t;"));
});
it("falls back to sql-formatter for the tabular indent styles", async () => {
// The tabular layouts pad every clause to a fixed column; the default
// layout rules do not reproduce them, so those settings keep the upstream
// formatter.
expect(await format("SELECT a, b FROM t WHERE x = 1;", { indentStyle: "tabularLeft" })).toBe(lines("SELECT a,", " b", "FROM t", "WHERE x = 1;"));
});
it("formats a dialect without its own grammar", async () => {
expect(await format("select * from t where a = 1 and b = 2;", {}, "generic")).toBe("SELECT * FROM t WHERE a = 1 AND b = 2;");
});
});