MCPcopy
hub / github.com/go-gorm/gorm / CreateInBatches

Method CreateInBatches

finisher_api.go:30–82  ·  view source on GitHub ↗

CreateInBatches inserts value in batches of batchSize

(value interface{}, batchSize int)

Source from the content-addressed store, hash-verified

28
29// CreateInBatches inserts value in batches of batchSize
30func (db *DB) CreateInBatches(value interface{}, batchSize int) (tx *DB) {
31 reflectValue := reflect.Indirect(reflect.ValueOf(value))
32
33 switch reflectValue.Kind() {
34 case reflect.Slice, reflect.Array:
35 var rowsAffected int64
36 tx = db.getInstance()
37
38 // the reflection length judgment of the optimized value
39 reflectLen := reflectValue.Len()
40
41 callFc := func(tx *DB) error {
42 for i := 0; i < reflectLen; i += batchSize {
43 ends := i + batchSize
44 if ends > reflectLen {
45 ends = reflectLen
46 }
47
48 subtx := tx.getInstance()
49 batchSlice := reflect.New(reflectValue.Type())
50 batchSlice.Elem().Set(reflectValue.Slice(i, ends))
51 subtx.Statement.Dest = batchSlice.Interface()
52
53 subtx.callbacks.Create().Execute(subtx)
54
55 if subtx.Error != nil {
56 return subtx.Error
57 }
58
59 resultSlice := reflect.Indirect(batchSlice)
60 for j := 0; j < resultSlice.Len(); j++ {
61 reflectValue.Index(i + j).Set(resultSlice.Index(j))
62 }
63
64 rowsAffected += subtx.RowsAffected
65 }
66 return nil
67 }
68
69 if tx.SkipDefaultTransaction || reflectLen <= batchSize {
70 tx.AddError(callFc(tx.Session(&Session{})))
71 } else {
72 tx.AddError(tx.Transaction(callFc))
73 }
74
75 tx.RowsAffected = rowsAffected
76 default:
77 tx = db.getInstance()
78 tx.Statement.Dest = value
79 tx = tx.callbacks.Create().Execute(tx)
80 }
81 return
82}
83
84// Save updates value in database. If value doesn't contain a matching primary key, value is inserted.
85func (db *DB) Save(value interface{}) (tx *DB) {

Callers 1

CreateMethod · 0.95

Calls 10

getInstanceMethod · 0.95
LenMethod · 0.80
ExecuteMethod · 0.80
SessionMethod · 0.80
TransactionMethod · 0.80
NewMethod · 0.65
TypeMethod · 0.65
SetMethod · 0.65
CreateMethod · 0.65
AddErrorMethod · 0.65

Tested by

no test coverage detected