Registry / database / pg-query-parser

pg-query-parser

JSON →
library0.3.0jsnpmunverified

pg-query-parser is a Node.js module that provides symmetric parsing and deparsing capabilities for PostgreSQL SQL statements. It leverages the *real* PostgreSQL parser (via `libpg_query`) to convert SQL strings into an Abstract Syntax Tree (AST) and back into a formatted SQL statement. The current stable version is 0.3.0. Its key differentiator is the ability to deparse the AST back into SQL, a functionality not natively available in PostgreSQL itself, enabling developers to programmatically modify parts of a SQL query's AST and serialize the changes back into valid SQL. This makes it useful for building query builders, optimizers, or tools that inspect and transform SQL statements programmatically. Release cadence appears infrequent, with a recent update for `ParamRef` support in v0.2.0, indicating ongoing maintenance.

npm install pg-query-parser
INSTALL
IMPORT
SIG · PG-QUERY-PARSER
P
pg-query-parser
databasejavascriptv0.3.0
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.

parser
const parser = require('pg-query-parser');
import parser from 'pg-query-parser';
The package primarily uses CommonJS `require()`. While Node.js can often interpret CJS via `import`, explicit `require` is the documented and most reliable method. Direct ESM import might require specific Node.js configuration or a wrapper.
parser.parse
const parser = require('pg-query-parser'); const ast = parser.parse('SELECT 1');
import { parse } from 'pg-query-parser'; // or const parse = require('pg-query-parser').parse;
The `parse` function is a method on the `parser` object returned by `require('pg-query-parser')`, not a named export. Direct destructuring `const { parse } = require(...)` might not work.
parser.deparse
const parser = require('pg-query-parser'); const sql = parser.deparse(ast);
import { deparse } from 'pg-query-parser'; // or const deparse = require('pg-query-parser').deparse;
The `deparse` function is a method on the `parser` object returned by `require('pg-query-parser')`, not a named export. Direct destructuring `const { deparse } = require(...)` might not work.

Demonstrates parsing a SQL query, modifying its Abstract Syntax Tree (AST) to change a table name, and then deparsing the modified AST back into a SQL string.

const parser = require('pg-query-parser'); // Example SQL query to parse const originalSql = 'SELECT * FROM test_table WHERE id = 1'; // Parse the SQL query into an Abstract Syntax Tree (AST) const parsedQuery = parser.parse(originalSql); // Check for parsing errors if (parsedQuery.error) { console.error('Parsing error:', parsedQuery.error.message); process.exit(1); } // Access the query array from the parsed object const queryAst = parsedQuery.query; // Modify a part of the AST: change the table name // This assumes a simple SELECT statement structure if (queryAst && queryAst[0] && queryAst[0].SelectStmt && queryAst[0].SelectStmt.fromClause && queryAst[0].SelectStmt.fromClause[0].RangeVar) { queryAst[0].SelectStmt.fromClause[0].RangeVar.relname = 'another_table'; } else { console.warn('Could not locate table name in AST for modification.'); } // Deparse the modified AST back into a SQL statement const rewrittenSql = parser.deparse(queryAst); console.log('Original SQL:', originalSql); console.log('Rewritten SQL:', rewrittenSql); // Expected output: SELECT * FROM "another_table" WHERE id = 1
Debug
Known issues
breakingThe Abstract Syntax Tree (AST) structure returned by `parser.parse()` is derived from PostgreSQL's internal parser. This structure can change between PostgreSQL versions or underlying `libpg_query` updates. Since `pg-query-parser` is in a low major version (0.x.x), subsequent minor versions may introduce breaking changes to the AST shape. Code that directly manipulates the AST may break.
fix
Always inspect the AST structure for specific PostgreSQL versions and adapt your code. Use `JSON.stringify(ast, null, 2)` to visualize the structure after parsing and verify your manipulation paths.
affects: >=0.2.0
gotchaThis package is a native Node.js module that depends on `libpg_query`, a C library. Installation via `npm install` requires a compatible C/C++ compiler toolchain (e.g., `build-essential` on Linux, Xcode Command Line Tools on macOS, Visual C++ Build Tools on Windows) for the target environment. Installation failures are common on systems without these build tools or during cross-compilation.
fix
Ensure your system has the necessary build tools installed. For Debian/Ubuntu, run `sudo apt-get install build-essential`. For macOS, run `xcode-select --install`. For Windows, install Visual Studio Build Tools with C++ desktop development workload. Check `node-gyp` documentation for platform-specific details.
affects: *
gotchaDirectly modifying the PostgreSQL AST can be complex and error-prone. The AST structure is deeply nested and highly dependent on the SQL statement's type and features. Incorrect modifications can lead to invalid SQL after deparsing, unexpected query behavior, or runtime errors.
fix
Start with simple queries to understand the AST structure before attempting complex transformations. Use `console.log(JSON.stringify(ast, null, 2))` to inspect the AST. Refer to PostgreSQL documentation on its internal query structures for deeper understanding when performing advanced manipulations.
affects: *
Errors
Common errors & fixes
Error: Cannot find module 'pg-query-parser'
The package was not installed, or there's a CommonJS/ESM module resolution issue in an ESM-only environment.
fix
Run `npm install pg-query-parser`. If using ESM, try dynamic import `const parser = await import('pg-query-parser');` or ensure your project's `package.json` `type` is not set to `module` if using `require()`.
Error: syntax error at or near "some_token"
The input SQL string provided to `parser.parse()` contains invalid PostgreSQL syntax. The error message originates from the underlying PostgreSQL parser.
fix
Correct the SQL query string to conform to valid PostgreSQL syntax. The `error` object returned by `parser.parse()` provides `lineNumber` and `cursorPosition` to help pinpoint the issue in the SQL.
TypeError: Cannot set properties of undefined (setting 'relname')
Attempting to access or modify a property within the AST that does not exist or has a different structure than expected for a given query type or PostgreSQL version.
fix
Thoroughly inspect the AST structure using `console.log(JSON.stringify(ast, null, 2))` for the specific SQL query being parsed. The AST structure is highly dependent on the SQL statement, and your access path must match the actual AST.
node-gyp rebuild failed
During `npm install`, the compilation of the native `libpg_query` dependency failed due to missing C/C++ build tools on the system.
fix
Install the necessary build tools for your operating system (e.g., `build-essential` on Debian/Ubuntu, Xcode Command Line Tools on macOS, Visual C++ Build Tools on Windows). Refer to the `node-gyp` documentation for detailed platform-specific requirements.
Upgrade
Version history
0.3.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
5 hits · last 30 days
node
4
Resources
pg-query-parser — npm install pg-query-parser · libregistry