-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace.go
42 lines (38 loc) · 1.02 KB
/
replace.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package edb
import (
"github.com/jinzhu/gorm"
"strings"
)
/*
** 批量替换插入,如果唯一键冲突,将删除旧的数据,插入新数据,可以设定表单名称,从而实现分表的策略
*/
func BatchReplace(db *gorm.DB, batch []DbMessage, tName string) error {
if len(batch) == 0 {
return nil
}
sql, values := batchReplaceSql(batch, tName)
if len(values) == 0 {
return nil
}
if err := db.Exec(sql, values...).Error; err != nil {
return err
}
return nil
}
func Replace(db *gorm.DB, msg DbMessage) error {
return db.Exec(InsertReplace+msg.TableName()+msg.Column()+OrmValue, msg.Values()).Error
}
func batchReplaceSql(messages []DbMessage, tName string) (sql string, values []interface{}) {
if len(messages) == 0 {
return "", nil
}
var str []string
for _, msg := range messages {
values = append(values, msg.Values())
str = append(str, OrmValue)
}
if tName == "" {
tName = messages[0].TableName()
}
return InsertReplace + tName + messages[0].Column() + strings.Join(str, ","), values
}