From 7845d4b2c2287fd900011151565b10edfaa74f0d Mon Sep 17 00:00:00 2001 From: Wleeaf <179125857+wleeaf@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:21:37 +0000 Subject: [PATCH] Keep parentheses that a clause needs around a subquery or row The paren_expr printer collapses nested parentheses into one pair. When the inner pair belongs to a subquery or a row constructor and the outer pair is part of the enclosing clause, both are required, and dropping one gives invalid SQL: CREATE POLICY admin_only ON permissions USING ((SELECT is_admin FROM users WHERE name = current_user)) was formatted with USING (SELECT ...), which PostgreSQL rejects. The same happened with GENERATED ALWAYS AS ((SELECT ...)) and with a row in PARTITION BY RANGE (((a, b))). Nested parentheses are now kept when the inner ones contain a subquery or a list. --- src/syntax/expr.ts | 11 +++++++++-- test/ddl/policy.test.ts | 7 +++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/syntax/expr.ts b/src/syntax/expr.ts index 7fc7c0f..209b4ed 100644 --- a/src/syntax/expr.ts +++ b/src/syntax/expr.ts @@ -66,8 +66,15 @@ export const exprMap: CstToDocMap = { } }, paren_expr: (print, node, path) => { - // discard unnecessary nested ((parentheses)) - if (isParenExpr(node.expr)) { + // discard unnecessary nested ((parentheses)), + // but not when the inner ones belong to a subquery or a row, + // as the outer ones may be required by the enclosing clause + if ( + isParenExpr(node.expr) && + !isSelectStmt(node.expr.expr) && + !isCompoundSelectStmt(node.expr.expr) && + !isListExpr(node.expr.expr) + ) { return print("expr"); } // Discard unnecessary parenthesis around function arguments diff --git a/test/ddl/policy.test.ts b/test/ddl/policy.test.ts index 22e29de..06861f9 100644 --- a/test/ddl/policy.test.ts +++ b/test/ddl/policy.test.ts @@ -33,6 +33,13 @@ describe("policy", () => { WITH CHECK (kind = 'public') `); }); + + it(`preserves parenthesis around subquery used as the USING condition`, async () => { + await testPostgresql(dedent` + CREATE POLICY admin_only ON permissions + USING ((SELECT is_admin FROM users WHERE name = current_user)) + `); + }); }); describe("alter policy", () => {