|
| 1 | +# plpgsql-parser |
| 2 | + |
| 3 | +Combined SQL + PL/pgSQL parser with hydrated ASTs and transform API. |
| 4 | + |
| 5 | +## Installation |
| 6 | + |
| 7 | +```bash |
| 8 | +npm install plpgsql-parser |
| 9 | +``` |
| 10 | + |
| 11 | +## Usage |
| 12 | + |
| 13 | +```typescript |
| 14 | +import { parse, transform, deparseSync, loadModule } from 'plpgsql-parser'; |
| 15 | + |
| 16 | +// Initialize the WASM module |
| 17 | +await loadModule(); |
| 18 | + |
| 19 | +// Parse SQL with PL/pgSQL functions - auto-detects and hydrates |
| 20 | +const result = parse(` |
| 21 | + CREATE FUNCTION my_func(p_id int) |
| 22 | + RETURNS void |
| 23 | + LANGUAGE plpgsql |
| 24 | + AS $$ |
| 25 | + BEGIN |
| 26 | + RAISE NOTICE 'Hello %', p_id; |
| 27 | + END; |
| 28 | + $$; |
| 29 | +`); |
| 30 | + |
| 31 | +console.log(result.functions.length); // 1 |
| 32 | +console.log(result.functions[0].plpgsql.hydrated); // Hydrated AST |
| 33 | + |
| 34 | +// Transform API for parse -> modify -> deparse pipeline |
| 35 | +const output = transformSync(sql, (ctx) => { |
| 36 | + // Modify the function name |
| 37 | + ctx.functions[0].stmt.funcname[0].String.sval = 'renamed_func'; |
| 38 | +}); |
| 39 | + |
| 40 | +// Deparse back to SQL |
| 41 | +const sql = deparseSync(result, { pretty: true }); |
| 42 | +``` |
| 43 | + |
| 44 | +## API |
| 45 | + |
| 46 | +### `parse(sql, options?)` |
| 47 | + |
| 48 | +Parses SQL and auto-detects PL/pgSQL functions, hydrating their bodies. |
| 49 | + |
| 50 | +Options: |
| 51 | +- `hydrate` (default: `true`) - Whether to hydrate PL/pgSQL function bodies |
| 52 | + |
| 53 | +Returns a `ParsedScript` with: |
| 54 | +- `sql` - The raw SQL parse result |
| 55 | +- `items` - Array of parsed items (statements and functions) |
| 56 | +- `functions` - Array of detected PL/pgSQL functions with hydrated ASTs |
| 57 | + |
| 58 | +### `transform(sql, callback, options?)` |
| 59 | + |
| 60 | +Async transform pipeline: parse -> modify -> deparse. |
| 61 | + |
| 62 | +### `transformSync(sql, callback, options?)` |
| 63 | + |
| 64 | +Sync version of transform. |
| 65 | + |
| 66 | +### `deparseSync(parsed, options?)` |
| 67 | + |
| 68 | +Converts a parsed script back to SQL. |
| 69 | + |
| 70 | +Options: |
| 71 | +- `pretty` (default: `true`) - Whether to pretty-print the output |
| 72 | + |
| 73 | +## Re-exports |
| 74 | + |
| 75 | +For power users, the package re-exports underlying primitives: |
| 76 | + |
| 77 | +- `parseSql` - SQL parser from `@libpg-query/parser` |
| 78 | +- `parsePlpgsqlBody` - PL/pgSQL parser from `@libpg-query/parser` |
| 79 | +- `deparseSql` - SQL deparser from `pgsql-deparser` |
| 80 | +- `deparsePlpgsqlBody` - PL/pgSQL deparser from `plpgsql-deparser` |
| 81 | +- `hydratePlpgsqlAst` - Hydration utility from `plpgsql-deparser` |
| 82 | +- `dehydratePlpgsqlAst` - Dehydration utility from `plpgsql-deparser` |
0 commit comments