forked from Shopify/ghostferry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cursor.go
305 lines (247 loc) · 7.82 KB
/
cursor.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
package ghostferry
import (
sqlorig "database/sql"
"fmt"
sql "github.com/Shopify/ghostferry/sqlwrapper"
"strings"
"github.com/Masterminds/squirrel"
"github.com/go-mysql-org/go-mysql/schema"
"github.com/sirupsen/logrus"
)
// both `sql.Tx` and `sql.DB` allow a SQL query to be `Prepare`d
type SqlPreparer interface {
Prepare(string) (*sqlorig.Stmt, error)
}
type SqlDBWithFakeRollback struct {
*sql.DB
}
func (d *SqlDBWithFakeRollback) Rollback() error {
return nil
}
// sql.DB does not implement Rollback, but can use SqlDBWithFakeRollback
// to perform a noop.
type SqlPreparerAndRollbacker interface {
SqlPreparer
Rollback() error
}
type CursorConfig struct {
DB *sql.DB
Throttler Throttler
ColumnsToSelect []string
BuildSelect func([]string, *TableSchema, uint64, uint64) (squirrel.SelectBuilder, error)
// BatchSize is a pointer to the BatchSize in Config.UpdatableConfig which can be independently updated from this code.
// Having it as a pointer allows the updated value to be read without needing additional code to copy the batch size value into the cursor config for each cursor we create.
BatchSize *uint64
BatchSizePerTableOverride *DataIterationBatchSizePerTableOverride
ReadRetries int
}
// returns a new Cursor with an embedded copy of itself
func (c *CursorConfig) NewCursor(table *TableSchema, startPaginationKey, maxPaginationKey uint64) *Cursor {
return &Cursor{
CursorConfig: *c,
Table: table,
MaxPaginationKey: maxPaginationKey,
RowLock: true,
lastSuccessfulPaginationKey: startPaginationKey,
}
}
// returns a new Cursor with an embedded copy of itself
func (c *CursorConfig) NewCursorWithoutRowLock(table *TableSchema, startPaginationKey, maxPaginationKey uint64) *Cursor {
cursor := c.NewCursor(table, startPaginationKey, maxPaginationKey)
cursor.RowLock = false
return cursor
}
func (c CursorConfig) GetBatchSize(schemaName string, tableName string) uint64 {
if c.BatchSizePerTableOverride != nil {
if batchSize, found := c.BatchSizePerTableOverride.TableOverride[schemaName][tableName]; found {
return batchSize
}
}
return *c.BatchSize
}
type Cursor struct {
CursorConfig
Table *TableSchema
MaxPaginationKey uint64
RowLock bool
paginationKeyColumn *schema.TableColumn
lastSuccessfulPaginationKey uint64
logger *logrus.Entry
}
func (c *Cursor) Each(f func(*RowBatch) error) error {
c.logger = logrus.WithFields(logrus.Fields{
"table": c.Table.String(),
"tag": "cursor",
})
c.paginationKeyColumn = c.Table.GetPaginationColumn()
if len(c.ColumnsToSelect) == 0 {
c.ColumnsToSelect = []string{"*"}
}
for c.lastSuccessfulPaginationKey < c.MaxPaginationKey {
var tx SqlPreparerAndRollbacker
var batch *RowBatch
var paginationKeypos uint64
err := WithRetries(c.ReadRetries, 0, c.logger, "fetch rows", func() (err error) {
if c.Throttler != nil {
WaitForThrottle(c.Throttler)
}
// Only need to use a transaction if RowLock == true. Otherwise
// we'd be wasting two extra round trips per batch, doing
// essentially a no-op.
if c.RowLock {
tx, err = c.DB.Begin()
if err != nil {
return err
}
} else {
tx = &SqlDBWithFakeRollback{c.DB}
}
batch, paginationKeypos, err = c.Fetch(tx)
if err == nil {
return nil
}
tx.Rollback()
return err
})
if err != nil {
return err
}
if batch.Size() == 0 {
tx.Rollback()
c.logger.Debug("did not reach max primary key, but the table is complete as there are no more rows")
break
}
if paginationKeypos <= c.lastSuccessfulPaginationKey {
tx.Rollback()
err = fmt.Errorf("new paginationKeypos %d <= lastSuccessfulPaginationKey %d", paginationKeypos, c.lastSuccessfulPaginationKey)
c.logger.WithError(err).Errorf("last successful paginationKey position did not advance")
return err
}
err = f(batch)
if err != nil {
tx.Rollback()
c.logger.WithError(err).Error("failed to call each callback")
return err
}
tx.Rollback()
c.lastSuccessfulPaginationKey = paginationKeypos
}
return nil
}
func (c *Cursor) Fetch(db SqlPreparer) (batch *RowBatch, paginationKeypos uint64, err error) {
var selectBuilder squirrel.SelectBuilder
batchSize := c.CursorConfig.GetBatchSize(c.Table.Schema, c.Table.Name)
if c.BuildSelect != nil {
selectBuilder, err = c.BuildSelect(c.ColumnsToSelect, c.Table, c.lastSuccessfulPaginationKey, batchSize)
if err != nil {
c.logger.WithError(err).Error("failed to apply filter for select")
return
}
} else {
selectBuilder = DefaultBuildSelect(c.ColumnsToSelect, c.Table, c.lastSuccessfulPaginationKey, batchSize)
}
if c.RowLock {
selectBuilder = selectBuilder.Suffix("FOR UPDATE")
}
query, args, err := selectBuilder.ToSql()
if err != nil {
c.logger.WithError(err).Error("failed to build chunking sql")
return
}
// With the inline verifier, the columns to be selected may be very large as
// the query generated will be very large. The code here simply hides the
// columns from the logger to not spam the logs.
splitQuery := strings.Split(query, "FROM")
loggedQuery := fmt.Sprintf("SELECT [omitted] FROM %s", splitQuery[1])
logger := c.logger.WithFields(logrus.Fields{
"sql": loggedQuery,
"args": args,
})
// This query must be a prepared query. If it is not, querying will use
// MySQL's plain text interface, which will scan all values into []uint8
// if we give it []interface{}.
stmt, err := db.Prepare(query)
if err != nil {
logger.WithError(err).Error("failed to prepare query")
return
}
defer stmt.Close()
rows, err := stmt.Query(args...)
if err != nil {
logger.WithError(err).Error("failed to query database")
return
}
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
logger.WithError(err).Error("failed to get columns")
return
}
var paginationKeyIndex int = -1
for idx, col := range columns {
if col == c.paginationKeyColumn.Name {
paginationKeyIndex = idx
break
}
}
if paginationKeyIndex < 0 {
err = fmt.Errorf("paginationKey is not found during iteration with columns: %v", columns)
logger.WithError(err).Error("failed to get paginationKey index")
return
}
var rowData RowData
var batchData []RowData
for rows.Next() {
rowData, err = ScanGenericRow(rows, len(columns))
if err != nil {
logger.WithError(err).Error("failed to scan row")
return
}
batchData = append(batchData, rowData)
}
err = rows.Err()
if err != nil {
return
}
if len(batchData) > 0 {
paginationKeypos, err = batchData[len(batchData)-1].GetUint64(paginationKeyIndex)
if err != nil {
logger.WithError(err).Error("failed to get uint64 paginationKey value")
return
}
}
batch = &RowBatch{
values: batchData,
paginationKeyIndex: paginationKeyIndex,
table: c.Table,
columns: columns,
}
logger.Debugf("found %d rows", batch.Size())
return
}
func ScanGenericRow(rows *sqlorig.Rows, columnCount int) (RowData, error) {
values := make(RowData, columnCount)
valuePtrs := make(RowData, columnCount)
for i, _ := range values {
valuePtrs[i] = &values[i]
}
err := rows.Scan(valuePtrs...)
return values, err
}
func ScanByteRow(rows *sqlorig.Rows, columnCount int) ([][]byte, error) {
values := make([][]byte, columnCount)
valuePtrs := make(RowData, columnCount)
for i, _ := range values {
valuePtrs[i] = &values[i]
}
err := rows.Scan(valuePtrs...)
return values, err
}
func DefaultBuildSelect(columns []string, table *TableSchema, lastPaginationKey, batchSize uint64) squirrel.SelectBuilder {
quotedPaginationKey := QuoteField(table.GetPaginationColumn().Name)
return squirrel.Select(columns...).
From(QuotedTableName(table)).
Where(squirrel.Gt{quotedPaginationKey: lastPaginationKey}).
Limit(batchSize).
OrderBy(quotedPaginationKey)
}