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-parserVerified import paths — ran on the pinned version, not inferred.
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.
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.
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.
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.
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()`.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.
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.
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.
No dependency data recorded yet.