Skip to content

Commit f7fe519

Browse files
committed
Merge branch 'gwax-sql-formatter' into master
2 parents 4d21421 + 72ef29b commit f7fe519

39 files changed

+13231
-7165
lines changed

.babelrc

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,4 @@
11
{
2-
"presets": [
3-
["es2015", {"loose": true}]
4-
],
5-
"plugins": [
6-
"add-module-exports",
7-
"transform-class-properties",
8-
"transform-function-bind",
9-
"transform-object-rest-spread",
10-
"transform-es3-member-expression-literals",
11-
"transform-es3-property-literals"
12-
]
2+
"presets": ["@babel/preset-env"],
3+
"plugins": ["@babel/plugin-proposal-class-properties", "add-module-exports"]
134
}

.editorconfig

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,4 @@ charset = utf-8
66
trim_trailing_whitespace = true
77
insert_final_newline = true
88
indent_style = space
9-
indent_size = 4
10-
11-
[{package.json,.travis.yml}]
12-
indent_style = space
139
indent_size = 2

.eslintignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
/bin
12
/lib
23
/dist
34
/coverage
5+
webpack.*.js

.eslintrc

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,19 @@
11
{
2-
"extends": "zt/base",
3-
"env": {
4-
"jest": true
5-
}
2+
"parser": "babel-eslint",
3+
"extends": ["airbnb-base", "prettier"],
4+
"plugins": ["prettier"],
5+
"rules": {
6+
"prettier/prettier": ["error"],
7+
"require-unicode-regexp": ["error"],
8+
"func-names": "error",
9+
"no-useless-concat": "off",
10+
"class-methods-use-this": "off",
11+
"no-param-reassign": "off",
12+
"prefer-template": "off",
13+
"no-plusplus": "off",
14+
"no-else-return": "off"
15+
},
16+
"env": {
17+
"jest": true
18+
}
619
}

.prettierignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/coverage
2+
/dist
3+
/lib
4+
/node_modules

.prettierrc.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"printWidth": 100,
3+
"singleQuote": true
4+
}

CONTRIBUTORS

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
Adrien Pyke <[email protected]>
2+
Adrien Pyke <[email protected]>
3+
Damon Davison <[email protected]>
4+
Davut Can Abacigil <[email protected]>
5+
6+
Erik Hirmo <[email protected]>
7+
George Leslie-Waksman <[email protected]>
8+
George Leslie-Waksman <[email protected]>
9+
Ian Campbell <[email protected]>
10+
Matheus Salmi <[email protected]>
11+
Matheus Teixeira <[email protected]>
12+
Nicolas Dermine <[email protected]>
13+
Offir Baron <[email protected]>
14+
Olexandr Sydorchuk <[email protected]>
15+
Rafael Pinto <[email protected]>
16+
Rahel Rjadnev-Meristo <[email protected]>
17+
Rahel Rjadnev-Meristo <[email protected]>
18+
Rene Saarsoo <[email protected]>
19+
Rene Saarsoo <[email protected]>
20+
Rene Saarsoo <[email protected]>
21+
Sasha Aliashkevich <[email protected]>
22+
Sergei Egorov <[email protected]>
23+
Tyler Jones <[email protected]>
24+
Uku Pattak <[email protected]>
25+
Uku Pattak <[email protected]>
26+
dependabot[bot] <dependabot[bot]@users.noreply.github.com>
27+
28+

LICENSE

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
The MIT License (MIT)
22

3-
Copyright (c) 2016-present ZeroTurnaround LLC
3+
Copyright (c) 2016-2020 ZeroTurnaround LLC
4+
Copyright (c) 2020-present George Leslie-Waksman and other contributors
45

56
Permission is hereby granted, free of charge, to any person obtaining a copy
67
of this software and associated documentation files (the "Software"), to deal

README.md

Lines changed: 79 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,62 +2,118 @@
22

33
**SQL Formatter** is a JavaScript library for pretty-printing SQL queries.
44
It started as a port of a [PHP Library][], but has since considerably diverged.
5-
It supports [Standard SQL][], [Couchbase N1QL][], [IBM DB2][] and [Oracle PL/SQL][] dialects.
5+
6+
SQL Formatter supports [Standard SQL][], [Couchbase N1QL][], [IBM DB2][],
7+
[Oracle PL/SQL][], [Amazon Redshift][], and [Spark][] dialects.
68

