Parsing SQL
Lanexio Parser implements SQL:2016 with dialect-specific lexing for PostgreSQL, MySQL, SQLite, and T-SQL. The parser accepts any SQL dialect through a configurable parse path and produces structured trees with keyword, identifier, literal, and clause nodes.
Quick start
Section titled “Quick start”-
Install the package.
Terminal window pnpm add @lanexio/parser-grammar-sqlTerminal window npm install @lanexio/parser-grammar-sqlTerminal window yarn add @lanexio/parser-grammar-sql -
Parse a SQL query.
import { parseSql } from '@lanexio/parser-grammar-sql';const encoder = new TextEncoder();const tree = parseSql(encoder.encode(`SELECT name, emailFROM usersWHERE active = trueORDER BY name`));
Dialect selection
Section titled “Dialect selection”Pass a dialect option to control quoting, comments, and operators:
import { parseSql } from '@lanexio/parser-grammar-sql';
const tree = parseSql(encoder.encode(` SELECT * FROM "users" WHERE "name" = 'Alice'`), { dialect: 'postgres' }); // PostgreSQL-style double-quoted identifiers| Dialect | Quoting | Comment | Notable |
|---|---|---|---|
'ansi' | 'string', "identifier" | --, /* */ | Default |
'postgres' | 'string', "identifier" | --, /* */ | :: casts, $$ strings |
'mysql' | 'string', `identifier` | #, --, /* */ | Backtick identifiers |
'sqlite' | 'string', "identifier" | --, /* */ | Concatenation |
'tsql' | 'string', [identifier] | --, /* */ | Bracket identifiers |
Inspecting the tree
Section titled “Inspecting the tree”const cursor = tree.cursor();cursor.gotoFirstChild(); // SELECT statement
while (cursor.gotoNextSibling()) { // Walk SELECT, FROM, WHERE, ORDER BY clauses console.log(cursor.current.kind);}