Skip to content
This repository has been archived by the owner on Jan 28, 2021. It is now read-only.

sql/analyzer: correctly qualify aliases with the same name as col #680

Merged
merged 1 commit into from
Apr 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,10 @@ var queries = []struct {
"SELECT '2018-05-02' - INTERVAL 1 DAY",
[]sql.Row{{time.Date(2018, time.May, 1, 0, 0, 0, 0, time.UTC)}},
},
{
`SELECT i AS i FROM mytable ORDER BY i`,
[]sql.Row{{int64(1)}, {int64(2)}, {int64(3)}},
},
}

func TestQueries(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion sql/analyzer/prune_columns.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ func fixRemainingFieldsIndexes(n sql.Node) (sql.Node, error) {

idx, ok := indexes[tableColumnPair{gf.Table(), gf.Name()}]
if !ok {
return nil, fmt.Errorf("unable to find column %q of table %q", gf.Name(), gf.Table())
return nil, ErrColumnTableNotFound.New(gf.Table(), gf.Name())
}

if idx == gf.Index() {
Expand Down
78 changes: 70 additions & 8 deletions sql/analyzer/resolve_columns.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,12 @@ func qualifyColumns(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error)
indexCols(name, n.Schema())
}

result, err := n.TransformExpressionsUp(func(e sql.Expression) (sql.Expression, error) {
exp, ok := n.(sql.Expressioner)
if !ok {
return n, nil
}

result, err := exp.TransformExpressions(func(e sql.Expression) (sql.Expression, error) {
a.Log("transforming expression of type: %T", e)
switch col := e.(type) {
case *expression.UnresolvedColumn:
Expand All @@ -160,16 +165,22 @@ func qualifyColumns(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error)
}

col = expression.NewUnresolvedQualifiedColumn(col.Table(), col.Name())

name := strings.ToLower(col.Name())
table := strings.ToLower(col.Table())
if table == "" {
// If a column has no table, it might be an alias
// defined in a child projection, so check that instead
// of incorrectly qualify it.
if isDefinedInChildProject(n, col) {
return col, nil
}

tables := dedupStrings(colIndex[name])
switch len(tables) {
case 0:
// If there are no tables that have any column with the column
// name let's just return it as it is. This may be an alias, so
// we'll wait for the reorder of the
// we'll wait for the reorder of the projection.
return col, nil
case 1:
col = expression.NewUnresolvedQualifiedColumn(
Expand Down Expand Up @@ -269,8 +280,54 @@ func qualifyColumns(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error)
})
}

func isDefinedInChildProject(n sql.Node, col *expression.UnresolvedColumn) bool {
var x sql.Node
for _, child := range n.Children() {
plan.Inspect(child, func(n sql.Node) bool {
switch n := n.(type) {
case *plan.SubqueryAlias:
return false
case *plan.Project, *plan.GroupBy:
if x == nil {
x = n
}
return false
default:
return true
}
})

if x != nil {
break
}
}

if x == nil {
return false
}

var found bool
plan.InspectExpressions(x, func(e sql.Expression) bool {
alias, ok := e.(*expression.Alias)
if ok && strings.ToLower(alias.Name()) == strings.ToLower(col.Name()) {
found = true
return false
}

return true
})

return found
}

var errGlobalVariablesNotSupported = errors.NewKind("can't resolve global variable, %s was requested")

const (
sessionTable = "@@" + sqlparser.SessionStr
sessionPrefix = sqlparser.SessionStr + "."
globalPrefix = sqlparser.GlobalStr + "."
)

func resolveColumns(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
span, ctx := ctx.Span("resolve_columns")
defer span.Finish()
Expand All @@ -282,6 +339,7 @@ func resolveColumns(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error)
return n, nil
}

var childSchema sql.Schema
colMap := make(map[string][]*sql.Column)
for _, child := range n.Children() {
if !child.Resolved() {
Expand All @@ -291,6 +349,7 @@ func resolveColumns(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error)
for _, col := range child.Schema() {
name := strings.ToLower(col.Name)
colMap[name] = append(colMap[name], col)
childSchema = append(childSchema, col)
}
}

Expand Down Expand Up @@ -318,13 +377,16 @@ func resolveColumns(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error)
return e, nil
}

const (
sessionTable = "@@" + sqlparser.SessionStr
sessionPrefix = sqlparser.SessionStr + "."
globalPrefix = sqlparser.GlobalStr + "."
)
name := strings.ToLower(uc.Name())
table := strings.ToLower(uc.Table())

// First of all, try to find the field in the child schema, which
// will resolve aliases.
if idx := childSchema.IndexOf(name, table); idx >= 0 {
col := childSchema[idx]
return expression.NewGetFieldWithTable(idx, col.Type, col.Source, col.Name, col.Nullable), nil
}

columns, ok := colMap[name]
if !ok {
switch uc := uc.(type) {
Expand Down
2 changes: 0 additions & 2 deletions sql/expression/function/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,8 +375,6 @@ func (d *YearWeek) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
return nil, errors.New("YEARWEEK: invalid day")
}

fmt.Println(yyyy, mm, dd)

mode := int64(0)
val, err := d.mode.Eval(ctx, row)
if err != nil {
Expand Down