-
-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathtable.go
More file actions
385 lines (307 loc) · 11 KB
/
Copy pathtable.go
File metadata and controls
385 lines (307 loc) · 11 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package mysql
import (
"bytes"
"context"
"database/sql"
"database/sql/driver"
"fmt"
"reflect"
"slices"
"strings"
"github.com/stephenafamo/bob"
"github.com/stephenafamo/bob/clause"
"github.com/stephenafamo/bob/dialect/mysql/dialect"
"github.com/stephenafamo/bob/dialect/mysql/dm"
"github.com/stephenafamo/bob/dialect/mysql/im"
"github.com/stephenafamo/bob/dialect/mysql/sm"
"github.com/stephenafamo/bob/dialect/mysql/um"
"github.com/stephenafamo/bob/expr"
"github.com/stephenafamo/bob/internal"
"github.com/stephenafamo/bob/internal/mappings"
"github.com/stephenafamo/bob/orm"
"github.com/stephenafamo/scan"
)
type setter[T any] = orm.Setter[T, *dialect.InsertQuery, *dialect.UpdateQuery]
func NewTable[T any, Tset setter[T], C bob.Expression](tableName string, columns C, uniques ...[]string) *Table[T, []T, Tset, C] {
return NewTablex[T, []T, Tset](tableName, columns, uniques...)
}
func NewTablex[T any, Tslice ~[]T, Tset setter[T], C bob.Expression](tableName string, columns C, uniques ...[]string) *Table[T, Tslice, Tset, C] {
setMapping := mappings.GetMappings(reflect.TypeOf(*new(Tset)))
view, mappings := newView[T, Tslice](tableName, columns)
t := &Table[T, Tslice, Tset, C]{
View: view,
pkCols: expr.NewColumnsExpr(mappings.PKs...).WithParent(view.alias),
setterMapping: setMapping,
nonGeneratedCols: internal.FilterNonZero(mappings.NonGenerated),
uniqueIdx: uniqueIndexes(setMapping.All, uniques...),
}
allAutoIncr := internal.FilterNonZero(mappings.AutoIncrement)
if len(allAutoIncr) == 1 {
t.autoIncrementColumn = allAutoIncr[0]
}
return t
}
// The table contains extract information from the struct and contains
// caches ???
type Table[T any, Tslice ~[]T, Tset setter[T], C bob.Expression] struct {
*View[T, Tslice, C]
pkCols expr.ColumnsExpr
setterMapping mappings.Mapping
nonGeneratedCols []string
BeforeInsertHooks bob.Hooks[Tset, bob.SkipModelHooksKey]
AfterInsertHooks bob.Hooks[Tslice, bob.SkipModelHooksKey]
BeforeUpdateHooks bob.Hooks[Tslice, bob.SkipModelHooksKey]
AfterUpdateHooks bob.Hooks[Tslice, bob.SkipModelHooksKey]
BeforeDeleteHooks bob.Hooks[Tslice, bob.SkipModelHooksKey]
AfterDeleteHooks bob.Hooks[Tslice, bob.SkipModelHooksKey]
InsertQueryHooks bob.Hooks[*dialect.InsertQuery, bob.SkipQueryHooksKey]
UpdateQueryHooks bob.Hooks[*dialect.UpdateQuery, bob.SkipQueryHooksKey]
DeleteQueryHooks bob.Hooks[*dialect.DeleteQuery, bob.SkipQueryHooksKey]
// The AUTO_INCREMENT column that we can use to retrieve values using lastInsertID
// If empty, there is no auto inc
autoIncrementColumn string
// field indexes of unique columns
uniqueIdx [][]int
}
// Returns the primary key columns for this table.
func (t *Table[T, Tslice, Tset, C]) PrimaryKey() expr.ColumnsExpr {
return t.pkCols
}
// Starts an insert query for this table
func (t *Table[T, Tslice, Tset, C]) Insert(queryMods ...bob.Mod[*dialect.InsertQuery]) *insertQuery[T, Tslice, Tset, C] {
q := &insertQuery[T, Tslice, Tset, C]{
ExecQuery: orm.ExecQuery[*dialect.InsertQuery]{
BaseQuery: Insert(im.Into(t.Name(), t.nonGeneratedCols...)),
Hooks: &t.InsertQueryHooks,
},
table: t,
}
return q.Apply(queryMods...)
}
// Starts an update query for this table
func (t *Table[T, Tslice, Tset, C]) Update(queryMods ...bob.Mod[*dialect.UpdateQuery]) *orm.ExecQuery[*dialect.UpdateQuery] {
q := &orm.ExecQuery[*dialect.UpdateQuery]{
BaseQuery: Update(um.Table(t.NameAs())),
Hooks: &t.UpdateQueryHooks,
}
return q.Apply(queryMods...)
}
// Starts a delete query for this table
func (t *Table[T, Tslice, Tset, C]) Delete(queryMods ...bob.Mod[*dialect.DeleteQuery]) *orm.ExecQuery[*dialect.DeleteQuery] {
q := &orm.ExecQuery[*dialect.DeleteQuery]{
BaseQuery: Delete(dm.From(t.NameAs())),
Hooks: &t.DeleteQueryHooks,
}
return q.Apply(queryMods...)
}
type insertQuery[T any, Ts ~[]T, Tset setter[T], C bob.Expression] struct {
orm.ExecQuery[*dialect.InsertQuery]
table *Table[T, Ts, Tset, C]
}
func (t *insertQuery[T, Ts, Tset, C]) Apply(queryMods ...bob.Mod[*dialect.InsertQuery]) *insertQuery[T, Ts, Tset, C] {
if t == nil {
return nil
}
next := *t
next.ExecQuery = *t.ExecQuery.Apply(queryMods...)
return &next
}
// Insert One Row
// NOTE: Because MySQL does not support RETURNING, this will insert the row and then run a SELECT query
// to retrieve the row.
// if there is no AUTO_INCREMENT column and the row was not inserted with unique values, it will return [orm.ErrCannotRetrieveRow]
// [orm.ErrCannotRetrieveRow] is also returned if its a query of the form INSERT INTO ... SELECT ...
func (t *insertQuery[T, Ts, Tset, C]) One(ctx context.Context, exec bob.Executor) (T, error) {
q, err := t.insertAll(ctx, exec)
if err != nil {
return *new(T), err
}
return bob.One(ctx, exec, q, t.table.scanner)
}
// Insert Many
// NOTE: Because MySQL does not support RETURNING, this will insert EACH ROW with individual queries
// and then attempt to retrieve all the rows using a SELECT query.
// if there is no AUTO_INCREMENT column and the row was not inserted with unique values, it will return [orm.ErrCannotRetrieveRow]
// [orm.ErrCannotRetrieveRow] is also returned if its a query of the form INSERT INTO ... SELECT ...
func (t *insertQuery[T, Ts, Tset, C]) All(ctx context.Context, exec bob.Executor) (Ts, error) {
q, err := t.insertAll(ctx, exec)
if err != nil {
return nil, err
}
return bob.Allx[bob.SliceTransformer[T, Ts]](ctx, exec, q, t.table.scanner)
}
// Insert Many and return a cursor
// NOTE: Because MySQL does not support RETURNING, this will insert EACH ROW with individual queries
// and then attempt to retrieve all the rows using a SELECT query.
// if there is no AUTO_INCREMENT column and the row was not inserted with unique values, it will return [orm.ErrCannotRetrieveRow]
// [orm.ErrCannotRetrieveRow] is also returned if its a query of the form INSERT INTO ... SELECT ...
func (t *insertQuery[T, Ts, Tset, C]) Cursor(ctx context.Context, exec bob.Executor) (scan.ICursor[T], error) {
q, err := t.insertAll(ctx, exec)
if err != nil {
return nil, err
}
return bob.Cursor(ctx, exec, q, t.table.scanner)
}
func (t *insertQuery[T, Tslice, Tset, C]) retrievable() error {
if t.Expression.Values.Query != nil {
return fmt.Errorf("inserting from query: %w", orm.ErrCannotRetrieveRow)
}
if len(t.Expression.DuplicateKeyUpdate.Set) > 0 {
return fmt.Errorf("has duplicate key update: %w", orm.ErrCannotRetrieveRow)
}
if t.table.autoIncrementColumn != "" {
return nil
}
if len(t.table.uniqueIdx) > 0 {
return nil
}
return fmt.Errorf("no auto increment column or unique index: %w", orm.ErrCannotRetrieveRow)
}
// inserts all and returns the select query
func (t *insertQuery[T, Ts, Tset, C]) insertAll(ctx context.Context, exec bob.Executor) (bob.Query, error) {
if retrievalErr := t.retrievable(); retrievalErr != nil {
return nil, retrievalErr
}
var err error
// Save the existing values
oldVals := t.Expression.Values.Vals
// Save and clear loaders - they will be transferred to the SELECT query
// This prevents bob.Exec from calling them with nil
loaders := t.Expression.GetLoaders()
t.Expression.SetLoaders()
// Run hooks
ctx, err = t.RunHooks(ctx, exec)
if err != nil {
return nil, err
}
// Clear hooks
t.Expression.SetHooks()
results := make([]sql.Result, len(oldVals))
for i := range oldVals {
rowVals := oldVals[i : i+1]
t.Expression.Values.Vals = rowVals
result, err := bob.Exec(ctx, exec, t.BaseQuery)
if err != nil {
return nil, err
}
results[i] = result
}
// Restore the values
t.Expression.Values.Vals = oldVals
return t.getInserted(oldVals, results, loaders)
}
func (t *insertQuery[T, Tslice, Tset, C]) getInserted(vals []clause.Value, results []sql.Result, loaders []bob.Loader) (bob.Query, error) {
w := &bytes.Buffer{}
if retrievalErr := t.retrievable(); retrievalErr != nil {
return nil, retrievalErr
}
query := Select(sm.Columns(t.table.ColumnsExpr()), sm.From(t.table.NameAs()))
// Change query type to Insert so that the correct hooks are run
query.QueryType = bob.QueryTypeInsert
// Transfer loaders to select query
query.Expression.SetLoaders(loaders...)
var autoIncrArgs []bob.Expression
idArgs := make([][]bob.Expression, len(t.table.uniqueIdx))
for i, val := range vals {
if t.table.autoIncrementColumn != "" && len(t.Expression.DuplicateKeyUpdate.Set) == 0 {
lastID, err := results[i].LastInsertId()
if err != nil {
return nil, err
}
autoIncrArgs = append(autoIncrArgs, Arg(lastID))
} else {
uIdx, uArgs := t.uniqueSet(w, val)
if uIdx == -1 || len(uArgs) == 0 {
return nil, fmt.Errorf("no unique index found: %w", orm.ErrCannotRetrieveRow)
}
idArgs[uIdx] = append(idArgs[uIdx], Group(uArgs...))
}
}
filters := make([]bob.Expression, 0, len(t.table.uniqueIdx))
if len(autoIncrArgs) > 0 {
filters = append(filters, Quote(t.table.autoIncrementColumn).In(autoIncrArgs...))
}
for i, args := range idArgs {
if len(args) == 0 {
continue
}
uCols := t.table.uniqueIdx[i]
if len(uCols) == 1 {
filters = append(filters, Quote(t.table.setterMapping.All[uCols[0]]).In(args...))
continue
}
filters = append(filters, Group(t.table.uniqueColNames(i)...).In(args...))
}
query = query.Apply(sm.Where(Or(filters...)))
return query, nil
}
func uniqueIndexes(allCols []string, uniques ...[]string) [][]int {
var indexes [][]int
for _, unique := range uniques {
index := make([]int, 0, len(unique))
for _, name := range unique {
for i, col := range allCols {
if name == col {
index = append(index, i)
}
}
}
// all columns found
if len(index) == len(unique) {
indexes = append(indexes, index)
}
}
return indexes
}
func isDefaultOrNull(w *bytes.Buffer, e bob.Expression) bool {
w.Reset()
if e == nil {
return true
}
args, err := e.WriteSQL(context.Background(), w, dialect.Dialect, 1)
if err != nil {
return false
}
if len(args) > 0 {
if args[0] == nil {
return true
}
if driverValue, ok := args[0].(driver.Valuer); ok {
if val, _ := driverValue.Value(); val == nil {
return true
}
}
return false
}
s := w.String()
return strings.EqualFold(s, "DEFAULT") || strings.EqualFold(s, "NULL")
}
func (t *insertQuery[T, Tslice, Tset, C]) uniqueSet(w *bytes.Buffer, row []bob.Expression) (int, []bob.Expression) {
Outer:
for whichUnique, unique := range t.table.uniqueIdx {
colVals := make([]bob.Expression, 0, len(unique))
for _, uniqueCol := range unique {
insertColIndex := slices.Index(t.Expression.Columns, t.table.setterMapping.All[uniqueCol])
insertedField := row[insertColIndex]
if insertedField == nil || isDefaultOrNull(w, insertedField) {
continue Outer
}
colVals = append(colVals, insertedField)
}
if len(colVals) == len(unique) {
return whichUnique, colVals
}
}
return -1, nil
}
func (t *Table[T, Tslice, Tset, C]) uniqueColNames(i int) []bob.Expression {
if i < 0 || i >= len(t.uniqueIdx) {
return nil
}
u := t.uniqueIdx[i]
colNames := make([]bob.Expression, len(u))
for i, col := range u {
colNames[i] = Quote(t.setterMapping.All[col])
}
return colNames
}