Socket
Socket
Sign inDemoInstall

sql-formatter

Package Overview
Dependencies
Maintainers
1
Versions
142
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

sql-formatter - npm Package Compare versions

Comparing version 1.0.0 to 1.1.0

lib/core/Params.js

16

lib/core/Formatter.js

@@ -25,2 +25,6 @@ "use strict";

var _Params = require("./Params");
var _Params2 = _interopRequireDefault(_Params);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

@@ -31,3 +35,4 @@

* @param {Object} cfg
* @param {Object} cfg.indent
* @param {Object} cfg.indent
* @param {Object} cfg.params
* @param {Tokenizer} tokenizer

@@ -41,2 +46,3 @@ */

this.inlineBlock = new _InlineBlock2["default"]();
this.params = new _Params2["default"](this.cfg.params);
this.tokenizer = tokenizer;

@@ -47,3 +53,3 @@ this.previousReservedWord = {};

/**
* Format the whitespace in a SQL string to make it easier to read.
* Formats whitespaces in a SQL string to make it easier to read.
*

@@ -87,2 +93,4 @@ * @param {String} query The SQL query string

formattedQuery = _this.formatClosingParentheses(token, formattedQuery);
} else if (token.type === _tokenTypes2["default"].PLACEHOLDER) {
formattedQuery = _this.formatPlaceholder(token, formattedQuery);
} else if (token.value === ",") {

@@ -168,2 +176,6 @@ formattedQuery = _this.formatComma(token, formattedQuery);

Formatter.prototype.formatPlaceholder = function formatPlaceholder(token, query) {
return query + this.params.get(token) + " ";
};
// Commas start a new line (unless within inline parentheses or SQL "LIMIT" clause)

@@ -170,0 +182,0 @@

81

lib/core/Tokenizer.js

@@ -28,3 +28,4 @@ "use strict";

* @param {String[]} cfg.closeParens Closing parentheses to enable, like ), ]
* @param {String[]} cfg.variableTypes Prefixes for variables, like @ and :
* @param {String[]} cfg.indexedPlaceholderTypes Prefixes for indexed placeholders, like ?
* @param {String[]} cfg.namedPlaceholderTypes Prefixes for named placeholders, like @ and :
*/

@@ -50,4 +51,5 @@ function Tokenizer(cfg) {

this.PLAIN_VARIABLE_REGEX = this.createVariableRegex(cfg.variableTypes, "[a-zA-Z0-9._$]+");
this.QUOTED_VARIABLE_REGEX = this.createVariableRegex(cfg.variableTypes, this.createStringPattern(cfg.stringTypes));
this.INDEXED_PLACEHOLDER_REGEX = this.createPlaceholderRegex(cfg.indexedPlaceholderTypes, "[0-9]*");
this.IDENT_NAMED_PLACEHOLDER_REGEX = this.createPlaceholderRegex(cfg.namedPlaceholderTypes, "[a-zA-Z0-9._$]+");
this.STRING_NAMED_PLACEHOLDER_REGEX = this.createPlaceholderRegex(cfg.namedPlaceholderTypes, this.createStringPattern(cfg.stringTypes));
}

@@ -90,7 +92,9 @@

