|
| 1 | +# plpgsql-parse |
| 2 | + |
| 3 | +<p align="center" width="100%"> |
| 4 | + <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" /> |
| 5 | +</p> |
| 6 | + |
| 7 | +Comment preserving PL/pgSQL parser. A wrapper around `plpgsql-parser` and `plpgsql-deparser` that preserves `--` line comments inside PL/pgSQL function bodies through parse-deparse round trips. |
| 8 | + |
| 9 | +## Installation |
| 10 | + |
| 11 | +```sh |
| 12 | +npm install plpgsql-parse |
| 13 | +``` |
| 14 | + |
| 15 | +## Features |
| 16 | + |
| 17 | +* **Body Comment Preservation** -- Retains `--` line comments inside PL/pgSQL function bodies (`$$...$$`) through parse-deparse cycles |
| 18 | +* **Outer SQL Comment Preservation** -- Preserves comments and whitespace outside function definitions via `pgsql-parse` |
| 19 | +* **Idempotent Round-Trips** -- `parse -> deparse -> parse -> deparse` produces identical output |
| 20 | +* **Non-Invasive** -- Does not modify `plpgsql-parser`, `plpgsql-deparser`, or any other upstream packages |
| 21 | + |
| 22 | +## How It Works |
| 23 | + |
| 24 | +1. Uses `pgsql-parse` for outer SQL comment and whitespace preservation |
| 25 | +2. For each PL/pgSQL function, scans the `$$...$$` body to extract `--` comments with line numbers |
| 26 | +3. Associates each comment with the nearest following PL/pgSQL statement (anchor) |
| 27 | +4. On deparse, re-injects comments by matching statement keywords against the deparsed output |
| 28 | + |
| 29 | +## API |
| 30 | + |
| 31 | +### Parse |
| 32 | + |
| 33 | +```typescript |
| 34 | +import { parseSync, deparseSync, loadModule } from 'plpgsql-parse'; |
| 35 | + |
| 36 | +await loadModule(); |
| 37 | + |
| 38 | +const result = parseSync(` |
| 39 | +-- Create a counter function |
| 40 | +CREATE FUNCTION get_count() RETURNS int LANGUAGE plpgsql AS $$ |
| 41 | +BEGIN |
| 42 | + -- Count active users |
| 43 | + RETURN (SELECT count(*) FROM users WHERE active); |
| 44 | +END; |
| 45 | +$$; |
| 46 | +`); |
| 47 | + |
| 48 | +// result.enhanced contains outer SQL comments/whitespace |
| 49 | +// result.functions contains body comments for each PL/pgSQL function |
| 50 | +const sql = deparseSync(result); |
| 51 | +// Output preserves both outer and body comments |
| 52 | +``` |
| 53 | + |
| 54 | +## Credits |
| 55 | + |
| 56 | +Built on the excellent work of several contributors: |
| 57 | + |
| 58 | +* **[Dan Lynch](https://github.com/pyramation)** -- official maintainer since 2018 and architect of the current implementation |
| 59 | +* **[Lukas Fittl](https://github.com/lfittl)** for [libpg_query](https://github.com/pganalyze/libpg_query) -- the core PostgreSQL parser that powers this project |
0 commit comments