|
| 1 | +--- |
| 2 | +name: ast-traversal |
| 3 | +description: How to walk PostgreSQL SQL and PL/pgSQL ASTs in this monorepo — choosing between walk, walkSql, walkSqlAst, walkPlpgsqlAst, and traverse; statement context, visitor composition, abort, and mutation. Use when reading, validating, or rewriting SQL/PL/pgSQL ASTs. |
| 4 | +--- |
| 5 | + |
| 6 | +# AST Traversal |
| 7 | + |
| 8 | +Everything in this repo that inspects or rewrites SQL goes through one of five |
| 9 | +functions. Pick the right one first; the rest of the work follows from it. |
| 10 | + |
| 11 | +## Choosing a function |
| 12 | + |
| 13 | +| Function | Package | Walks | Mutates | |
| 14 | +|---|---|---|---| |
| 15 | +| `walk(ast, visitors, opts?)` | `@pgsql/traverse` | any AST — parsed script, `ParseResult`, SQL node, PL/pgSQL node | no | |
| 16 | +| `walkSql(text, visitors, opts?)` | `plpgsql-parser` | SQL **text**: parses, hydrates PL/pgSQL bodies, then `walk`s | no | |
| 17 | +| `walkSqlAst(ast, visitor)` | `@pgsql/traverse` | SQL AST only | no | |
| 18 | +| `walkPlpgsqlAst(ast, visitor, opts?)` | `@pgsql/traverse` | PL/pgSQL AST only | no | |
| 19 | +| `traverse(ast, mutableVisitor)` | `@pgsql/traverse` | SQL AST, with insert/remove/replace | yes | |
| 20 | + |
| 21 | +Decision rules: |
| 22 | + |
| 23 | +- **Have a string?** `walkSql`. It is the only entry point that parses. |
| 24 | +- **Have an AST and don't care which universe it is from?** `walk`. |
| 25 | +- **Want exactly one node universe and no statement context?** `walkSqlAst` or |
| 26 | + `walkPlpgsqlAst`. These are the primitives `walk` is built on; reach for them |
| 27 | + when writing a reusable visitor that some other walker will drive (this is why |
| 28 | + `@pgsql/transform` exports visitor *factories* rather than walkers). |
| 29 | +- **Need to change the tree structurally?** `traverse`. Note that read-only |
| 30 | + walkers hand you the real node objects, so field-level edits (renaming a |
| 31 | + schema, rewriting a name list) work under `walk` too — `traverse` is for |
| 32 | + inserting, removing, and replacing nodes. |
| 33 | + |
| 34 | +Never hand-roll `transformSync(sql, ..., { hydrate: true })` plus a |
| 35 | +per-statement loop plus a PL/pgSQL walk. That harness *is* `walk`. |
| 36 | + |
| 37 | +## Visitors |
| 38 | + |
| 39 | +A visitor is either a callback (fires on every node) or an object keyed by node |
| 40 | +tag. SQL tags and `PLpgSQL_*` tags may be mixed in one object — `walk` routes |
| 41 | +each node to the right walker. |
| 42 | + |
| 43 | +```ts |
| 44 | +import { walk } from '@pgsql/traverse'; |
| 45 | + |
| 46 | +walk(ast, { |
| 47 | + RangeVar: (path) => console.log(path.node.relname), |
| 48 | + PLpgSQL_stmt_dynexecute: (path) => console.log('dynamic EXECUTE', path.node) |
| 49 | +}); |
| 50 | +``` |
| 51 | + |
| 52 | +Pass an **array** of visitors to run independent concerns in a single parse: |
| 53 | + |
| 54 | +```ts |
| 55 | +walkSql(sql, [blockedSchemas, readOnlySchemas, blockedFunctions]); |
| 56 | +``` |
| 57 | + |
| 58 | +Each callback receives `(path, ctx)`: |
| 59 | + |
| 60 | +- `path` — a `NodePath` (SQL) or `PlpgsqlNodePath` (PL/pgSQL): `tag`, `node`, |
| 61 | + `parent`, `keyPath`. This is *structure*: where the node sits. |
| 62 | +- `ctx` — a `WalkContext`: `stmtTag`, `stmtIndex`, `isWrite`, `isRead`, |
| 63 | + `insideFunction`, `functionName`, `abort()`. This is *situation*: what the |
| 64 | + node is part of. |
| 65 | + |
| 66 | +The reserved `statement` key fires once per top-level statement, before its |
| 67 | +children — the hook for per-statement setup or classification. |
| 68 | + |
| 69 | +## Control flow |
| 70 | + |
| 71 | +Two distinct mechanisms, do not confuse them: |
| 72 | + |
| 73 | +- `return false` — skip this node's children, keep walking siblings. |
| 74 | +- `ctx.abort(reason?)` — end the whole walk. `walk`/`walkSql` return |
| 75 | + `{ aborted, reason, reasons }`. This is what a validator wants: the first |
| 76 | + rejection ends the work. |
| 77 | + |
| 78 | +```ts |
| 79 | +const result = walkSql(sql, { |
| 80 | + RangeVar: (path, ctx) => { |
| 81 | + if (ctx.isWrite && path.node.schemaname === 'audit') { |
| 82 | + ctx.abort(`cannot write to ${path.node.schemaname}`); |
| 83 | + } |
| 84 | + } |
| 85 | +}); |
| 86 | +if (result.aborted) reject(result.reason); |
| 87 | +``` |
| 88 | + |
| 89 | +Unparseable input from `walkSql` comes back as `{ aborted: true, reason }` |
| 90 | +rather than a thrown error, so "rejected" and "not understood" are one code path. |
| 91 | + |
| 92 | +## Worked examples |
| 93 | + |
| 94 | +### Collect every table a script touches, including inside function bodies |
| 95 | + |
| 96 | +```ts |
| 97 | +import { loadModule, walkSql } from 'plpgsql-parser'; |
| 98 | + |
| 99 | +await loadModule(); // once per process: libpg-query is WASM |
| 100 | + |
| 101 | +const tables = new Set<string>(); |
| 102 | +walkSql(sql, { |
| 103 | + RangeVar: (path, ctx) => { |
| 104 | + const name = path.node.schemaname |
| 105 | + ? `${path.node.schemaname}.${path.node.relname}` |
| 106 | + : path.node.relname; |
| 107 | + tables.add(ctx.insideFunction ? `${name} (via ${ctx.functionName})` : name); |
| 108 | + } |
| 109 | +}); |
| 110 | +``` |
| 111 | + |
| 112 | +### Classify statements without a second parse |
| 113 | + |
| 114 | +```ts |
| 115 | +walkSql(sql, { |
| 116 | + statement: (path, ctx) => { |
| 117 | + console.log(ctx.stmtIndex, path.tag, ctx.isWrite ? 'write' : 'read'); |
| 118 | + } |
| 119 | +}); |
| 120 | +``` |
| 121 | + |
| 122 | +### Rewrite schema names on a parsed script |
| 123 | + |
| 124 | +Field-level rewrites work through the read-only walker because `path.node` is the |
| 125 | +live node. This is exactly how `@pgsql/transform` renames schemas: |
| 126 | + |
| 127 | +```ts |
| 128 | +import { transformSync } from 'plpgsql-parser'; |
| 129 | +import { walk } from '@pgsql/traverse'; |
| 130 | + |
| 131 | +const out = transformSync(sql, (ctx) => { |
| 132 | + walk(ctx, { |
| 133 | + RangeVar: (path) => { |
| 134 | + const to = mapping.get(path.node.schemaname); |
| 135 | + if (to) path.node.schemaname = to; |
| 136 | + } |
| 137 | + }); |
| 138 | +}, { hydrate: true, pretty: true }); |
| 139 | +``` |
| 140 | + |
| 141 | +`transformSync` gives the callback a parsed script (`{ sql, functions }`), which |
| 142 | +`walk` dispatches over directly — statements first, then every hydrated body. |
| 143 | + |
| 144 | +### Restructure the tree |
| 145 | + |
| 146 | +```ts |
| 147 | +import { traverse } from '@pgsql/traverse'; |
| 148 | + |
| 149 | +traverse(ast, { |
| 150 | + RawStmt: { |
| 151 | + enter: (path) => { |
| 152 | + if (isRedundant(path.node)) path.remove(); |
| 153 | + } |
| 154 | + } |
| 155 | +}); |
| 156 | +``` |
| 157 | + |
| 158 | +### Drive a reusable visitor from a primitive |
| 159 | + |
| 160 | +When a caller already owns the traversal loop (per-statement state, custom |
| 161 | +ordering), build the visitor separately and hand it to the primitive: |
| 162 | + |
| 163 | +```ts |
| 164 | +import { walkSqlAst } from '@pgsql/traverse'; |
| 165 | + |
| 166 | +for (const stmt of parseResult.stmts) { |
| 167 | + walkSqlAst(stmt.stmt, createFactsVisitor(factsFor(stmt))); |
| 168 | +} |
| 169 | +``` |
| 170 | + |
| 171 | +## Options |
| 172 | + |
| 173 | +`walk` and `walkSql` share: |
| 174 | + |
| 175 | +- `walkFunctionBodies` (default `true`) — walk hydrated PL/pgSQL bodies. Under |
| 176 | + `walkSql`, `false` also skips the PL/pgSQL parse, so turn it off when the |
| 177 | + visitors only care about top-level SQL. |
| 178 | +- `walkSqlExpressions` (default `true`) — recurse into the SQL expressions inside |
| 179 | + those bodies. |
| 180 | +- `sqlVisitor` — override the visitor used for those SQL expressions. |
| 181 | + |
| 182 | +## Gotchas |
| 183 | + |
| 184 | +- **Call `loadModule()` before any parse.** `libpg-query` is WASM; `parseSync` / |
| 185 | + `walkSql` throw `WASM module not initialized` otherwise. |
| 186 | +- **PL/pgSQL bodies are opaque until hydrated.** Without `{ hydrate: true }` a |
| 187 | + function body is a query string, and no SQL visitor will ever fire inside it. |
| 188 | +- **Untagged typed fields exist.** `CreatePolicyStmt.table` is a bare `RangeVar` |
| 189 | + with no `{ RangeVar: ... }` wrapper. `walkSqlAst` handles this via the runtime |
| 190 | + schema, which is why hand-written recursion over `Object.keys` misses nodes. |
| 191 | +- **`@pgsql/traverse` must stay parser-free.** It depends on types only; adding a |
| 192 | + parser dependency would cycle and pull WASM into the leaf package. Anything |
| 193 | + that needs to parse belongs in `plpgsql-parser` or above. |
| 194 | +- **Fixtures are the regression gate for transform work.** After changing any |
| 195 | + traversal in `@pgsql/transform`, `pnpm --filter @pgsql/transform test` output |
| 196 | + must be byte-identical; see the `testing-fixtures` skill. |
0 commit comments