pgsql-ast-parser

a Postgres SQL syntax parser

README

🏃‍♀️pgsql-ast-parser is a Postgres SQL syntax parser. It produces a typed AST (Abstract Syntax Tree), covering the most common syntaxes of pgsql.


❤It works both in node or in browser.

⚠This parser does not support (yet) PL/pgSQL. It might not even cover some funky syntaxes.

❤Open an issue if you find an bug or unsupported syntax !  

🔗This parser has been created to implement pg-mem , an in-memory postgres db emulator. 👉play with it here

⭐this repo if you like this package, it helps to motivate me :)

📐Installation


With NodeJS


  1. ``` shell
  2. npm i pgsql-ast-parser
  3. ```

With Deno


Just reference it like that:

  1. ``` ts
  2. import { /* imports here */ } from 'https://deno.land/x/pgsql_ast_parser/mod.ts';
  3. ```

📖Parsing SQL


⚠I strongly recommend NOT using this parser without Typescript. It will work, but types are awesome.

Parse sql to an AST like this:

  1. ``` ts
  2. import { parse, Statement } from 'pgsql-ast-parser';

  3. // parse multiple statements
  4. const ast: Statement[] = parse(`BEGIN TRANSACTION;
  5.                                 insert into my_table values (1, 'two')`);

  6. // parse a single statement
  7. const ast: Statement = parseFirst(`SELECT * FROM "my_table";`);
  8. ```

🔍Inspecting SQL AST


Once you have parsed an AST, you might want to traverse it easily to know what's in it.

There is a helper for that: astVisitor .

Here is an example which lists all the tables used in a request, and which counts how many joins it contains:

  1. ``` ts
  2. import { astVisitor, parse } from 'pgsql-ast-parser';

  3. const tables = new Set();
  4. let joins = 0;
  5. const visitor = astVisitor(map => ({

  6.     // implement here AST parts you want to hook

  7.     tableRef: t => tables.add(t.name),
  8.     join: t => {
  9.         joins++;
  10.         // call the default implementation of 'join'
  11.         // this will ensure that the subtree is also traversed.
  12.         map.super().join(t);
  13.     }
  14. }))

  15. // start traversing a statement
  16. visitor.statement(parseFirst(`select * from ta left join tb on ta.id=tb.id`));

  17. // print result
  18. console.log(`Used tables ${[...tables].join(', ')} with ${joins} joins !`)
  19. ```

You'll find that AST visitors (that's the name of this pattern) are quite flexible and powerful once you get used to them !

👉Here is the implementation of toSql which uses an astVisitor to reconstitude SQL from an AST (see below).

🖨Converting an AST to SQL


That's super easy:

  1. ``` ts
  2. import { toSql } from 'pgsql-ast-parser';

  3. const sql: string = toSql.statement(myAst);
  4. ```

Like with astVisitor()or astModifier(), you can also convert subparts of AST to SQL (not necessarily a whole statement) by calling other methods of toSql.

📝Modifying SQL AST


There is a special kind of visitor, which I called astMapper , which allows you to traverse & modify ASTs on the fly.

For instance, you could rename a table in a request like this:

  1. ``` ts
  2. import { toSql, parseFirst, astMapper } from 'pgsql-ast-parser';

  3. // create a mapper
  4. const mapper = astMapper(map => ({
  5.     tableRef: t => {
  6.         if (t.name === 'foo') {
  7.             return {
  8.                  // Dont do that... see below
  9.                  // (I wrote this like that for the sake of explainability)
  10.                 ...t,
  11.                 name: 'bar',
  12.             }
  13.         }

  14.         // call the default implementation of 'tableRef'
  15.         // this will ensure that the subtree is also traversed.
  16.         return map.super().tableRef(t);
  17.     }
  18. }))

  19. // parse + map + reconvert to sql
  20. const modified = mapper.statement(parseFirst('select * from foo'));

  21. console.log(toSql.statement(modified!)); //  =>  SELECT * FROM "bar"
  22. ```

Good to know: If you use Typescript, return types will force  you to return something compatible with a valid AST.

However, if you wish to remove a node from a tree, you can return null. For instance, this sample removes all references to column 'foo':

  1. ``` ts
  2. // create a mapper
  3. const mapper = astMapper(map => ({
  4.     ref: c => c.name === 'foo' ? null : c,
  5. }))

  6. // process sql
  7. const result = mapper.statement(parseFirst('select foo, bar from test'));

  8. // Prints: SELECT "bar" FROM "test"
  9. console.log(toSql.statement(result!));
  10. ```

If no valid AST can be produced after having removed it, resultwill be null.

A note on astMapperperformance:


The AST default modifier tries to be as efficient as possible: It does not copy AST parts as long as they do not have changed.

If you wan to avoid unnecessary copies, try to return the original argument as much as possible when nothing has changed.

For instance, instead of writing this:

  1. ``` ts
  2.     member(val: a.ExprMember) {
  3.         const operand = someOperandTransformation(val.operand);
  4.         if (!operand) {
  5.             return null;
  6.         }
  7.         return {
  8.             ...val,
  9.             operand,
  10.         }
  11.     }
  12. ```

Prefer an implement that checks that nothing has changed, for instance by using the assignChanged()helper.

  1. ``` ts
  2.     member(val: a.ExprMember) {
  3.         const operand = someOperandTransformation(val.operand);
  4.         if (!operand) {
  5.             return null;
  6.         }
  7.         return assignChanged(val, {
  8.             operand,
  9.         });
  10.     }
  11. ```

It's pretty easy to implement. To deal with this kind optimization with arrays, there is a arrayNilMap()helper exposed:

  1. ``` ts
  2. const newArray = arrayNilMap(array, elem => transform(elem));
  3. if (newArray === array) {
  4.     // transform() has not changed any element in the array !
  5. }
  6. ```

Parsing literal values


Postgres implements several literal syntaxes (string-to-something converters), whiches parsers are exposed as helper functions by this pgsql-ast-parser:

parseArrayLiteral()parses arrays literals syntaxes (for instance {a,b,c})
* `parseGeometricLiteral()`parses `geometric types` (for instance, things like `(1,2)`or `<(1,2),3>`)
parseIntervalLiteral()parses interval inputs literals (such as P1Y2DT1Hor 1 yr 2 days 1 hr)

FAQ


How to parse named parameters like :name?* 👉See here (TLDR )
Can I get detailed a location for each AST node ?👉Yes. Pass the option {locationTracking: true}to parse(), and use the locationOf(node)function.
Can I get the comments that the parser has ignored ?👉Yes. Use parseWithComments()instead of parse()

Development


Pull requests are welcome :)

To start hacking this lib, you'll have to:

Use vscode
Install mocha test explorer with HMR support extension
npm start
Reload unit tests in vscode

... once done, tests should appear. HMR is on, which means that changes in your code are instantly propagated to unit tests. This allows for ultra fast development cycles (running tests takes less than 1 sec).

To debug tests: Just hit "run" (F5, or whatever)... vscode should attach the mocha worker. Then run the test you want to debug.