SqlWhereParser
What is it?
SqlWhereParser parses the WHERE portion of an SQL-like string into an abstract syntax tree.
const sql = 'name = "Shaun Persad" AND age >= 27';const parser = ;const parsed = parser;/** * The tree is object-based, where each key is the operator, and its value is an array of the operands. * The number of operands depends on if the operation is defined as unary, binary, or ternary in the config. */;
You can also evaluate the query in-line as the expressions are being built.
const sql = 'name = "Shaun Persad" AND age >= (20 + 7)';const parser = ;/** * This evaluator function will evaluate the "+" operator with its operands by adding its operands together. */const parsed = parser; ;
This evaluation can also be used to convert the AST into a specific tree, like a MongoDB query.
const sql = 'name = "Shaun Persad" AND age >= 27';const parser = ;/** * This will map each operand to its mongoDB equivalent. */const parsed = parser; ;
SqlWhereParser can also parse into an array-like structure, where each sub-array is its own group of parentheses in the SQL.
const sql = '(name = "Shaun Persad") AND (age >= (20 + 7))';const parser = ;const sqlArray = parser;;
This array structure is useful for displaying the query on the front-end, e.g. as HTML.
const sql = '(name = "Shaun Persad") AND age >= (20 + 7)';const parser = ;const sqlArray = parser;/** * This function will recursively map the elements of the array to HTML. */const toHtml = { if toConvert && toConvertconstructor === SqlWhereParserOperator return `<strong class="operator"></strong>`; if !toConvert || !toConvertconstructor === Array return `<span class="operand"></span>`; const html = toConvert; return `<div class="expression"></div>`;}; const html = ;;
Installation
npm install sql-where-parser
.
// or if in the browser: <script src="sql-where-parser/sql-where-parser.min.js"></script>
Usage
require
it, and create a new instance.
//const SqlWhereParser = require('sql-where-parser');const sql = 'name = "Shaun Persad" AND age >= 27';const parser = ; const parsed = parser; // Abstract syntax treeconst sqlArray = parser; // Array
Advanced Usage
Supplying a config object
here for all options
seeModifying the config can be used to add new operators:
const config = SqlWhereParserdefaultConfig; // start off with the default config.configoperators5'<=>' = 2; // number of operands to expect for this operator.configoperators5'<>' = 2; // number of operands to expect for this operator.configtokenizershouldTokenize;const sql = 'name <> "Shaun Persad" AND age <=> 27';const parser = config; // use the new configconst parsed = parser;;
API
For the full API documentation and more examples, see here.