SQL Parser for Node.js

5.4.0 · active · verified Sun Apr 19

Node.js SQL Parser is a versatile library designed to parse various SQL statements into a structured Abstract Syntax Tree (AST) and then reconstruct the SQL from that AST. It supports a comprehensive range of SQL dialects, including MySQL, PostgreSQL, SQLite, Athena, BigQuery, Snowflake, and TransactSQL, among others. Currently at version 5.4.0, the package maintains an active development pace with frequent minor and patch updates, consistently adding support for new SQL syntax features and improving existing dialect compatibility. Key differentiators include its extensive multi-dialect support, the ability to extract visited table and column lists with associated authority, and its dual functionality for both SQL parsing and generation. It offers both Node.js module and browser UMD bundles, providing flexibility across different environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the SQL parser, parse a sample SQL query into an AST, extract table and column lists, and then reconstruct the SQL from the AST. It highlights the basic workflow for SQL analysis and manipulation.

import { Parser, AST } from 'node-sql-parser';

const sqlQuery = "SELECT id, name FROM users WHERE age > 25 AND city = 'New York';";

// Initialize the parser, defaulting to MySQL dialect. For other dialects, pass { dialect: 'postgresql' } as an option.
const parser = new Parser();

try {
  // Parse the SQL query into an Abstract Syntax Tree (AST).
  const ast: AST[] = parser.astify(sqlQuery) as AST[];
  console.log('Parsed AST:', JSON.stringify(ast, null, 2));

  // Get the list of tables visited in the SQL statement.
  const tables = parser.tableList(sqlQuery);
  console.log('Visited Tables:', tables);

  // Get the list of columns visited in the SQL statement.
  const columns = parser.columnList(sqlQuery);
  console.log('Visited Columns:', columns);

  // Convert the AST back into a SQL string.
  const reconstructedSql = parser.sqlify(ast);
  console.log('Reconstructed SQL:', reconstructedSql);
} catch (error: any) {
  console.error('SQL Parsing Error:', error.message);
}

view raw JSON →