vitess-sqlparser
vitess-sqlparser copied to clipboard
How do you add a new where clause to an existing sql statement?
I am unable to figure how to construct an Expr to pass to AddWhere method. Lets say I have a query like "SELECT * FROM product WHERE price < 500". Now how do I add "discount <= 10"? This is the closest I came to a solution:
left := sqlparser.NewStrVal([]byte("price"))
right := sqlparser.NewStrVal([]byte("?"))
comp := &sqlparser.ComparisonExpr{
Operator: sqlparser.LessEqualStr,
Left: left,
Right: right,
}
fmt.Printf("%v\n", sqlparser.String(comp))
sel := stmt.(*sqlparser.Select)
sel.AddWhere(comp)
fmt.Printf("%v\n", sqlparser.String(sel))
But this seems to quote the left in single quotes, because I assume it is considering it as a value instead of a column name. So how do I add a column name expr?
I think you'll want to use something like this: https://github.com/vitessio/vitess/blob/v18.0.1/go/vt/sqlparser/ast_test.go#L91
That will provide a Column name instead of a String value type.