What is node-sql-parser?
The node-sql-parser package is a powerful tool for parsing, formatting, and analyzing SQL queries in Node.js. It supports various SQL dialects and provides a range of functionalities to work with SQL queries programmatically.
What are node-sql-parser's main functionalities?
SQL Parsing
This feature allows you to parse SQL queries into an Abstract Syntax Tree (AST). The AST can be used for further analysis or transformation of the SQL query.
const { Parser } = require('node-sql-parser');
const parser = new Parser();
const sql = 'SELECT * FROM users WHERE age > 30';
const ast = parser.astify(sql);
console.log(JSON.stringify(ast, null, 2));
SQL Formatting
This feature allows you to format SQL queries. You can convert an AST back into a SQL string, which can be useful for standardizing the format of SQL queries.
const { Parser } = require('node-sql-parser');
const parser = new Parser();
const sql = 'SELECT * FROM users WHERE age > 30';
const formattedSQL = parser.sqlify(parser.astify(sql));
console.log(formattedSQL);
SQL Dialect Support
This feature allows you to specify the SQL dialect (e.g., MySQL, PostgreSQL) when parsing SQL queries. This ensures that the parser correctly interprets the syntax and semantics of the specified dialect.
const { Parser } = require('node-sql-parser');
const parser = new Parser();
const sql = 'SELECT * FROM users WHERE age > 30';
const ast = parser.astify(sql, { database: 'mysql' });
console.log(JSON.stringify(ast, null, 2));
Other packages similar to node-sql-parser
sql-parser
The sql-parser package is a simple SQL parser for Node.js. It provides basic parsing capabilities but lacks the advanced features and dialect support of node-sql-parser.
sql-formatter
The sql-formatter package focuses on formatting SQL queries. It provides a range of formatting options but does not offer parsing or AST generation capabilities like node-sql-parser.
sequelize
Sequelize is an ORM for Node.js that supports various SQL dialects. While it provides some query parsing and generation capabilities, its primary focus is on database interaction and ORM functionalities, making it more comprehensive but also more complex than node-sql-parser.
Nodejs SQL Parser
Parse simple SQL statements into an abstract syntax tree (AST) with the visited tableList, columnList and convert it back to SQL.
:star: Features
- support multiple sql statement seperate by semicolon
- support select, delete, update and insert type
- support drop, truncate and rename command
- output the table and column list that the sql visited with the corresponding authority
- support various databases engine
:tada: Install
npm install node-sql-parser --save
or
yarn add node-sql-parser
npm install @taozhi8833998/node-sql-parser --registry=https://npm.pkg.github.com/
From Browser
Import the JS file in your page:
<script src="https://unpkg.com/node-sql-parser/umd/index.umd.js"></script>
<script src="https://unpkg.com/node-sql-parser/umd/mysql.umd.js"></script>
<script src="https://unpkg.com/node-sql-parser/umd/postgresql.umd.js"></script>
NodeSQLParser
object is on window
<!DOCTYPE html>
<html lang="en" >
<head>
<title>node-sql-parser</title>
<meta charset="utf-8" />
</head>
<body>
<p><em>Check console to see the output</em></p>
<script src="https://unpkg.com/node-sql-parser/umd/mysql.umd.js"></script>
<script>
window.onload = function () {
const parser = new NodeSQLParser.Parser()
const ast = parser.astify("select id, name from students where age < 18")
console.log(ast)
const sql = parser.sqlify(ast)
console.log(sql)
}
</script>
</body>
</html>
:rocket: Usage
Supported Database SQL Syntax
- BigQuery
- DB2
- Hive
- MariaDB
- MySQL
- PostgresQL
- Sqlite(developing)
- TransactSQL
- FlinkSQL
- New issue could be made for other new database.
Create AST for SQL statement
const { Parser } = require('node-sql-parser');
const parser = new Parser();
const ast = parser.astify('SELECT * FROM t');
console.log(ast);
{
"with": null,
"type": "select",
"options": null,
"distinct": null,
"columns": "*",
"from": [
{
"db": null,
"table": "t",
"as": null
}
],
"where": null,
"groupby": null,
"having": null,
"orderby": null,
"limit": null
}
Convert AST back to SQL
const opt = {
database: 'MySQL'
}
const { Parser } = require('node-sql-parser/build/mysql');
const parser = new Parser()
const ast = parser.astify('SELECT * FROM t', opt);
const sql = parser.sqlify(ast, opt);
console.log(sql);
Get TableList, ColumnList, Ast by parse
function
const opt = {
database: 'MariaDB'
}
const { Parser } = require('node-sql-parser/build/mariadb');
const parser = new Parser()
const { tableList, columnList, ast } = parser.parse('SELECT * FROM t', opt);
Get the SQL visited tables
- get the table list that the sql visited
- the format is {type}::{dbName}::{tableName} // type could be select, update, delete or insert
const opt = {
database: 'MySQL'
}
const { Parser } = require('node-sql-parser/build/mysql');
const parser = new Parser();
const tableList = parser.tableList('SELECT * FROM t', opt);
console.log(tableList);
Get the SQL visited columns
- get the column list that the sql visited
- the format is {type}::{tableName}::{columnName} // type could be select, update, delete or insert
- for
select *
, delete
and insert into tableName values()
without specified columns, the .*
column authority regex is required
const opt = {
database: 'MySQL'
}
const { Parser } = require('node-sql-parser/build/mysql');
const parser = new Parser();
const columnList = parser.columnList('SELECT t.id FROM t', opt);
console.log(columnList);
Check the SQL with Authority List
- check table authority
whiteListCheck
function check on table
mode and MySQL
database by default
const { Parser } = require('node-sql-parser');
const parser = new Parser();
const sql = 'UPDATE a SET id = 1 WHERE name IN (SELECT name FROM b)'
const whiteTableList = ['(select|update)::(.*)::(a|b)']
const opt = {
database: 'MySQL',
type: 'table',
}
parser.whiteListCheck(sql, whiteTableList, opt)
const { Parser } = require('node-sql-parser');
const parser = new Parser();
const sql = 'UPDATE a SET id = 1 WHERE name IN (SELECT name FROM b)'
const whiteColumnList = ['select::null::name', 'update::a::id']
const opt = {
database: 'MySQL',
type: 'column',
}
parser.whiteListCheck(sql, whiteColumnList, opt)
:kissing_heart: Acknowledgement
This project is based on the SQL parser extracted from flora-sql-parser module.
License
GPLv2
Buy me a Coffee
If you like my project, Star in the corresponding project right corner. Your support is my biggest encouragement! ^_^
You can also scan the qr code below or open paypal link to donate to Author.
Paypal
Donate money by paypal to my account taozhi8833998@163.com
AliPay(支付宝)
Wechat(微信)
Explain
If you have made a donation, you can leave your name and email in the issue, your name will be written to the donation list.