{"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.","language":"javascript","status":"active","last_verified":"Sun Apr 19","install":{"commands":["npm install pg-query-parser"],"cli":null},"imports":["const parser = require('pg-query-parser');","const parser = require('pg-query-parser');\nconst ast = parser.parse('SELECT 1');","const parser = require('pg-query-parser');\nconst sql = parser.deparse(ast);"],"auth":{"required":false,"env_vars":[]},"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.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}