-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert.go
More file actions
310 lines (260 loc) · 5.93 KB
/
Copy pathinsert.go
File metadata and controls
310 lines (260 loc) · 5.93 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
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package sqlbldr
// cspell: ignore pala, ivals
import (
"context"
"fmt"
"reflect"
"strings"
)
// InsertStatement a builder for insert statements
// insert into person (id,name, email)
// values (1, 'lala', 'lala@mail.com')
// Insert("person").
// Values([]Person{
// {1, "lala", "lala@mail.com"},
// {2, "pala", "pala@mail.com"},
// })
//
// Or
//
// Insert("person").
// Values(Person{1, "lala", "lala@mail.com"})
//
// Or
//
// Insert("person")
// Values(map[string]interface{})
//
// Or
//
// Insert("person")
// Values([]map[string]interface{})
type InsertStatement struct {
sql string
table string
columns []string
exclude []string
values interface{}
args []interface{}
returns string
err error
tag string
}
// Insert creates an insert statement
func Insert(table string) *InsertStatement {
stmt := new(InsertStatement)
return stmt.Insert(table)
}
// Insert is used to specify the table to be used in the insert statement
func (s *InsertStatement) Insert(table string) *InsertStatement {
s.table = table
return s
}
// Exclude specify columns to be excluded from insert
// expects "a,b,c" or []string{"a", "b", "c"}
func (s *InsertStatement) Exclude(ex interface{}) *InsertStatement {
// if err abort
if s.err != nil {
return s
}
if str, ok := ex.(string); ok {
parts := strings.Split(str, ",")
retv := make([]string, len(parts))
for i, p := range parts {
retv[i] = strings.TrimSpace(p)
}
s.exclude = retv
return s
}
slStr, ok := ex.([]string)
if !ok {
s.err = fmt.Errorf("Exclude: accepts only string, []string received %T", ex)
return s
}
s.exclude = slStr
return s
}
// Returns specify column to be returned after insert (typically id)
func (s *InsertStatement) Returns(ret string) *InsertStatement {
// if err abort
if s.err != nil {
return s
}
s.returns = ret
return s
}
// Values used to specify data that is inserted into the database.
// Supports
// struct, []struct, map[string]interface{}, []map[string]interface{}
// example:
// stmt.Values([]struct {
// ID int
// Name string `db:"full_name"`
// }{
// {1, "chidi"},
// {2, "bosman"},
// {3, "nwa"},
// })
func (s *InsertStatement) Values(data interface{}) *InsertStatement {
// if err abort
if s.err != nil {
return s
}
isStruct := IsStruct(data) || IsSliceStruct(data)
isMap := IsMap(data) || IsSliceMap(data)
if !isStruct && !isMap {
s.err = fmt.Errorf("expecting struct, []struct, map[string]interface{}, []map[string]interface{}")
return s
}
s.values = data
return s
}
// Build ...
func (s *InsertStatement) Build() (qry string, sArgs []interface{}) {
// if err abort
if s.err != nil {
return "error", nil
}
// set tag
s.tag = tagName
var err error
// get column names
if err = s.extractColumns(); err != nil {
return "error", nil
}
// get values
if sArgs, err = s.extractValues(); err != nil {
return "error", nil
}
// build qry
qCols := quotedStrings(s.columns)
s.sql = fmt.Sprintf(
`INSERT INTO "%s" (%s) VALUES `,
s.table,
strings.Join(qCols, ", "),
)
qs := make([]string, len(s.columns))
for i := 0; i < len(s.columns); i++ {
qs[i] = "?"
}
qStr := strings.Join(qs, ", ")
vCnt := len(sArgs) / len(s.columns)
vp := make([]string, vCnt)
for i := 0; i < vCnt; i++ {
vp[i] = fmt.Sprintf("(%s)", qStr)
}
s.sql += strings.Join(vp, ", ")
// add returns if required
if len(s.returns) > 0 {
s.sql += fmt.Sprintf(` RETURNING "%s"`, s.returns)
}
// values
// sArgs = values
qry = s.sql
return
}
// Exec ...
func (s *InsertStatement) Exec(ctx context.Context, db DBI, lastID interface{}) (int64, error) {
qry, args := s.Build()
if s.err != nil {
return 0, s.err
}
affected, err := Exec(ctx, db, lastID, qry, args...)
if err != nil {
s.err = err
return 0, err
}
return affected, nil
}
func (s *InsertStatement) extractValues() ([]interface{}, error) {
values := []interface{}{}
if IsStruct(s.values) {
retv, err := GetStructValues(s.values, s.exclude)
if err != nil {
s.err = err
return nil, err
}
values = append(values, retv...)
} else if IsSliceStruct(s.values) {
// convert s.values --> []interface{} so that we can use GetStructValues
// to extract attribute values and append them to values
v, err := StructToInterface(s.values)
if err != nil {
s.err = err
return nil, err
}
// append the values of each struct to values
ivals := v.([]interface{})
for i := 0; i < len(ivals); i++ {
retv, err := GetStructValues(ivals[i], s.exclude)
if err != nil {
s.err = err
return nil, err
}
values = append(values, retv...)
}
} else if IsMap(s.values) {
retv, err := GetMapValues(s.values)
if err != nil {
s.err = err
return nil, err
}
values = append(values, retv...)
} else if IsSliceMap(s.values) {
var rErr error
EachSliceItem(s.values, func(i int, v reflect.Value) bool {
retv, rErr := GetMapValues(v.Interface())
if rErr != nil {
s.err = rErr
return true
}
values = append(values, retv...)
return false
})
if rErr != nil {
s.err = rErr
return nil, rErr
}
} else if v, ok := s.values.([]Map); ok {
for i := range v {
retv, err := GetMapValues(v[i])
if err != nil {
s.err = err
return nil, err
}
values = append(values, retv...)
}
}
return values, nil
}
func (s *InsertStatement) extractColumns() error {
columns := []string{}
if IsSliceStruct(s.values) || IsStruct(s.values) {
s.err = nil
columns, s.err = GetStructFields(s.values, s.tag, s.exclude)
if s.err != nil {
return s.err
}
} else if IsMap(s.values) {
s.err = nil
columns, s.err = GetMapKeys(s.values)
if s.err != nil {
return s.err
}
} else if IsSliceMap(s.values) {
s.err = nil
i := GetSliceItem(s.values, 0)
if i == nil {
return fmt.Errorf("empty slice")
}
columns, s.err = GetMapKeys(i)
if s.err != nil {
return s.err
}
}
for i := range columns {
columns[i] = Underscore(strings.TrimSpace(columns[i]))
}
s.columns = columns
return nil
}