Tokenizer.prototype.createVariableRegex = function createVariableRegex(variableTypes, pattern) {
if (variableTypes.length === 0) {
Tokenizer.prototype.createPlaceholderRegex = function createPlaceholderRegex(types, pattern) {
if (_lodash2["default"].isEmpty(types)) {
return false;
}
return new RegExp("^((?:" + variableTypes.map(_lodash2["default"].escapeRegExp).join("|") + ")(?:" + pattern + "))\\S");
var typesRegex = types.map(_lodash2["default"].escapeRegExp).join("|");
return new RegExp("^((?:" + typesRegex + ")(?:" + pattern + "))");
};

@@ -126,3 +130,3 @@

Tokenizer.prototype.getNextToken = function getNextToken(input, previousToken) {
return this.getWhitespaceToken(input) || this.getCommentToken(input) || this.getStringToken(input) || this.getOpenParenToken(input) || this.getCloseParenToken(input) || this.getVariableToken(input) || this.getNumberToken(input) || this.getReservedWordToken(input, previousToken) || this.getWordToken(input) || this.getOperatorToken(input);
return this.getWhitespaceToken(input) || this.getCommentToken(input) || this.getStringToken(input) || this.getOpenParenToken(input) || this.getCloseParenToken(input) || this.getPlaceholderToken(input) || this.getNumberToken(input) || this.getReservedWordToken(input, previousToken) || this.getWordToken(input) || this.getOperatorToken(input);
};

@@ -182,22 +186,57 @@

Tokenizer.prototype.getVariableToken = function getVariableToken(input) {
return this.getPlainVariableToken(input) || this.getQuotedVariableToken(input);
Tokenizer.prototype.getPlaceholderToken = function getPlaceholderToken(input) {
return this.getIdentNamedPlaceholderToken(input) || this.getStringNamedPlaceholderToken(input) || this.getIndexedPlaceholderToken(input);
};
Tokenizer.prototype.getPlainVariableToken = function getPlainVariableToken(input) {
return this.getTokenOnFirstMatch({
Tokenizer.prototype.getIdentNamedPlaceholderToken = function getIdentNamedPlaceholderToken(input) {
return this.getPlaceholderTokenWithKey({
input: input,
type: _tokenTypes2["default"].VARIABLE,
regex: this.PLAIN_VARIABLE_REGEX
regex: this.IDENT_NAMED_PLACEHOLDER_REGEX,
parseKey: function parseKey(v) {
return v.slice(1);
}
});
};
Tokenizer.prototype.getQuotedVariableToken = function getQuotedVariableToken(input) {
return this.getTokenOnFirstMatch({
Tokenizer.prototype.getStringNamedPlaceholderToken = function getStringNamedPlaceholderToken(input) {
var _this = this;
return this.getPlaceholderTokenWithKey({
input: input,
type: _tokenTypes2["default"].VARIABLE,
regex: this.QUOTED_VARIABLE_REGEX
regex: this.STRING_NAMED_PLACEHOLDER_REGEX,
parseKey: function parseKey(v) {
return _this.getEscapedPlaceholderKey({ key: v.slice(2, -1), quoteChar: v.slice(-1) });
}
});
};
Tokenizer.prototype.getIndexedPlaceholderToken = function getIndexedPlaceholderToken(input) {
return this.getPlaceholderTokenWithKey({
input: input,
regex: this.INDEXED_PLACEHOLDER_REGEX,
parseKey: function parseKey(v) {
return v.slice(1);
}
});
};
Tokenizer.prototype.getPlaceholderTokenWithKey = function getPlaceholderTokenWithKey(_ref) {
var input = _ref.input,
regex = _ref.regex,
parseKey = _ref.parseKey;
var token = this.getTokenOnFirstMatch({ input: input, regex: regex, type: _tokenTypes2["default"].PLACEHOLDER });
if (token) {
token.key = parseKey(token.value);
}
return token;
};
Tokenizer.prototype.getEscapedPlaceholderKey = function getEscapedPlaceholderKey(_ref2) {
var key = _ref2.key,
quoteChar = _ref2.quoteChar;
return key.replace(new RegExp(_lodash2["default"].escapeRegExp("\\") + quoteChar, "g"), quoteChar);
};
// Decimal, binary, or hex numbers

@@ -266,6 +305,6 @@

Tokenizer.prototype.getTokenOnFirstMatch = function getTokenOnFirstMatch(_ref) {
var input = _ref.input,
type = _ref.type,
regex = _ref.regex;
Tokenizer.prototype.getTokenOnFirstMatch = function getTokenOnFirstMatch(_ref3) {
var input = _ref3.input,
type = _ref3.type,
regex = _ref3.regex;

@@ -272,0 +311,0 @@ var matches = input.match(regex);

@@ -20,4 +20,4 @@ "use strict";

NUMBER: "number",
VARIABLE: "variable"
PLACEHOLDER: "placeholder"
};
module.exports = exports["default"];

@@ -54,3 +54,3 @@ "use strict";

closeParens: [")", "]", "}"],
variableTypes: []
namedPlaceholderTypes: ["$"]
});

@@ -57,0 +57,0 @@ }

@@ -54,3 +54,4 @@ "use strict";

closeParens: [")"],
variableTypes: ["@", ":"]
indexedPlaceholderTypes: ["?"],
namedPlaceholderTypes: ["@", ":"]
});

@@ -57,0 +58,0 @@ }

@@ -23,2 +23,3 @@ "use strict";

* @param {String} cfg.indent Characters used for indentation, default is " " (2 spaces)
* @param {Object} cfg.params Collection of params for placeholder replacement
* @return {String}

@@ -25,0 +26,0 @@ */

{
"name": "sql-formatter",
"version": "1.0.0",
"version": "1.1.0",
"description": "Formats whitespaces in a SQL query to make it more readable",

@@ -5,0 +5,0 @@ "license": "MIT",

@@ -48,2 +48,27 @@ # 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)

### Placeholders replacement
```js
// Named placeholders
sqlFormatter.format("SELECT * FROM tbl WHERE foo = @foo", {
params: {foo: "'bar'"}
}));
// Indexed placeholders
sqlFormatter.format("SELECT * FROM tbl WHERE foo = ?", {
params: ["'bar'"]
}));
```
Both result in:
```
SELECT
*
FROM
tbl
WHERE
foo = 'bar'
```
## Usage without NPM

@@ -50,0 +75,0 @@

import _ from "lodash";
import sqlTokenTypes from "./tokenTypes";
import tokenTypes from "./tokenTypes";
import Indentation from "./Indentation";
import InlineBlock from "./InlineBlock";
import Params from "./Params";

@@ -9,3 +10,4 @@ export default class Formatter {

* @param {Object} cfg
* @param {Object} cfg.indent
* @param {Object} cfg.indent
* @param {Object} cfg.params
* @param {Tokenizer} tokenizer

@@ -17,2 +19,3 @@ */

this.inlineBlock = new InlineBlock();
this.params = new Params(this.cfg.params);
this.tokenizer = tokenizer;

@@ -23,3 +26,3 @@ this.previousReservedWord = {};

/**
* Format the whitespace in a SQL string to make it easier to read.
* Formats whitespaces in a SQL string to make it easier to read.
*

@@ -40,29 +43,32 @@ * @param {String} query The SQL query string

tokens.forEach((token, index) => {
if (token.type === sqlTokenTypes.WHITESPACE) {
if (token.type === tokenTypes.WHITESPACE) {
return;
}
else if (token.type === sqlTokenTypes.LINE_COMMENT) {
else if (token.type === tokenTypes.LINE_COMMENT) {
formattedQuery = this.formatLineComment(token, formattedQuery);
}
else if (token.type === sqlTokenTypes.BLOCK_COMMENT) {
else if (token.type === tokenTypes.BLOCK_COMMENT) {
formattedQuery = this.formatBlockComment(token, formattedQuery);
}
else if (token.type === sqlTokenTypes.RESERVED_TOPLEVEL) {
else if (token.type === tokenTypes.RESERVED_TOPLEVEL) {
formattedQuery = this.formatToplevelReservedWord(token, formattedQuery);
this.previousReservedWord = token;
}
else if (token.type === sqlTokenTypes.RESERVED_NEWLINE) {
else if (token.type === tokenTypes.RESERVED_NEWLINE) {
formattedQuery = this.formatNewlineReservedWord(token, formattedQuery);
this.previousReservedWord = token;
}
else if (token.type === sqlTokenTypes.RESERVED) {
else if (token.type === tokenTypes.RESERVED) {
formattedQuery = this.formatWithSpaces(token, formattedQuery);
this.previousReservedWord = token;
}
else if (token.type === sqlTokenTypes.OPEN_PAREN) {
else if (token.type === tokenTypes.OPEN_PAREN) {
formattedQuery = this.formatOpeningParentheses(tokens, index, formattedQuery);
}
else if (token.type === sqlTokenTypes.CLOSE_PAREN) {
else if (token.type === tokenTypes.CLOSE_PAREN) {
formattedQuery = this.formatClosingParentheses(token, formattedQuery);
}
else if (token.type === tokenTypes.PLACEHOLDER) {
formattedQuery = this.formatPlaceholder(token, formattedQuery);
}
else if (token.value === ",") {

@@ -120,3 +126,3 @@ formattedQuery = this.formatComma(token, formattedQuery);

const previousToken = tokens[index - 1];
if (previousToken && previousToken.type !== sqlTokenTypes.WHITESPACE && previousToken.type !== sqlTokenTypes.OPEN_PAREN) {
if (previousToken && previousToken.type !== tokenTypes.WHITESPACE && previousToken.type !== tokenTypes.OPEN_PAREN) {
query = _.trimEnd(query);

@@ -147,2 +153,6 @@ }

formatPlaceholder(token, query) {
return query + this.params.get(token) + " ";
}
// Commas start a new line (unless within inline parentheses or SQL "LIMIT" clause)

@@ -149,0 +159,0 @@ formatComma(token, query) {

@@ -1,2 +0,2 @@

import sqlTokenTypes from "./tokenTypes";
import tokenTypes from "./tokenTypes";

@@ -66,6 +66,6 @@ const INLINE_MAX_LENGTH = 50;

if (token.type === sqlTokenTypes.OPEN_PAREN) {
if (token.type === tokenTypes.OPEN_PAREN) {
level++;
}
else if (token.type === sqlTokenTypes.CLOSE_PAREN) {
else if (token.type === tokenTypes.CLOSE_PAREN) {
level--;

@@ -87,8 +87,8 @@ if (level === 0) {

isForbiddenToken({type, value}) {
return type === sqlTokenTypes.RESERVED_TOPLEVEL ||
type === sqlTokenTypes.RESERVED_NEWLINE ||
type === sqlTokenTypes.COMMENT ||
type === sqlTokenTypes.BLOCK_COMMENT ||
return type === tokenTypes.RESERVED_TOPLEVEL ||
type === tokenTypes.RESERVED_NEWLINE ||
type === tokenTypes.COMMENT ||
type === tokenTypes.BLOCK_COMMENT ||
value === ";";
}
}
import _ from "lodash";
import sqlTokenTypes from "./tokenTypes";
import tokenTypes from "./tokenTypes";

@@ -13,3 +13,4 @@ export default class Tokenizer {

* @param {String[]} cfg.closeParens Closing parentheses to enable, like ), ]
* @param {String[]} cfg.variableTypes Prefixes for variables, like @ and :
* @param {String[]} cfg.indexedPlaceholderTypes Prefixes for indexed placeholders, like ?
* @param {String[]} cfg.namedPlaceholderTypes Prefixes for named placeholders, like @ and :
*/

@@ -33,4 +34,8 @@ constructor(cfg) {

this.PLAIN_VARIABLE_REGEX = this.createVariableRegex(cfg.variableTypes, "[a-zA-Z0-9._$]+");
this.QUOTED_VARIABLE_REGEX = this.createVariableRegex(cfg.variableTypes, this.createStringPattern(cfg.stringTypes));
this.INDEXED_PLACEHOLDER_REGEX = this.createPlaceholderRegex(cfg.indexedPlaceholderTypes, "[0-9]*");
this.IDENT_NAMED_PLACEHOLDER_REGEX = this.createPlaceholderRegex(cfg.namedPlaceholderTypes, "[a-zA-Z0-9._$]+");
this.STRING_NAMED_PLACEHOLDER_REGEX = this.createPlaceholderRegex(
cfg.namedPlaceholderTypes,
this.createStringPattern(cfg.stringTypes)
);
}

@@ -71,9 +76,9 @@

createVariableRegex(variableTypes, pattern) {
if (variableTypes.length === 0) {
createPlaceholderRegex(types, pattern) {
if (_.isEmpty(types)) {
return false;
}
return new RegExp(
"^((?:" + variableTypes.map(_.escapeRegExp).join("|") + ")(?:" + pattern + "))\\S"
);
const typesRegex = types.map(_.escapeRegExp).join("|");
return new RegExp(`^((?:${typesRegex})(?:${pattern}))`);
}

@@ -112,3 +117,3 @@

this.getCloseParenToken(input) ||
this.getVariableToken(input) ||
this.getPlaceholderToken(input) ||
this.getNumberToken(input) ||

@@ -123,3 +128,3 @@ this.getReservedWordToken(input, previousToken) ||

input,
type: sqlTokenTypes.WHITESPACE,
type: tokenTypes.WHITESPACE,
regex: this.WHITESPACE_REGEX

@@ -136,3 +141,3 @@ });

input,
type: sqlTokenTypes.LINE_COMMENT,
type: tokenTypes.LINE_COMMENT,
regex: this.LINE_COMMENT_REGEX

@@ -145,3 +150,3 @@ });

input,
type: sqlTokenTypes.BLOCK_COMMENT,
type: tokenTypes.BLOCK_COMMENT,
regex: this.BLOCK_COMMENT_REGEX

@@ -154,3 +159,3 @@ });

input,
type: sqlTokenTypes.STRING,
type: tokenTypes.STRING,
regex: this.STRING_REGEX

@@ -163,3 +168,3 @@ });

