Skip to content
This repository has been archived by the owner on Jul 6, 2022. It is now read-only.

Commit

Permalink
v5.0.0-beta
Browse files Browse the repository at this point in the history
PR (#27)

* configure for typescript

* prettier

* convert to typescript

* add default options

* fix uppercase default for tests

add count keyword

* sort and dedupe keywords

* add support for escaped keywords as identifiers

* fix keyword identifier for non critical tests

* add @typescript-eslint/eslint-plugin

* fix webpack

* add basic alias processing

missing double word case

* add missing keywords to redshift

fix column alias edge case

* add alias tests

* ♻️

* fix handling of never alias option

* prettier check

* add newline for itemCount setting

* add newline for lineWidth

* update newline hybrid rule logic

* implement newline mode tests

* ♻️

* prettier check

* add eslint-config-airbnb-typescript

* add @typescript-eslint/parser

* fix eslint errors

* convert relevant import to type imports

* remove ts extension from import in test files

* remove sqlformatter d ts

* add dense operator option

* add operator test

* add NewlineMode enum

* move types to types file

* add AliasMode enum

* convert enums into string enums

* ♻️

* add semicolon newline option

* add unit test for semicolon newline

* add maxLength function

* add tabulation function

* add KeywordMode type

* add keyword style examples

* remove TopLevelIndents and merge reserved token logic

* add basic 10-space keyword positioning

* add support for multi item clauses

* add support for long keywords

* add unit tests for tenSpace modes

fix block end index logic

* add tests to accept tenSpace modes

* fix ON keyword

* fix bug with TopLevelIndent on nested blocks starting with FROM (

* add commaPosition option

* add post format method

* add basic tabular mode

* add formatting for comma before column

* add unit test for comma modes

fix tabular option

* add tests for accepting comma modes

* add AliasPosition flag

* add basic tabular alias function

* add unit tests for alias position

fix alias joining

* add tests for accepting tabular aliases

* switch delta from unit test as potential keyword

* fix regex flags

* fix alias tests

* add tests for aliasPosition x keywordPosition edge cases

* limit keywordPosition to standard and tenSpace

* add test case for long keywords

* move keywords that should be in reservedNewlineWords

* dedupe keywords

* update redshift keywords

* split reserved words into categories

add links to docs

* update Db2 keywords

* update MariaDb keywords

* update MySql keywords

* update N1ql keywords

* update Postgres keywords

* update Spark keywords

* update TSQL keywords

* update union/intersect/except lists

* split reservedDependentClause from reservedNewline

* fix case statements to support dependent clause

* update dependent clauses for remaining messages

* fix tests and keyword discrepancies

* rename TopLevelWord to Command

* rename TopLevelNoIndent to Binary Command

* move joins to BinaryCommands

* rename Newline words to Logical Operators

* rename reservedWords to Keywords

* rename openParen to Block Start

* rename closeParen to Block End

* move Logical Operator down

* add comments for reserved word categories

* fix PlSql test with CROSS/OUTER APPLY

* convert all members for formatters classes to static

* add paren options type

* add basic formatting for open paren position

* add basic close paren position formatting

* add test for open and close paren position

* decline reservedFunctionParens and functionParenSpace

* convert token type into TokenType enum

* use TypeToken enum to build mapped Regex table

* simplify tokenizer class

* simplify isToken

* update Tokenizer with PR comments

* rename isTopLevel to IsCommand

* add flag to toggle breaking before boolean operator

* support break after operator

add test

* update tests with static class members

* Update Db2FormatterTest.js

* add changelog

* update README

* update package.json

* fix semicolonNewline type

* Create dependabot.yml

* update sqlfmt node script to use config file

* add changelog

* Create dependabot.yml

* update README

* update package.json

* fix semicolonNewline type
  • Loading branch information
inferrinizzard committed Nov 5, 2021
1 parent 3cd6d98 commit 84b513e
Show file tree
Hide file tree
Showing 88 changed files with 19,977 additions and 16,479 deletions.
4 changes: 2 additions & 2 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"presets": ["@babel/preset-env"],
"plugins": ["@babel/plugin-proposal-class-properties", "add-module-exports"]
"presets": ["@babel/preset-env", "@babel/preset-typescript"],
"plugins": ["@babel/plugin-proposal-class-properties", "add-module-exports"]
}
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_style = tab
indent_size = 2
58 changes: 39 additions & 19 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,21 +1,41 @@
{
"parser": "babel-eslint",
"extends": ["airbnb-base", "prettier"],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": ["error"],
"curly": ["error", "all"],
"require-unicode-regexp": ["error"],
"func-names": "error",
"no-useless-concat": "off",
"class-methods-use-this": "off",
"no-param-reassign": "off",
"prefer-template": "off",
"no-plusplus": "off",
"no-else-return": "off",
"no-use-before-define": "off"
},
"env": {
"jest": true
}
"parser": "@typescript-eslint/parser",
"parserOptions": { "project": "./tsconfig.json", "ecmaVersion": 6, "sourceType": "module" },
"extends": ["airbnb-base", "airbnb-typescript/base", "plugin:import/typescript", "prettier"],
"plugins": ["@typescript-eslint", "prettier"],
"rules": {
"class-methods-use-this": "off",
"curly": ["error", "all"],
"eqeqeq": "warn",
"func-names": "error",
"no-continue": "off",
"no-param-reassign": "off",
"no-plusplus": "off",
"no-else-return": "off",
"no-use-before-define": "warn",
"no-useless-concat": "off",
"prefer-template": "off",
"prettier/prettier": ["error"],
"@typescript-eslint/comma-dangle": "off",
"@typescript-eslint/indent": "off",
"@typescript-eslint/lines-between-class-members": "off",
"@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/quotes": [
"warn",
"single",
{ "avoidEscape": true, "allowTemplateLiterals": true }
],
"@typescript-eslint/semi": "warn"
},
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".ts"]
}
}
},
"env": {
"jest": true
}
}
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
/dist
/lib
/node_modules
yarn.lock
LICENSE
10 changes: 8 additions & 2 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
{
"printWidth": 100,
"singleQuote": true
"printWidth": 100,
"singleQuote": true,
"arrowParens": "avoid",
"semi": true,
"bracketSpacing": true,
"useTabs": true,
"tabWidth": 2,
"endOfLine": "auto"
}
72 changes: 72 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# CHANGELOG

