更新gdb.Update方法

This commit is contained in:
sunmoon 2020-11-28 13:52:17 +08:00
parent bc8142974f
commit 09bb0c9397
3 changed files with 74 additions and 2 deletions

View File

@ -214,6 +214,12 @@ type Link interface {
Prepare(sql string) (*sql.Stmt, error)
}
// Counter is the type for update count.
type Counter struct {
Field string
Value float64
}
type (
// Value is the field value type.
Value = *gvar.Var

View File

@ -699,8 +699,24 @@ func (c *Core) DoUpdate(link Link, table string, data interface{}, condition str
dataMap = ConvertDataForTableRecord(data)
)
for k, v := range dataMap {
fields = append(fields, c.DB.QuoteWord(k)+"=?")
params = append(params, v)
switch value := v.(type) {
case Counter, *Counter:
counter := value.(Counter)
if counter.Value != 0 {
column := c.DB.QuoteWord(counter.Field)
var symbol string
if counter.Value < 0 {
symbol = "-"
} else {
symbol = "+"
}
fields = append(fields, fmt.Sprintf("%s=%s%s?", column, column, symbol))
params = append(params, v)
}
default:
fields = append(fields, c.DB.QuoteWord(k)+"=?")
params = append(params, v)
}
}
updates = strings.Join(fields, ",")
default:

View File

@ -10,6 +10,8 @@ import (
"fmt"
"github.com/gogf/gf/container/garray"
"github.com/gogf/gf/encoding/gparser"
"github.com/gogf/gf/util/gconv"
"reflect"
"testing"
"time"
@ -1405,3 +1407,51 @@ func Test_Empty_Slice_Argument(t *testing.T) {
t.Assert(len(result), 0)
})
}
// update counter test
func Test_DB_UpdateCounter(t *testing.T) {
tableName := "update_counter_test"
defer dropTable(tableName)
_, err := db.Exec(fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s (
id int(10) unsigned NOT NULL,
views int(8) unsigned DEFAULT '0' NOT NULL ,
updated_time int(10) unsigned DEFAULT '0' NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`, tableName))
if err != nil {
gtest.Fatal(err)
}
id := 1
insertData := g.Map{
"id": id,
"views": 0,
"updated_time": 0,
}
_, err = db.Insert(tableName, insertData)
if err != nil {
gtest.Fatal(err)
}
gtest.C(t, func(t *gtest.T) {
gdbCounter := &gdb.Counter{
Field: "views",
Value: 1,
}
updateData := g.Map{
"views": gdbCounter,
"updated_time": gtime.Now().Unix(),
}
result, err := db.Update(tableName, updateData, "id="+gconv.String(id))
t.Assert(err, nil)
n, _ := result.RowsAffected()
t.Assert(n, 1)
one, err := db.Table(tableName).Where("id", id).One()
t.Assert(err, nil)
t.Assert(one["id"].Int(), 3)
t.Assert(one["passport"].String(), "user_3")
t.Assert(one["password"].String(), "987654321")
t.Assert(one["nickname"].String(), "name_3")
t.Assert(one["login_times"].String(), "1")
})
}