Masterminds / squirrel

Fluent SQL generation for golang
Other
6.96k stars 465 forks source link

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

Open MagiClouds opened 4 years ago

MagiClouds commented 4 years ago

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?

tagus commented 4 years ago

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.

MagiClouds commented 4 years ago

You solved my problem. Thank you

jamiesun commented 4 years ago

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