-
Notifications
You must be signed in to change notification settings - Fork 6
/
table_helpers.go
302 lines (245 loc) · 7.07 KB
/
table_helpers.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
package mybench
import (
"fmt"
"math"
"strings"
"sync"
"github.com/sirupsen/logrus"
)
func QuestionMarksStringList(n int) string {
s := strings.Repeat("?,", n)
return s[:len(s)-1]
}
type Column struct {
// Name of the column
Name string
// SQL definition of the column
Definition string
// The data generator for the data of this column.
Generator DataGenerator
}
// This struct provides helpers for creating and seeding a table.
type Table struct {
// The name of the table
Name string
// The list of columns. The order of the columns in the table follows the
// order of this slice.
Columns []*Column
// The columns for the primary key for the table. This is a slice as it
// supports a composite primary key.
PrimaryKey []string
// A list of columns for indices.
Indices [][]string
// A list of columns for unique indices.
UniqueKeys [][]string
// Additional table options appended to the end of the CREATE TABLE
// statements, such as compression settings, auto increment settings, and so
// on.
TableOptions string
columnsMap map[string]*Column
}
func InitializeTable(t Table) Table {
t.columnsMap = make(map[string]*Column)
for _, column := range t.Columns {
t.columnsMap[column.Name] = column
}
return t
}
func (t Table) Generate(r *Rand, column string) interface{} {
return t.columnsMap[column].Generator.Generate(r)
}
func (t Table) SampleFromExisting(r *Rand, column string) interface{} {
return t.columnsMap[column].Generator.SampleFromExisting(r)
}
func (t Table) CreateTableQuery() string {
var buf strings.Builder
buf.WriteString(fmt.Sprintf("CREATE TABLE `%s` (", t.Name))
for _, column := range t.Columns {
buf.WriteString(fmt.Sprintf("`%s` %s", column.Name, column.Definition))
buf.WriteString(",")
}
buf.WriteString("PRIMARY KEY (")
for i, column := range t.PrimaryKey {
buf.WriteString(fmt.Sprintf("`%s`", column))
if i < len(t.PrimaryKey)-1 {
buf.WriteString(",")
}
}
buf.WriteString(")")
if len(t.Indices) > 0 {
buf.WriteString(",")
for i, index := range t.Indices {
buf.WriteString(fmt.Sprintf("KEY (%s)", strings.Join(index, ",")))
if i < len(t.Indices)-1 {
buf.WriteString(",")
}
}
}
if len(t.UniqueKeys) > 0 {
buf.WriteString(",")
for i, index := range t.UniqueKeys {
buf.WriteString(fmt.Sprintf("UNIQUE KEY (%s)", strings.Join(index, ",")))
if i < len(t.UniqueKeys)-1 {
buf.WriteString(",")
}
}
}
buf.WriteString(")")
if t.TableOptions != "" {
buf.WriteString(" ")
buf.WriteString(t.TableOptions)
}
return buf.String()
}
func (t Table) DropTableQuery() string {
return fmt.Sprintf("DROP TABLE IF EXISTS `%s`", t.Name)
}
func (t Table) InsertQuery(r *Rand, batchSize int, valueOverride map[string]interface{}) (string, []interface{}) {
var buf strings.Builder
buf.WriteString(fmt.Sprintf("INSERT INTO `%s` (", t.Name))
for i, column := range t.Columns {
buf.WriteString("`" + column.Name + "`")
if i < len(t.Columns)-1 {
buf.WriteString(",")
}
}
buf.WriteString(") VALUES ")
questionMarks := strings.Repeat("?,", len(t.Columns))
questionMarks = "(" + questionMarks[:len(questionMarks)-1] + "),"
questionMarks = strings.Repeat(questionMarks, batchSize)
questionMarks = questionMarks[:len(questionMarks)-1]
buf.WriteString(questionMarks)
args := make([]interface{}, 0, len(t.Columns)*batchSize)
for i := 0; i < batchSize; i++ {
for _, column := range t.Columns {
var value interface{}
if valueOverride != nil {
v, found := valueOverride[column.Name]
if found {
value = v
} else {
value = column.Generator.Generate(r)
}
} else {
value = column.Generator.Generate(r)
}
args = append(args, value)
}
}
return buf.String(), args
}
func (t Table) InsertQueryList(r *Rand, valueOverrides []map[string]interface{}) (string, []interface{}) {
var buf strings.Builder
buf.WriteString(fmt.Sprintf("INSERT INTO `%s` (", t.Name))
for i, column := range t.Columns {
buf.WriteString("`" + column.Name + "`")
if i < len(t.Columns)-1 {
buf.WriteString(",")
}
}
buf.WriteString(") VALUES ")
questionMarks := strings.Repeat("?,", len(t.Columns))
questionMarks = "(" + questionMarks[:len(questionMarks)-1] + "),"
questionMarks = strings.Repeat(questionMarks, len(valueOverrides))
questionMarks = questionMarks[:len(questionMarks)-1]
buf.WriteString(questionMarks)
args := make([]interface{}, 0, len(t.Columns)*len(valueOverrides))
for _, valueOverride := range valueOverrides {
for _, column := range t.Columns {
var value interface{}
if valueOverride != nil {
v, found := valueOverride[column.Name]
if found {
value = v
} else {
value = column.Generator.Generate(r)
}
} else {
value = column.Generator.Generate(r)
}
args = append(args, value)
}
}
return buf.String(), args
}
// Drop and recreate the table with data seeded via the data generators.
//
// totalrows specifies the total number of rows to insert into the new table.
// batchSize controls how many rows to insert in one INSERT statement (200 is
// usually a good starting point), concurrency is the number of goroutines used
// to insert the data.
//
// If concurrency is 0, it is set by default to 16. This allows the loader to
// reuse the -concurrency flag (which is default 0).
func (t Table) ReloadData(databaseConfig DatabaseConfig, totalrows int64, batchSize int64, concurrency int) {
if concurrency <= 0 { // apply default if no valid concurrency is given
concurrency = 16
}
logger := logrus.WithFields(logrus.Fields{
"table": t.Name,
"totalrows": totalrows,
})
logger.WithFields(logrus.Fields{
"batchSize": batchSize,
"concurrency": concurrency,
}).Info("reloading data")
conn, err := databaseConfig.Connection()
if err != nil {
panic(err)
}
defer conn.Close()
_, err = conn.Execute(t.DropTableQuery())
if err != nil {
panic(err)
}
_, err = conn.Execute(t.CreateTableQuery())
if err != nil {
panic(err)
}
wg := &sync.WaitGroup{}
batchSizeChan := make(chan int64)
wg.Add(concurrency)
for i := 0; i < concurrency; i++ {
go func() {
defer wg.Done()
conn, err := databaseConfig.Connection()
if err != nil {
panic(err)
}
defer conn.Close()
r := NewRand()
for {
batchSize, open := <-batchSizeChan
if !open {
return
}
query, args := t.InsertQuery(r, int(batchSize), nil)
_, err = conn.Execute(query, args...)
if err != nil {
logger.WithFields(logrus.Fields{
"query": query,
"args": args,
}).Error(err)
panic(err)
}
}
}()
}
rowsInserted := int64(0)
lastLoggedPct := -1.0
for rowsInserted < totalrows {
if totalrows-rowsInserted < batchSize {
batchSize = totalrows - rowsInserted
}
pct := float64(rowsInserted) / float64(totalrows) * 100
if pct-lastLoggedPct > 1 {
lastLoggedPct = pct
logger.WithFields(logrus.Fields{"pct": math.Round(pct*100) / 100.0, "rowsInserted": rowsInserted}).Info("loading data")
}
batchSizeChan <- batchSize
rowsInserted += batchSize
}
close(batchSizeChan)
wg.Wait()
logger.WithFields(logrus.Fields{"pct": 100.0, "rowsInserted": rowsInserted}).Info("data reloaded")
}