Skip to content

[CALCITE-7343] RelToSqlConverter generate wrong sql when scalar correlated sub-query in Project#4810

Merged
mihaibudiu merged 1 commit intoapache:mainfrom
Dwrite:calcite-7343
Mar 4, 2026
Merged

[CALCITE-7343] RelToSqlConverter generate wrong sql when scalar correlated sub-query in Project#4810
mihaibudiu merged 1 commit intoapache:mainfrom
Dwrite:calcite-7343

Conversation

@Dwrite
Copy link

@Dwrite Dwrite commented Feb 27, 2026

Summary

Fixes scalar correlated subquery SQL generation by ensuring proper table alias handling for correlation variables, particularly in deeply nested scenarios.

Changes

Core Strategy: Context-Aware Aliasing

  • Always generates explicit aliases for correlated subqueries
  • Prioritizes natural table identifiers (e.g., "EMP") over synthetic ones (e.g., "t") when the relation is a simple TableScan
  • Uses correlation scope stack to support multi-level nested subqueries

Key Benefits:

  1. DML Compatibility: Ensures UPDATE/DELETE statements remain valid in dialects that prohibit target table aliasing
  2. SQL Readability: Produces intuitive SQL where correlations reference source table names
  3. Multi-level Nesting: Correctly handles deeply nested correlated subqueries

Test Coverage

  • ✅ Single-level scalar correlated subquery
  • ✅ Deeply nested scalar correlated subqueries (2+ levels)
  • ✅ UPDATE with correlated subquery (no unnecessary alias)
  • ✅ Backward compatibility with existing correlation scenarios

Future Work

Follow-up PRs will extend this fix to:

  • Filter nodes: Correlated subqueries in WHERE/HAVING clauses
  • Join nodes: Correlated subqueries in JOIN conditions
  • ⏳ Other correlation scenarios (EXISTS, IN, etc.)

The infrastructure (correlation scope stack, Result.resetAliasForCorrelation) is designed to be reusable for these future enhancements.

@xiedeyantu
Copy link
Member

Please keep the PR title, commit message, and Jira title consistent with each other. Do not use "Fix" in the title.

@Dwrite Dwrite changed the title [CALCITE-7343] Fix RelToSqlConverter to ensure proper aliasing for correlated sub-queries in Project [CALCITE-7343] RelToSqlConverter generate wrong sql when scalar correlated sub-query in Project Feb 28, 2026
@sonarqubecloud
Copy link

sonarqubecloud bot commented Mar 3, 2026

@xiedeyantu
Copy link
Member

I have no further comments.

@mihaibudiu mihaibudiu added the LGTM-will-merge-soon Overall PR looks OK. Only minor things left. label Mar 4, 2026
@mihaibudiu
Copy link
Contributor

If there are no further comments I plan to merge this

@mihaibudiu mihaibudiu merged commit 6071268 into apache:main Mar 4, 2026
36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

LGTM-will-merge-soon Overall PR looks OK. Only minor things left.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants