forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbulk_test.go
97 lines (77 loc) · 2.4 KB
/
bulk_test.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
package sqlstore
import (
"context"
"testing"
"github.com/stretchr/testify/require"
)
type bulkTestItem struct {
ID int64
Value string `xorm:"varchar(10)"`
}
func TestBatching(t *testing.T) {
t.Run("InBatches", func(t *testing.T) {
t.Run("calls fn 0 times if items is empty", func(t *testing.T) {
var calls int
fn := func(batch any) error { calls += 1; return nil }
opts := BulkOpSettings{BatchSize: DefaultBatchSize}
err := InBatches([]int{}, opts, fn)
require.NoError(t, err)
require.Zero(t, calls)
})
t.Run("succeeds if batch size is nonpositive", func(t *testing.T) {
var calls int
fn := func(batch any) error { calls += 1; return nil }
opts := BulkOpSettings{BatchSize: DefaultBatchSize}
err := InBatches([]int{1, 2, 3}, opts, fn)
require.NoError(t, err)
require.Equal(t, 1, calls)
})
t.Run("rejects if items is not a slice", func(t *testing.T) {
var calls int
fn := func(batch any) error { calls += 1; return nil }
opts := BulkOpSettings{BatchSize: DefaultBatchSize}
err := InBatches("lol", opts, fn)
require.Error(t, err)
})
t.Run("calls expected number of times when batch size does not evenly divide length", func(t *testing.T) {
var calls int
fn := func(batch any) error { calls += 1; return nil }
opts := BulkOpSettings{BatchSize: 5}
vals := make([]int, 93)
err := InBatches(vals, opts, fn)
require.NoError(t, err)
require.Equal(t, 19, calls)
})
})
}
func TestIntegrationBulkOps(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
db, _ := InitTestDB(t)
err := db.engine.Sync(new(bulkTestItem))
require.NoError(t, err)
t.Run("insert several records", func(t *testing.T) {
vals := make([]bulkTestItem, 45)
opts := NativeSettingsForDialect(db.GetDialect())
opts.BatchSize = 10
var inserted int64
err := db.WithDbSession(context.Background(), func(sess *DBSession) error {
ins, err := sess.BulkInsert(bulkTestItem{}, vals, opts)
inserted = ins
return err
})
require.NoError(t, err)
require.Equal(t, int64(45), inserted)
assertTableCount(t, db, bulkTestItem{}, 45)
})
}
func assertTableCount(t *testing.T, db *SQLStore, table any, expCount int64) {
t.Helper()
err := db.WithDbSession(context.Background(), func(sess *DBSession) error {
total, err := sess.Table(bulkTestItem{}).Count()
require.Equal(t, expCount, total)
return err
})
require.NoError(t, err)
}