prettier-plugin-sql-cst 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -40,6 +40,24 @@ ORDER BY client.name
40
40
  LIMIT 100
41
41
  ```
42
42
 
43
+ ## Formatting philosophy
44
+
45
+ - Adapt formatting based on expression length.
46
+ - Stick to one style and avoid configuration options.
47
+ - Format embedded languages (like JSON data and JavaScript programs).
48
+ - When unsure, preserve existing syntax.
49
+
50
+ ## Non-whitespace formatting
51
+
52
+ Currently this plugin preserves most of the syntax elements
53
+ and concentrates mainly on the layout of whitespace.
54
+ For example it does not add/remove paratheses.
55
+
56
+ There are some opinionated non-whitespace changes though:
57
+
58
+ - UPPERCASE all keywords.
59
+ - Add `AS` keyword to all alias definitions.
60
+
43
61
  ## Getting started
44
62
 
45
63
  Install it as any other Prettier plugin:
@@ -51,15 +69,39 @@ npm install --save-dev prettier prettier-plugin-sql-cst
51
69
  Then use it on SQL files though Prettier command line tool or Prettier extension
52
70
  for your editor of choice.
53
71
 
72
+ ## Choosing an SQL dialect
73
+
74
+ By default the plugin will determine SQL dialect based on file extension:
75
+
76
+ - `.sql` or `.sqlite` - SQLite
77
+ - `.bigquery` - BigQuery
78
+
79
+ You can override this behavior with a prettier configuration:
80
+
81
+ ```json
82
+ {
83
+ "overrides": [
84
+ {
85
+ "files": ["*.sql"],
86
+ "options": { "parser": "bigquery" }
87
+ }
88
+ ]
89
+ }
90
+ ```
91
+
92
+ The plugin provides the following parsers:
93
+
94
+ - `sqlite`
95
+ - `bigquery`
96
+
54
97
  ## Configuration
55
98
 
56
99
  The standard Prettier options [printWidth][], [tabWidth][], [useTabs][] apply.
57
100
  There are also some SQL-specific options:
58
101
 
59
- | API Option | Default | Description |
60
- | ---------------- | :--------: | ------------------------------------------------------ |
61
- | `sqlKeywordCase` | `preserve` | Converts SQL keywords to `upper` or `lower` case. |
62
- | `sqlAliasAs` | `preserve` | Uses AS keyword in aliases either `always` or `never`. |
102
+ | API Option | Default | Description |
103
+ | ---------------- | :-----: | ------------------------------------------------------------------------- |
104
+ | `sqlKeywordCase` | `upper` | Converts SQL keywords to `upper` or `lower` case, or `preserve` existing. |
63
105
 
64
106
  ## Limitations and development status
65
107
 
@@ -75,22 +117,6 @@ Formatting of the following SQL statements is fully implemented:
75
117
  - CREATE / DROP VIEW
76
118
  - CREATE / DROP INDEX
77
119
 
78
- Unlike Prettier for JavaScript, this plugin currently preserves all the syntax elements.
79
- For example it does not add/remove paratheses or modify the case of keywords (by default).
80
- It only manipulates whitespace.
81
-
82
- This will likely change in the future, with the goal of being more opinionated.
83
- Some possibilities:
84
-
85
- - capitalize all keywords
86
- - ensure all alias definitions use the `AS` keyword.
87
- - ensure consistent use of quotes (e.g. always quote keywords)
88
- - eliminate redundant parenthesis.
89
-
90
- The exact formatting style is also very much still in flux.
91
- The overall goal is to have no options to configure different styles,
92
- but rather to develop one opinionated style of formatting SQL.
93
-
94
120
  [prettier]: https://prettier.io/
95
121
  [printWidth]: https://prettier.io/docs/en/options.html#print-width
96
122
  [tabWidth]: https://prettier.io/docs/en/options.html#tab-width
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.embedJson = void 0;
15
+ var node_utils_1 = require("./node_utils");
16
+ var print_utils_1 = require("./print_utils");
17
+ var embedJson = function (path, print, textToDoc, options) {
18
+ var node = path.getValue();
19
+ var parent = path.getParentNode();
20
+ if ((0, node_utils_1.isStringLiteral)(node) && (0, node_utils_1.isJsonLiteral)(parent)) {
21
+ if (containsTripleQuote(node.value) ||
22
+ containsBackslash(node.value) ||
23
+ isRawString(node)) {
24
+ // Give up for now. Don't format JSON inside the string.
25
+ // Tackle these corner-case in the future.
26
+ return null;
27
+ }
28
+ var json = textToDoc(node.value, __assign(__assign({}, options), { parser: "json" }));
29
+ var inlineQuote = containsSingleQuote(node.value) ? "'''" : "'";
30
+ return [
31
+ (0, print_utils_1.ifBreak)("'''", inlineQuote),
32
+ (0, print_utils_1.indent)([print_utils_1.softline, (0, print_utils_1.stripTrailingHardline)(json)]),
33
+ print_utils_1.softline,
34
+ (0, print_utils_1.ifBreak)("'''", inlineQuote),
35
+ ];
36
+ }
37
+ return null;
38
+ };
39
+ exports.embedJson = embedJson;
40
+ var containsSingleQuote = function (json) { return /'/.test(json); };
41
+ var containsTripleQuote = function (json) { return /'''/.test(json); };
42
+ var containsBackslash = function (json) { return /\\/.test(json); };
43
+ var isRawString = function (node) { return /^R/i.test(node.text); };
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.printers = exports.parsers = exports.languages = exports.options = void 0;
4
4
  var sql_parser_cst_1 = require("sql-parser-cst");
5
5
  var printSql_1 = require("./printSql");
6
+ var embedJson_1 = require("./embedJson");
6
7
  var utils_1 = require("./utils");
7
8
  var transformCst_1 = require("./transform/transformCst");
8
9
  var options_1 = require("./options");
@@ -11,12 +12,12 @@ exports.languages = [
11
12
  {
12
13
  extensions: [".sql", ".sqlite"],
13
14
  name: "SQLite SQL",
14
- parsers: ["sql-parser-cst-sqlite"],
15
+ parsers: ["sqlite"],
15
16
  },
16
17
  {
17
18
  extensions: [".bigquery"],
18
19
  name: "BigQuery SQL",
19
- parsers: ["sql-parser-cst-bigquery"],
20
+ parsers: ["bigquery"],
20
21
  },
21
22
  ];
22
23
  var createParser = function (dialect) { return ({
@@ -33,12 +34,13 @@ var createParser = function (dialect) { return ({
33
34
  locEnd: function (node) { var _a; return (_a = node.range) === null || _a === void 0 ? void 0 : _a[1]; },
34
35
  }); };
35
36
  exports.parsers = {
36
- "sql-parser-cst-sqlite": createParser("sqlite"),
37
- "sql-parser-cst-bigquery": createParser("bigquery"),
37
+ sqlite: createParser("sqlite"),
38
+ bigquery: createParser("bigquery"),
38
39
  };
39
40
  exports.printers = {
40
41
  "sql-cst": {
41
42
  print: printSql_1.printSql,
43
+ embed: embedJson_1.embedJson,
42
44
  printComment: function (path) {
43
45
  return path.getValue().text;
44
46
  },
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isKeyword = exports.isCreateTableStmt = exports.isFuncCall = exports.isValuesClause = void 0;
3
+ exports.isStringLiteral = exports.isJsonLiteral = exports.isEmpty = exports.isKeyword = exports.isCreateTableStmt = exports.isFuncCall = exports.isValuesClause = void 0;
4
4
  var utils_1 = require("./utils");
5
5
  var is = function (type) {
6
6
  return function (node) {
@@ -11,3 +11,6 @@ exports.isValuesClause = is("values_clause");
11
11
  exports.isFuncCall = is("func_call");
12
12
  exports.isCreateTableStmt = is("create_table_stmt");
13
13
  exports.isKeyword = is("keyword");
14
+ exports.isEmpty = is("empty");
15
+ exports.isJsonLiteral = is("json_literal");
16
+ exports.isStringLiteral = is("string_literal");
package/dist/options.js CHANGED
@@ -6,7 +6,7 @@ exports.options = {
6
6
  type: "choice",
7
7
  category: "SQL",
8
8
  since: "0.1.0",
9
- default: "preserve",
9
+ default: "upper",
10
10
  description: "Enforces upper/lower case for SQL keywords",
11
11
  choices: [
12
12
  {
@@ -17,16 +17,4 @@ exports.options = {
17
17
  { value: "lower", description: "forces all keywords to lowercase" },
18
18
  ],
19
19
  },
20
- sqlAliasAs: {
21
- type: "choice",
22
- category: "SQL",
23
- since: "0.1.1",
24
- default: "preserve",
25
- description: "Enforce or forbid use of AS keyword in aliases",
26
- choices: [
27
- { value: "preserve", description: "keeps existing style" },
28
- { value: "always", description: "always includes AS keyword" },
29
- { value: "never", description: "never include AS keyword" },
30
- ],
31
- },
32
20
  };
@@ -1,11 +1,12 @@
1
1
  "use strict";
2
2
  var _a;
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.containsNewline = exports.join = exports.lineSuffix = exports.group = exports.indent = exports.softline = exports.hardline = exports.line = void 0;
4
+ exports.containsNewline = exports.join = exports.stripTrailingHardline = exports.ifBreak = exports.lineSuffix = exports.group = exports.indent = exports.softline = exports.hardline = exports.line = void 0;
5
5
  var prettier_1 = require("prettier");
6
6
  var utils_1 = require("./utils");
7
- exports.line = (_a = prettier_1.doc.builders, _a.line), exports.hardline = _a.hardline, exports.softline = _a.softline, exports.indent = _a.indent, exports.group = _a.group, exports.lineSuffix = _a.lineSuffix;
7
+ exports.line = (_a = prettier_1.doc.builders, _a.line), exports.hardline = _a.hardline, exports.softline = _a.softline, exports.indent = _a.indent, exports.group = _a.group, exports.lineSuffix = _a.lineSuffix, exports.ifBreak = _a.ifBreak;
8
8
  var origJoin = prettier_1.doc.builders.join;
9
+ exports.stripTrailingHardline = prettier_1.doc.utils.stripTrailingHardline;
9
10
  /** Improved join() that also accepts a non-array docs parameter */
10
11
  var join = function (sep, docs) {
11
12
  return (0, utils_1.isArray)(docs) ? origJoin(sep, docs) : docs;
@@ -12,4 +12,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.dataTypeMap = void 0;
13
13
  exports.dataTypeMap = {
14
14
  data_type: function (print) { return __spreadArray([print.spaced("nameKw")], print(["params"]), true); },
15
+ generic_type_params: function (print) { return ["<", print("params"), ">"]; },
16
+ array_type_param: function (print) { return print("dataType"); },
17
+ struct_type_param: function (print) { return print.spaced(["name", "dataType"]); },
15
18
  };
@@ -12,10 +12,25 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.exprMap = void 0;
13
13
  var print_utils_1 = require("../print_utils");
14
14
  var node_utils_1 = require("../node_utils");
15
+ var utils_1 = require("../utils");
15
16
  exports.exprMap = {
16
17
  list_expr: function (print, node, path) {
17
18
  var parent = path.getParentNode();
18
- return (0, print_utils_1.join)([",", (0, node_utils_1.isValuesClause)(parent) ? print_utils_1.hardline : print_utils_1.line], print("items").map(function (it) { return (0, print_utils_1.group)(it); }));
19
+ var children = print("items").map(function (it) { return (0, print_utils_1.group)(it); });
20
+ var lineType = (0, node_utils_1.isValuesClause)(parent) ? print_utils_1.hardline : print_utils_1.line;
21
+ // When last item is type:empty, we're dealing with a trailing comma.
22
+ // Don't add a space (or newline) after it.
23
+ // We still want to print it though, as it might have comments attached.
24
+ if ((0, node_utils_1.isEmpty)((0, utils_1.last)(node.items))) {
25
+ return [
26
+ (0, print_utils_1.join)([",", lineType], children.slice(0, -1)),
27
+ ",",
28
+ (0, utils_1.last)(children),
29
+ ];
30
+ }
31
+ else {
32
+ return (0, print_utils_1.join)([",", lineType], children);
33
+ }
19
34
  },
20
35
  paren_expr: function (print, node, path) {
21
36
  var parent = path.getParentNode();
@@ -28,7 +43,9 @@ exports.exprMap = {
28
43
  }
29
44
  return print.spaced(["left", "operator", "right"]);
30
45
  },
31
- prefix_op_expr: function (print) { return print.spaced(["operator", "expr"]); },
46
+ prefix_op_expr: function (print, node) {
47
+ return ((0, utils_1.isString)(node.operator) ? print : print.spaced)(["operator", "expr"]);
48
+ },
32
49
  postfix_op_expr: function (print) { return print.spaced(["expr", "operator"]); },
33
50
  between_expr: function (print) {
34
51
  return print.spaced(["left", "betweenKw", "begin", "andKw", "end"]);
@@ -61,10 +78,28 @@ exports.exprMap = {
61
78
  cast_expr: function (print) { return print(["castKw", "args"]); },
62
79
  cast_arg: function (print) { return print.spaced(["expr", "asKw", "dataType"]); },
63
80
  raise_expr: function (print) { return print(["raiseKw", "args"]); },
81
+ interval_expr: function (print) { return print.spaced(["intervalKw", "expr", "unit"]); },
82
+ interval_unit_range: function (print) {
83
+ return print.spaced(["fromUnitKw", "toKw", "toUnitKw"]);
84
+ },
85
+ array_expr: function (print) {
86
+ return (0, print_utils_1.group)(["[", (0, print_utils_1.indent)([print_utils_1.softline, print("expr")]), print_utils_1.softline, "]"]);
87
+ },
88
+ struct_expr: function (print) {
89
+ return (0, print_utils_1.group)(["(", (0, print_utils_1.indent)([print_utils_1.softline, print("expr")]), print_utils_1.softline, ")"]);
90
+ },
91
+ typed_expr: function (print) { return print(["dataType", "expr"]); },
64
92
  number_literal: function (print) { return print("text"); },
65
93
  boolean_literal: function (print) { return print("valueKw"); },
66
94
  string_literal: function (print) { return print("text"); },
67
95
  null_literal: function (print) { return print("nullKw"); },
96
+ numeric_literal: function (print) { return print.spaced(["numericKw", "string"]); },
97
+ bignumeric_literal: function (print) { return print.spaced(["bignumericKw", "string"]); },
98
+ date_literal: function (print) { return print.spaced(["dateKw", "string"]); },
99
+ time_literal: function (print) { return print.spaced(["timeKw", "string"]); },
100
+ datetime_literal: function (print) { return print.spaced(["datetimeKw", "string"]); },
101
+ timestamp_literal: function (print) { return print.spaced(["timestampKw", "string"]); },
102
+ json_literal: function (print) { return print.spaced(["jsonKw", "string"]); },
68
103
  identifier: function (print) { return print("text"); },
69
104
  };
70
105
  var isBooleanOp = function (_a) {
@@ -3,19 +3,22 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.programMap = void 0;
4
4
  var print_utils_1 = require("../print_utils");
5
5
  exports.programMap = {
6
- program: function (print, node, path) { return path.map(printLineWith(print), "statements"); },
6
+ program: function (print, node) { return [
7
+ print("statements").map(function (doc, i) {
8
+ return printStatement(doc, i, node.statements);
9
+ }),
10
+ print_utils_1.hardline,
11
+ ]; },
7
12
  };
8
- var printLineWith = function (print) {
9
- return function (childPath, i, all) {
10
- var node = childPath.getValue();
11
- if (i === 0) {
12
- return print(childPath);
13
- }
14
- else if (i < all.length - 1 || node.type !== "empty") {
15
- return [";", print_utils_1.hardline, print_utils_1.hardline, print(childPath)];
16
- }
17
- else {
18
- return [";", print(childPath)];
19
- }
20
- };
13
+ var printStatement = function (doc, i, statements) {
14
+ var node = statements[i];
15
+ if (i === 0) {
16
+ return doc;
17
+ }
18
+ else if (i < statements.length - 1 || node.type !== "empty") {
19
+ return [";", print_utils_1.hardline, print_utils_1.hardline, doc];
20
+ }
21
+ else {
22
+ return [";", doc];
23
+ }
21
24
  };
@@ -24,7 +24,7 @@ exports.selectMap = {
24
24
  ]; },
25
25
  select_clause: function (print) {
26
26
  return (0, print_utils_1.group)([
27
- print.spaced(["selectKw", "distinctKw"]),
27
+ print.spaced(["selectKw", "distinctKw", "asStructOrValueKw"]),
28
28
  (0, print_utils_1.indent)([print_utils_1.line, print("columns")]),
29
29
  ]);
30
30
  },
@@ -66,6 +66,7 @@ exports.selectMap = {
66
66
  group_by_clause: function (print) {
67
67
  return (0, print_utils_1.group)([print.spaced("groupByKw"), (0, print_utils_1.indent)([print_utils_1.line, print("columns")])]);
68
68
  },
69
+ group_by_rollup: function (print) { return print(["rollupKw", "columns"]); },
69
70
  partition_by_clause: function (print) {
70
71
  return (0, print_utils_1.group)([
71
72
  print.spaced("partitionByKw"),
@@ -75,6 +76,9 @@ exports.selectMap = {
75
76
  having_clause: function (print) {
76
77
  return (0, print_utils_1.group)([print("havingKw"), (0, print_utils_1.indent)([print_utils_1.line, print("expr")])]);
77
78
  },
79
+ qualify_clause: function (print) {
80
+ return (0, print_utils_1.group)([print("qualifyKw"), (0, print_utils_1.indent)([print_utils_1.line, print("expr")])]);
81
+ },
78
82
  returning_clause: function (print) {
79
83
  return (0, print_utils_1.group)([print("returningKw"), (0, print_utils_1.indent)([print_utils_1.line, print("columns")])]);
80
84
  },
@@ -1,36 +1,12 @@
1
1
  "use strict";
2
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
3
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
4
- if (ar || !(i in from)) {
5
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
6
- ar[i] = from[i];
7
- }
8
- }
9
- return to.concat(ar || Array.prototype.slice.call(from));
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.processAliasAs = void 0;
13
4
  var sql_parser_cst_1 = require("sql-parser-cst");
14
- var processAliasAs = function (cst, options) {
5
+ // Adds AS keyword to aliases if none exists
6
+ var processAliasAs = function (cst) {
15
7
  var mutateAliases = (0, sql_parser_cst_1.cstVisitor)({
16
8
  alias: function (node) {
17
- var _a, _b;
18
- switch (options.sqlAliasAs) {
19
- case "preserve":
20
- // do nothing
21
- break;
22
- case "always":
23
- // Add AS keyword if none exists
24
- node.asKw = node.asKw || { type: "keyword", name: "AS", text: "AS" };
25
- break;
26
- case "never":
27
- // Remove AS keyword and ensure comments attached to it don't get lost
28
- if (node.asKw && (((_a = node.leading) === null || _a === void 0 ? void 0 : _a.length) || ((_b = node.trailing) === null || _b === void 0 ? void 0 : _b.length))) {
29
- var comments = __spreadArray(__spreadArray([], (node.leading || []), true), (node.trailing || []), true);
30
- node.alias.leading = __spreadArray(__spreadArray([], comments, true), (node.alias.leading || []), true);
31
- }
32
- node.asKw = undefined;
33
- }
9
+ node.asKw = node.asKw || { type: "keyword", name: "AS", text: "AS" };
34
10
  },
35
11
  });
36
12
  mutateAliases(cst);
@@ -3,5 +3,5 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.transformCst = void 0;
4
4
  var comments_1 = require("./comments");
5
5
  var aliasAs_1 = require("./aliasAs");
6
- var transformCst = function (cst, options) { return (0, comments_1.moveCommentsToRoot)((0, aliasAs_1.processAliasAs)(cst, options)); };
6
+ var transformCst = function (cst, options) { return (0, comments_1.moveCommentsToRoot)((0, aliasAs_1.processAliasAs)(cst)); };
7
7
  exports.transformCst = transformCst;
package/dist/utils.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.arrayWrap = exports.isNode = exports.isEmptyArray = exports.isArray = exports.isObject = exports.isString = exports.isDefined = void 0;
3
+ exports.last = exports.arrayWrap = exports.isNode = exports.isEmptyArray = exports.isArray = exports.isObject = exports.isString = exports.isDefined = void 0;
4
4
  var isDefined = function (value) {
5
5
  return value !== undefined;
6
6
  };
@@ -26,3 +26,5 @@ var isCommentType = function (type) {
26
26
  };
27
27
  var arrayWrap = function (x) { return ((0, exports.isArray)(x) ? x : [x]); };
28
28
  exports.arrayWrap = arrayWrap;
29
+ var last = function (arr) { return arr[arr.length - 1]; };
30
+ exports.last = last;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prettier-plugin-sql-cst",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Prettier plugin for SQL",
5
5
  "author": "Rene Saarsoo <nene@triin.net>",
6
6
  "license": "GPL-3.0-or-later",
@@ -29,7 +29,7 @@
29
29
  ],
30
30
  "dependencies": {
31
31
  "prettier": "^2.8.2",
32
- "sql-parser-cst": "^0.11.0"
32
+ "sql-parser-cst": "^0.11.1"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/jest": "^29.2.5",