Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

prettier-sql

inferrinizzard6.7kMIT5.1.1TypeScript support: included

Format whitespace in a SQL query to make it more readable

sql, formatter, format, n1ql, redshift, spark, whitespace, mysql, mariadb, postgresql, pl/sql, transact-sql, db2

readme

Prettier SQL NPM version GitHub Workflow Status (event) Coveralls VSCode

Prettier SQL is a JavaScript library for pretty-printing SQL queries.

It started as a port of a PHP Library, but has since considerably diverged.

Prettier SQL supports the following dialects:

It does not support:

  • Stored procedures.
  • Changing of the delimiter type to something else than ;.

Try the demo.

Table of contents

Install

Get the latest version from NPM:

npm install prettier-sql

Also available with yarn:

yarn add prettier-sql

Documentation

You can read more about how the library works in DOC.md

Usage

Usage as library

import { format } from 'prettier-sql';

console.log(format('SELECT * FROM tbl'));

This will output:

SELECT
  *
FROM
  tbl

You can also pass in configuration options:

format('SELECT * FROM tbl', {
    language: 'spark', // Defaults to "sql" (see the above list of supported dialects)
    indent: '  ', // Defaults to two spaces
    uppercase: false, // Defaults to true
    linesBetweenQueries: 2, // Defaults to 1
});

Placeholders replacement

// Named placeholders
format("SELECT * FROM tbl WHERE foo = @foo", {
  params: {foo: "'bar'"}
}));

// Indexed placeholders
format("SELECT * FROM tbl WHERE foo = ?", {
  params: ["'bar'"]
}));

Both result in:

SELECT
  *
FROM
  tbl
WHERE
  foo = 'bar'

Usage from command line

The CLI tool will be installed under prettier-sql and may be invoked via npx prettier-sql:

prettier-sql -h
usage: sqlfmt.js [-h] [-o OUTPUT] \
[-l {bigquery,db2,hive,mariadb,mysql,n1ql,plsql,postgresql,redshift,spark,sql,tsql}] [-c CONFIG] [--version] [FILE]

