Comment and whitespace preserving PostgreSQL parser. A drop-in enhancement for pgsql-parser that preserves SQL comments (-- line and /* */ block) and vertical whitespace (blank lines) through parse-deparse round trips.
npm install pgsql-parse- Comment Preservation -- Retains
--line comments and/* */block comments through parse-deparse cycles - Vertical Whitespace -- Preserves blank lines between statements for readable output
- Idempotent Round-Trips --
parse -> deparse -> parse -> deparseproduces identical output - Drop-in API -- Re-exports
parse,parseSync,deparse,deparseSync,loadModulefrompgsql-parser - Synthetic AST Nodes --
RawCommentandRawWhitespacenodes interleaved into thestmtsarray by byte position
- A pure TypeScript scanner extracts comment and whitespace tokens with byte positions from the raw SQL text
- Enhanced
parse/parseSynccall the standardlibpg-queryparser, then interleave syntheticRawCommentandRawWhitespacenodes into thestmtsarray based on byte position deparseEnhanced()dispatches on node type -- realRawStmtentries go through the standard deparser, while synthetic nodes emit their comment text or blank lines directly
import { parse, parseSync, deparseEnhanced, loadModule } from 'pgsql-parse';
// Async (handles initialization automatically)
const result = await parse(`
-- Create users table
CREATE TABLE users (id serial PRIMARY KEY);
-- Create posts table
CREATE TABLE posts (id serial PRIMARY KEY);
`);
// result.stmts contains RawComment, RawWhitespace, and RawStmt nodes
const sql = deparseEnhanced(result);
// Output preserves comments and blank linesimport { parseSync, deparseEnhanced, loadModule } from 'pgsql-parse';
await loadModule();
const result = parseSync('-- comment\nSELECT 1;');
const sql = deparseEnhanced(result);import { isRawComment, isRawWhitespace, isRawStmt } from 'pgsql-parse';
for (const stmt of result.stmts) {
if (isRawComment(stmt)) {
console.log('Comment:', stmt.RawComment.text);
} else if (isRawWhitespace(stmt)) {
console.log('Blank lines:', stmt.RawWhitespace.lines);
} else if (isRawStmt(stmt)) {
console.log('Statement:', stmt);
}
}Built on the excellent work of several contributors:
- Dan Lynch -- official maintainer since 2018 and architect of the current implementation
- Lukas Fittl for libpg_query -- the core PostgreSQL parser that powers this project