## NEXT [5.0.0] : 2021-11-03

### Added

New Features:

- 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)

### Removed

Files Removed:

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

### Updated

Major changes:

- converted repo to Typescript
- overhauled Keyword lists for all languages

Other:

- 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
84 changes: 59 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,16 @@ It does not support:
- Stored procedures.
- Changing of the delimiter type to something else than `;`.

→ [Try the demo.](https://zeroturnaround.github.io/sql-formatter/)
[Try the demo.](https://zeroturnaround.github.io/sql-formatter/)

# Table of contents

- [Install](#install)
- [Usage](#usage)
- [Usage as library](#usage-as-library)
- [Usage from command line](#usage-from-command-line)
- [Usage without NPM](#usage-without-npm)
- [Contributing](#contributing)

## Install

Expand All @@ -31,7 +40,9 @@ Get the latest version from NPM:
npm install sql-formatter
```

## Usage as library
## Usage

### Usage as library

```js
import { format } from 'sql-formatter';
Expand All @@ -52,10 +63,10 @@ You can also pass in configuration options:

```js
format('SELECT * FROM tbl', {
language: 'spark', // Defaults to "sql" (see the above list of supported dialects)
indent: ' ', // Defaults to two spaces
uppercase: bool, // Defaults to false (not safe to use when SQL dialect has case-sensitive identifiers)
linesBetweenQueries: 2, // Defaults to 1
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
});
```

Expand All @@ -75,7 +86,7 @@ format("SELECT * FROM tbl WHERE foo = ?", {

Both result in:

```
```sql
SELECT
*
FROM
Expand All @@ -84,7 +95,7 @@ WHERE
foo = 'bar'
```

## Usage from command line
### Usage from command line

The CLI tool will be installed under `sql-formatter`
and may be invoked via `npx sql-formatter`:
Expand All @@ -94,34 +105,30 @@ sql-formatter -h
```

```
usage: sql-formatter [-h] [-o OUTPUT] [-l {db2,mariadb,mysql,n1ql,plsql,postgresql,redshift,spark,sql,tsql}]
[-i N | -t] [-u] [--lines-between-queries N] [--version] [FILE]
usage: sqlfmt.js [-h] [-o OUTPUT] \
[-l {db2,mariadb,mysql,n1ql,plsql,postgresql,redshift,spark,sql,tsql}] [-c CONFIG] [--version] [FILE]
SQL Formatter
positional arguments:
FILE Input SQL file (defaults to stdin)
FILE Input SQL file (defaults to stdin)
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
File to write SQL output (defaults to stdout)
-l {db2,mariadb,mysql,n1ql,plsql,postgresql,redshift,spark,sql,tsql},
--language {db2,mariadb,mysql,n1ql,plsql,postgresql,redshift,spark,sql,tsql}
SQL Formatter dialect (defaults to basic sql)
-i N, --indent N Number of spaces to indent query blocks (defaults to 2)
-t, --tab-indent Indent query blocks with tabs instead of spaces
-u, --uppercase Capitalize language keywords
--lines-between-queries N
How many newlines to insert between queries (separated by ";")
--version show program's version number and exit
-h, --help show this help message and exit
-o, --output OUTPUT
File to write SQL output (defaults to stdout)
-l, --language {db2,mariadb,mysql,n1ql,plsql,postgresql,redshift,spark,sql,tsql}
SQL Formatter dialect (defaults to basic 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.

```sh
echo 'select * from tbl where id = 3' | sql-formatter -u
echo 'select * from tbl where id = 3' | sql-formatter
```

```sql
Expand All @@ -133,7 +140,34 @@ WHERE
id = 3
```

## Usage without NPM
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

```json
{
"indent": string,
"uppercase": boolean,
"keywordPosition": "standard" | "tenSpaceLeft" | "tenSpaceRight",
"newline": {
"mode": "always" | "itemCount" | "lineWidth" | "hybrid" | "never",
"itemCount":? 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 SQL Formatter available as a global variable `window.sqlFormatter`.
Expand Down
Loading

0 comments on commit 84b513e

Please sign in to comment.