squirrel icon indicating copy to clipboard operation
squirrel copied to clipboard

Update(table).Set("balance", sq.Expr("? + ?", "balance", price)) is no effect

Open MagiClouds opened this issue 5 years ago • 3 comments

hi,

import ( "fmt" sq "github.com/Masterminds/squirrel" "github.com/Masterminds/structable" )

func UpdateUserBalance(db sq.DBProxyBeginner, uid int, price int64) error { query := sq.Update(table).Set("balance", sq.Expr("? + ?", "balance", price)) query = query.Where(sq.Eq{"id": uid}) s, i, e := query.ToSql() fmt.Println(s, i, e ) _, err := query.RunWith(db).Exec() return err }

s = "UPDATE pzb_user SET balance = ? + ? WHERE id = ?" i = [balance 1800 3] err = nil

i want UPDATE pzb_user SET balance = balance + 1800 WHERE id = 3 But no matter how many times you execute it, the result is always 1800 is this ·sq.Expr("? + ?", "balance", price)· not available?

MagiClouds avatar Mar 23 '20 07:03 MagiClouds

I don't think prepared statements allow you to bind a non-value component to a parameter thus you would always end up setting balance to 1800. Since you already know that you want add to the existing value of balance, you can structure your query as the following.

query := sq.Update(table).
    Set("balance", sq.Expr("balance + ?", price)).
    Where(sq.Eq{"id": uid})

This is actually a property of the underlying db and not squirrel.

tagus avatar Mar 24 '20 20:03 tagus

You solved my problem. Thank you

MagiClouds avatar Mar 25 '20 02:03 MagiClouds

This solves my problem, too. Thank you very much.

jamiesun avatar Oct 04 '20 04:10 jamiesun