vitess-sqlparser icon indicating copy to clipboard operation
vitess-sqlparser copied to clipboard

example of parser details

Open sunshine69 opened this issue 2 years ago • 3 comments

Hi there,

From the example we just print the parse out. How can I get - that is like type (create or alter etc, DDL type, ) table name, columns etc, all details?

the thing I could see is using WalkSubtree and parse them out however it is not obvious to new users like me without reading code and finding types etc..

So a more example to show the detailed portion of the parsed stmt would be great.

Thanks

sunshine69 avatar Jun 10 '22 03:06 sunshine69

stmt, err := sqlparser.Parse("select hello, skywhat from user_items where user_id = 1 limit 10")
if err != nil {
	panic(err)
}
tableName := stmt.(*sqlparser.Select).From[0].(*sqlparser.AliasedTableExpr).Expr.(sqlparser.TableName).Name.String()

selectCol0 := stmt.(*sqlparser.Select).SelectExprs[0].(*sqlparser.AliasedExpr).Expr.(*sqlparser.ColName).Name.String()
selectCol1 := stmt.(*sqlparser.Select).SelectExprs[1].(*sqlparser.AliasedExpr).Expr.(*sqlparser.ColName).Name.String()

operator := stmt.(*sqlparser.Select).Where.Expr.(*sqlparser.ComparisonExpr).Operator

leftVal := stmt.(*sqlparser.Select).Where.Expr.(*sqlparser.ComparisonExpr).Left.(*sqlparser.ColName).Name.String()

rightVal := stmt.(*sqlparser.Select).Where.Expr.(*sqlparser.ComparisonExpr).Right.(*sqlparser.SQLVal).Val

limitNum := stmt.(*sqlparser.Select).Limit.Rowcount.(*sqlparser.SQLVal).Val
fmt.Printf("select %s, %s from %s where %s %s %s limit %s", selectCol0, selectCol1, tableName, leftVal, operator, string(rightVal), string(limitNum))

skywhat avatar Jul 23 '22 02:07 skywhat