Skip to content

[BUG]: Unnecessary parentheses in UNION ALL subqueries for CTE statements causing syntax errors #4526

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
1 task done
wmzy opened this issue May 16, 2025 · 0 comments
Open
1 task done
Labels
bug Something isn't working

Comments

@wmzy
Copy link

wmzy commented May 16, 2025

Report hasn't been filed before.

  • I have verified that the bug I'm about to report hasn't been filed before.

What version of drizzle-orm are you using?

0.40.1

What version of drizzle-kit are you using?

0.30.5

Other packages

No response

Describe the Bug

Description

When using the unionAll method to build Common Table Expressions (CTEs), Drizzle ORM adds extra parentheses around each subquery, which can cause syntax errors in some cases.

Steps to Reproduce

When creating a CTE using this pattern:

const cte = qb.$with('name').as(
  qb
    .select()
    .from(tableA)
    .where(/* condition */)
    .unionAll(
      qb
        .select()
        .from(tableB)
        .where(/* condition */)
    )
);

Generated SQL (with issue)

with "name" as (
    (select columns from tableA where condition) 
    union all 
    (select columns from tableB where condition)
)

Expected SQL

with "name" as (
    select columns from tableA where condition
    union all 
    select columns from tableB where condition
)

Root Cause

In the Drizzle ORM source code, the unionAll method implementation automatically adds parentheses around each subquery. While this might be necessary for standalone UNION ALL queries, it's redundant when building CTE subqueries and can lead to syntax errors.

Suggested Fix

Modify the unionAll method implementation to avoid adding extra parentheses in CTE contexts, or provide an option to control whether parentheses are added around subqueries.

@wmzy wmzy added the bug Something isn't working label May 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant