pganalyze / pg_query_go

Go library to parse and normalize SQL queries using the PostgreSQL query parser
BSD 3-Clause "New" or "Revised" License
663 stars 79 forks source link

How to normalize list nodes? #56

Open benchub opened 2 years ago

benchub commented 2 years ago

I would like to modify the parse tree so that in (1) and in (1,2,3) end up looking the same. I can find the list node well enough, but it's not clear how to replace it - not only do I not know what function to use to make a new list node with a single item, it's not clear to me how that would affect the locations of all the other parse tree tokens.

If you could give an example of this, that would be amazing.

lfittl commented 2 years ago

@benchub Not sure if you are still looking for this - but the quick TLDR is that you would construct the appropriate Protobuf structure. See here for a similar example than the one you are asking for: https://github.com/pganalyze/pg_query_go/blob/ee7bb71c40fda2563e733efedce380e2c177fa2d/parse_test.go#L152-L203

And then pass it to the Deparse function:

https://github.com/pganalyze/pg_query_go#deparsing-a-parse-tree-back-into-a-sql-statement-experimental

Just in case you were worried about the Location fields - you don't need to do anything about those, they are only added for debugging by the parser, and are not used during deparsing.