-
Notifications
You must be signed in to change notification settings - Fork 0
/
dml_insert.go
84 lines (74 loc) · 2.21 KB
/
dml_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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package spnr
import (
"context"
"fmt"
"reflect"
"strings"
"cloud.google.com/go/spanner"
"github.com/pkg/errors"
)
// Insert build and execute insert statement from the passed struct.
// You can pass either a struct or a slice of struct to target.
// If you pass a slice of struct, this method will build a statement which insert multiple records in one statement like the following
// INSERT INTO `TableName` (`Column1`, `Column2`) VALUES ('a', 'b'), ('c', 'd'), ...;
func (d *DML) Insert(ctx context.Context, tx *spanner.ReadWriteTransaction, target any) (rowCount int64, err error) {
isStruct, err := validateStructOrStructSliceType(target)
if err != nil {
return 0, err
}
if isStruct {
rowCount, err := tx.Update(ctx, *d.buildInsertStmt(target))
return rowCount, errors.WithStack(err)
} else {
rowCount, err := tx.Update(ctx, *d.buildInsertAllStmt(target))
return rowCount, errors.WithStack(err)
}
}
func (d *DML) buildInsertStmt(target any) *spanner.Statement {
var columns []string
var values []string
params := map[string]any{}
for _, field := range toFields(target) {
columns = append(columns, quote(field.name))
values = append(values, addPlaceHolder(field.name))
params[field.name] = field.value
}
sql := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)",
d.getTableName(),
strings.Join(columns, ", "),
strings.Join(values, ", "),
)
d.log(sql, params)
return &spanner.Statement{
SQL: sql,
Params: params,
}
}
func (d *DML) buildInsertAllStmt(target any) *spanner.Statement {
var columns []string
var valuesList []string
params := map[string]any{}
slice := reflect.ValueOf(target).Elem()
for i := 0; i < slice.Len(); i++ {
var values []string
for _, field := range structValToFields(slice.Index(i)) {
if i == 0 {
columns = append(columns, quote(field.name))
}
param := addIdx(field.name, i)
values = append(values, addPlaceHolder(param))
params[param] = field.value
}
valuesList = append(valuesList, "("+strings.Join(values, ", ")+")")
}
sql := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s",
d.getTableName(),
strings.Join(columns, ", "),
strings.Join(valuesList, ", "),
)
d.log(sql, params)
return &spanner.Statement{
SQL: sql,
Params: params,
}
}