Don't parenthesize the top level SQL SELECT statements in codegen
Parenthesized statements are not valid in all contexts in Postgres so
take care not to parethesize the top level `SELECT` statements.
@@ -142,8 +142,12 @@ class SQLSourceGenerator(codegen.SourceGenerator):
self._visit_values_expr(node)
return
- self.new_lines = 1
+ # This is a very crude detection of whether this SELECT is
+ # a top level statement.
+ parenthesize = bool(self.result)
+ if parenthesize:
+ self.new_lines = 1
self.write('(')
if node.ctes:
@@ -235,6 +239,7 @@ class SQLSourceGenerator(codegen.SourceGenerator):
self.visit(node.limit_count)
self.indentation -= 1
+ if parenthesize:
self.new_lines = 1
self.write(')')
