benjie / prettier-plugin-pg

[WIP] Plugin for prettier to support formatting of PostgreSQL-flavour SQL, including function bodies in SQL, pgSQL, PLV8, plpython, etc.
MIT License
277 stars 5 forks source link

Finish converting `print.js` to use the prettier helpers #1

Open benjie opened 6 years ago

benjie commented 6 years ago

print.js was originally based on this file to give us a head start:

https://github.com/pyramation/pg-query-parser/blob/8a83b18bfd3ff85d40f10ea1d679e4605a8b1022/src/deparser.js

It's been reformatted to not be class-based, but the code still needs quite a bit of re-writing. When you're confused what the code is doing it's probably because it's broken - look at the relevant part of the old code to see what the intent was.

Everywhere that's currently using deparse needs to go - we've changed the signature of the visitors so they need to be used with print now instead.

Old code was like this:

['A_Indices'](node) {
  // ...
}

New code generally follows this pattern:

['A_Indices'](path, options, print) {
  const node = path.getValue(); // < This is the same node as in the old code
  // ...
}

Here's come common patterns in the ... section above:

Old code:

    if (node.lidx) {
      return format('[%s:%s]', this.deparse(node.lidx), this.deparse(node.uidx));
    }

    return format('[%s]', this.deparse(node.uidx));

New code:

    if (node.lidx) {
      return concat(['[', path.call(print, 'lidx'), ':', path.call(print, 'uidx'), ']']);
    }

    return concat(['[', path.call(print, 'uidx'), ']']);

Old code:

    const fields = node.fields.map(field => {
      return this.deparse(field);
    });

    return fields.join('.');

New code:

    return join('.', path.map(print, 'fields'));

Note the helpers:


Since prettier is happy dealing with strings it's wise to start at the bottom (i.e. the "statement" AST nodes) and then work your way up through the tree until all branches and leaves are prettier Doc elements.

Handy reference: