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
muslnode 18–226 runs
build_error
glibcnode 18–226 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.fixThoroughly 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.fixIf 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.fixFor 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.
fixEnsure 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.
fixCarefully 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.
fixAlways 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.
Audit
Dependencies
No dependency data recorded yet.