Prettier SQL

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)
  -l, --language  {bigquery,db2,hive,mariadb,mysql,n1ql,plsql,postgresql,redshift,spark,sql,tsql}
                    SQL dialect (defaults to standard sql)
  -c, --config    CONFIG
                    Path to config json file (will 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.

echo 'select * from tbl where id = 3' | prettier-sql
SELECT
  *
FROM
  tbl
WHERE
  id = 3

The tool also accepts a JSON config file with the --config option that takes this form: \ All fields are optional and all fields that are not specified will be filled with their default values

{
    "indent": string,
    "uppercase": boolean,
    "keywordPosition": "standard" | "tenSpaceLeft" | "tenSpaceRight",
    "newline": "always" | "lineWidth" | "never" | number,
    "breakBeforeBooleanOperator": boolean,
    "aliasAs": "always" | "select" | "never",
    "tabulateAlias": boolean,
    "commaPosition": "before" | "after" | "tabular",
    "parenOptions": {
        "openParenNewline": boolean,
        "closeParenNewline": boolean
    },
    "lineWidth": number,
    "linesBetweenQueries": number,
    "denseOperators": boolean,
    "semicolonNewline": boolean,
}

Usage without NPM

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 Prettier SQL available as a global variable window.prettierSql.

Usage with VSCode

Prettier SQL is also available as a VSCode extension here: \ https://marketplace.visualstudio.com/items?itemName=inferrinizzard.prettier-sql-vscode

Contributing

Please see CONTRIBUTING.md

License

MIT

changelog

CHANGELOG

[5.1.1] : 2022-04-06

Updated

  • restored itemCount setting for VScode extension
  • added JSDocs for all files
  • added conditional skips for Jest tests
  • added missing BigQuery, hive from demo page language dropdown

Fixed

  • fixed bug with CASE and Inline Block interaction
  • fixed bug with END not adding spacings before END
  • fixed bug with CommaPosition.before when the line had no preceding whitespace
  • fixed bug where AS in CAST functions would get deleted when AliasAs.never
  • fixed bug where AS would get deleted in CTE definition when AliasAs.never

[5.1.0] : 2021-12-21

Known Issues

  • newline: number does not work with [foo], [ and ] both count as 1 token each so [foo] would be 3 items
    • array[0] or map[key] do still work as they are parsed as WORD
  • BigQuery formatter fails a few tests (ALTER TABLE, tricky line comments) due to those tests not including valid BigQuery SQL, those tests are currently skipped

Added

Source:

  • consumed VSCode Extension as subrepo
  • added support for Hive language
  • added support for BigQuery language
  • added keyword dedupe on Formatter classes via Set

VSCode:

  • added command prettier-sql-vscode.format-selection
    • Formats SQL selections
  • added settings to override user/workspace tabSize and insertSpaces settings
  • added error message on format fail
  • added setting to override formatting language for sql files when SQL flavour does not have a VSCode language ID (Microsoft PostgreSQL and MSSQL Extensions)

Other:

  • demo page now deployed as git repo subtree, served from root/ (subtree of static/)

Updated

  • fixed handling of newline options
  • simplified NewlineMode config
  • fixed ; indentation when used with semicolonNewline and tenSpace configs
  • Formatter now uses numeric for loop to allow for index manipulation
  • updated linesBetweenQueries to add an extra newline (0 lines = 1 line break, no space in between)
  • renamed Formatter class files to <flavour>.formatter.ts
  • renamed test files to <flavour>.test.js

Removed

  • removed newline: hybrid config
    • newline: number now acts like hybrid

[5.0.1] : 2021-11-24

Updated

  • fixed bug when using SELECT * and denseOperators
  • fixed aliasAs option on demo page
  • fixed handling of tokens with aliasAs flag
  • demo page now prints stack trace in textarea on error

[5.0.0] : 2021-11-22

Added

Source:

  • added support for ES6 module exports with TypeScript
    • updated webpack with ts-loader for module types
    • added tsc to babel commonjs build command
  • added index.ts pass-through export

Other:

  • added GH Actions for CI build
  • added issue templates

Updated

Source:

  • updated demo page for all new options

Other:

  • renamed library to prettier-sql

Fixed

  • fixed bugs related to operator tokens

Removed

  • removed Travis CI (replaced by GH Actions)

[5.0.0-beta] : 2021-11-03

Added

Source:

  • added option aliasAs to toggle use of AS in column, table, query aliases
    • modes: always (SELECT and table), select (SELECT only), never
  • added option newline to specify rules for inserting newlines within SQL Statements
    • modes: \ always (break before all arguments) \ lineWidth (break after line exceeds lineWidth) \ itemCount (break after n items) \ hybrid (lineWidth OR itemCount) \ never (place all Statements on one line)
  • added flag denseOperators to toggle spaces around binary operators (=, +, %, etc.)
  • added flag semicolonNewline to toggle placing semicolon on newline vs same line
  • added flag tabulateAlias for alias tabular mode, aligned on longest line, not including AS
  • added option commaPosition to specify comma placement within listed Statements
    • modes: \ before(comma goes before column), \ after(standard), \ tabular(aligned to longest line)
  • added option keywordPosition to support vertically aligned keywords
    • modes: \ standard, \ tenSpaceLeft(left-aligned within keyword column), \ tenSpaceRight(right-aligned within keyword column)
  • added flag breakBeforeBooleanOperator to toggle breaking before or after logical operators like AND and OR
  • added options parenOptions for misc rules regarding parenthesis position
    • openParenNewline - flag for opening paren on newline or same line
    • closeParenNewline - flag for closing paren on newline or same line

Other:

  • added enums for all typed config options

Files Added:

  • test/comma.js (tests for comma position)
  • test/alias.js (tests for alias AS and alias position)
  • test/keywordPosition.js (tests for keyword position modes)
  • test/newline.js (tests for newline modes)
  • test/parenthesis.js (tests for paren positions)

Updated

Source:

  • converted repo to Typescript
  • overhauled Keyword lists for all languages
  • added default options for all configs
  • updated CLI to use config file
  • renamed Keyword categories to semantic Keyword types
    • reservedTopLevelWord → reservedCommand
    • reservedTopLevelWordNoIndent → reservedBinaryCommand
    • reservedNewline → reservedDependentClause & reservedLogicalOperator
    • reservedWord → reservedKeyword
    • added reservedFunctions
  • updated Tokenizer class and token.ts to be more DRY

Removed

  • tokenTypes.ts (token types moved to TokenType enum in token.ts)
  • sqlFormatter.d.ts (converted to TypeScript)