From c392c1f12ea7775282848a2101cbec413ccb45c6 Mon Sep 17 00:00:00 2001 From: "xinfei.wu" Date: Tue, 31 Dec 2019 01:31:00 +0800 Subject: [PATCH] UpdateStmt supports IncrBy and DecrBy (#198) --- update.go | 13 +++++++++++++ update_test.go | 12 ++++++++++++ 2 files changed, 25 insertions(+) diff --git a/update.go b/update.go index fe5df861..fc4ee7e5 100644 --- a/update.go +++ b/update.go @@ -56,6 +56,7 @@ func (b *UpdateStmt) Build(d Dialect, buf Buffer) error { buf.WriteString(placeholder) buf.WriteValue(v) + i++ } @@ -174,6 +175,18 @@ func (b *UpdateStmt) SetMap(m map[string]interface{}) *UpdateStmt { return b } +// IncrBy increases column by value +func (b *UpdateStmt) IncrBy(column string, value interface{}) *UpdateStmt { + b.Value[column] = Expr("? + ?", I(column), value) + return b +} + +// DecrBy decreases column by value +func (b *UpdateStmt) DecrBy(column string, value interface{}) *UpdateStmt { + b.Value[column] = Expr("? - ?", I(column), value) + return b +} + func (b *UpdateStmt) Limit(n uint64) *UpdateStmt { b.LimitCount = int64(n) return b diff --git a/update_test.go b/update_test.go index ecd9b50c..fd67437e 100644 --- a/update_test.go +++ b/update_test.go @@ -48,3 +48,15 @@ func TestPostgresUpdateReturning(t *testing.T) { require.Equal(t, 1, sess.EventReceiver.(*testTraceReceiver).finished) require.Equal(t, 0, sess.EventReceiver.(*testTraceReceiver).errored) } + +func TestUpdateIncrBy(t *testing.T) { + buf := NewBuffer() + builder := Update("table").IncrBy("a", 1).Where(Eq("b", 2)) + err := builder.Build(dialect.MySQL, buf) + require.NoError(t, err) + + sqlstr, err := InterpolateForDialect(buf.String(), buf.Value(), dialect.MySQL) + require.NoError(t, err) + + require.Equal(t, "UPDATE `table` SET `a` = `a` + 1 WHERE (`b` = 2)", sqlstr) +}