Postgres SQL AST Parser

12.0.2 · active · verified Tue Apr 21

pgsql-ast-parser is a JavaScript and TypeScript library designed for parsing PostgreSQL SQL syntax into a typed Abstract Syntax Tree (AST), and then facilitating its modification or conversion back to SQL. It is currently at version 12.0.2 and appears to have an active release cadence, with major versions indicating significant structural changes to the AST. Key differentiators include its ability to run in both Node.js and browser environments, its robust TypeScript typing which is strongly recommended for usage, and its foundational role as the underlying parser for `pg-mem`, an in-memory PostgreSQL database emulator. While it covers most common PostgreSQL syntaxes, it explicitly states it does not support PL/pgSQL or some obscure syntaxes, requiring users to test specific complex queries.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to parse a SQL statement and then use an `astVisitor` to traverse the Abstract Syntax Tree, collecting all referenced table names and counting the number of joins.

import { astVisitor, parseFirst } from 'pgsql-ast-parser';

const tables = new Set<string>();
let joins = 0;

// Create an AST visitor to collect information
const visitor = astVisitor(map => ({
    // Hook into table reference nodes to get table names
    tableRef: t => tables.add(t.name),
    // Hook into join nodes to count joins
    join: t => {
        joins++;
        // Call the default implementation to ensure subtrees are also traversed
        map.super().join(t);
    }
}));

// Parse a single SQL statement into an AST
const sqlStatement = `SELECT o.order_id, c.customer_name FROM orders AS o LEFT JOIN customers AS c ON o.customer_id = c.customer_id WHERE o.order_date > '2023-01-01';`;
const ast = parseFirst(sqlStatement);

// Start traversing the AST with our visitor
visitor.statement(ast);

// Print the collected results
console.log(`SQL: ${sqlStatement}`);
console.log(`Used tables: ${[...tables].join(', ')}`);
console.log(`Number of joins: ${joins}`);

view raw JSON →