{"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.","language":"javascript","status":"active","last_verified":"Tue Apr 21","install":{"commands":["npm install pgsql-ast-parser"],"cli":null},"imports":["import { parse, Statement } from 'pgsql-ast-parser';","import { parseFirst } from 'pgsql-ast-parser';","import { astVisitor, toSql, astMapper } from 'pgsql-ast-parser';"],"auth":{"required":false,"env_vars":[]},"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.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}