Skip to content

Commit e61ed87

Browse files
committed
Propagate WITH clause to subsequent SELECTs in UNION queries
In ClickHouse's EXPLAIN AST output, the WITH clause from the first SELECT in a UNION ALL/UNION query is propagated to subsequent SELECTs. The inherited WITH clause is output at the END of children for those subsequent SELECT queries. This fix applies the same WITH clause propagation logic that was already implemented for INTERSECT/EXCEPT queries to plain UNION queries. Fixes tests: - 01515_with_global_and_with_propagation (stmt5, stmt11) - 03671_pk_in_subquery_context_expired (stmt7) - 03611_uniqExact_bug (stmt2) - 03033_analyzer_resolve_from_parent_scope (stmt4) - 01236_graphite_mt (stmt4)
1 parent f1f302b commit e61ed87

6 files changed

Lines changed: 19 additions & 28 deletions

File tree

internal/explain/select.go

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -300,8 +300,20 @@ func explainSelectWithUnionQuery(sb *strings.Builder, n *ast.SelectWithUnionQuer
300300
selects := simplifyUnionSelects(n.Selects)
301301
// Wrap selects in ExpressionList
302302
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(selects))
303-
for _, sel := range selects {
304-
Node(sb, sel, depth+2)
303+
304+
// Check if first operand has a WITH clause to be inherited by subsequent operands
305+
var inheritedWith []ast.Expression
306+
if len(selects) > 0 {
307+
inheritedWith = extractWithClause(selects[0])
308+
}
309+
310+
for i, sel := range selects {
311+
if i > 0 && len(inheritedWith) > 0 {
312+
// Subsequent operands inherit the WITH clause from the first operand
313+
explainSelectQueryWithInheritedWith(sb, sel, inheritedWith, depth+2)
314+
} else {
315+
Node(sb, sel, depth+2)
316+
}
305317
}
306318
// INTO OUTFILE clause - check if any SelectQuery has IntoOutfile set
307319
for _, sel := range n.Selects {
Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1 @@
1-
{
2-
"explain_todo": {
3-
"stmt4": true
4-
}
5-
}
1+
{}
Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1 @@
1-
{
2-
"explain_todo": {
3-
"stmt11": true,
4-
"stmt5": true
5-
}
6-
}
1+
{}
Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1 @@
1-
{
2-
"explain_todo": {
3-
"stmt4": true
4-
}
5-
}
1+
{}
Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1 @@
1-
{
2-
"explain_todo": {
3-
"stmt2": true
4-
}
5-
}
1+
{}
Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1 @@
1-
{
2-
"explain_todo": {
3-
"stmt7": true
4-
}
5-
}
1+
{}

0 commit comments

Comments
 (0)