@@ -64,6 +64,20 @@ func outputColumns(qc *QueryCatalog, node ast.Node) ([]*Column, error) {
6464 targets = n .ReturningList
6565 case * ast.SelectStmt :
6666 targets = n .TargetList
67+
68+ if n .GroupClause != nil {
69+ for _ , item := range n .GroupClause .Items {
70+ ref , ok := item .(* ast.ColumnRef )
71+ if ! ok {
72+ continue
73+ }
74+
75+ if err := findColumnForRef (ref , tables ); err != nil {
76+ return nil , err
77+ }
78+ }
79+ }
80+
6781 // For UNION queries, targets is empty and we need to look for the
6882 // columns in Largs.
6983 if len (targets .Items ) == 0 && n .Larg != nil {
@@ -470,3 +484,44 @@ func outputColumnRefs(res *ast.ResTarget, tables []*Table, node *ast.ColumnRef)
470484 }
471485 return cols , nil
472486}
487+
488+ func findColumnForRef (ref * ast.ColumnRef , tables []* Table ) error {
489+ parts := stringSlice (ref .Fields )
490+ var alias , name string
491+ if len (parts ) == 1 {
492+ name = parts [0 ]
493+ } else if len (parts ) == 2 {
494+ alias = parts [0 ]
495+ name = parts [1 ]
496+ }
497+
498+ var found int
499+ for _ , t := range tables {
500+ if alias != "" && t .Rel .Name != alias {
501+ continue
502+ }
503+ for _ , c := range t .Columns {
504+ if c .Name == name {
505+ found ++
506+ continue
507+ }
508+ }
509+ }
510+
511+ if found == 0 {
512+ return & sqlerr.Error {
513+ Code : "42703" ,
514+ Message : fmt .Sprintf ("column reference \" %s\" not found" , name ),
515+ Location : ref .Location ,
516+ }
517+ }
518+ if found > 1 {
519+ return & sqlerr.Error {
520+ Code : "42703" ,
521+ Message : fmt .Sprintf ("column reference \" %s\" is ambiguous" , name ),
522+ Location : ref .Location ,
523+ }
524+ }
525+
526+ return nil
527+ }
0 commit comments