Gathering detailed insights and metrics for sql-formatter
Gathering detailed insights and metrics for sql-formatter
Gathering detailed insights and metrics for sql-formatter
Gathering detailed insights and metrics for sql-formatter
A whitespace formatter for different query languages
npm install sql-formatter
97.2
Supply Chain
98.6
Quality
91.9
Maintenance
100
Vulnerability
99.6
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
2,377 Stars
2,922 Commits
405 Forks
28 Watching
9 Branches
49 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
TypeScript (95.5%)
Nearley (1.74%)
JavaScript (1.41%)
HTML (1.13%)
CSS (0.21%)
Cumulative downloads
Total Downloads
Last day
1.4%
133,510
Compared to previous day
Last week
4.4%
703,863
Compared to previous week
Last month
11.4%
2,898,214
Compared to previous month
Last year
154.2%
25,145,776
Compared to previous year
35
SQL Formatter is a JavaScript library for pretty-printing SQL queries.
It started as a port of a PHP Library, but has since considerably diverged.
It supports various SQL dialects: GCP BigQuery, IBM DB2, Apache Hive, MariaDB, MySQL, TiDB, Couchbase N1QL, Oracle PL/SQL, PostgreSQL, Amazon Redshift, SingleStoreDB, Snowflake, Spark, SQL Server Transact-SQL, Trino (and Presto). See language option docs for more details.
It does not support:
;
.Get the latest version from NPM:
1npm install sql-formatter
Also available with yarn:
1yarn add sql-formatter
1import { format } from 'sql-formatter'; 2 3console.log(format('SELECT * FROM tbl', { language: 'mysql' }));
This will output:
1SELECT
2 *
3FROM
4 tbl
You can also pass in configuration options:
1format('SELECT * FROM tbl', { 2 language: 'spark', 3 tabWidth: 2, 4 keywordCase: 'upper', 5 linesBetweenQueries: 2, 6});
You can disable the formatter for a section of SQL by surrounding it with disable/enable comments:
1/* sql-formatter-disable */
2SELECT * FROM tbl1;
3/* sql-formatter-enable */
4SELECT * FROM tbl2;
which produces:
1/* sql-formatter-disable */
2SELECT * FROM tbl1;
3/* sql-formatter-enable */
4SELECT
5 *
6FROM
7 tbl2;
The formatter doesn't even parse the code between these comments. So in case there's some SQL that happens to crash SQL Formatter, you can at comment the culprit out (at least until the issue gets fixed in SQL Formatter).
In addition to formatting, this library can also perform placeholder replacement in prepared SQL statements:
1format('SELECT * FROM tbl WHERE foo = ?', { 2 params: ["'bar'"], 3});
Results in:
1SELECT
2 *
3FROM
4 tbl
5WHERE
6 foo = 'bar'
For more details see docs of params option.
The CLI tool will be installed under sql-formatter
and may be invoked via npx sql-formatter
:
1sql-formatter -h
usage: sql-formatter [-h] [-o OUTPUT] \
[-l {bigquery,db2,db2i,hive,mariadb,mysql,n1ql,plsql,postgresql,redshift,singlestoredb,snowflake,spark,sql,sqlite,tidb,transactsql,trino,tsql}] [-c CONFIG] [--version] [FILE]
SQL Formatter
positional arguments:
FILE Input SQL file (defaults to stdin)
optional arguments:
-h, --help show this help message and exit
-o, --output OUTPUT
File to write SQL output (defaults to stdout)
--fix Update the file in-place
-l, --language {bigquery,db2,db2i,hive,mariadb,mysql,n1ql,plsql,postgresql,redshift,singlestoredb,snowflake,spark,sql,sqlite,tidb,trino,tsql}
SQL dialect (defaults to basic sql)
-c, --config CONFIG
Path to config JSON file or json string (will find a file named '.sql-formatter.json' or use default configs if unspecified)
--version show program's version number and exit
By default, the tool takes queries from stdin and processes them to stdout but
one can also name an input file name or use the --output
option.
1echo 'select * from tbl where id = 3' | sql-formatter
1select
2 *
3from
4 tbl
5where
6 id = 3
The tool also accepts a JSON config file named .sql-formatter.json in the current or any parent directory, or with the --config
option that takes this form:
1{ 2 "language": "spark", 3 "tabWidth": 2, 4 "keywordCase": "upper", 5 "linesBetweenQueries": 2 6}
All fields are optional and all fields that are not specified will be filled with their default values.
language
the SQL dialect to use (when using format()
).dialect
the SQL dialect to use (when using formatDialect()
since version 12).tabWidth
amount of indentation to use.useTabs
to use tabs for indentation.keywordCase
uppercases or lowercases keywords.dataTypeCase
uppercases or lowercases data types.functionCase
uppercases or lowercases function names.identifierCase
uppercases or lowercases identifiers. (experimental!)indentStyle
defines overall indentation style. (deprecated!)logicalOperatorNewline
newline before or after boolean operator (AND, OR, XOR).expressionWidth
maximum number of characters in parenthesized expressions to be kept on single line.linesBetweenQueries
how many newlines to insert between queries.denseOperators
packs operators densely without spaces.newlineBeforeSemicolon
places semicolon on separate line.params
collection of values for placeholder replacement.paramTypes
specifies parameter placeholders types to support.If you don't use a module bundler, clone the repository, run npm install
and grab a file from /dist
directory to use inside a <script>
tag.
This makes SQL Formatter available as a global variable window.sqlFormatter
.
The most common cause is that you haven't specified an SQL dialect. Instead of calling the library simply:
1format('select [col] from tbl'); 2// Throws: Parse error: Unexpected "[col] from" at line 1 column 8
pick the proper dialect, like:
1format('select [col] from tbl', { language: 'transactsql' });
Or when using the VSCode extension: Settings -> SQL-Formatter-VSCode: SQLFlavourOverride.
This typically happens when bundling an appication with Webpack.
The cause is that Babel (through babel-loader
) is not configured
to support class properties syntax:
| export default class ExpressionFormatter {
> inline = false;
This syntax is widely supported in all major browsers (except old IE)
and support for it is included to the default @babel/preset-env
.
Possible fixes:
@babel/preset-env
@babel/plugin-proposal-class-properties
The Prettier SQL VSCode extension is no more maintained by its author.
Please use the official SQL Formatter VSCode extension to get the latest fixes from SQL Formatter library.
For example, you might have an SQL like:
1SELECT {col1}, {col2} FROM {tablename}
While templating is not directly supported by SQL Formatter, the workaround is to use paramTypes config option to treat these occurances of templating constructs as prepared-statement parameter-placeholders:
1format('SELECT {col1}, {col2} FROM {tablename};', { 2 paramTypes: { custom: [{ regex: String.raw`\{\w+\}` }] }, 3});
This won't work for all possible templating constructs, but should solve the most common use cases.
The development of this formatter is currently in maintenance mode. Bugs will get fixed if feasible, but new features will likely not be added.
I have started a new SQL formatting tool: prettier-plugin-sql-cst.
Give it a try if you'd like to take your SQL auto-formatting to the next level.
Please see CONTRIBUTING.md
No vulnerabilities found.
No security vulnerabilities found.