input,
type: sqlTokenTypes.OPEN_PAREN,
type: tokenTypes.OPEN_PAREN,
regex: this.OPEN_PAREN_REGEX

@@ -172,3 +177,3 @@ });

input,
type: sqlTokenTypes.CLOSE_PAREN,
type: tokenTypes.CLOSE_PAREN,
regex: this.CLOSE_PAREN_REGEX

@@ -178,22 +183,44 @@ });

getVariableToken(input) {
return this.getPlainVariableToken(input) || this.getQuotedVariableToken(input);
getPlaceholderToken(input) {
return this.getIdentNamedPlaceholderToken(input) ||
this.getStringNamedPlaceholderToken(input) ||
this.getIndexedPlaceholderToken(input);
}
getPlainVariableToken(input) {
return this.getTokenOnFirstMatch({
getIdentNamedPlaceholderToken(input) {
return this.getPlaceholderTokenWithKey({
input,
type: sqlTokenTypes.VARIABLE,
regex: this.PLAIN_VARIABLE_REGEX
regex: this.IDENT_NAMED_PLACEHOLDER_REGEX,
parseKey: (v) => v.slice(1)
});
}
getQuotedVariableToken(input) {
return this.getTokenOnFirstMatch({
getStringNamedPlaceholderToken(input) {
return this.getPlaceholderTokenWithKey({
input,
type: sqlTokenTypes.VARIABLE,
regex: this.QUOTED_VARIABLE_REGEX
regex: this.STRING_NAMED_PLACEHOLDER_REGEX,
parseKey: (v) => this.getEscapedPlaceholderKey({key: v.slice(2, -1), quoteChar: v.slice(-1)})
});
}
getIndexedPlaceholderToken(input) {
return this.getPlaceholderTokenWithKey({
input,
regex: this.INDEXED_PLACEHOLDER_REGEX,
parseKey: (v) => v.slice(1)
});
}
getPlaceholderTokenWithKey({input, regex, parseKey}) {
const token = this.getTokenOnFirstMatch({input, regex, type: tokenTypes.PLACEHOLDER});
if (token) {
token.key = parseKey(token.value);
}
return token;
}
getEscapedPlaceholderKey({key, quoteChar}) {
return key.replace(new RegExp(_.escapeRegExp("\\") + quoteChar, "g"), quoteChar);
}
// Decimal, binary, or hex numbers

@@ -203,3 +230,3 @@ getNumberToken(input) {

input,
type: sqlTokenTypes.NUMBER,
type: tokenTypes.NUMBER,
regex: this.NUMBER_REGEX

@@ -213,3 +240,3 @@ });

input,
type: sqlTokenTypes.OPERATOR,
type: tokenTypes.OPERATOR,
regex: this.OPERATOR_REGEX

@@ -231,3 +258,3 @@ });

input,
type: sqlTokenTypes.RESERVED_TOPLEVEL,
type: tokenTypes.RESERVED_TOPLEVEL,
regex: this.RESERVED_TOPLEVEL_REGEX

@@ -240,3 +267,3 @@ });

input,
type: sqlTokenTypes.RESERVED_NEWLINE,
type: tokenTypes.RESERVED_NEWLINE,
regex: this.RESERVED_NEWLINE_REGEX

@@ -249,3 +276,3 @@ });

