{"id":13763,"library":"pg-query-parser","title":"PostgreSQL Query Parser","description":"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.","status":"active","version":"0.3.0","language":"javascript","source_language":"en","source_url":"git://github.com/zhm/pg-query-parser","tags":["javascript","sql","postgres","postgresql","pg","query","database"],"install":[{"cmd":"npm install pg-query-parser","lang":"bash","label":"npm"},{"cmd":"yarn add pg-query-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add pg-query-parser","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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.","wrong":"import parser from 'pg-query-parser';","symbol":"parser","correct":"const parser = require('pg-query-parser');"},{"note":"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.","wrong":"import { parse } from 'pg-query-parser';\n// or const parse = require('pg-query-parser').parse;","symbol":"parser.parse","correct":"const parser = require('pg-query-parser');\nconst ast = parser.parse('SELECT 1');"},{"note":"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.","wrong":"import { deparse } from 'pg-query-parser';\n// or const deparse = require('pg-query-parser').deparse;","symbol":"parser.deparse","correct":"const parser = require('pg-query-parser');\nconst sql = parser.deparse(ast);"}],"quickstart":{"code":"const parser = require('pg-query-parser');\n\n// Example SQL query to parse\nconst originalSql = 'SELECT * FROM test_table WHERE id = 1';\n\n// Parse the SQL query into an Abstract Syntax Tree (AST)\nconst parsedQuery = parser.parse(originalSql);\n\n// Check for parsing errors\nif (parsedQuery.error) {\n  console.error('Parsing error:', parsedQuery.error.message);\n  process.exit(1);\n}\n\n// Access the query array from the parsed object\nconst queryAst = parsedQuery.query;\n\n// Modify a part of the AST: change the table name\n// This assumes a simple SELECT statement structure\nif (queryAst && queryAst[0] && queryAst[0].SelectStmt && queryAst[0].SelectStmt.fromClause && queryAst[0].SelectStmt.fromClause[0].RangeVar) {\n  queryAst[0].SelectStmt.fromClause[0].RangeVar.relname = 'another_table';\n} else {\n  console.warn('Could not locate table name in AST for modification.');\n}\n\n// Deparse the modified AST back into a SQL statement\nconst rewrittenSql = parser.deparse(queryAst);\n\nconsole.log('Original SQL:', originalSql);\nconsole.log('Rewritten SQL:', rewrittenSql);\n// Expected output: SELECT * FROM \"another_table\" WHERE id = 1","lang":"javascript","description":"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."},"warnings":[{"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.","message":"The 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.","severity":"breaking","affected_versions":">=0.2.0"},{"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.","message":"This 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.","severity":"gotcha","affected_versions":"*"},{"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.","message":"Directly 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.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"search_vec":"'0.3.0':54 'abil':60 'abstract':38 'appear':116 'ast':41,64,87 'avail':72 'back':43,65,92 'build':101 'builder':103 'cadenc':115 'capabl':18 'chang':91 'convert':33 'current':50 'databas':136 'depars':17,62 'develop':77 'differenti':57 'enabl':76 'format':46 'function':69 'indic':127 'infrequ':117 'inspect':108 'javascript':130 'key':56 'leverag':24 'libpg':30 'mainten':129 'make':97 'modifi':80 'modul':11 'nativ':71 'node.js':10 'ongo':128 'optim':104 'paramref':123 'pars':15 'parser':3,7,28 'part':81 'pg':5,134 'pg-query-pars':4 'postgr':132 'postgresql':1,20,27,74,133 'programmat':79,113 'provid':13 'queri':2,6,31,85,102,135 'real':26 'recent':120 'releas':114 'serial':89 'sql':21,34,47,67,84,95,111,131 'stabl':51 'statement':22,48,112 'string':35 'support':124 'symmetr':14 'syntax':39 'tool':106 'transform':110 'tree':40 'updat':121 'use':99 'v0.2.0':126 'valid':94 'version':52 'via':29","created_at":"2026-04-20T01:56:10.828381+00:00","updated_at":"2026-04-20T01:56:10.828381+00:00","problems":[{"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()`.","cause":"The package was not installed, or there's a CommonJS/ESM module resolution issue in an ESM-only environment.","error":"Error: Cannot find module 'pg-query-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.","cause":"The input SQL string provided to `parser.parse()` contains invalid PostgreSQL syntax. The error message originates from the underlying PostgreSQL parser.","error":"Error: syntax error at or near \"some_token\""},{"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.","cause":"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.","error":"TypeError: Cannot set properties of undefined (setting 'relname')"},{"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.","cause":"During `npm install`, the compilation of the native `libpg_query` dependency failed due to missing C/C++ build tools on the system.","error":"node-gyp rebuild failed"}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/zhm/pg-query-parser","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/pg-query-parser","openapi_spec":null,"status_page":null,"smithery":null,"categories":["database","serialization"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}