blastrain / vitess-sqlparser

simply SQL Parser for Go ( powered by vitess and TiDB )
Apache License 2.0
421 stars 75 forks source link

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

Open vamshiaruru32 opened 1 year ago

vamshiaruru32 commented 1 year ago

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?

dustin-decker commented 9 months ago

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.