-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathinsert_batch.go
148 lines (129 loc) · 3.68 KB
/
insert_batch.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sqlchemy
import (
"bytes"
"fmt"
"reflect"
"strings"
"yunion.io/x/log"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/gotypes"
"yunion.io/x/pkg/util/reflectutils"
"yunion.io/x/pkg/util/timeutils"
)
const (
sqlLineLimit = 100
)
func (t *STableSpec) InsertBatch(dataList []interface{}) error {
qChar := t.Database().backend.QuoteChar()
var sql string
var fieldCount int
{
buffer := new(bytes.Buffer)
buffer.WriteString("INSERT INTO ")
buffer.WriteString(qChar)
buffer.WriteString(t.Name())
buffer.WriteString(qChar)
buffer.WriteString(" (")
headers := make([]string, 0)
format := make([]string, 0)
for _, col := range t.Columns() {
if col.IsAutoIncrement() {
continue
}
name := col.Name()
headers = append(headers, fmt.Sprintf("%s%s%s", qChar, name, qChar))
if col.IsCreatedAt() || col.IsUpdatedAt() {
if t.Database().backend.SupportMixedInsertVariables() {
format = append(format, t.Database().backend.CurrentUTCTimeStampString())
} else {
format = append(format, "?")
fieldCount++
}
continue
}
format = append(format, "?")
fieldCount++
}
buffer.WriteString(strings.Join(headers, ","))
buffer.WriteString(") VALUES ")
buffer.WriteString("(")
buffer.WriteString(strings.Join(format, ","))
buffer.WriteString(")")
sql = buffer.String()
if DEBUG_SQLCHEMY {
log.Debugf("batchInsert SQL: %s", buffer.String())
}
}
batchParams := make([][]interface{}, 0)
now := timeutils.UtcNow()
errs := make([]error, 0)
for i := range dataList {
v := dataList[i]
var params []interface{}
modelValue := reflect.Indirect(reflect.ValueOf(v))
beforeInsert(modelValue)
dataFields := reflectutils.FetchStructFieldValueSet(modelValue)
for _, col := range t.Columns() {
if col.IsAutoIncrement() {
continue
}
if col.IsCreatedAt() || col.IsUpdatedAt() {
if !t.Database().backend.SupportMixedInsertVariables() {
params = append(params, now)
}
continue
}
ov, find := dataFields.GetInterface(col.Name())
if !find || gotypes.IsNil(ov) || col.IsZero(ov) {
// empty column
if col.IsSupportDefault() && (len(col.Default()) > 0 || col.IsString()) {
params = append(params, col.ConvertFromString(col.Default()))
} else {
params = append(params, nil)
}
} else {
// validate text width
if col.IsString() && col.GetWidth() > 0 {
newStr, ok := ov.(string)
if ok && len(newStr) > col.GetWidth() {
ov = newStr[:col.GetWidth()]
}
}
params = append(params, col.ConvertFromValue(ov))
}
}
if len(params) != fieldCount {
log.Errorf("expect %d got %d(%#v)", fieldCount, len(params), params)
}
batchParams = append(batchParams, params)
if len(batchParams) >= sqlLineLimit || (i+1) == len(dataList) {
results, err := t.Database().TxBatchExec(sql, batchParams)
if err != nil {
return errors.Wrap(err, "TxBatchExec")
}
for _, result := range results {
if result.Error != nil {
errs = append(errs, result.Error)
}
}
if len(errs) != 0 {
return errors.NewAggregate(errs)
}
batchParams = make([][]interface{}, 0)
}
}
return nil
}