forked from nene/prettier-plugin-sql-cst
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathembedSql.ts
More file actions
56 lines (47 loc) · 1.33 KB
/
Copy pathembedSql.ts
File metadata and controls
56 lines (47 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { Printer } from "prettier";
import { CreateFunctionStmt, Node, StringLiteral } from "sql-parser-cst";
import {
isAsClause,
isCreateFunctionStmt,
isLanguageClause,
isStringLiteral,
} from "./node_utils";
import { hardline, indent, stripTrailingHardline } from "./print_utils";
export const embedSql: NonNullable<Printer<Node>["embed"]> = (path, options) => {
const node = path.node;
const parent = path.getParentNode(0);
const grandParent = path.getParentNode(1);
if (
isStringLiteral(node) &&
isAsClause(parent) &&
isCreateFunctionStmt(grandParent) &&
grandParent.clauses.some(isSqlLanguageClause)
) {
return async (textToDoc) => {
const quote = detectQuote(node);
if (quote) {
const sql = await textToDoc(node.value, options);
return [
quote,
indent([hardline, stripTrailingHardline(sql)]),
hardline,
quote,
];
}
};
}
return null;
};
const isSqlLanguageClause = (
clause: CreateFunctionStmt["clauses"][0],
): boolean => isLanguageClause(clause) && clause.name.name === "sql";
const detectQuote = (
node: StringLiteral,
): string | undefined => {
const match = node.text.match(/^('|\$[^$]*\$)/);
const quote = match?.[1];
if (quote && node.text.endsWith(quote)) {
return quote;
}
return undefined;
};