Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ The plugin provides the following parsers:
- `bigquery`
- `postgresql` (**experimental! expect crashes**)
- `plpgsql` (**experimental! expect crashes**)
- `psql` (**experimental!**): formats PostgreSQL SQL between standalone psql commands. Select it explicitly with `--parser psql`; `COPY FROM STDIN` is not supported yet.
- `mysql` (**experimental! expect crashes**)
- `mariadb` (**experimental! expect crashes**)

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
],
"dependencies": {
"prettier": "^3.0.3",
"sql-parser-cst": "^0.43.0"
"sql-parser-cst": "git+https://github.com/arnodirlam/sql-parser-cst.git#0a00400f"
},
"devDependencies": {
"@types/jest": "^30.0.0",
Expand Down
11 changes: 9 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,19 @@ export const languages: SupportLanguage[] = [
name: "Experimental PL/pgSQL",
parsers: ["plpgsql"],
},
{
extensions: [],
name: "Experimental psql",
parsers: ["psql"],
},
];

const createParser = (dialect: DialectName): Parser<Node> => ({
const createParser = (dialect: DialectName, psql = false): Parser<Node> => ({
parse: (text, options) =>
transformCst(
parse(text, {
dialect,
psql,
includeRange: true,
includeComments: true,
filename: options.filepath,
Expand All @@ -61,13 +67,14 @@ const createParser = (dialect: DialectName): Parser<Node> => ({
locEnd: (node) => node.range?.[1] as number,
});

export const parsers: Record<DialectName, Parser<Node>> = {
export const parsers: Record<DialectName | "psql", Parser<Node>> = {
sqlite: createParser("sqlite"),
bigquery: createParser("bigquery"),
mysql: createParser("mysql"),
mariadb: createParser("mariadb"),
postgresql: createParser("postgresql"),
plpgsql: createParser("plpgsql"),
psql: createParser("postgresql", true),
};

export const printers: Record<"sql-cst", Printer> = {
Expand Down
4 changes: 2 additions & 2 deletions src/languageClause.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
Identifier,
StringLiteral,
} from "sql-parser-cst";
import { isIdentifier, isLanguageClause } from "./node_utils";
import { isLanguageClause } from "./node_utils";

export const isJavaScriptLanguageClause = (
clause: CreateFunctionStmt["clauses"][0],
Expand All @@ -22,4 +22,4 @@ export const isPlpgsqlLanguageClause = (
languageName(clause.name).toLowerCase() === "plpgsql";

const languageName = (node: Identifier | StringLiteral): string =>
isIdentifier(node) ? node.name : node.value;
node.type === "string_literal" ? node.value : node.name;
3 changes: 3 additions & 0 deletions src/syntax/expr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,9 @@ export const exprMap: CstToDocMap<AllExprNodes> = {
}
}
},
psql_variable: (print, node) => node.text,
/** cst-ignore: name */
psql_identifier: (print, node) => node.text,
/** cst-ignore: name */
variable: (print, node, path, options) =>
isQuotedVariable(node) ? print("text") : printIdentifier(node, options),
Expand Down
31 changes: 28 additions & 3 deletions src/syntax/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,37 @@ import { CstToDocMap } from "../CstToDocMap";
import { AllPrettierOptions } from "src/options";

export const programMap: CstToDocMap<Program> = {
program: (print, node, path, options) =>
print("statements").map((doc, i) =>
program: (print, node, path, options) => {
const statements = print("statements");
if (node.psql) {
if (statements.length === 0) {
return statements;
}
return [
...statements.map((doc, i) => {
if (i === 0) {
return doc;
}
const prevNode = node.statements[i - 1];
const currentNode = node.statements[i];
const separator = hasEmptyLineBetweenNodes(
prevNode,
currentNode,
options,
)
? [hardline, hardline]
: hardline;
return [separator, doc];
}),
hardline,
];
}
return statements.map((doc, i) =>
i === node.statements.length - 1
? printFinalStatement(doc, i, node.statements, options)
: printStatement(doc, i, node.statements, options),
),
);
},
};

const printStatement = (
Expand Down
40 changes: 40 additions & 0 deletions src/syntax/psql.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { PsqlCommand, PsqlQuery } from "sql-parser-cst";
import { CstToDocMap } from "../CstToDocMap";
import { hardline } from "../print_utils";
import { AllPrettierOptions } from "../options";

export const psqlMap: CstToDocMap<PsqlCommand | PsqlQuery> = {
psql_command: (print, node, path, options) => {
const start = node.range?.[0];
if (start === undefined) {
return node.text;
}
const lineStart = options.originalText.lastIndexOf("\n", start - 1) + 1;
return options.originalText.slice(lineStart, start) + node.text;
},
psql_query: (print, node, path, options) => {
if (!node.terminator.startsWith("\\")) {
return [print("query"), node.terminator];
}

const queryEnd = node.query.range?.[1] ?? node.range?.[0] ?? 0;
const trailingEnd = (node.query.trailing ?? []).reduce(
(end, comment) => Math.max(end, comment.range?.[1] ?? end),
queryEnd,
);
const commandStart =
(node.range?.[1] ?? trailingEnd) - node.terminator.length;
const gap = options.originalText.slice(trailingEnd, commandStart);
const lineBreaks = gap.match(/\r\n|\r|\n/g)?.length ?? 0;
const indentation = gap.slice(
Math.max(gap.lastIndexOf("\n"), gap.lastIndexOf("\r")) + 1,
);

return [
print("query"),
...Array.from({ length: Math.max(lineBreaks, 1) }, () => hardline),
indentation,
node.terminator,
];
},
};
2 changes: 2 additions & 0 deletions src/syntax/transformMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { parameterMap } from "./parameter";
import { policyMap } from "./policy";
import { preparedStatementsMap } from "./prepared_statements";
import { proceduralLanguageMap } from "./procedural_language";
import { psqlMap } from "./psql";
import { procedureMap } from "./procedure";
import { procClauseMap } from "./proc_clause";
import { programMap } from "./program";
Expand Down Expand Up @@ -79,6 +80,7 @@ export const transformMap: CstToDocMap<Node> = {
...policyMap,
...preparedStatementsMap,
...procClauseMap,
...psqlMap,
...proceduralLanguageMap,
...procedureMap,
...programMap,
Expand Down
2 changes: 1 addition & 1 deletion src/transform/transformCst.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const transformCst: TransformFn = (
moveCommentsToRoot,
stripTrailingCommas,
];
if (options.sqlFinalSemicolon) {
if (options.sqlFinalSemicolon && !cst.psql) {
transforms.push(addFinalSemicolon);
}
if (options.sqlCanonicalSyntax) {
Expand Down
66 changes: 66 additions & 0 deletions test/psql.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import * as prettier from "prettier";
import * as plugin from "../src";

const format = (sql: string, options: prettier.Options = {}) =>
prettier.format(sql, { parser: "psql", plugins: [plugin], ...options });

describe("psql parser", () => {
it("formats SQL while preserving standalone commands and arguments", async () => {
const sql = String.raw`\set ON_ERROR_STOP on
\restrict abc123
\if :ready
select id,name from widgets where active=true
\gset widget_
\else
\echo 'Not ready' :name
\quit
\endif
\unrestrict abc123
`;

const expected = String.raw`\set ON_ERROR_STOP on
\restrict abc123
\if :ready
SELECT id, name FROM widgets WHERE active = TRUE
\gset widget_
\else
\echo 'Not ready' :name
\quit
\endif
\unrestrict abc123
`;

expect(await format(sql)).toBe(expected);
expect(await format(expected)).toBe(expected);
});

it("preserves query terminators without adding semicolons", async () => {
expect(await format("select 1 as result\n\\gset result_\n")).toBe(
"SELECT 1 AS result\n\\gset result_\n",
);
});

it("formats semicolon-terminated queries without changing boundaries", async () => {
expect(await format("select 1;\n\\echo done\nselect 2\n")).toBe(
"SELECT 1;\n\\echo done\nSELECT 2\n",
);
});

it("preserves psql variable references", async () => {
expect(
await format("select :value, :'name', :\"table\", :{?ready}\n"),
).toBe("SELECT :value, :'name', :\"table\", :{?ready}\n");
});

it("preserves command indentation and blank lines", async () => {
expect(await format("select 1\n\n \\gset\n\n \\echo done\n")).toBe(
"SELECT 1\n\n \\gset\n\n \\echo done\n",
);
});

it("preserves SQL comments before query commands", async () => {
expect(await format("select 1 -- keep this\n\\gset\n")).toBe(
"SELECT 1 -- keep this\n\\gset\n",
);
});
});
5 changes: 2 additions & 3 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2778,10 +2778,9 @@ sprintf-js@~1.0.2:
resolved "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz"
integrity sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==

sql-parser-cst@^0.43.0:
"sql-parser-cst@git+https://github.com/arnodirlam/sql-parser-cst.git#0a00400f":
version "0.43.0"
resolved "https://registry.yarnpkg.com/sql-parser-cst/-/sql-parser-cst-0.43.0.tgz#fcb33015328102c37f1c6644dc0a98dd74e594dd"
integrity sha512-T/pCNnKOlY6AN4b3xr8C3bmEnmRblr7h6Aful/sTTp2hR0tXs/LKpvL8uLuFSTB87Lw03biCeHX9wTOIHSMlwQ==
resolved "git+https://github.com/arnodirlam/sql-parser-cst.git#0a00400f981eafca6b8670dc7aaece1b5548b633"

stack-utils@^2.0.6:
version "2.0.6"
Expand Down
Loading