Skip to content

Instantly share code, notes, and snippets.

@supershabam
Last active September 9, 2015 02:43
Show Gist options
  • Save supershabam/ba1a0f071744327d6b30 to your computer and use it in GitHub Desktop.
Save supershabam/ba1a0f071744327d6b30 to your computer and use it in GitHub Desktop.
vitess sql parser to get a list of columns a query will generate
package main
import (
"errors"
"fmt"
"log"
"github.com/youtube/vitess/go/vt/sqlparser"
)
func columnNames(sql string) ([]string, error) {
cn := []string{}
stmt, err := sqlparser.Parse(sql)
if err != nil {
return cn, err
}
s, ok := stmt.(*sqlparser.Select)
if !ok {
return cn, errors.New("expected select statement for given sql")
}
for _, expr := range s.SelectExprs {
nse, ok := expr.(*sqlparser.NonStarExpr)
if !ok {
return cn, errors.New("unhandled select expression type")
}
// if there is an As, we don't care what type it is, we'll use that as the column name
if len(nse.As) > 0 {
cn = append(cn, string(nse.As))
continue
}
// if there was no AS, we only accept ColName types as our value, other types are invalid
col, ok := nse.Expr.(*sqlparser.ColName)
if !ok {
return cn, errors.New("select expression is not column name and has no AS clause")
}
cn = append(cn, string(col.Name))
}
return cn, nil
}
func main() {
cn, err := columnNames("select (select * from feef) as lulz, poop as feef, count(*) as fish, jerks from (select ass from jerks)")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v\n", cn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment