Registry / database / pgsql-parser

pgsql-parser

JSON →
library17.9.15jsnpmunverified

pgsql-parser is a JavaScript/TypeScript library designed for parsing PostgreSQL SQL queries into an Abstract Syntax Tree (AST) and deparsing ASTs back into SQL. It leverages the actual PostgreSQL C parser, compiled to WebAssembly, to ensure 100% compatibility with PostgreSQL's syntax. The current stable version, as specified, is 17.9.15. The project is part of a broader monorepo that includes related packages like `@pgsql/parser` for multi-version parsing, `@pgsql/deparser` for AST-to-SQL conversion only, and `@pgsql/types` for comprehensive TypeScript definitions of AST nodes. It offers symmetric operations, meaning an AST generated from SQL can be perfectly converted back to the original SQL, and is extensively tested for reliability. This library is ideal for tools requiring deep SQL analysis, modification, or code generation, providing a robust and type-safe foundation for working with PostgreSQL at the AST level. Its release cadence follows the PostgreSQL versioning and related ecosystem packages are frequently updated.

npm install pgsql-parser
INSTALL
IMPORT
SIG · PGSQL-PARSER
P
pgsql-parser
databasejavascriptv17.9.15
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
import { parse } from 'pgsql-parser';
const { parse } = require('pgsql-parser');
The `parse` function is the primary entry point for converting SQL strings into a PostgreSQL AST. The library is primarily designed for ESM usage; CommonJS `require` might not be directly supported or could lead to bundling issues in modern environments.
deparse
import { deparse } from 'pgsql-parser';
const { deparse } = require('pgsql-parser');
The `deparse` function converts a PostgreSQL AST back into a SQL string. Ensure the AST structure is valid for the target PostgreSQL version to prevent deparsing errors. For dedicated deparsing, `pgsql-deparser` can be used.
ParseResult
import type { ParseResult } from 'pgsql-parser';
When working with TypeScript, `ParseResult` provides the type definition for the Abstract Syntax Tree returned by the `parse` function. For specific PostgreSQL version types (e.g., v17), you might also import from `@pgsql/types` or version-specific paths in `@pgsql/parser`.
Parser (multi-version)
import { Parser } from '@pgsql/parser'; const parser = new Parser({ version: 17 });
import Parser from '@pgsql/parser'; // Default import is often incorrect import { Parser } from 'pgsql-parser'; // Incorrect package for multi-version parser
For dynamically selecting or supporting multiple PostgreSQL versions (e.g., 15, 16, 17), use the `Parser` class from the `@pgsql/parser` package. The default version is typically the latest supported (e.g., 17).

Demonstrates how to parse a PostgreSQL SQL query into an AST, programmatically modify the AST (e.g., change a table name), and then deparse the modified AST back into a SQL string using `pgsql-parser`.

import { parse, deparse } from 'pgsql-parser'; import type { SelectStmt } from '@pgsql/types'; async function main() { const sqlQuery = "SELECT id, name FROM users WHERE status = 'active' ORDER BY name ASC;"; try { // Parse the SQL query into an Abstract Syntax Tree (AST) const ast = await parse(sqlQuery); console.log('Original AST:', JSON.stringify(ast, null, 2)); // Example: Modify the AST (e.g., change the table name) // The AST structure can be complex and depends on the PostgreSQL version. // Assuming a simple SelectStmt structure for demonstration. if (ast && ast.stmts && ast.stmts.length > 0) { const selectStmt = ast.stmts[0]?.stmt?.SelectStmt as SelectStmt | undefined; if (selectStmt && selectStmt.fromClause && selectStmt.fromClause.length > 0) { const rangeVar = selectStmt.fromClause[0]?.RangeVar; if (rangeVar) { rangeVar.relname = 'customers'; // Change 'users' to 'customers' console.log('\nModified AST:', JSON.stringify(ast, null, 2)); // Deparse the modified AST back into a SQL string const modifiedSql = await deparse(ast); console.log('\nModified SQL:', modifiedSql); } } } } catch (error) { if (error instanceof Error) { console.error('Parsing failed:', error.message); } else { console.error('An unknown error occurred:', error); } } } main();
Debug
Known issues
breakingThe internal structure of the Abstract Syntax Tree (AST) produced by the parser can change significantly between major PostgreSQL versions. Code that directly manipulates or relies on specific AST node shapes may break when upgrading the underlying PostgreSQL parser version.
fix
Thoroughly test AST-dependent code against each new PostgreSQL version. Consider using higher-level AST manipulation utilities (if provided by the ecosystem) or robust type guards and validation when accessing AST properties. Refer to PostgreSQL's own AST documentation and the library's changelog for specific schema changes.
affects: All versions (on major PostgreSQL version bumps)
gotchaPerformance-critical applications should be aware of potential overhead during the initial loading of the WebAssembly (WASM) module, which powers the C parser. While generally optimized, the first parse operation might be slightly slower.
fix
If initial latency is a concern, consider a 'warm-up' parse of a simple query during application startup to ensure the WASM module is loaded and ready before critical operations. For serverless functions, this might mean provisioning sufficient memory or using cold-start mitigation strategies.
affects: >=1.0.0
gotchaThe `pgsql-parser` package uses the latest available PostgreSQL parser version. If you require parsing SQL compatible with specific, older PostgreSQL versions, the `@pgsql/parser` package should be used instead, as it provides explicit version selection capabilities.
fix
For multi-version support, install `@pgsql/parser` and instantiate `new Parser({ version: N })` where `N` is your target PostgreSQL version (e.g., 15, 16). `import { parse } from '@pgsql/parser/v{N}';` can be used for tree-shaking specific versions.
affects: >=1.0.0
Errors
Common errors & fixes
SyntaxError: Cannot use import statement outside a module
Attempting to use ES module `import` syntax in a CommonJS (`.js` without `"type": "module"` or `.cjs`) Node.js environment.
fix
Ensure your project is configured for ES Modules by adding `"type": "module"` to your `package.json` file or by using `.mjs` file extensions for your module files. Alternatively, if forced to use CommonJS, you might need to use dynamic `import()` or find a CommonJS compatible build of the library if available, though `pgsql-parser` primarily targets ESM.
Error: syntax error at or near "<token>"
The SQL query provided to the `parse` function contains invalid PostgreSQL syntax. This error originates from the underlying PostgreSQL C parser.
fix
Carefully review the SQL query for typos, missing or misplaced commas/parentheses, incorrect keywords, or dialect-specific syntax not supported by PostgreSQL. The error message usually indicates the exact position ('at or near "<token>"') where the parsing failed.
TypeError: Cannot read properties of undefined (reading 'SelectStmt')
Attempting to access properties of the Abstract Syntax Tree (AST) without proper null/undefined checks, or assuming an AST structure that doesn't match the parsed SQL or the PostgreSQL version.
fix
Always perform defensive programming by checking for `null` or `undefined` at each level of the AST when traversing or modifying it. Refer to the `@pgsql/types` package for accurate TypeScript definitions and the PostgreSQL documentation for the expected AST structure for your target version. Use TypeScript for better compile-time checks.
Upgrade
Version history
17.9.15latest on npm
Audit
Dependencies

No dependency data recorded yet.

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