79
&rarr; [Try the demo.](https://zeroturnaround.github.io/sql-formatter/)
810

911
## Install
1012

1113
Get the latest version from NPM:
1214

13-
```
15+
```sh
1416
npm install sql-formatter
1517
```
1618

19+
## Command Line Interface
20+
21+
The CLI tool will be installed under `sql-formatter`
22+
and may be invoked via `npx sql-formatter`:
23+
24+
```sh
25+
sql-formatter -h
26+
```
27+
28+
```
29+
usage: sql-formatter [-h] [-v] [-f FILE] [-o OUTPUT]
30+
[-l {db2,n1ql,pl/sql,plsql,redshift,spark,sql}]
31+
[-i N | -t] [-u] [--lines-between-queries N]
32+
33+
34+
SQL Formatter
35+
36+
Optional arguments:
37+
-h, --help Show this help message and exit.
38+
-v, --version Show program's version number and exit.
39+
-f FILE, --file FILE Input SQL file (defaults to stdin)
40+
-o OUTPUT, --output OUTPUT
41+
File to write SQL output (defaults to stdout)
42+
-l {db2,n1ql,pl/sql,plsql,redshift,spark,sql}, --langauge {db2,n1ql,pl/sql,plsql,redshift,spark,sql}
43+
SQL Formatter dialect (defaults to basic sql)
44+
-i N, --indent N Number of spaces to indent query blocks (defaults to
45+
2)
46+
-t, --tab-indent Indent query blocks with tabs instead of spaces
47+
-u, --uppercase Capitalize language keywords
48+
--lines-between-queries N
49+
How many newlines to insert between queries
50+
(separated by ";")
51+
```
52+
53+
By default, the tool takes queries from stdin and processes them to stdout but
54+
the `-f`/`--file` and `-o`/`--output` flags can be used to alter this behavior.
55+
56+
```sh
57+
echo 'select * from tbl where id = 3' | sql-formatter -u
58+
```
59+
60+
```sql
61+
SELECT
62+
*
63+
FROM
64+
tbl
65+
WHERE
66+
id = 3
67+
```
68+
1769
## Usage
1870

1971
```js
20-
import sqlFormatter from "sql-formatter";
72+
import sqlFormatter from 'sql-formatter';
2173

22-
console.log(sqlFormatter.format("SELECT * FROM table1"));
74+
console.log(sqlFormatter.format('SELECT * FROM tbl'));
2375
```
2476

2577
This will output:
2678

27-
```
79+
```sql
2880
SELECT
2981
*
3082
FROM
31-
table1
83+
tbl
3284
```
3385

3486
You can also pass in configuration options:
3587

3688
```js
37-
sqlFormatter.format("SELECT *", {
38-
language: "n1ql", // Defaults to "sql"
39-
indent: " " // Defaults to two spaces
89+
sqlFormatter.format('SELECT * FROM tbl', {
90+
language: 'spark', // Defaults to "sql"
91+
indent: ' ', // Defaults to two spaces
92+
uppercase: bool, // Defaults to false
93+
linesBetweenQueries: 2, // Defaults to 1
4094
});
4195
```
4296

43-
Currently just four SQL dialects are supported:
97+
Currently six SQL dialects are supported:
4498

4599
- **sql** - [Standard SQL][]
46100
- **n1ql** - [Couchbase N1QL][]
47101
- **db2** - [IBM DB2][]
48102
- **pl/sql** - [Oracle PL/SQL][]
103+
- **redshift** - [Amazon Redshift][]
104+
- **spark** - [Spark][]
49105

50106
### Placeholders replacement
51107

52108
```js
53109
// Named placeholders
54110
sqlFormatter.format("SELECT * FROM tbl WHERE foo = @foo", {
55-
params: {foo: "'bar'"}
111+
params: {foo: "'bar'"}
56112
}));
57113

58114
// Indexed placeholders
59115
sqlFormatter.format("SELECT * FROM tbl WHERE foo = ?", {
60-
params: ["'bar'"]
116+
params: ["'bar'"]
61117
}));
62118
```
63119

@@ -79,9 +135,10 @@ This makes SQL Formatter available as a global variable `window.sqlFormatter`.
79135

80136
## Contributing
81137

82-
```bash
83-
# run linter and tests
84-
$ npm run check
138+
Make sure to run all checks:
139+
140+
```sh
141+
npm run check
85142
```
86143

87144
...and you're ready to poke us with a pull request.
@@ -90,8 +147,10 @@ $ npm run check
90147

91148
[MIT](https://github.com/zeroturnaround/sql-formatter/blob/master/LICENSE)
92149

93-
[PHP library]: https://github.com/jdorn/sql-formatter
94-
[Standard SQL]: https://en.wikipedia.org/wiki/SQL:2011
95-
[Couchbase N1QL]: http://www.couchbase.com/n1ql
96-
[IBM DB2]: https://www.ibm.com/analytics/us/en/technology/db2/
97-
[Oracle PL/SQL]: http://www.oracle.com/technetwork/database/features/plsql/index.html
150+
[php library]: https://github.com/jdorn/sql-formatter
151+
[standard sql]: https://en.wikipedia.org/wiki/SQL:2011
152+
[couchbase n1ql]: http://www.couchbase.com/n1ql
153+
[ibm db2]: https://www.ibm.com/analytics/us/en/technology/db2/
154+
[oracle pl/sql]: http://www.oracle.com/technetwork/database/features/plsql/index.html
155+
[amazon redshift]: https://docs.aws.amazon.com/redshift/latest/dg/cm_chap_SQLCommandRef.html
156+
[spark]: https://spark.apache.org/docs/latest/api/sql/index.html

bin/sqlfmt.js

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
#!/usr/bin/env node
2+
3+
'use strict';
4+
5+
const { format, FORMATTERS } = require('../lib/sqlFormatter');
6+
const fs = require('fs');
7+
const { version } = require('../package.json');
8+
const { ArgumentParser } = require('argparse');
9+
10+
const formatterKeys = Object.keys(FORMATTERS);
11+
12+
function getArgs() {
13+
const parser = new ArgumentParser({
14+
version,
15+
addHelp: true,
16+
description: 'SQL Formatter',
17+
});
18+
19+
parser.addArgument(['-f', '--file'], {
20+
help: 'Input SQL file (defaults to stdin)',
21+
});
22+
parser.addArgument(['-o', '--output'], {
23+
help: 'File to write SQL output (defaults to stdout)',
24+
});
25+
26+
parser.addArgument(['-l', '--language'], {
27+
help: 'SQL Formatter dialect (defaults to basic sql)',
28+
choices: formatterKeys,
29+
defaultValue: 'sql',
30+
});
31+
32+
const indentationGroup = parser.addMutuallyExclusiveGroup();
33+
indentationGroup.addArgument(['-i', '--indent'], {
34+
help: 'Number of spaces to indent query blocks (defaults to 2)',
35+
metavar: 'N',
36+
type: 'int',
37+
defaultValue: 2,
38+
});
39+
indentationGroup.addArgument(['-t', '--tab-indent'], {
40+
help: 'Indent query blocks with tabs instead of spaces',
41+
action: 'storeTrue',
42+
});
43+
44+
parser.addArgument(['-u', '--uppercase'], {
45+
help: 'Capitalize language keywords',
46+
action: 'storeTrue',
47+
});
48+
49+
parser.addArgument(['--lines-between-queries'], {
50+
help: 'How many newlines to insert between queries (separated by ";")',
51+
metavar: 'N',
52+
type: 'int',
53+
default: 1,
54+
});
55+
56+
return parser.parseArgs();
57+
}
58+
59+
function configFromArgs(args) {
60+
return {
61+
language: args.language,
62+
indent: args.tab_indent ? '\t' : ' '.repeat(args.indent),
63+
uppercase: args.uppercase,
64+
linesBetweenQueries: args.lines_between_queries,
65+
};
66+
}
67+
68+
function getInput(file) {
69+
const infile = file || process.stdin.fd;
70+
try {
71+
return fs.readFileSync(infile, 'utf-8');
72+
} catch (e) {
73+
if (e.code === 'EAGAIN') {
74+
console.error('Error: no file specified and no data in stdin');
75+
process.exit(1);
76+
}
77+
if (e.code === 'ENOENT') {
78+
console.error(`Error: could not open file ${infile}`);
79+
process.exit(1);
80+
}
81+
throw e;
82+
}
83+
}
84+
85+
function writeOutput(file, query) {
86+
if (file === null) {
87+
// No output file, write to console
88+
console.log(query);
89+
} else {
90+
fs.writeFileSync(file, query);
91+
}
92+
}
93+
94+
const args = getArgs();
95+
const cfg = configFromArgs(args);
96+
const query = getInput(args.file);
97+
const formattedQuery = format(query, cfg).trim() + '\n';
98+
writeOutput(args.output, formattedQuery);

0 commit comments

Comments
 (0)