Skip to content

Allow select aliases to be in group by/having #3073

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

Merged
merged 8 commits into from
Aug 14, 2025
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
28 changes: 14 additions & 14 deletions enginetest/queries/queries.go
Original file line number Diff line number Diff line change
Expand Up @@ -9352,6 +9352,20 @@ from typestable`,
{"0"}, {"1"}, {"0"}, {"1"},
},
},
// https://github.com/dolthub/dolt/issues/7095
// References in group by and having should be allowed to match select aliases
{
Query: "select y as z from xy group by (y) having AVG(z) > 0",
Expected: []sql.Row{{1}, {2}, {3}},
},
{
Query: "select y as z from xy group by (z) having AVG(z) > 0",
Expected: []sql.Row{{1}, {2}, {3}},
},
{
Query: "select y + 1 as z from xy group by (z) having AVG(z) > 1",
Expected: []sql.Row{{2}, {3}, {4}},
},
}

var KeylessQueries = []QueryTest{
Expand Down Expand Up @@ -9603,20 +9617,6 @@ FROM mytable;`,
{"DECIMAL"},
},
},
// https://github.com/dolthub/dolt/issues/7095
// References in group by and having should be allowed to match select aliases
{
Query: "select y as z from xy group by (y) having AVG(z) > 0",
Expected: []sql.Row{{1}, {2}, {3}},
},
{
Query: "select y as z from xy group by (z) having AVG(z) > 0",
Expected: []sql.Row{{1}, {2}, {3}},
},
{
Query: "select y + 1 as z from xy group by (z) having AVG(z) > 1",
Expected: []sql.Row{{2}, {3}, {4}},
},
}

var VersionedQueries = []QueryTest{
Expand Down
14 changes: 6 additions & 8 deletions sql/planbuilder/aggregates.go
Original file line number Diff line number Diff line change
Expand Up @@ -372,17 +372,14 @@ func (b *Builder) buildAggFunctionArgs(inScope *scope, e *ast.FuncExpr, gb *grou
var args []sql.Expression
for _, arg := range e.Exprs {
e := b.selectExprToExpression(inScope, arg)
// if GetField is an alias, alias must be masking a column
if gf, ok := e.(*expression.GetField); ok && gf.TableId() == 0 {
e = b.selectExprToExpression(inScope.parent, arg)
}
switch e := e.(type) {
case *expression.GetField:
if e.TableId() == 0 {
// TODO: not sure where this came from but it's not true
// aliases are not valid aggregate arguments, the alias must be masking a column
gf := b.selectExprToExpression(inScope.parent, arg)
var ok bool
e, ok = gf.(*expression.GetField)
if !ok || e.TableId() == 0 {
b.handleErr(fmt.Errorf("failed to resolve aggregate column argument: %s", gf))
}
b.handleErr(fmt.Errorf("failed to resolve aggregate column argument: %s", e))
}
args = append(args, e)
col := scopeColumn{tableId: e.TableID(), db: e.Database(), table: e.Table(), col: e.Name(), scalar: e, typ: e.Type(), nullable: e.IsNullable()}
Expand Down Expand Up @@ -953,6 +950,7 @@ func (b *Builder) buildHaving(fromScope, projScope, outScope *scope, having *ast
havingScope := b.newScope()
if fromScope.parent != nil {
havingScope.parent = fromScope.parent
havingScope.parent.selectAliases = fromScope.selectAliases
}

// add columns from fromScope referenced in the groupBy
Expand Down
4 changes: 4 additions & 0 deletions sql/planbuilder/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ func (b *Builder) analyzeSelectList(inScope, outScope *scope, selectExprs ast.Se
col.scalar = e
tempScope.addColumn(col)
}
if inScope.selectAliases == nil {
inScope.selectAliases = make(map[string]sql.Expression)
}
inScope.selectAliases[e.Name()] = e
exprs = append(exprs, e)
default:
exprs = append(exprs, pe)
Expand Down
7 changes: 4 additions & 3 deletions sql/planbuilder/scalar.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,14 +123,15 @@ func (b *Builder) buildScalar(inScope *scope, e ast.Expr) (ex sql.Expression) {
colName := strings.ToLower(v.Name.String())
c, ok := inScope.resolveColumn(dbName, tblName, colName, true, false)
if !ok {
if aliasedExpr, ok := inScope.selectAliases[colName]; ok {
return aliasedExpr
}
sysVar, scope, ok := b.buildSysVar(v, ast.SetScope_None)
if ok {
return sysVar
}
var err error
if scope == ast.SetScope_User {
err = sql.ErrUnknownUserVariable.New(colName)
} else if scope == ast.SetScope_Persist || scope == ast.SetScope_PersistOnly {
if scope == ast.SetScope_User || scope == ast.SetScope_Persist || scope == ast.SetScope_PersistOnly {
err = sql.ErrUnknownUserVariable.New(colName)
} else if scope == ast.SetScope_Global || scope == ast.SetScope_Session {
err = sql.ErrUnknownSystemVariable.New(colName)
Expand Down
13 changes: 11 additions & 2 deletions sql/planbuilder/scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ type scope struct {

insertTableAlias string
insertColumnAliases map[string]string

selectAliases map[string]sql.Expression
}

// resolveColumn matches a variable use to a column definition with a unique
Expand Down Expand Up @@ -441,6 +443,12 @@ func (s *scope) copy() *scope {
if !s.colset.Empty() {
ret.colset = s.colset.Copy()
}
if s.selectAliases != nil {
ret.selectAliases = make(map[string]sql.Expression, len(s.selectAliases))
for k, v := range s.selectAliases {
ret.selectAliases[k] = v
}
}

return &ret
}
Expand Down Expand Up @@ -644,8 +652,9 @@ func (c scopeColumn) withOriginal(origTbl, col string) scopeColumn {
// scalarGf returns a getField reference to this column's expression.
func (c scopeColumn) scalarGf() sql.Expression {
if c.scalar != nil {
if p, ok := c.scalar.(*expression.ProcedureParam); ok {
return p
switch e := c.scalar.(type) {
case *expression.ProcedureParam:
return e
}
}
if c.originalCol != "" {
Expand Down
Loading