Skip to content

Commit 3f47d14

Browse files
committed
address nick's review comments
1 parent 50c492d commit 3f47d14

File tree

1 file changed

+23
-15
lines changed

1 file changed

+23
-15
lines changed

sql/analyzer/replace_subqueries.go

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -34,29 +34,37 @@ func replaceSubqueries(ctx *sql.Context, a *Analyzer, n sql.Node, scope *plan.Sc
3434
}
3535

3636
return transform.NodeWithOpaque(n, func(node sql.Node) (sql.Node, transform.TreeIdentity, error) {
37-
if sqa, ok := node.(*plan.SubqueryAlias); ok && len(sqa.ColumnNames) == 0 {
37+
if sqa, ok := node.(*plan.SubqueryAlias); ok {
3838
switch child := sqa.Child.(type) {
3939
case *plan.Project:
40-
if table, ok := child.Child.(*plan.ResolvedTable); ok {
41-
if child.Schema().Equals(table.Schema()) {
40+
if len(sqa.ColumnNames) == 0 {
41+
if table, ok := child.Child.(*plan.ResolvedTable); ok && child.Schema().Equals(table.Schema()) {
4242
return plan.NewTableAlias(sqa.Name(), table), transform.NewTree, nil
43+
4344
}
4445
}
4546
case *plan.TableAlias:
46-
return plan.NewTableAlias(sqa.Name(), getResolvedTable(child)), transform.NewTree, nil
47-
case *plan.SubqueryAlias:
48-
colIdMap := make(map[sql.ColumnId]sql.ColumnId)
49-
colId, colIdOk := sqa.Columns().Next(1)
50-
childColId, childColIdOk := child.Columns().Next(1)
51-
for colIdOk && childColIdOk {
52-
colIdMap[colId] = childColId
53-
colId, colIdOk = sqa.Columns().Next(colId + 1)
54-
childColId, childColIdOk = child.Columns().Next(childColId + 1)
47+
if len(sqa.ColumnNames) == 0 {
48+
return plan.NewTableAlias(sqa.Name(), getResolvedTable(child)), transform.NewTree, nil
5549
}
56-
for col, _ := range sqa.ScopeMapping {
57-
sqa.ScopeMapping[col] = child.ScopeMapping[colIdMap[col]]
50+
case *plan.SubqueryAlias:
51+
if sqa.Columns().Len() == child.Columns().Len() {
52+
// childColIdMap maps each ColumnId from sqa to the corresponding child ColumnId
53+
childColIdMap := make(map[sql.ColumnId]sql.ColumnId)
54+
colId, colIdOk := sqa.Columns().Next(1)
55+
childColId, childColIdOk := child.Columns().Next(1)
56+
for colIdOk && childColIdOk {
57+
childColIdMap[colId] = childColId
58+
colId, colIdOk = sqa.Columns().Next(colId + 1)
59+
childColId, childColIdOk = child.Columns().Next(childColId + 1)
60+
}
61+
scopeMapping := make(map[sql.ColumnId]sql.Expression)
62+
for col, _ := range sqa.ScopeMapping {
63+
// remap child scope mapping to sqa scope mapping
64+
scopeMapping[col] = child.ScopeMapping[childColIdMap[col]]
65+
}
66+
return sqa.WithChild(child.Child).WithScopeMapping(scopeMapping), transform.NewTree, nil
5867
}
59-
return sqa.WithChild(child.Child), transform.NewTree, nil
6068
}
6169

6270
}

0 commit comments

Comments
 (0)