Registry / database / pgsql-ast-parser

pgsql-ast-parser

JSON →
library12.0.2jsnpmunverified

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.

npm install pgsql-ast-parser
INSTALL
IMPORT
SIG · PGSQL-AST-PARSER
P
pgsql-ast-parser
databasejavascriptv12.0.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

parse, Statement
import { parse, Statement } from 'pgsql-ast-parser';
const { parse, Statement } = require('pgsql-ast-parser');
These are the primary function for parsing multiple SQL statements and the core type for AST nodes. The library ships with TypeScript types.
parseFirst
import { parseFirst } from 'pgsql-ast-parser';
import parseFirst from 'pgsql-ast-parser';
Use this named import for parsing a single SQL statement; it returns a single Statement object instead of an array.
astVisitor, toSql, astMapper
import { astVisitor, toSql, astMapper } from 'pgsql-ast-parser';
const astVisitor = require('pgsql-ast-parser').astVisitor;
These are utility functions for traversing (astVisitor), converting back to SQL (toSql), and modifying (astMapper) the parsed AST. All are named exports.

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}`);
Debug
Known issues
breakingIn version 9.0.0, the AST interface for `ALTER TABLE` statements changed. The `change` property was renamed to `changes` and is now an array of `TableAlteration[]`.
fix
Update code that accesses `ALTER TABLE` AST nodes to use the `changes` array property instead of `change`.
affects: >=9.0.0
breakingVersion 8.0.0 introduced a significant breaking change in how `INSERT` statements are parsed. The `InsertStatement` now has a single `insert` property, unifying the parsing logic for `INSERT ... VALUES` and `INSERT ... SELECT`.
fix
Refactor code that inspects `INSERT` statement ASTs to account for the new unified `insert` property, rather than separate `values` or `select` properties.
affects: >=8.0.0
gotchaThe parser does not (yet) support PL/pgSQL or some advanced/funky PostgreSQL syntaxes. Attempting to parse such SQL might result in parsing errors.
fix
Avoid parsing PL/pgSQL blocks directly. For complex or unusual SQL, test parsing capabilities thoroughly and consider simplifying the input SQL or contributing support for missing syntax.
affects: >=1.0.0
gotchaWhile usable in JavaScript, the library strongly recommends using TypeScript due to the complexity and depth of the generated Abstract Syntax Tree (AST) types. Without TypeScript, navigating the AST can be prone to errors.
fix
Utilize TypeScript in your project to leverage the provided type definitions for the AST, which will greatly improve developer experience and reduce type-related bugs when working with the parsed SQL structures.
affects: >=1.0.0
Errors
Common errors & fixes
Syntax Error: Unexpected token at position X
The input SQL string contains syntax that the parser does not understand or is malformed.
fix
Review the SQL query for typos or unsupported features (like PL/pgSQL). Simplify the query or test specific parts to isolate the problematic syntax. If it's standard PostgreSQL syntax, consider opening a bug report.
Property 'X' does not exist on type 'Y'
This TypeScript error occurs when attempting to access a property on an AST node that is either not present on that specific node type or has changed in a breaking library version.
fix
Consult the library's TypeScript definitions and AST documentation for the specific `pgsql-ast-parser` version you are using. Ensure your code aligns with the current AST structure, especially after major version upgrades.
require is not defined
You are attempting to use CommonJS `require()` to import `pgsql-ast-parser` in an ES module (ESM) environment (e.g., in a file where `type: "module"` is set in `package.json` or a `.mjs` file).
fix
Change your import statements from `const pkg = require('pgsql-ast-parser');` to `import * as pkg from 'pgsql-ast-parser';` or `import { parse } from 'pgsql-ast-parser';`.
Upgrade
Version history
12.0.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
8 hits · last 30 days
node
8
Resources
pgsql-ast-parser — npm install pgsql-ast-parser · libregistry