plpgsql-parse 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Dan Lynch <pyramation@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,84 @@
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
60
+
61
+ ---
62
+
63
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
64
+
65
+ ## Related
66
+
67
+ * [pgpm](https://pgpm.dev): A Postgres Package Manager that brings modular development to PostgreSQL with reusable packages, deterministic migrations, recursive dependency resolution, and tag-aware versioning.
68
+ * [pgsql-test](https://www.npmjs.com/package/pgsql-test): Instant, isolated PostgreSQL databases for each test with automatic transaction rollbacks, context switching, and clean seeding for fast, reliable database testing.
69
+ * [pgsql-seed](https://www.npmjs.com/package/pgsql-seed): PostgreSQL seeding utilities for CSV, JSON, SQL data loading, and pgpm deployment.
70
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): The real PostgreSQL parser for Node.js, providing symmetric parsing and deparsing of SQL statements with actual PostgreSQL parser integration.
71
+ * [pgsql-deparser](https://www.npmjs.com/package/pgsql-deparser): A streamlined tool designed for converting PostgreSQL ASTs back into SQL queries, focusing solely on deparser functionality to complement `pgsql-parser`.
72
+ * [@pgsql/parser](https://www.npmjs.com/package/@pgsql/parser): Multi-version PostgreSQL parser with dynamic version selection at runtime, supporting PostgreSQL 15, 16, and 17 in a single package.
73
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): Offers TypeScript type definitions for PostgreSQL AST nodes, facilitating type-safe construction, analysis, and manipulation of ASTs.
74
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): Provides TypeScript enum definitions for PostgreSQL constants, enabling type-safe usage of PostgreSQL enums and constants in your applications.
75
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): A comprehensive utility library for PostgreSQL, offering type-safe AST node creation and enum value conversions, simplifying the construction and manipulation of PostgreSQL ASTs.
76
+ * [@pgsql/traverse](https://www.npmjs.com/package/@pgsql/traverse): PostgreSQL AST traversal utilities for pgsql-parser, providing a visitor pattern for traversing PostgreSQL Abstract Syntax Tree nodes, similar to Babel's traverse functionality but specifically designed for PostgreSQL AST structures.
77
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): A TypeScript tool that parses PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
78
+ * [libpg-query](https://github.com/constructive-io/libpg-query-node): The real PostgreSQL parser exposed for Node.js, used primarily in `pgsql-parser` for parsing and deparsing SQL queries.
79
+
80
+ ## Disclaimer
81
+
82
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
83
+
84
+ No developer or entity involved in creating Software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the Software code or Software CLI, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Scanner for extracting comments from PL/pgSQL function bodies.
3
+ *
4
+ * Uses simple line-based scanning since the body text has already been
5
+ * extracted from the dollar-quoted string — no need to worry about
6
+ * string literal boundaries at this level.
7
+ */
8
+ import type { BodyComment } from './types';
9
+ /**
10
+ * Scan a PL/pgSQL function body for -- line comments.
11
+ *
12
+ * Returns an array of BodyComment objects ordered by line number.
13
+ * Only detects standalone comment lines (lines where the first
14
+ * non-whitespace content is --). Inline trailing comments on code
15
+ * lines are not extracted since the PL/pgSQL deparser cannot
16
+ * reconstruct them at the right position.
17
+ */
18
+ export declare function scanBodyComments(body: string): BodyComment[];
19
+ /**
20
+ * A comment group: one or more consecutive comment lines
21
+ * associated with the code that follows them.
22
+ */
23
+ export interface CommentGroup {
24
+ /** The comment lines (trimmed, with -- prefix) */
25
+ comments: string[];
26
+ /**
27
+ * The lineno of the PL/pgSQL statement this group precedes.
28
+ * null if the comments are at the end of the body (after all statements).
29
+ */
30
+ anchorLineno: number | null;
31
+ }
32
+ /**
33
+ * Associate body comments with PL/pgSQL statement line numbers.
34
+ *
35
+ * For each comment, finds the first statement whose lineno is greater
36
+ * than the comment's line number. Groups consecutive comments together.
37
+ *
38
+ * @param comments - Comments extracted by scanBodyComments
39
+ * @param stmtLinenos - Sorted array of statement lineno values from the PL/pgSQL AST
40
+ */
41
+ export declare function groupCommentsByAnchor(comments: BodyComment[], stmtLinenos: number[]): CommentGroup[];
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ /**
3
+ * Scanner for extracting comments from PL/pgSQL function bodies.
4
+ *
5
+ * Uses simple line-based scanning since the body text has already been
6
+ * extracted from the dollar-quoted string — no need to worry about
7
+ * string literal boundaries at this level.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.scanBodyComments = scanBodyComments;
11
+ exports.groupCommentsByAnchor = groupCommentsByAnchor;
12
+ /**
13
+ * Scan a PL/pgSQL function body for -- line comments.
14
+ *
15
+ * Returns an array of BodyComment objects ordered by line number.
16
+ * Only detects standalone comment lines (lines where the first
17
+ * non-whitespace content is --). Inline trailing comments on code
18
+ * lines are not extracted since the PL/pgSQL deparser cannot
19
+ * reconstruct them at the right position.
20
+ */
21
+ function scanBodyComments(body) {
22
+ const lines = body.split('\n');
23
+ const comments = [];
24
+ for (let i = 0; i < lines.length; i++) {
25
+ const trimmed = lines[i].trim();
26
+ if (trimmed.startsWith('--')) {
27
+ comments.push({
28
+ text: trimmed,
29
+ lineNo: i + 1, // 1-based
30
+ standalone: true,
31
+ });
32
+ }
33
+ }
34
+ return comments;
35
+ }
36
+ /**
37
+ * Associate body comments with PL/pgSQL statement line numbers.
38
+ *
39
+ * For each comment, finds the first statement whose lineno is greater
40
+ * than the comment's line number. Groups consecutive comments together.
41
+ *
42
+ * @param comments - Comments extracted by scanBodyComments
43
+ * @param stmtLinenos - Sorted array of statement lineno values from the PL/pgSQL AST
44
+ */
45
+ function groupCommentsByAnchor(comments, stmtLinenos) {
46
+ if (comments.length === 0)
47
+ return [];
48
+ const groups = [];
49
+ let currentGroup = [];
50
+ let lastLineNo = -1;
51
+ for (const comment of comments) {
52
+ // Start a new group if there's a gap (non-consecutive lines)
53
+ if (lastLineNo >= 0 && comment.lineNo > lastLineNo + 1) {
54
+ if (currentGroup.length > 0) {
55
+ const anchor = findAnchorLineno(lastLineNo, stmtLinenos);
56
+ groups.push({ comments: [...currentGroup], anchorLineno: anchor });
57
+ currentGroup = [];
58
+ }
59
+ }
60
+ currentGroup.push(comment.text);
61
+ lastLineNo = comment.lineNo;
62
+ }
63
+ // Flush remaining group
64
+ if (currentGroup.length > 0) {
65
+ const anchor = findAnchorLineno(lastLineNo, stmtLinenos);
66
+ groups.push({ comments: [...currentGroup], anchorLineno: anchor });
67
+ }
68
+ return groups;
69
+ }
70
+ /**
71
+ * Find the first statement lineno that comes after the given line number.
72
+ */
73
+ function findAnchorLineno(afterLine, stmtLinenos) {
74
+ for (const lineno of stmtLinenos) {
75
+ if (lineno > afterLine) {
76
+ return lineno;
77
+ }
78
+ }
79
+ return null;
80
+ }
package/deparse.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Enhanced deparse that re-injects body comments into PL/pgSQL function
3
+ * bodies after the standard plpgsql-deparser has produced its output.
4
+ *
5
+ * Also handles outer SQL comments/whitespace via pgsql-parse's deparser.
6
+ *
7
+ * This module does NOT modify plpgsql-deparser or pgsql-deparser.
8
+ */
9
+ import type { PlpgsqlParseResult } from './types';
10
+ export interface DeparseOptions {
11
+ pretty?: boolean;
12
+ newline?: string;
13
+ }
14
+ /**
15
+ * Deparse a PlpgsqlParseResult back to SQL, preserving both outer
16
+ * comments/whitespace AND comments inside PL/pgSQL function bodies.
17
+ */
18
+ export declare function deparseSync(result: PlpgsqlParseResult, options?: DeparseOptions): string;
19
+ /**
20
+ * Async version of deparseSync.
21
+ */
22
+ export declare function deparse(result: PlpgsqlParseResult, options?: DeparseOptions): Promise<string>;