Skip to content

ZHANGDAXIA01/node-sql-parser

 
 

Repository files navigation

GanJiang SQL Parser

Build Status license npm version NPM downloads Coverage Status Dependencies issues

Parse simple SQL statements into an abstract syntax tree (AST) with the visited tableList and convert it back to SQL.

⭐ Features

  • support multiple sql statement seperate by semicolon
  • support select, delete, update and insert type
  • output the table list that the sql visited with the corresponding authority

🚀 Usage

Create AST for SQL statement

const { Parser } = require('node-sql-parser');
const parser = new Parser();
const ast = parser.sqlToAst('SELECT * FROM t');

console.log(ast);

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 { Parser } = require('node-sql-parser');
const parser = new Parser();
const tableList = parser.tableList('SELECT * FROM t');

console.log(tableList); // ["select::null::t"]

Check the SQL with Authority List

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 whiteList = ['(select|update)::(.*)::(a|b)'] // array that contain multiple authorities
parser.whiteListCheck(sql, whiteList) // if check failed, an error would be thrown with relevant error message, if passed it would return undefined

Convert AST back to SQL

  • Only SELECT SQL statements are supported for converting ast back to sql currently
const { Parser, util } = require('node-sql-parser');
const parser = new Parser()
const ast = parser.sqlToAst('SELECT * FROM t');
const sql = util.astToSQL(ast);

console.log(sql); // SELECT * FROM `t`

😘 Acknowledgement

This project is based on the SQL parser extracted from flora-sql-parser module.

License

MIT

About

Parse simple SQL statements into an abstract syntax tree (AST) with the visited tableList and convert it back to SQL

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • JavaScript 100.0%