{"id":15758,"library":"pgsql-ast-parser","title":"Postgres SQL AST Parser","description":"pgsql-ast-parser is a JavaScript and TypeScript library designed for parsing PostgreSQL SQL syntax into a typed Abstract Syntax Tree (AST), and then facilitating its modification or conversion back to SQL. It is currently at version 12.0.2 and appears to have an active release cadence, with major versions indicating significant structural changes to the AST. Key differentiators include its ability to run in both Node.js and browser environments, its robust TypeScript typing which is strongly recommended for usage, and its foundational role as the underlying parser for `pg-mem`, an in-memory PostgreSQL database emulator. While it covers most common PostgreSQL syntaxes, it explicitly states it does not support PL/pgSQL or some obscure syntaxes, requiring users to test specific complex queries.","status":"active","version":"12.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/oguimbal/pgsql-ast-parser","tags":["javascript","postgres","db","database","pg","sql","pgsql","postgresql","node","typescript"],"install":[{"cmd":"npm install pgsql-ast-parser","lang":"bash","label":"npm"},{"cmd":"yarn add pgsql-ast-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add pgsql-ast-parser","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"These are the primary function for parsing multiple SQL statements and the core type for AST nodes. The library ships with TypeScript types.","wrong":"const { parse, Statement } = require('pgsql-ast-parser');","symbol":"parse, Statement","correct":"import { parse, Statement } from 'pgsql-ast-parser';"},{"note":"Use this named import for parsing a single SQL statement; it returns a single Statement object instead of an array.","wrong":"import parseFirst from 'pgsql-ast-parser';","symbol":"parseFirst","correct":"import { parseFirst } from 'pgsql-ast-parser';"},{"note":"These are utility functions for traversing (astVisitor), converting back to SQL (toSql), and modifying (astMapper) the parsed AST. All are named exports.","wrong":"const astVisitor = require('pgsql-ast-parser').astVisitor;","symbol":"astVisitor, toSql, astMapper","correct":"import { astVisitor, toSql, astMapper } from 'pgsql-ast-parser';"}],"quickstart":{"code":"import { astVisitor, parseFirst } from 'pgsql-ast-parser';\n\nconst tables = new Set<string>();\nlet joins = 0;\n\n// Create an AST visitor to collect information\nconst visitor = astVisitor(map => ({\n    // Hook into table reference nodes to get table names\n    tableRef: t => tables.add(t.name),\n    // Hook into join nodes to count joins\n    join: t => {\n        joins++;\n        // Call the default implementation to ensure subtrees are also traversed\n        map.super().join(t);\n    }\n}));\n\n// Parse a single SQL statement into an AST\nconst sqlStatement = `SELECT o.order_id, c.customer_name FROM orders AS o LEFT JOIN customers AS c ON o.customer_id = c.customer_id WHERE o.order_date > '2023-01-01';`;\nconst ast = parseFirst(sqlStatement);\n\n// Start traversing the AST with our visitor\nvisitor.statement(ast);\n\n// Print the collected results\nconsole.log(`SQL: ${sqlStatement}`);\nconsole.log(`Used tables: ${[...tables].join(', ')}`);\nconsole.log(`Number of joins: ${joins}`);","lang":"typescript","description":"This example demonstrates how to parse a SQL statement and then use an `astVisitor` to traverse the Abstract Syntax Tree, collecting all referenced table names and counting the number of joins."},"warnings":[{"fix":"Update code that accesses `ALTER TABLE` AST nodes to use the `changes` array property instead of `change`.","message":"In version 9.0.0, the AST interface for `ALTER TABLE` statements changed. The `change` property was renamed to `changes` and is now an array of `TableAlteration[]`.","severity":"breaking","affected_versions":">=9.0.0"},{"fix":"Refactor code that inspects `INSERT` statement ASTs to account for the new unified `insert` property, rather than separate `values` or `select` properties.","message":"Version 8.0.0 introduced a significant breaking change in how `INSERT` statements are parsed. The `InsertStatement` now has a single `insert` property, unifying the parsing logic for `INSERT ... VALUES` and `INSERT ... SELECT`.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"Avoid parsing PL/pgSQL blocks directly. For complex or unusual SQL, test parsing capabilities thoroughly and consider simplifying the input SQL or contributing support for missing syntax.","message":"The parser does not (yet) support PL/pgSQL or some advanced/funky PostgreSQL syntaxes. Attempting to parse such SQL might result in parsing errors.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Utilize TypeScript in your project to leverage the provided type definitions for the AST, which will greatly improve developer experience and reduce type-related bugs when working with the parsed SQL structures.","message":"While usable in JavaScript, the library strongly recommends using TypeScript due to the complexity and depth of the generated Abstract Syntax Tree (AST) types. Without TypeScript, navigating the AST can be prone to errors.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Review the SQL query for typos or unsupported features (like PL/pgSQL). Simplify the query or test specific parts to isolate the problematic syntax. If it's standard PostgreSQL syntax, consider opening a bug report.","cause":"The input SQL string contains syntax that the parser does not understand or is malformed.","error":"Syntax Error: Unexpected token at position X"},{"fix":"Consult the library's TypeScript definitions and AST documentation for the specific `pgsql-ast-parser` version you are using. Ensure your code aligns with the current AST structure, especially after major version upgrades.","cause":"This TypeScript error occurs when attempting to access a property on an AST node that is either not present on that specific node type or has changed in a breaking library version.","error":"Property 'X' does not exist on type 'Y'"},{"fix":"Change your import statements from `const pkg = require('pgsql-ast-parser');` to `import * as pkg from 'pgsql-ast-parser';` or `import { parse } from 'pgsql-ast-parser';`.","cause":"You are attempting to use CommonJS `require()` to import `pgsql-ast-parser` in an ES module (ESM) environment (e.g., in a file where `type: \"module\"` is set in `package.json` or a `.mjs` file).","error":"require is not defined"}],"ecosystem":"npm"}