Skip to content

Commit

Permalink
UpdateStmt supports IncrBy and DecrBy (#198)
Browse files Browse the repository at this point in the history
  • Loading branch information
jiyeyuran authored and taylorchu committed Dec 30, 2019
1 parent 3f07b54 commit c392c1f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
13 changes: 13 additions & 0 deletions update.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ func (b *UpdateStmt) Build(d Dialect, buf Buffer) error {
buf.WriteString(placeholder)

buf.WriteValue(v)

i++
}

Expand Down Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions update_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit c392c1f

Please sign in to comment.