-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmanager.go
executable file
·647 lines (588 loc) · 23.2 KB
/
manager.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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
package dsc
import (
"database/sql"
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/viant/toolbox"
)
var defaultBatchSize = 512
var BulkInsertAllType = "insertAll"
var UnionSelectInsert = "unionSelectInsert"
var CopyLocalInsert = "copyLocalInsert"
// AbstractManager represent general abstraction for datastore implementation.
// Note that ExecuteOnConnection, ReadAllOnWithHandlerOnConnection may need to be implemented for particular datastore.
type AbstractManager struct {
Manager
config *Config
connectionProvider ConnectionProvider
tableDescriptorRegistry TableDescriptorRegistry
limiter *Limiter
}
// Config returns a config.
func (m *AbstractManager) Config() *Config {
return m.config
}
// ConnectionProvider returns a connection provider.
func (m *AbstractManager) ConnectionProvider() ConnectionProvider {
return m.connectionProvider
}
// Execute executes passed in sql with parameters. It returns sql result, or an error.
func (m *AbstractManager) Execute(sql string, sqlParameters ...interface{}) (result sql.Result, err error) {
var connection Connection
connection, err = m.Manager.ConnectionProvider().Get()
if err != nil {
return nil, err
}
defer connection.Close()
return m.Manager.ExecuteOnConnection(connection, sql, sqlParameters)
}
// ExecuteAll passed in SQL. It returns sql result, or an error.
func (m *AbstractManager) ExecuteAll(sqls []string) ([]sql.Result, error) {
connection, err := m.Manager.ConnectionProvider().Get()
if err != nil {
return nil, err
}
defer connection.Close()
return m.Manager.ExecuteAllOnConnection(connection, sqls)
}
// Acquire if max request per second is specified this function will throttle any request exceeding specified max
func (m *AbstractManager) Acquire() {
if m.config.MaxRequestPerSecond == 0 {
return
}
m.limiter.Acquire()
}
// ExecuteAllOnConnection executes passed in SQL on connection. It returns sql result, or an error.
func (m *AbstractManager) ExecuteAllOnConnection(connection Connection, sqls []string) ([]sql.Result, error) {
var result = make([]sql.Result, len(sqls))
err := connection.Begin()
if err != nil {
return nil, err
}
defer func() {
if err == nil {
connection.Commit()
}
if err != nil {
connection.Rollback()
}
}()
for i, sql := range sqls {
var err error
result[i], err = m.Manager.ExecuteOnConnection(connection, sql, nil)
if err != nil {
return result, err
}
}
return result, nil
}
// ReadAllWithHandler executes query with parameters and for each fetch row call reading handler with a scanner, to continue reading next row, scanner needs to return true.
func (m *AbstractManager) ReadAllWithHandler(query string, queryParameters []interface{}, readingHandler func(scanner Scanner) (toContinue bool, err error)) error {
connection, err := m.Manager.ConnectionProvider().Get()
if err != nil {
return err
}
defer connection.Close()
return m.Manager.ReadAllOnWithHandlerOnConnection(connection, query, queryParameters, readingHandler)
}
// ReadAll executes query with parameters and fetches all table rows. The row is mapped to result slice pointer with record mapper.
func (m AbstractManager) ReadAll(resultSlicePointer interface{}, query string, queryParameters []interface{}, mapper RecordMapper) error {
connection, err := m.Manager.ConnectionProvider().Get()
if err != nil {
return err
}
defer connection.Close()
return m.Manager.ReadAllOnConnection(connection, resultSlicePointer, query, queryParameters, mapper)
}
// ReadAllOnConnection executes query with parameters on passed in connection and fetches all table rows. The row is mapped to result slice pointer with record mapper.
func (m *AbstractManager) ReadAllOnConnection(connection Connection, resultSlicePointer interface{}, query string, queryParameters []interface{}, mapper RecordMapper) error {
toolbox.AssertPointerKind(resultSlicePointer, reflect.Slice, "resultSlicePointer")
slice := reflect.ValueOf(resultSlicePointer).Elem()
if mapper == nil {
mapper = NewRecordMapperIfNeeded(mapper, reflect.TypeOf(resultSlicePointer).Elem().Elem())
}
err := m.Manager.ReadAllOnWithHandlerOnConnection(connection, query, queryParameters, func(scannalbe Scanner) (toContinue bool, err error) {
mapped, providerError := mapper.Map(scannalbe)
if providerError != nil {
return false, fmt.Errorf("failed to map row sql: %v due to %v", query, providerError.Error())
}
if mapped != nil {
//only add to slice i
mappedValue := reflect.ValueOf(mapped)
if reflect.TypeOf(resultSlicePointer).Elem().Kind() == reflect.Slice && reflect.TypeOf(resultSlicePointer).Elem().Elem().Kind() != mappedValue.Kind() {
if mappedValue.Kind() == reflect.Ptr {
mappedValue = mappedValue.Elem()
}
}
slice.Set(reflect.Append(slice, mappedValue))
}
return true, nil
})
return err
}
// ReadSingle executes query with parameters and reads on connection single table row. The row is mapped to result pointer with record mapper.
func (m *AbstractManager) ReadSingle(resultPointer interface{}, query string, queryParameters []interface{}, mapper RecordMapper) (success bool, err error) {
connection, err := m.Manager.ConnectionProvider().Get()
if err != nil {
return false, err
}
defer connection.Close()
return m.Manager.ReadSingleOnConnection(connection, resultPointer, query, queryParameters, mapper)
}
// ReadSingleOnConnection executes query with parameters on passed in connection and reads single table row. The row is mapped to result pointer with record mapper.
func (m *AbstractManager) ReadSingleOnConnection(connection Connection, resultPointer interface{}, query string, queryParameters []interface{}, mapper RecordMapper) (success bool, err error) {
toolbox.AssertKind(resultPointer, reflect.Ptr, "resultStruct")
if mapper == nil {
mapper = NewRecordMapperIfNeeded(mapper, reflect.TypeOf(resultPointer).Elem())
}
var mapped interface{}
var elementType = reflect.TypeOf(resultPointer).Elem()
err = m.Manager.ReadAllOnWithHandlerOnConnection(connection, query, queryParameters, func(scanner Scanner) (toContinue bool, err error) {
mapped, err = mapper.Map(scanner)
if err != nil {
return false, fmt.Errorf("failed to map record: %v with %T due to %v", query, mapper, err)
}
if mapped != nil {
if elementType.Kind() == reflect.Slice {
slice := reflect.ValueOf(resultPointer).Elem()
toolbox.ProcessSlice(mapped, func(item interface{}) bool {
if item == nil {
slice.Set(reflect.Append(slice, reflect.Zero(elementType)))
return true
}
slice.Set(reflect.Append(slice, reflect.ValueOf(item)))
return true
})
} else if elementType.Kind() == reflect.Map {
if err = toolbox.ProcessMap(mapped, func(key, value interface{}) bool {
aMap := reflect.ValueOf(resultPointer).Elem()
aMap.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(value))
return true
}); err != nil {
return false, err
}
} else {
if reflect.ValueOf(mapped).Kind() == reflect.Ptr {
mapped = reflect.ValueOf(mapped).Elem().Interface()
}
reflect.ValueOf(resultPointer).Elem().Set(reflect.ValueOf(mapped))
}
success = true
}
return false, nil
})
return success, err
}
// PersistAll persists all table rows, dmlProvider is used to generate insert or update statement. It returns number of inserted, updated or error.
// If driver allows this operation is executed in one transaction.
func (m *AbstractManager) PersistAll(dataPointer interface{}, table string, provider DmlProvider) (int, int, error) {
connection, err := m.Manager.ConnectionProvider().Get()
if err != nil {
return 0, 0, err
}
defer connection.Close()
err = connection.Begin()
if err != nil {
return 0, 0, fmt.Errorf("failed to start transaction on %v due to %v", m.config.Descriptor, err)
}
inserted, updated, err := m.Manager.PersistAllOnConnection(connection, dataPointer, table, provider)
if err == nil {
commitErr := connection.Commit()
if commitErr != nil {
return 0, 0, fmt.Errorf("failed to commit on %v due to %v", m.config.Descriptor, commitErr)
}
} else {
rollbackErr := connection.Rollback()
if rollbackErr != nil {
return 0, 0, fmt.Errorf("failed to rollback on %v due to %v, %v", m.config.Descriptor, err, rollbackErr)
}
}
return inserted, updated, err
}
// RegisterDescriptorIfNeeded register a table descriptor if there it is not present, returns a pointer to a table descriptor.
func (m *AbstractManager) RegisterDescriptorIfNeeded(table string, instance interface{}) (*TableDescriptor, error) {
if !m.tableDescriptorRegistry.Has(table) {
descriptor, err := NewTableDescriptor(table, instance)
if err != nil {
return nil, err
}
_ = m.tableDescriptorRegistry.Register(descriptor)
}
var result = m.tableDescriptorRegistry.Get(table)
if result != nil {
return result, nil
}
return nil, fmt.Errorf("failed to lookup descriptor for table: %v", table)
}
// PersistAllOnConnection persists on connection all table rows, dmlProvider is used to generate insert or update statement. It returns number of inserted, updated or error.
func (m *AbstractManager) PersistAllOnConnection(connection Connection, dataPointer interface{}, table string, provider DmlProvider) (inserted int, updated int, err error) {
if ranger, isRanger := dataPointer.(toolbox.Ranger); isRanger {
collection := toolbox.AsSlice(ranger)
dataPointer = &collection
} else if iterator, isRanger := dataPointer.(toolbox.Iterator); isRanger {
collection := toolbox.AsSlice(iterator)
dataPointer = &collection
}
toolbox.AssertPointerKind(dataPointer, reflect.Slice, "resultSlicePointer")
structType := reflect.TypeOf(dataPointer).Elem().Elem()
provider, err = NewDmlProviderIfNeeded(provider, table, structType)
if err != nil {
return 0, 0, err
}
descriptor, err := m.RegisterDescriptorIfNeeded(table, dataPointer)
if err != nil {
return 0, 0, err
}
insertables, updatables, err := m.Manager.ClassifyDataAsInsertableOrUpdatable(connection, dataPointer, table, provider)
if err != nil {
return 0, 0, err
}
var isStructPointer = structType.Kind() == reflect.Ptr
var insertableMapping map[int]int
if descriptor.Autoincrement {
//we need to store original position of item, vs insertables, to set back autoincrement changed item to original slice
insertableMapping = make(map[int]int)
toolbox.ProcessSliceWithIndex(dataPointer, func(index int, value interface{}) bool {
for j, insertable := range insertables {
if isStructPointer {
if insertable == value {
insertableMapping[j] = index
break
}
} else {
if reflect.DeepEqual(insertable, value) {
insertableMapping[j] = index
break
}
}
}
return true
})
}
inserted, insertErr := m.Manager.PersistData(connection, insertables, table, provider, func(item interface{}) *ParametrizedSQL {
return provider.Get(SQLTypeInsert, item)
})
if insertErr != nil {
return 0, 0, insertErr
}
if descriptor.Autoincrement {
for k, v := range insertableMapping {
value := insertables[k]
toolbox.SetSliceValue(dataPointer, v, value)
}
}
updated, updateErr := m.Manager.PersistData(connection, updatables, table, provider, func(item interface{}) *ParametrizedSQL {
return provider.Get(SQLTypeUpdate, item)
})
if updateErr != nil {
return 0, 0, updateErr
}
return inserted, updated, nil
}
// PersistSingle persists single table row, dmlProvider is used to generate insert or update statement. It returns number of inserted, updated or error.
func (m *AbstractManager) PersistSingle(dataPointer interface{}, table string, provider DmlProvider) (inserted int, updated int, err error) {
slice := convertToTypesSlice(dataPointer)
inserted, updated, err = m.Manager.PersistAll(slice, table, provider)
if err != nil {
return 0, 0, err
}
if inserted > 0 {
descriptor, err := m.RegisterDescriptorIfNeeded(table, dataPointer)
if err != nil {
return 0, 0, err
}
if descriptor.Autoincrement {
value := toolbox.GetSliceValue(slice, 0)
reflect.ValueOf(dataPointer).Elem().Set(reflect.ValueOf(value))
}
}
return inserted, updated, err
}
// PersistSingleOnConnection persists on connection single table row, dmlProvider is used to generate insert or udpate statement. It returns number of inserted, updated or error.
func (m *AbstractManager) PersistSingleOnConnection(connection Connection, dataPointer interface{}, table string, provider DmlProvider) (inserted int, updated int, err error) {
slice := []interface{}{dataPointer}
return m.Manager.PersistAllOnConnection(connection, &slice, table, provider)
}
// PersistData batch data on connection on table, keySetter is used to optionally set autoincrement column, sqlProvider handler will generate ParametrizedSQL with Insert or Update statement.
func (m *AbstractManager) PersistData(connection Connection, data interface{}, table string, keySetter KeySetter, sqlProvider func(item interface{}) *ParametrizedSQL) (int, error) {
var collection = make([]interface{}, 0)
updateId := func(index int, seq int64) {
if seq == 0 || index < 0 {
return
}
var ptrType = false
dataType := reflect.TypeOf(collection[index])
itemValue := reflect.ValueOf(collection[index])
if dataType.Kind() == reflect.Ptr {
dataType = dataType.Elem()
ptrType = true
}
if itemValue.Kind() == reflect.Ptr {
itemValue = itemValue.Elem()
ptrType = true
}
structPointerValue := reflect.New(dataType)
reflect.Indirect(structPointerValue).Set(itemValue)
if keySetter != nil {
keySetter.SetKey(structPointerValue.Interface(), seq)
}
if ptrType {
collection[index] = structPointerValue.Interface()
} else {
collection[index] = structPointerValue.Elem().Interface()
}
}
var batch = newBatch(table, connection, m, sqlProvider, updateId)
var err error
if ranger, ok := data.(toolbox.Ranger); ok {
err = ranger.Range(func(item interface{}) (b bool, e error) {
err = batch.persist(-1, item)
return err == nil, err
})
} else if iterator, ok := data.(toolbox.Iterator); ok {
for iterator.HasNext() && err == nil {
var item interface{}
if err = iterator.Next(&item); err == nil {
err = batch.persist(-1, item)
}
}
} else if toolbox.IsSlice(data) {
collection = toolbox.AsSlice(data)
for i, item := range collection {
if err = batch.persist(i, item); err != nil {
break
}
}
}
if batch != nil && err == nil {
if _, err := batch.flush(); err != nil {
return 0, err
}
}
return batch.processed, err
}
func (m *AbstractManager) fetchDataInBatches(connection Connection, sqlsWihtArguments []*ParametrizedSQL, mapper RecordMapper) (*[][]interface{}, error) {
var rows = make([][]interface{}, 0)
for _, sqlWihtArguments := range sqlsWihtArguments {
if len(sqlWihtArguments.Values) == 0 {
break
}
err := m.Manager.ReadAllOnConnection(connection, &rows, sqlWihtArguments.SQL, sqlWihtArguments.Values, mapper)
if err != nil {
return nil, err
}
}
return &rows, nil
}
func (m *AbstractManager) fetchExistingData(connection Connection, table string, pkValues [][]interface{}, provider DmlProvider) ([][]interface{}, error) {
var rows = make([][]interface{}, 0)
descriptor := m.tableDescriptorRegistry.Get(table)
if len(pkValues) > 0 {
descriptor := TableDescriptor{Table: table, PkColumns: descriptor.PkColumns}
sqlBuilder := NewQueryBuilder(&descriptor, "")
sqlWithArguments := sqlBuilder.BuildBatchedQueryOnPk(descriptor.PkColumns, pkValues, defaultBatchSize)
var mapper = NewColumnarRecordMapper(false, reflect.TypeOf(rows))
batched, err := m.fetchDataInBatches(connection, sqlWithArguments, mapper)
if err != nil {
return nil, err
}
rows = append(rows, (*batched)...)
}
return rows, nil
}
// ClassifyDataAsInsertableOrUpdatable classifies passed in data as insertable or updatable.
func (m *AbstractManager) ClassifyDataAsInsertableOrUpdatable(connection Connection, dataPointer interface{}, table string, provider DmlProvider) ([]interface{}, []interface{}, error) {
if provider == nil {
return nil, nil, errors.New("provider was nil")
}
var rowsByKey = make(map[string]interface{}, 0)
var candidates, insertables, updatables = make([]interface{}, 0), make([]interface{}, 0), make([]interface{}, 0)
var pkValues = make([][]interface{}, 0)
hasPK := len(m.tableDescriptorRegistry.Get(table).PkColumns) > 0
toolbox.ProcessSlice(dataPointer, func(row interface{}) bool {
var pkValueForThisRow = provider.Key(row)
for _, v := range pkValueForThisRow {
if v == nil { //if pk value null, this row has to be insertable
insertables = append(insertables, row)
return true
}
}
candidates = append(candidates, row)
key := toolbox.JoinAsString(pkValueForThisRow, "")
pkValues = append(pkValues, pkValueForThisRow)
rowsByKey[key] = row
return true
})
if hasPK { //only if has PK, otherwise always insert
//fetch all existing pk values into rows to classify as updatable
rows, err := m.fetchExistingData(connection, table, pkValues, provider)
if err != nil {
return nil, nil, fmt.Errorf("failed to fetch existing data: due to:\n\t%v", err.Error())
}
//process existing rows and add mapped entires as updatables
for _, row := range rows {
key := toolbox.JoinAsString(row, "")
if instance, ok := rowsByKey[key]; ok {
updatables = append(updatables, instance)
delete(rowsByKey, key)
}
}
}
//go over all candidates and if no key or entries still found in rows by key then classify as insertable
for _, candidate := range candidates {
var values = provider.Key(candidate)
key := toolbox.JoinAsString(values, "")
if _, ok := rowsByKey[key]; ok {
insertables = append(insertables, candidate)
}
}
return insertables, updatables, nil
}
// DeleteAll deletes all rows for passed in table, key provider is used to extract primary keys. It returns number of deleted rows or error.
func (m *AbstractManager) DeleteAll(dataPointer interface{}, table string, keyProvider KeyGetter) (deleted int, err error) {
connection, err := m.Manager.ConnectionProvider().Get()
if err != nil {
return 0, err
}
defer connection.Close()
err = connection.Begin()
if err != nil {
return 0, fmt.Errorf("failed to start transaction on %v due to %v", m.config.Descriptor, err)
}
deleted, err = m.DeleteAllOnConnection(connection, dataPointer, table, keyProvider)
if err == nil {
commitErr := connection.Commit()
if commitErr != nil {
return 0, fmt.Errorf("failed to commit on %v due to %v", m.config.Descriptor, commitErr)
}
} else {
rollbackErr := connection.Rollback()
if rollbackErr != nil {
return 0, fmt.Errorf("failed to rollback on %v due to %v, %v", m.config.Descriptor, err, rollbackErr)
}
}
return deleted, err
}
// DeleteAllOnConnection deletes all rows on connection from table, key provider is used to extract primary keys. It returns number of deleted rows or error.
// If driver allows this operation is executed in one transaction.
func (m *AbstractManager) DeleteAllOnConnection(connection Connection, dataPointer interface{}, table string, keyProvider KeyGetter) (deleted int, err error) {
deleted = 0
structType := toolbox.DiscoverTypeByKind(dataPointer, reflect.Struct)
keyProvider, err = NewKeyGetterIfNeeded(keyProvider, table, structType)
if err != nil {
return 0, err
}
m.RegisterDescriptorIfNeeded(table, dataPointer)
descriptor := m.tableDescriptorRegistry.Get(table)
toolbox.ProcessSlice(dataPointer, func(item interface{}) bool {
if err != nil {
return false
}
where := m.buildPKWhere(descriptor)
if len(descriptor.PkColumns) > 1 {
values := strings.Repeat("?,", len(descriptor.PkColumns))
values = values[0 : len(values)-1]
where = where + " IN (" + values + ")"
} else {
where = where + " = ?"
}
dml := fmt.Sprintf(deleteSQLTemplate, table, where)
var result sql.Result
result, err = m.Manager.ExecuteOnConnection(connection, dml, keyProvider.Key(item))
if err != nil {
return false
}
var affected int64
affected, err = result.RowsAffected()
if err == nil {
deleted = deleted + int(affected)
}
return true
})
if err != nil {
return 0, err
}
return deleted, nil
}
func (m *AbstractManager) buildPKWhere(descriptor *TableDescriptor) string {
var pk = descriptor.PkColumns
updateReserved(pk)
where := strings.Join(pk, ",")
return where
}
// DeleteSingle deletes single row from table on for passed in data pointer, key provider is used to extract primary keys. It returns boolean if successful, or error.
func (m *AbstractManager) DeleteSingle(dataPointer interface{}, table string, keyProvider KeyGetter) (bool, error) {
connection, err := m.Manager.ConnectionProvider().Get()
if err != nil {
return false, err
}
defer connection.Close()
err = connection.Begin()
if err != nil {
return false, fmt.Errorf("failed to start transaction on %v due to %v", m.config.Descriptor, err)
}
suceess, err := m.DeleteSingleOnConnection(connection, dataPointer, table, keyProvider)
if err == nil {
commitErr := connection.Commit()
if commitErr != nil {
return false, fmt.Errorf("failed to commit on %v due to %v", m.config.Descriptor, commitErr)
}
} else {
rollbackErr := connection.Rollback()
if rollbackErr != nil {
return false, fmt.Errorf("failed to rollback on %v due to %v, %v", m.config.Descriptor, err, rollbackErr)
}
}
return suceess, err
}
func convertToTypesSlice(dataPointer interface{}) interface{} {
toolbox.AssertPointerKind(dataPointer, reflect.Struct, "slicePointer")
sliceValue := reflect.ValueOf(toolbox.DereferenceValue(dataPointer))
sliceType := reflect.SliceOf(sliceValue.Type())
slicePointer := reflect.New(sliceType)
slice := slicePointer.Elem()
slice.Set(reflect.Append(slice, sliceValue))
return slicePointer.Interface()
}
// DeleteSingleOnConnection deletes data on connection from table on for passed in data pointer, key provider is used to extract primary keys. It returns true if successful.
func (m *AbstractManager) DeleteSingleOnConnection(connection Connection, dataPointer interface{}, table string, keyProvider KeyGetter) (bool, error) {
toolbox.AssertPointerKind(dataPointer, reflect.Struct, "dataPointer")
slice := convertToTypesSlice(dataPointer)
deleted, err := m.Manager.DeleteAllOnConnection(connection, slice, table, keyProvider)
if err != nil {
return false, err
}
return deleted == 1, nil
}
// ExpandSQL expands sql with passed in arguments
func (m *AbstractManager) ExpandSQL(sql string, arguments []interface{}) string {
for _, arg := range arguments {
stringArg := toolbox.AsString(arg)
if arg == nil {
stringArg = "NULL"
} else {
if toolbox.IsString(arg) || toolbox.CanConvertToString(arg) {
stringArg = "'" + stringArg + "'"
}
}
sql = strings.Replace(sql, "?", stringArg, 1)
}
return sql
}
// TableDescriptorRegistry returns a table descriptor registry
func (m *AbstractManager) TableDescriptorRegistry() TableDescriptorRegistry {
return m.tableDescriptorRegistry
}
// NewAbstractManager create a new abstract manager, it takes config, conneciton provider, and target (sub class) manager
func NewAbstractManager(config *Config, connectionProvider ConnectionProvider, self Manager) *AbstractManager {
var descriptorRegistry = newTableDescriptorRegistry()
var result = &AbstractManager{config: config, connectionProvider: connectionProvider, Manager: self, tableDescriptorRegistry: descriptorRegistry}
descriptorRegistry.manager = result
if config.MaxRequestPerSecond > 0 {
result.limiter = NewLimiter(time.Second, config.MaxRequestPerSecond)
}
return result
}