Skip to content

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.

  1. Install the package.

    Terminal window
    pnpm add @lanexio/parser-grammar-sql
  2. Parse a SQL query.

    import { parseSql } from '@lanexio/parser-grammar-sql';
    const encoder = new TextEncoder();
    const tree = parseSql(encoder.encode(`
    SELECT name, email
    FROM users
    WHERE active = true
    ORDER BY name
    `));

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
DialectQuotingCommentNotable
'ansi''string', "identifier"--, /* */Default
'postgres''string', "identifier"--, /* */:: casts, $$ strings
'mysql''string', `identifier`#, --, /* */Backtick identifiers
'sqlite''string', "identifier"--, /* */Concatenation
'tsql''string', [identifier]--, /* */Bracket identifiers
const cursor = tree.cursor();
cursor.gotoFirstChild(); // SELECT statement
while (cursor.gotoNextSibling()) {
// Walk SELECT, FROM, WHERE, ORDER BY clauses
console.log(cursor.current.kind);
}