{"id":13767,"library":"pgsql-parser","title":"PostgreSQL Query Parser","description":"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.","status":"active","version":"17.9.15","language":"javascript","source_language":"en","source_url":"https://github.com/constructive-io/pgsql-parser","tags":["javascript","sql","postgres","postgresql","pg","parser","query","database","typescript"],"install":[{"cmd":"npm install pgsql-parser","lang":"bash","label":"npm"},{"cmd":"yarn add pgsql-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add pgsql-parser","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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.","wrong":"const { parse } = require('pgsql-parser');","symbol":"parse","correct":"import { parse } from 'pgsql-parser';"},{"note":"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.","wrong":"const { deparse } = require('pgsql-parser');","symbol":"deparse","correct":"import { deparse } from 'pgsql-parser';"},{"note":"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`.","symbol":"ParseResult","correct":"import type { ParseResult } from 'pgsql-parser';"},{"note":"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).","wrong":"import Parser from '@pgsql/parser'; // Default import is often incorrect\nimport { Parser } from 'pgsql-parser'; // Incorrect package for multi-version parser","symbol":"Parser (multi-version)","correct":"import { Parser } from '@pgsql/parser';\nconst parser = new Parser({ version: 17 });"}],"quickstart":{"code":"import { parse, deparse } from 'pgsql-parser';\nimport type { SelectStmt } from '@pgsql/types';\n\nasync function main() {\n  const sqlQuery = \"SELECT id, name FROM users WHERE status = 'active' ORDER BY name ASC;\";\n\n  try {\n    // Parse the SQL query into an Abstract Syntax Tree (AST)\n    const ast = await parse(sqlQuery);\n    console.log('Original AST:', JSON.stringify(ast, null, 2));\n\n    // Example: Modify the AST (e.g., change the table name)\n    // The AST structure can be complex and depends on the PostgreSQL version.\n    // Assuming a simple SelectStmt structure for demonstration.\n    if (ast && ast.stmts && ast.stmts.length > 0) {\n      const selectStmt = ast.stmts[0]?.stmt?.SelectStmt as SelectStmt | undefined;\n      if (selectStmt && selectStmt.fromClause && selectStmt.fromClause.length > 0) {\n        const rangeVar = selectStmt.fromClause[0]?.RangeVar;\n        if (rangeVar) {\n          rangeVar.relname = 'customers'; // Change 'users' to 'customers'\n          console.log('\\nModified AST:', JSON.stringify(ast, null, 2));\n\n          // Deparse the modified AST back into a SQL string\n          const modifiedSql = await deparse(ast);\n          console.log('\\nModified SQL:', modifiedSql);\n        }\n      }\n    }\n\n  } catch (error) {\n    if (error instanceof Error) {\n      console.error('Parsing failed:', error.message);\n    } else {\n      console.error('An unknown error occurred:', error);\n    }\n  }\n}\n\nmain();","lang":"typescript","description":"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`."},"warnings":[{"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.","message":"The 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.","severity":"breaking","affected_versions":"All versions (on major PostgreSQL version bumps)"},{"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.","message":"Performance-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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"The `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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"search_vec":"'100':41 '17.9.15':54 'abstract':19 'actual':32 'analysi':125 'ast':22,25,77,89,97,144 'ast-to-sql':76 'back':26,105 'broader':61 'c':34 'cadenc':148 'code':128 'compat':42 'compil':36 'comprehens':85 'convers':80 'convert':104 'current':48 'databas':167 'deep':123 'definit':87 'depars':24 'design':11 'ecosystem':155 'ensur':40 'extens':112 'follow':149 'foundat':137 'frequent':158 'generat':98,129 'ideal':119 'includ':64 'javascript':160 'javascript/typescript':9 'level':145 'leverag':30 'librari':10,117 'like':67 'mean':95 'modif':126 'monorepo':62 'multi':71 'multi-vers':70 'node':90 'offer':92 'oper':94 'origin':108 'packag':66,156 'pars':13,73 'parser':3,6,35,165 'part':58 'perfect':103 'pg':164 'pgsql':5 'pgsql-parser':4 'pgsql/deparser':74 'pgsql/parser':68 'pgsql/types':83 'postgr':162 'postgresql':1,14,33,44,141,151,163 'project':56 'provid':130 'queri':2,16,166 'relat':65,154 'releas':147 'reliabl':115 'requir':122 'robust':132 'safe':136 'specifi':52 'sql':15,28,79,100,109,124,161 'stabl':49 'symmetr':93 'syntax':20,46 'test':113 'tool':121 'tree':21 'type':135 'type-saf':134 'typescript':86,168 'updat':159 'version':50,72,152 'webassembl':38 'work':139","created_at":"2026-04-20T01:56:12.322912+00:00","updated_at":"2026-04-20T01:56:12.322912+00:00","problems":[{"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.","cause":"Attempting to use ES module `import` syntax in a CommonJS (`.js` without `\"type\": \"module\"` or `.cjs`) Node.js environment.","error":"SyntaxError: Cannot use import statement outside a module"},{"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.","cause":"The SQL query provided to the `parse` function contains invalid PostgreSQL syntax. This error originates from the underlying PostgreSQL C parser.","error":"Error: syntax error at or near \"<token>\""},{"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.","cause":"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.","error":"TypeError: Cannot read properties of undefined (reading 'SelectStmt')"}],"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":"https://pgsql.js.org","github":"https://github.com/constructive-io/pgsql-parser","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/pgsql-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}}