-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathupdater.go
349 lines (317 loc) · 9.68 KB
/
updater.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
package replica
import (
stdsql "database/sql"
"errors"
"github.com/apecloud/myduckserver/catalog"
"strings"
"github.com/apecloud/myduckserver/binlog"
"github.com/apecloud/myduckserver/binlogreplication"
"github.com/dolthub/go-mysql-server/sql"
"github.com/sirupsen/logrus"
"vitess.io/vitess/go/mysql"
)
var ErrPartialPrimaryKeyUpdate = errors.New("primary key columns are (partially) updated but are not fully specified in the binlog")
func isPkUpdate(schema sql.Schema, identifyColumns, dataColumns mysql.Bitmap) bool {
for i, c := range schema {
if c.PrimaryKey && identifyColumns.Bit(i) && dataColumns.Bit(i) {
return true
}
}
return false
}
func getPrimaryKeyIndices(schema sql.Schema, columns mysql.Bitmap) []int {
var count int
var indices []int
for i, c := range schema {
set := columns.Count() > i && columns.Bit(i)
if c.PrimaryKey && !set {
return nil
} else if c.PrimaryKey && set {
indices = append(indices, count)
}
if set {
count++
}
}
return indices
}
func (twp *tableWriterProvider) newTableUpdater(
ctx *sql.Context,
txn *stdsql.Tx,
databaseName, tableName string,
pkSchema sql.PrimaryKeySchema,
columnCount, rowCount int,
identifyColumns, dataColumns mysql.Bitmap,
eventType binlog.RowEventType,
) (*tableUpdater, error) {
schema := pkSchema.Schema
pkColumns := pkSchema.PkOrdinals
pkIndicesInIdentify := getPrimaryKeyIndices(schema, identifyColumns)
pkIndicesInData := getPrimaryKeyIndices(schema, dataColumns)
if len(pkIndicesInIdentify) == 0 && len(pkColumns) > 0 {
pkColumns = nil // disable primary key utilization
}
pkSubSchema := make(sql.Schema, len(pkColumns))
for i, idx := range pkColumns {
pkSubSchema[i] = schema[idx]
}
var (
sql string
paramCount int
pkUpdate bool
replace = false
cleanup string
fullTableName = quoteIdentifier(databaseName) + "." + quoteIdentifier(tableName)
keyCount, dataCount = identifyColumns.BitCount(), dataColumns.BitCount()
)
switch eventType {
case binlog.DeleteRowEvent:
sql, paramCount = buildDeleteTemplate(fullTableName, columnCount, schema, pkColumns, identifyColumns)
case binlog.UpdateRowEvent:
pkUpdate = isPkUpdate(schema, identifyColumns, dataColumns)
if pkUpdate {
// If the primary key is being updated, we need to use DELETE + INSERT.
//
// For example, if the primary has executed `UPDATE t SET pk = pk + 1;`,
// then both `UPDATE` and `INSERT OR REPLACE` will fail on the replica because the primary key is being updated:
// - `UPDATE` will fail because of violation of the primary key constraint.
// - `REPLACE` will fail because it will insert a new row but leave the old row unchanged.
//
// However, `DELETE` then `INSERT` in the same transaction will still fail
// due to the over-eager unique constraint checking in DuckDB, just like the `UPDATE` case.
//
// The only way to work around this without breaking atomicity is to do `INSERT OR REPLACE` first,
// then `DELETE` the old row if the primary key has actually been modified.
// This requires the occurrence of the primary key columns in both the `identifyColumns` and `dataColumns`.
if len(pkIndicesInIdentify) == 0 || len(pkIndicesInData) == 0 {
return nil, ErrPartialPrimaryKeyUpdate
}
sql, paramCount = buildInsertTemplate(fullTableName, columnCount, true)
cleanup, _ = buildDeleteTemplate(fullTableName, columnCount, schema, pkColumns, identifyColumns)
replace = true
} else if keyCount < columnCount || dataCount < columnCount {
sql, paramCount = buildUpdateTemplate(fullTableName, columnCount, schema, pkColumns, identifyColumns, dataColumns)
} else {
sql, paramCount = buildInsertTemplate(fullTableName, columnCount, true)
replace = true
}
case binlog.InsertRowEvent:
sql, paramCount = buildInsertTemplate(fullTableName, columnCount, false)
}
logrus.WithFields(logrus.Fields{
"sql": sql,
"replace": replace,
"cleanup": cleanup,
"keyCount": keyCount,
"dataCount": dataCount,
"pkUpdate": pkUpdate,
}).Infoln("Creating table updater...")
stmt, err := txn.PrepareContext(ctx.Context, sql)
if err != nil {
return nil, err
}
return &tableUpdater{
provider: twp.provider,
stmt: stmt,
replace: replace,
cleanup: cleanup,
paramCount: paramCount,
pkIndicesInIdentify: pkIndicesInIdentify,
pkIndicesInData: pkIndicesInData,
}, nil
}
func buildInsertTemplate(tableName string, columnCount int, replace bool) (string, int) {
var builder strings.Builder
builder.Grow(32)
builder.WriteString("INSERT")
if replace {
builder.WriteString(" OR REPLACE")
}
builder.WriteString(" INTO ")
builder.WriteString(tableName)
builder.WriteString(" VALUES (")
for i := range columnCount {
builder.WriteString("?")
if i < columnCount-1 {
builder.WriteString(", ")
}
}
builder.WriteString(")")
return builder.String(), columnCount
}
func buildDeleteTemplate(tableName string, columnCount int, schema sql.Schema, pkColumns []int, identifyColumns mysql.Bitmap) (string, int) {
var builder strings.Builder
builder.Grow(32)
builder.WriteString("DELETE FROM ")
builder.WriteString(tableName)
builder.WriteString(" WHERE ")
if len(pkColumns) > 0 {
for i, c := range pkColumns {
if i > 0 {
builder.WriteString(" AND ")
}
builder.WriteString(quoteIdentifier(schema[c].Name))
builder.WriteString(" = ?")
}
return builder.String(), len(pkColumns)
}
count := 0
for i := range columnCount {
if identifyColumns.Bit(i) {
if count > 0 {
builder.WriteString(" AND ")
}
builder.WriteString(quoteIdentifier(schema[i].Name))
builder.WriteString(" = ?")
count++
}
}
return builder.String(), count
}
func buildUpdateTemplate(tableName string, columnCount int, schema sql.Schema, pkColumns []int, identifyColumns, dataColumns mysql.Bitmap) (string, int) {
var builder strings.Builder
builder.Grow(32)
builder.WriteString("UPDATE ")
builder.WriteString(tableName)
builder.WriteString(" SET ")
count := 0
dataCount := dataColumns.BitCount()
for i := range columnCount {
if dataColumns.Bit(i) {
if count > 0 {
builder.WriteString(", ")
}
builder.WriteString(quoteIdentifier(schema[i].Name))
builder.WriteString(" = ?")
count++
}
}
builder.WriteString(" WHERE ")
if len(pkColumns) > 0 {
for i, c := range pkColumns {
if i > 0 {
builder.WriteString(" AND ")
}
builder.WriteString(quoteIdentifier(schema[c].Name))
builder.WriteString(" = ?")
}
return builder.String(), dataCount + len(pkColumns)
}
count = 0
for i := range columnCount {
if identifyColumns.Bit(i) {
if count > 0 {
builder.WriteString(" AND ")
}
builder.WriteString(quoteIdentifier(schema[i].Name))
builder.WriteString(" = ?")
count++
}
}
return builder.String(), dataCount + identifyColumns.BitCount()
}
type tableUpdater struct {
provider *catalog.DatabaseProvider
tx *stdsql.Tx
stmt *stdsql.Stmt
replace bool
cleanup string
paramCount int
pkSubSchema sql.Schema
pkIndicesInIdentify []int
pkIndicesInData []int
}
var _ binlogreplication.TableWriter = &tableUpdater{}
func (tu *tableUpdater) Insert(ctx *sql.Context, rows []sql.Row) error {
defer tu.stmt.Close()
for _, row := range rows {
if _, err := tu.stmt.ExecContext(ctx.Context, row...); err != nil {
return err
}
}
return nil
}
func (tu *tableUpdater) Delete(ctx *sql.Context, keyRows []sql.Row) error {
defer tu.stmt.Close()
buf := make(sql.Row, len(tu.pkIndicesInIdentify))
for _, row := range keyRows {
var keys sql.Row
if len(tu.pkIndicesInIdentify) > 0 {
for i, idx := range tu.pkIndicesInIdentify {
buf[i] = row[idx]
}
keys = buf
} else {
keys = row
}
if _, err := tu.stmt.ExecContext(ctx.Context, keys...); err != nil {
return err
}
}
return nil
}
func (tu *tableUpdater) Update(ctx *sql.Context, keyRows []sql.Row, valueRows []sql.Row) error {
if tu.replace && tu.cleanup == "" {
return tu.Insert(ctx, valueRows)
}
if tu.cleanup != "" {
return tu.doInsertThenDelete(ctx, keyRows, valueRows)
}
// UPDATE t SET col1 = ?, col2 = ? WHERE key1 = ? AND key2 = ?
buf := make([]interface{}, tu.paramCount)
for i, values := range valueRows {
keys := keyRows[i]
copy(buf, values)
if len(tu.pkIndicesInIdentify) > 0 {
for j, idx := range tu.pkIndicesInIdentify {
buf[len(values)+j] = keys[idx]
}
} else {
copy(buf[len(values):], keys)
}
args := buf[:len(values)+len(keys)]
if _, err := tu.stmt.ExecContext(ctx.Context, args...); err != nil {
return err
}
}
return nil
}
// https://duckdb.org/docs/sql/indexes#over-eager-unique-constraint-checking
// https://github.com/duckdb/duckdb/issues/14133
func (tu *tableUpdater) doInsertThenDelete(ctx *sql.Context, beforeRows []sql.Row, afterRows []sql.Row) error {
var err error
// INSERT OR REPLACE
if err = tu.Insert(ctx, afterRows); err != nil {
return err
}
// DELETE if the primary key has actually been modified
stmt, err := tu.tx.PrepareContext(ctx.Context, tu.cleanup)
if err != nil {
return err
}
defer stmt.Close()
beforeKey := make(sql.Row, len(tu.pkSubSchema))
afterKey := make(sql.Row, len(tu.pkSubSchema))
for i, before := range beforeRows {
after := afterRows[i]
for j, idx := range tu.pkIndicesInIdentify {
beforeKey[j] = before[idx]
}
for j, idx := range tu.pkIndicesInData {
afterKey[j] = after[idx]
}
if yes, err := beforeKey.Equals(afterKey, tu.pkSubSchema); err != nil {
return err
} else if yes {
// the row has already been deleted by the INSERT OR REPLACE statement
continue
}
if _, err := stmt.ExecContext(ctx.Context, beforeKey...); err != nil {
return err
}
}
return nil
}
func quoteIdentifier(identifier string) string {
return `"` + identifier + `"`
}