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

How do you add a new where clause to an existing sql statement?

Open vamshiaruru32 opened this issue 2 years ago • 1 comments

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?

vamshiaruru32 avatar Jul 14 '23 01:07 vamshiaruru32

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.

dustin-decker avatar Dec 10 '23 18:12 dustin-decker