1 | # SQL Formatter [![NPM version](https://img.shields.io/npm/v/sql-formatter.svg)](https://npmjs.com/package/sql-formatter) [![Build Status](https://travis-ci.org/zeroturnaround/sql-formatter.svg?branch=master)](https://travis-ci.org/zeroturnaround/sql-formatter) [![Coverage Status](https://coveralls.io/repos/github/zeroturnaround/sql-formatter/badge.svg?branch=master)](https://coveralls.io/github/zeroturnaround/sql-formatter?branch=master)
|
2 |
|
3 | **SQL Formatter** is a JavaScript library for pretty-printing SQL queries.
|
4 | It started as a port of a [PHP Library][], but has since considerably diverged.
|
5 | It supports [Standard SQL][] and [Couchbase N1QL][] dialects.
|
6 |
|
7 | → [Try the demo.](https://zeroturnaround.github.io/sql-formatter/)
|
8 |
|
9 | ## Install
|
10 |
|
11 | Get the latest version from NPM:
|
12 |
|
13 | ```
|
14 | npm install --save sql-formatter
|
15 | ```
|
16 |
|
17 | ## Usage
|
18 |
|
19 | ```js
|
20 | import sqlFormatter from "sql-formatter";
|
21 |
|
22 | console.log(sqlFormatter.format("SELECT * FROM table1"));
|
23 | ```
|
24 |
|
25 | This will output:
|
26 |
|
27 | ```
|
28 | SELECT
|
29 | *
|
30 | FROM
|
31 | table1
|
32 | ```
|
33 |
|
34 | You can also pass in configuration options:
|
35 |
|
36 | ```js
|
37 | sqlFormatter.format("SELECT *", {
|
38 | language: "n1ql" // Defaults to "sql"
|
39 | indent: " " // Defaults to two spaces
|
40 | });
|
41 | ```
|
42 |
|
43 | Currently just two SQL dialects are supported:
|
44 |
|
45 | - **sql** - [Standard SQL][]
|
46 | - **n1ql** - [Couchbase N1QL][]
|
47 |
|
48 | ### Placeholders replacement
|
49 |
|
50 | ```js
|
51 | // Named placeholders
|
52 | sqlFormatter.format("SELECT * FROM tbl WHERE foo = @foo", {
|
53 | params: {foo: "'bar'"}
|
54 | }));
|
55 |
|
56 | // Indexed placeholders
|
57 | sqlFormatter.format("SELECT * FROM tbl WHERE foo = ?", {
|
58 | params: ["'bar'"]
|
59 | }));
|
60 | ```
|
61 |
|
62 | Both result in:
|
63 |
|
64 | ```
|
65 | SELECT
|
66 | *
|
67 | FROM
|
68 | tbl
|
69 | WHERE
|
70 | foo = 'bar'
|
71 | ```
|
72 |
|
73 | ## Usage without NPM
|
74 |
|
75 | 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.
|
76 | This makes SQL Formatter available as a global variable `window.sqlFormatter`.
|
77 |
|
78 | ## Contributing
|
79 |
|
80 | ```bash
|
81 | # run linter and tests
|
82 | $ npm run check
|
83 | ```
|
84 |
|
85 | ...and you're ready to poke us with a pull request.
|
86 |
|
87 | ## License
|
88 |
|
89 | [MIT](https://github.com/zeroturnaround/sql-formatter/blob/master/LICENSE)
|
90 |
|
91 | [PHP library]: https://github.com/jdorn/sql-formatter
|
92 | [Standard SQL]: https://en.wikipedia.org/wiki/SQL:2011
|
93 | [Couchbase N1QL]: http://www.couchbase.com/n1ql
|