feat(sql): support comma position configuration in SQL formatter
This commit is contained in:
1 parent
9a6a2049bf
commit
760423873a
23 files changed
+222
-5
No files matched your search
@@ -20,6 +20,7 @@ import {
|
||||
serializeSqlFormatterConfig,
|
||||
syncSqlFormatterConfigDraft,
|
||||
type SqlFormatterCase,
|
||||
type SqlFormatterCommaPosition,
|
||||
type SqlFormatterExpressionWidth,
|
||||
type SqlFormatterFromClauseLayout,
|
||||
type SqlFormatterIndentStyle,
|
||||
@@ -83,6 +84,11 @@ const logicalOperatorOptions: { value: SqlFormatterLogicalOperatorNewline; label
|
||||
{ value: "none", labelKey: "settings.sqlFormatterLogicalSameLine" },
|
||||
];
|
||||
|
||||
const commaPositionOptions: { value: SqlFormatterCommaPosition; labelKey: string }[] = [
|
||||
{ value: "after", labelKey: "settings.sqlFormatterCommaPositionAfter" },
|
||||
{ value: "before", labelKey: "settings.sqlFormatterCommaPositionBefore" },
|
||||
];
|
||||
|
||||
const fromClauseLayoutOptions: { value: SqlFormatterFromClauseLayout; labelKey: string }[] = [
|
||||
{ value: "newLine", labelKey: "settings.sqlFormatterFromNewLine" },
|
||||
{ value: "sameLine", labelKey: "settings.sqlFormatterFromSameLine" },
|
||||
@@ -106,6 +112,7 @@ const sqlFormatterOptionLabelKeys: Record<keyof SqlFormatterOptionSettings, stri
|
||||
useTabs: "settings.sqlFormatterIndent",
|
||||
tabWidth: "settings.sqlFormatterTabWidth",
|
||||
logicalOperatorNewline: "settings.sqlFormatterLogicalOperatorNewline",
|
||||
commaPosition: "settings.sqlFormatterCommaPosition",
|
||||
fromClauseLayout: "settings.sqlFormatterFromClauseLayout",
|
||||
expressionWidth: "settings.sqlFormatterExpressionWidth",
|
||||
linesBetweenQueries: "settings.sqlFormatterLinesBetweenQueries",
|
||||
@@ -202,6 +209,10 @@ function onFromClauseLayout(value: any) {
|
||||
if (value === "newLine" || value === "sameLine") updateOption("fromClauseLayout", value);
|
||||
}
|
||||
|
||||
function onCommaPosition(value: any) {
|
||||
if (value === "after" || value === "before") updateOption("commaPosition", value);
|
||||
}
|
||||
|
||||
function onTabWidth(value: any) {
|
||||
const next = Number(value);
|
||||
if (next === 2 || next === 4) updateOption("tabWidth", next);
|
||||
@@ -638,6 +649,22 @@ onBeforeUnmount(() => {
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<Label>{{ t("settings.sqlFormatterCommaPosition") }}</Label>
|
||||
<Select :model-value="settings.commaPosition" @update:model-value="onCommaPosition">
|
||||
<SelectTrigger class="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="option in commaPositionOptions" :key="option.value" :value="option.value">
|
||||
{{ t(option.labelKey) }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<div class="space-y-2">
|
||||
<Label>{{ t("settings.sqlFormatterExpressionWidth") }}</Label>
|
||||
<Select :model-value="String(settings.expressionWidth)" @update:model-value="onExpressionWidth">
|
||||
|
||||
@@ -6945,6 +6945,9 @@ export default withEnglishFallback({
|
||||
sqlFormatterLogicalBefore: "Operatordan əvvəl",
|
||||
sqlFormatterLogicalAfter: "Operatordan sonra",
|
||||
sqlFormatterLogicalSameLine: "Eyni sətirdə saxla",
|
||||
sqlFormatterCommaPosition: "Vergül mövqeyi",
|
||||
sqlFormatterCommaPositionAfter: "Elementdən sonra",
|
||||
sqlFormatterCommaPositionBefore: "Elementdən əvvəl",
|
||||
sqlFormatterFromClauseLayout: "FROM bəndinin düzülüşü",
|
||||
sqlFormatterFromNewLine: "Cədvəl növbəti sətirdə",
|
||||
sqlFormatterFromSameLine: "FROM ilk cədvəllə birlikdə",
|
||||
|
||||
@@ -7846,6 +7846,9 @@ export default {
|
||||
sqlFormatterLogicalBefore: "Before operator",
|
||||
sqlFormatterLogicalAfter: "After operator",
|
||||
sqlFormatterLogicalSameLine: "Keep on same line",
|
||||
sqlFormatterCommaPosition: "Comma position",
|
||||
sqlFormatterCommaPositionAfter: "After item (trailing)",
|
||||
sqlFormatterCommaPositionBefore: "Before item (leading)",
|
||||
sqlFormatterFromClauseLayout: "FROM clause layout",
|
||||
sqlFormatterFromNewLine: "Table on next line",
|
||||
sqlFormatterFromSameLine: "FROM with first table",
|
||||
|
||||
@@ -7183,6 +7183,9 @@ export default withEnglishFallback({
|
||||
sqlFormatterLogicalBefore: "Antes del operador",
|
||||
sqlFormatterLogicalAfter: "Después del operador",
|
||||
sqlFormatterLogicalSameLine: "Mantener en la misma línea",
|
||||
sqlFormatterCommaPosition: "Posición de coma",
|
||||
sqlFormatterCommaPositionAfter: "Después del elemento",
|
||||
sqlFormatterCommaPositionBefore: "Antes del elemento",
|
||||
sqlFormatterFromClauseLayout: "Diseño de la cláusula FROM",
|
||||
sqlFormatterFromNewLine: "Tabla en la línea siguiente",
|
||||
sqlFormatterFromSameLine: "FROM con la primera tabla",
|
||||
|
||||
@@ -7676,6 +7676,9 @@ export default withEnglishFallback({
|
||||
sqlFormatterLogicalBefore: "Sebelum operator",
|
||||
sqlFormatterLogicalAfter: "Setelah operator",
|
||||
sqlFormatterLogicalSameLine: "Tetap pada baris yang sama",
|
||||
sqlFormatterCommaPosition: "Posisi koma",
|
||||
sqlFormatterCommaPositionAfter: "Setelah item",
|
||||
sqlFormatterCommaPositionBefore: "Sebelum item",
|
||||
sqlFormatterFromClauseLayout: "Tata letak klausa FROM",
|
||||
sqlFormatterFromNewLine: "Tabel pada baris berikutnya",
|
||||
sqlFormatterFromSameLine: "FROM dengan tabel pertama",
|
||||
|
||||
@@ -6961,6 +6961,9 @@ export default withEnglishFallback({
|
||||
sqlFormatterLogicalBefore: "Prima dell'operatore",
|
||||
sqlFormatterLogicalAfter: "Dopo l'operatore",
|
||||
sqlFormatterLogicalSameLine: "Mantieni sulla stessa riga",
|
||||
sqlFormatterCommaPosition: "Posizione virgola",
|
||||
sqlFormatterCommaPositionAfter: "Dopo l'elemento",
|
||||
sqlFormatterCommaPositionBefore: "Prima dell'elemento",
|
||||
sqlFormatterFromClauseLayout: "Layout della clausola FROM",
|
||||
sqlFormatterFromNewLine: "Tabella sulla riga successiva",
|
||||
sqlFormatterFromSameLine: "FROM con la prima tabella",
|
||||
|
||||
@@ -6991,6 +6991,9 @@ export default withEnglishFallback({
|
||||
sqlFormatterLogicalBefore: "演算子の前",
|
||||
sqlFormatterLogicalAfter: "演算子の後",
|
||||
sqlFormatterLogicalSameLine: "同じ行に保持",
|
||||
sqlFormatterCommaPosition: "カンマの位置",
|
||||
sqlFormatterCommaPositionAfter: "項目の後(行末)",
|
||||
sqlFormatterCommaPositionBefore: "項目の前(行頭)",
|
||||
sqlFormatterFromClauseLayout: "FROM 句のレイアウト",
|
||||
sqlFormatterFromNewLine: "テーブルを次の行に配置",
|
||||
sqlFormatterFromSameLine: "FROM と最初のテーブルを同じ行に配置",
|
||||
|
||||
@@ -6766,6 +6766,9 @@ export default withEnglishFallback({
|
||||
sqlFormatterLogicalBefore: "연산자 앞",
|
||||
sqlFormatterLogicalAfter: "연산자 뒤",
|
||||
sqlFormatterLogicalSameLine: "같은 줄 유지",
|
||||
sqlFormatterCommaPosition: "쉼표 위치",
|
||||
sqlFormatterCommaPositionAfter: "항목 뒤 (줄 끝)",
|
||||
sqlFormatterCommaPositionBefore: "항목 앞 (줄 시작)",
|
||||
sqlFormatterFromClauseLayout: "FROM 절 레이아웃",
|
||||
sqlFormatterFromNewLine: "다음 줄에 테이블 배치",
|
||||
sqlFormatterFromSameLine: "FROM과 첫 번째 테이블을 같은 줄에 배치",
|
||||
|
||||
@@ -6962,6 +6962,9 @@ export default withEnglishFallback({
|
||||
sqlFormatterLogicalBefore: "Antes do operador",
|
||||
sqlFormatterLogicalAfter: "Depois do operador",
|
||||
sqlFormatterLogicalSameLine: "Manter na mesma linha",
|
||||
sqlFormatterCommaPosition: "Posição da vírgula",
|
||||
sqlFormatterCommaPositionAfter: "Após o item",
|
||||
sqlFormatterCommaPositionBefore: "Antes do item",
|
||||
sqlFormatterFromClauseLayout: "Layout da cláusula FROM",
|
||||
sqlFormatterFromNewLine: "Tabela na linha seguinte",
|
||||
sqlFormatterFromSameLine: "FROM com a primeira tabela",
|
||||
|
||||
@@ -8166,6 +8166,9 @@ export default withEnglishFallback({
|
||||
sqlFormatterLogicalBefore: "Перед оператором",
|
||||
sqlFormatterLogicalAfter: "После оператора",
|
||||
sqlFormatterLogicalSameLine: "Оставлять в той же строке",
|
||||
sqlFormatterCommaPosition: "Положение запятой",
|
||||
sqlFormatterCommaPositionAfter: "После элемента",
|
||||
sqlFormatterCommaPositionBefore: "Перед элементом",
|
||||
sqlFormatterFromClauseLayout: "Размещение предложения FROM",
|
||||
sqlFormatterFromNewLine: "Таблица на следующей строке",
|
||||
sqlFormatterFromSameLine: "FROM с первой таблицей",
|
||||
|
||||
@@ -6826,6 +6826,9 @@ export default withEnglishFallback({
|
||||
sqlFormatterLogicalBefore: "İşleçten önce",
|
||||
sqlFormatterLogicalAfter: "İşleçten sonra",
|
||||
sqlFormatterLogicalSameLine: "Aynı satırda tut",
|
||||
sqlFormatterCommaPosition: "Virgül konumu",
|
||||
sqlFormatterCommaPositionAfter: "Öğeden sonra",
|
||||
sqlFormatterCommaPositionBefore: "Öğeden önce",
|
||||
sqlFormatterFromClauseLayout: "FROM yan tümcesi düzeni",
|
||||
sqlFormatterFromNewLine: "Tablo bir sonraki satırda",
|
||||
sqlFormatterFromSameLine: "FROM ilk tabloyla birlikte",
|
||||
|
||||
@@ -7832,6 +7832,9 @@ export default withEnglishFallback({
|
||||
sqlFormatterLogicalBefore: "运算符前换行",
|
||||
sqlFormatterLogicalAfter: "运算符后换行",
|
||||
sqlFormatterLogicalSameLine: "逻辑条件保持同一行",
|
||||
sqlFormatterCommaPosition: "逗号位置",
|
||||
sqlFormatterCommaPositionAfter: "字段后置(行尾)",
|
||||
sqlFormatterCommaPositionBefore: "字段前置(行首)",
|
||||
sqlFormatterFromClauseLayout: "FROM 子句布局",
|
||||
sqlFormatterFromNewLine: "FROM 与表名分行",
|
||||
sqlFormatterFromSameLine: "FROM 与首个表同行",
|
||||
|
||||
@@ -6315,6 +6315,9 @@ export default withEnglishFallback({
|
||||
sqlFormatterLogicalBefore: "運算子前換行",
|
||||
sqlFormatterLogicalAfter: "運算子後換行",
|
||||
sqlFormatterLogicalSameLine: "邏輯條件保持同一行",
|
||||
sqlFormatterCommaPosition: "逗號位置",
|
||||
sqlFormatterCommaPositionAfter: "欄位後置(行尾)",
|
||||
sqlFormatterCommaPositionBefore: "欄位前置(行首)",
|
||||
sqlFormatterFromClauseLayout: "FROM 子句版面",
|
||||
sqlFormatterFromNewLine: "表名另起一行",
|
||||
sqlFormatterFromSameLine: "FROM 與第一個表同行",
|
||||
|
||||
@@ -632,4 +632,21 @@ AND owner_id = 42`,
|
||||
expect(formatted).toContain("SELECT");
|
||||
expect(formatted).toContain("::jsonb");
|
||||
});
|
||||
|
||||
it("formats multiline items with leading comma position", async () => {
|
||||
const sql = "SELECT col1, col2, col3 FROM tbl WHERE a = 1;";
|
||||
const formatted = await formatSqlText(sql, "generic", { commaPosition: "before", indentStyle: "tabularLeft" });
|
||||
|
||||
expect(formatted).toContain(", col2");
|
||||
expect(formatted).toContain(", col3");
|
||||
expect(formatted).not.toMatch(/col1,/);
|
||||
});
|
||||
|
||||
it("preserves line comments when formatting with leading comma position", async () => {
|
||||
const sql = "SELECT\n col1, -- first column\n col2 -- second column\nFROM tbl;";
|
||||
const formatted = await formatSqlText(sql, "generic", { commaPosition: "before", indentStyle: "tabularLeft" });
|
||||
|
||||
expect(formatted).toContain("col1 -- first column");
|
||||
expect(formatted).toMatch(/,\s*col2\s*-- second column/);
|
||||
});
|
||||
});
|
||||
@@ -72,4 +72,20 @@ describe("sqlFormatterConfig shortcut storage", () => {
|
||||
expect(optIn).toEqual(expect.objectContaining({ ok: true }));
|
||||
if (optIn.ok) expect(optIn.settings.preserveEmptyLines).toBe(true);
|
||||
});
|
||||
|
||||
it("defaults commaPosition to after and accepts before", () => {
|
||||
const defaultConfig = JSON.parse(serializeSqlFormatterConfig({}));
|
||||
expect(defaultConfig.options.commaPosition).toBe("after");
|
||||
|
||||
const beforeResult = parseSqlFormatterConfig(JSON.stringify({ version: 1, formatter: "sql-formatter", options: { commaPosition: "before" } }));
|
||||
expect(beforeResult).toEqual(expect.objectContaining({ ok: true }));
|
||||
if (beforeResult.ok) expect(beforeResult.settings.commaPosition).toBe("before");
|
||||
expect(JSON.parse(serializeSqlFormatterConfig({ commaPosition: "before" })).options.commaPosition).toBe("before");
|
||||
|
||||
const invalidResult = parseSqlFormatterConfig(JSON.stringify({ version: 1, formatter: "sql-formatter", options: { commaPosition: "invalid" } }));
|
||||
expect(invalidResult).toEqual(expect.objectContaining({ ok: false }));
|
||||
|
||||
// sqlFormatterOptions must not include commaPosition so third-party sql-formatter does not throw
|
||||
expect("commaPosition" in sqlFormatterOptions({ commaPosition: "before" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -321,4 +321,42 @@ describe("sql layout", () => {
|
||||
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;");
|
||||
});
|
||||
|
||||
it("formats a query with leading comma position (#7723, #5110)", async () => {
|
||||
const sql = lines("SELECT loc_id, loc_name, loc_type, delivery_emp_num, update_time", "FROM tbl", "WHERE rn = 1;");
|
||||
|
||||
expect(await format(sql, { commaPosition: "before" })).toBe(lines("SELECT loc_id", " , loc_name", " , loc_type", " , delivery_emp_num", " , update_time", "FROM tbl", "WHERE rn = 1;"));
|
||||
});
|
||||
|
||||
it("formats aligned projection aliases with leading commas", async () => {
|
||||
const sql = lines("SELECT id AS emp_id, department_name AS dept, active_status AS status", "FROM employees;");
|
||||
|
||||
expect(await format(sql, { commaPosition: "before" })).toBe(lines("SELECT id AS emp_id", " , department_name AS dept", " , active_status AS status", "FROM employees;"));
|
||||
});
|
||||
|
||||
it("formats CREATE TABLE with leading commas in DDL", 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 '运达员信息表';",
|
||||
);
|
||||
|
||||
expect(await format(sql, { commaPosition: "before" })).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 '运达员信息表';",
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -175,6 +175,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
|
||||
{ id: "formatter-tab-width", category: "formatter", titleKey: "settings.sqlFormatterTabWidth", targetId: "formatter" },
|
||||
{ id: "formatter-indent-style", category: "formatter", titleKey: "settings.sqlFormatterIndentStyle", targetId: "formatter" },
|
||||
{ id: "formatter-logical-operator-newline", category: "formatter", titleKey: "settings.sqlFormatterLogicalOperatorNewline", targetId: "formatter" },
|
||||
{ id: "formatter-comma-position", category: "formatter", titleKey: "settings.sqlFormatterCommaPosition", targetId: "formatter" },
|
||||
{ id: "formatter-from-clause-layout", category: "formatter", titleKey: "settings.sqlFormatterFromClauseLayout", targetId: "formatter" },
|
||||
{ id: "formatter-expression-width", category: "formatter", titleKey: "settings.sqlFormatterExpressionWidth", targetId: "formatter" },
|
||||
{ id: "formatter-lines-between-queries", category: "formatter", titleKey: "settings.sqlFormatterLinesBetweenQueries", targetId: "formatter" },
|
||||
|
||||
@@ -109,7 +109,16 @@ export function createTableLayout(statement: StatementNode, ctx: SqlLayoutContex
|
||||
const modifierWidth = Math.max(0, ...columns.map((column) => column.modifiers.length));
|
||||
|
||||
definitions.forEach((definition, index) => {
|
||||
writer.newline(indent);
|
||||
if (ctx.options.commaPosition === "before") {
|
||||
if (index === 0) {
|
||||
writer.newline(indent + 2);
|
||||
} else {
|
||||
writer.newline(indent);
|
||||
writer.write(", ");
|
||||
}
|
||||
} else {
|
||||
writer.newline(indent);
|
||||
}
|
||||
if (definition.kind === "column") {
|
||||
const { name: columnName, type, modifiers, tail } = definition.column;
|
||||
writer.write(columnName.padEnd(nameWidth));
|
||||
@@ -117,9 +126,9 @@ export function createTableLayout(statement: StatementNode, ctx: SqlLayoutContex
|
||||
if (modifiers) writer.write(` ${modifiers.padStart(modifierWidth)}`);
|
||||
if (tail) writer.write(` ${tail}`);
|
||||
} else {
|
||||
emitDefinition(writer, definition.nodes, indent, ctx);
|
||||
emitDefinition(writer, definition.nodes, ctx.options.commaPosition === "before" ? indent + 2 : indent, ctx);
|
||||
}
|
||||
if (index < definitions.length - 1) writer.write(",");
|
||||
if (ctx.options.commaPosition !== "before" && index < definitions.length - 1) writer.write(",");
|
||||
});
|
||||
|
||||
writer.newline(0);
|
||||
|
||||
@@ -19,6 +19,7 @@ export const DEFAULT_SQL_LAYOUT_OPTIONS: SqlLayoutOptions = {
|
||||
linesBetweenQueries: 1,
|
||||
useTabs: false,
|
||||
fromClauseSourceOnSameLine: true,
|
||||
commaPosition: "after",
|
||||
};
|
||||
|
||||
export interface SqlLayoutRequest {
|
||||
|
||||
@@ -30,6 +30,13 @@ export interface SqlLayoutOptions {
|
||||
* wherever it fits, matching the element alignment rule.
|
||||
*/
|
||||
logicalOperatorNewline: "before" | "after" | "none";
|
||||
/**
|
||||
* Where commas are placed in multiline item lists.
|
||||
*
|
||||
* `after` places commas at the end of the line (trailing comma);
|
||||
* `before` places commas at the start of continuation lines (leading comma).
|
||||
*/
|
||||
commaPosition: "after" | "before";
|
||||
/** Blank lines left between two statements. */
|
||||
linesBetweenQueries: number;
|
||||
/** Whether indentation is written with tab characters. */
|
||||
|
||||
@@ -83,7 +83,13 @@ function printClause(writer: Writer, clause: ClauseNode, baseColumn: number, ctx
|
||||
if (sourceOnOwnLine) writer.newline(baseColumn + ctx.options.indentWidth);
|
||||
else writer.space();
|
||||
} else {
|
||||
writer.newline(itemColumn);
|
||||
if (ctx.options.commaPosition === "before") {
|
||||
const leadingIndent = sourceOnOwnLine ? baseColumn + ctx.options.indentWidth : Math.max(baseColumn, itemColumn - 2);
|
||||
writer.newline(leadingIndent);
|
||||
writer.write(", ");
|
||||
} else {
|
||||
writer.newline(itemColumn);
|
||||
}
|
||||
}
|
||||
if (alignedAliases) {
|
||||
const aligned = alignedAliases[index];
|
||||
@@ -97,7 +103,7 @@ function printClause(writer: Writer, clause: ClauseNode, baseColumn: number, ctx
|
||||
} else {
|
||||
printElement(writer, item, baseColumn, childCtx);
|
||||
}
|
||||
if (index < items.length - 1) writer.write(",");
|
||||
if (ctx.options.commaPosition !== "before" && index < items.length - 1) writer.write(",");
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -409,6 +409,7 @@ export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "ge
|
||||
fromClauseSourceOnSameLine: normalizedSettings.fromClauseLayout === "sameLine",
|
||||
keywordCase: normalizedSettings.keywordCase,
|
||||
logicalOperatorNewline: normalizedSettings.logicalOperatorNewline,
|
||||
commaPosition: normalizedSettings.commaPosition,
|
||||
};
|
||||
const usesDefaultStyle = normalizedSettings.indentStyle === "standard";
|
||||
|
||||
@@ -668,6 +669,56 @@ function keepFromClauseAndFirstSourceOnSameLine(sql: string): string {
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function formatLeadingCommas(sql: string, dialect: SqlFormatDialect = "generic"): string {
|
||||
const { masked, spans } = maskStringAndCommentSpans(sql, dialect);
|
||||
const lines = masked.split("\n");
|
||||
|
||||
for (let i = 0; i < lines.length; i += 1) {
|
||||
const match = lines[i].match(/^(.*),\s*((?:\x00\d+\x00\s*)*)$/);
|
||||
if (!match || match[1].trim().length === 0) continue;
|
||||
|
||||
let j = i + 1;
|
||||
while (j < lines.length) {
|
||||
const trimmed = lines[j].trim();
|
||||
if (!trimmed) {
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
if (/^(?:\x00\d+\x00\s*)+$/.test(trimmed)) {
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (j >= lines.length) continue;
|
||||
|
||||
const nextTrimmed = lines[j].trim();
|
||||
if (nextTrimmed.startsWith(")") || nextTrimmed.startsWith("]") || nextTrimmed.startsWith(";") || nextTrimmed.startsWith(",")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const codeBeforeComma = match[1].trimEnd();
|
||||
const trailingComments = match[2] ? (codeBeforeComma.endsWith(" ") ? match[2] : ` ${match[2]}`) : "";
|
||||
lines[i] = codeBeforeComma + trailingComments;
|
||||
|
||||
const nextIndentMatch = lines[j].match(/^(\s*)/);
|
||||
const nextIndent = nextIndentMatch ? nextIndentMatch[1] : "";
|
||||
const nextRest = lines[j].slice(nextIndent.length);
|
||||
const currentIndentMatch = lines[i].match(/^(\s*)/);
|
||||
const currentIndent = currentIndentMatch ? currentIndentMatch[1] : "";
|
||||
|
||||
if (currentIndent === nextIndent) {
|
||||
lines[j] = `${nextIndent}, ${nextRest}`;
|
||||
} else if (nextIndent.length >= 2) {
|
||||
lines[j] = `${nextIndent.slice(0, -2)}, ${nextRest}`;
|
||||
} else {
|
||||
lines[j] = `${nextIndent}, ${nextRest}`;
|
||||
}
|
||||
}
|
||||
|
||||
return restoreSpans(lines.join("\n"), spans);
|
||||
}
|
||||
|
||||
/**
|
||||
* The text-level passes applied to whatever the formatter produced, whether the
|
||||
* default style's layout printer or sql-formatter itself.
|
||||
@@ -684,6 +735,7 @@ function applySqlFormatterLayout(sql: string, settings: SqlFormatterSettings, di
|
||||
let formatted = normalizeLikeOperatorCase(sql, settings, dialect);
|
||||
if (settings.logicalOperatorNewline === "none") formatted = keepLogicalOperatorsOnSameLine(formatted, dialect);
|
||||
if (settings.fromClauseLayout === "sameLine") formatted = keepFromClauseAndFirstSourceOnSameLine(formatted);
|
||||
if (settings.commaPosition === "before") formatted = formatLeadingCommas(formatted, dialect);
|
||||
return formatted;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ export const SQL_FORMATTER_CONFIG_FORMATTER = "sql-formatter";
|
||||
const CASE_VALUES = ["preserve", "upper", "lower"] as const;
|
||||
const INDENT_STYLE_VALUES = ["standard", "tabularLeft", "tabularRight"] as const;
|
||||
const LOGICAL_OPERATOR_NEWLINE_VALUES = ["before", "after", "none"] as const;
|
||||
const COMMA_POSITION_VALUES = ["after", "before"] as const;
|
||||
const FROM_CLAUSE_LAYOUT_VALUES = ["newLine", "sameLine"] as const;
|
||||
const TAB_WIDTH_VALUES = [2, 4] as const;
|
||||
const EXPRESSION_WIDTH_VALUES = [50, 80, 120] as const;
|
||||
@@ -15,6 +16,7 @@ const SQL_FORMATTER_LEGACY_OPTION_KEYS = new Set(["params"]);
|
||||
export type SqlFormatterCase = (typeof CASE_VALUES)[number];
|
||||
export type SqlFormatterIndentStyle = (typeof INDENT_STYLE_VALUES)[number];
|
||||
export type SqlFormatterLogicalOperatorNewline = (typeof LOGICAL_OPERATOR_NEWLINE_VALUES)[number];
|
||||
export type SqlFormatterCommaPosition = (typeof COMMA_POSITION_VALUES)[number];
|
||||
export type SqlFormatterFromClauseLayout = (typeof FROM_CLAUSE_LAYOUT_VALUES)[number];
|
||||
export type SqlFormatterTabWidth = (typeof TAB_WIDTH_VALUES)[number];
|
||||
export type SqlFormatterExpressionWidth = (typeof EXPRESSION_WIDTH_VALUES)[number];
|
||||
@@ -46,6 +48,7 @@ export interface SqlFormatterOptionSettings {
|
||||
useTabs: boolean;
|
||||
tabWidth: SqlFormatterTabWidth;
|
||||
logicalOperatorNewline: SqlFormatterLogicalOperatorNewline;
|
||||
commaPosition: SqlFormatterCommaPosition;
|
||||
fromClauseLayout: SqlFormatterFromClauseLayout;
|
||||
expressionWidth: SqlFormatterExpressionWidth;
|
||||
linesBetweenQueries: SqlFormatterLinesBetweenQueries;
|
||||
@@ -74,6 +77,7 @@ export const DEFAULT_SQL_FORMATTER_SETTINGS: SqlFormatterSettings = {
|
||||
useTabs: false,
|
||||
tabWidth: 2,
|
||||
logicalOperatorNewline: "before",
|
||||
commaPosition: "after",
|
||||
fromClauseLayout: "sameLine",
|
||||
expressionWidth: 120,
|
||||
linesBetweenQueries: 1,
|
||||
@@ -92,6 +96,7 @@ const SQL_FORMATTER_OPTION_KEYS = new Set<keyof SqlFormatterOptionSettings>([
|
||||
"useTabs",
|
||||
"tabWidth",
|
||||
"logicalOperatorNewline",
|
||||
"commaPosition",
|
||||
"fromClauseLayout",
|
||||
"expressionWidth",
|
||||
"linesBetweenQueries",
|
||||
@@ -110,6 +115,7 @@ const SQL_FORMATTER_OPTION_VALIDATORS: Record<keyof SqlFormatterOptionSettings,
|
||||
useTabs: (value) => typeof value === "boolean",
|
||||
tabWidth: (value) => isNumberChoice(value, TAB_WIDTH_VALUES),
|
||||
logicalOperatorNewline: (value) => isStringChoice(value, LOGICAL_OPERATOR_NEWLINE_VALUES),
|
||||
commaPosition: (value) => isStringChoice(value, COMMA_POSITION_VALUES),
|
||||
fromClauseLayout: (value) => isStringChoice(value, FROM_CLAUSE_LAYOUT_VALUES),
|
||||
expressionWidth: (value) => isNumberChoice(value, EXPRESSION_WIDTH_VALUES),
|
||||
linesBetweenQueries: (value) => isNumberChoice(value, LINES_BETWEEN_QUERIES_VALUES),
|
||||
@@ -192,6 +198,7 @@ export function sqlFormatterOptionSettings(settings: unknown): SqlFormatterOptio
|
||||
useTabs: normalizeBoolean(input.useTabs, DEFAULT_SQL_FORMATTER_SETTINGS.useTabs),
|
||||
tabWidth: normalizeNumberChoice(input.tabWidth, TAB_WIDTH_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.tabWidth),
|
||||
logicalOperatorNewline: normalizeChoice(input.logicalOperatorNewline, LOGICAL_OPERATOR_NEWLINE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.logicalOperatorNewline),
|
||||
commaPosition: normalizeChoice(input.commaPosition, COMMA_POSITION_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.commaPosition),
|
||||
fromClauseLayout: normalizeChoice(input.fromClauseLayout, FROM_CLAUSE_LAYOUT_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.fromClauseLayout),
|
||||
expressionWidth: normalizeNumberChoice(input.expressionWidth, EXPRESSION_WIDTH_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.expressionWidth),
|
||||
linesBetweenQueries: normalizeNumberChoice(input.linesBetweenQueries, LINES_BETWEEN_QUERIES_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.linesBetweenQueries),
|
||||
|
||||
Reference in new issue
Block a user