libpg_query icon indicating copy to clipboard operation
libpg_query copied to clipboard

Deparser incorrectly deparses `DEFAULT` expression in `CREATE TABLE` query

Open mpokryva opened this issue 1 year ago • 2 comments

The following query (taken from the Postgres regression tests) unfortunately produces an invalid query when ran through the deparser: CREATE TABLE error_tbl (b1 bool DEFAULT (1 IN (1, 2))) produces CREATE TABLE error_tbl (b1 bool DEFAULT 1 IN (1, 2)) (note the missing parentheses).

When I run the above in psql, I get ERROR: syntax error at or near "IN".

Let me know what I can do to help to fix the issue! This library has been super helpful, really appreciate all the work y'all have put in.

mpokryva avatar Apr 25 '23 13:04 mpokryva

@mpokryva Thanks for the report!

It looks like we've omitted constraints.sql from the list of filenames for the regression tests used by the deparser, thus this wasn't noticed before.

I think that may have happened because of the intentional parsing error that gets triggered in the regression tests (essentially to cover the case you're describing), which we didn't used to handle correctly, but we now should be able to ignore.

To fix, I think we should do two things:

  1. Add constraints.sql to the list of regression tests the deparser tests against
  2. Figure out a way to add the parenthesis, without always adding them

On the second point: We could of course just explicitly add parenthesis here around the deparseExpr call here: https://github.com/pganalyze/libpg_query/blob/15-latest/src/pg_query_deparse.c#L4612 -- but that would then lead to odd statements like "DEFAULT (1)" instead of "DEFAULT 1".

I think what we may need to do is pass an extra flag to deparseExpr (e.g. isBExpr) that then sets the context for deparseAExpr to DEPARSE_NODE_CONTEXT_A_EXPR, thus adding the outer parens (see https://github.com/pganalyze/libpg_query/blob/15-latest/src/pg_query_deparse.c#L2888).

Do you want to try making a PR for this?

lfittl avatar Apr 25 '23 20:04 lfittl

I'll give it a shot within the next week 🤞. In crunch time right now:)

mpokryva avatar Apr 27 '23 14:04 mpokryva