pganalyze / libpg_query

C library for accessing the PostgreSQL parser outside of the server environment
BSD 3-Clause "New" or "Revised" License
1.21k stars 182 forks source link

Pretty print Deparse output #194

Closed fenos closed 1 year ago

fenos commented 1 year ago

Hi, awesome library!

I'm wondering if there is a way of outputting a properly formatted SQL with Deparse. I'm building at runtime a pg_query.ParseResult struct then feeding it to Deparse

Currently, it outputs everything on 1 line. Any tips?

lelit commented 1 year ago

No, that's not implemented in the library's Deparser.

If Python is an option, give pglast a try.

fenos commented 1 year ago

Gotcha, any alternative for go?

lfittl commented 1 year ago

To expand on the comment by @lelit (who is the author of pglast), its correct the deparser built into libpg_query doesn't support this directly at this point.

To do it today, you can get locations from the library another way and then add whitespace using your own logic on the deparser output. To get the locations you can either:

1) Run the deparsed query through the scan function, which gets you the basic type of each token (keyword, comment, etc) 2) Use the location fields in the parser nodes (see depesz post for an example of this: https://www.depesz.com/2022/08/31/new-sql-pretty-printer-based-on-parsing-and-not-regexps/) - note you'd have to reparse the queries for this, since the deparser doesn't populate the location fields

We may also add an option for this to libpg_query directly (which would then also be available in the Go bindings), but part of why we haven't done this yet is that everyone has different opinions on how to format SQL.

That said I'd be open to discuss a patch that makes this configurable in the libpg_query deparser, if it can be kept simple enough in the existing deparser code.