-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert.go
More file actions
50 lines (37 loc) · 1.06 KB
/
insert.go
File metadata and controls
50 lines (37 loc) · 1.06 KB
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
package sqlp
import (
"context"
"strings"
ref "github.com/kaboc/sqlp/reflect"
)
func insertContext(ctx context.Context, sq sqler, tableName string, structSlice interface{}) (Result, error) {
var result Result
if err := isStructSlice(structSlice); err != nil {
return result, err
}
sliceV := ref.ValueOf(structSlice)
sliceLen := sliceV.Len()
fields := ref.GetStructFields(sliceV)
fieldLen := len(fields)
values := make([]string, sliceLen)
binds := make([]interface{}, sliceLen*fieldLen)
for i1 := 0; i1 < sliceLen; i1++ {
values[i1] = "(" + strings.Repeat("?,", fieldLen)[:fieldLen*2-1] + ")"
dataV := sliceV.Index(i1)
for i2, v := range fields {
binds[i1*fieldLen+i2] = dataV.FieldByName(v.Name).Interface()
}
}
columnNames := make([]string, fieldLen)
for i3, v := range fields {
columnNames[i3] = v.Tag
}
query := `INSERT INTO ` + tableName + `
(` + strings.Join(columnNames, ",") + `)
VALUES ` + strings.Join(values, ",")
res, err := execContext(ctx, sq, query, binds...)
if err != nil {
return result, err
}
return res, nil
}