input,
type: sqlTokenTypes.RESERVED,
type: tokenTypes.RESERVED,
regex: this.RESERVED_PLAIN_REGEX

@@ -258,3 +285,3 @@ });

input,
type: sqlTokenTypes.WORD,
type: tokenTypes.WORD,
regex: this.WORD_REGEX

@@ -261,0 +288,0 @@ });

@@ -17,3 +17,3 @@ /**

NUMBER: "number",
VARIABLE: "variable"
PLACEHOLDER: "placeholder"
};

@@ -56,3 +56,3 @@ import Formatter from "../core/Formatter";

closeParens: [")", "]", "}"],
variableTypes: [],
namedPlaceholderTypes: ["$"]
});

@@ -59,0 +59,0 @@ }

@@ -75,3 +75,4 @@ import Formatter from "../core/Formatter";

closeParens: [")"],
variableTypes: ["@", ":"],
indexedPlaceholderTypes: ["?"],
namedPlaceholderTypes: ["@", ":"]
});

@@ -78,0 +79,0 @@ }

@@ -12,2 +12,3 @@ import N1qlFormatter from "./languages/N1qlFormatter";

* @param {String} cfg.indent Characters used for indentation, default is " " (2 spaces)
* @param {Object} cfg.params Collection of params for placeholder replacement
* @return {String}

@@ -14,0 +15,0 @@ */

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc