-
Notifications
You must be signed in to change notification settings - Fork 6
/
insert.go
59 lines (48 loc) · 1.83 KB
/
insert.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package querybuilder
import (
"fmt"
"github.com/goal-web/contracts"
"github.com/goal-web/supports/utils"
"strings"
)
func getInsertType(insertType2 ...contracts.InsertType) contracts.InsertType {
if len(insertType2) > 0 {
return insertType2[0]
}
return contracts.Insert
}
func (builder *Builder) CreateSql(value contracts.Fields, insertType2 ...contracts.InsertType) (sql string, bindings []interface{}) {
if len(value) == 0 {
return
}
keys := make([]string, 0)
valuesString := fmt.Sprintf("(%s)", strings.Join(utils.MakeSymbolArray("?", len(value)), ","))
for name, field := range value {
bindings = append(bindings, field)
keys = append(keys, name)
}
sql = fmt.Sprintf("%s into %s %s values %s", getInsertType(insertType2...), builder.table, fmt.Sprintf("(%s)", strings.Join(keys, ",")), valuesString)
return
}
func (builder *Builder) InsertSql(values []contracts.Fields, insertType2 ...contracts.InsertType) (sql string, bindings []interface{}) {
if len(values) == 0 {
return
}
fields := utils.GetMapKeys(values[0])
valuesString := make([]string, 0)
for _, value := range values {
valuesString = append(valuesString, fmt.Sprintf("(%s)", strings.Join(utils.MakeSymbolArray("?", len(value)), ",")))
for _, field := range fields {
bindings = append(bindings, value[field])
}
}
fieldsString := fmt.Sprintf(" (%s)", strings.Join(fields, ","))
sql = fmt.Sprintf("%s into %s%s values %s", getInsertType(insertType2...), builder.table, fieldsString, strings.Join(valuesString, ","))
return
}
func (builder *Builder) InsertIgnoreSql(values []contracts.Fields) (sql string, bindings []interface{}) {
return builder.InsertSql(values, contracts.InsertIgnore)
}
func (builder *Builder) InsertReplaceSql(values []contracts.Fields) (sql string, bindings []interface{}) {
return builder.InsertSql(values, contracts.InsertReplace)
}