-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathschema.go
496 lines (422 loc) · 12.8 KB
/
schema.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// Copyright © 2024 Meroxa, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mysql
import (
"context"
"encoding/binary"
"fmt"
"math"
"strconv"
"time"
sdk "github.com/conduitio/conduit-connector-sdk"
"github.com/conduitio/conduit-connector-sdk/schema"
mysqlschema "github.com/go-mysql-org/go-mysql/schema"
"github.com/hamba/avro/v2"
"github.com/jmoiron/sqlx"
)
// schemaMapper maps mysql schemas to conduit avro schemas, and it uses them to
// format values.
type schemaMapper struct {
schema *schemaSubjectVersion
colTypes map[string]*avroNamedType
}
func newSchemaMapper() *schemaMapper {
return &schemaMapper{
colTypes: make(map[string]*avroNamedType),
}
}
type avroType struct {
Type avro.Type
isBit bool
isDate bool
}
var sqlColtypeToAvroTypeMap = map[string]avroType{
// Numeric types
"TINYINT": {Type: avro.Int},
"SMALLINT": {Type: avro.Int},
"MEDIUMINT": {Type: avro.Int},
"INT": {Type: avro.Int},
"BIGINT": {Type: avro.Long},
"UNSIGNED TINYINT": {Type: avro.Int},
"UNSIGNED SMALLINT": {Type: avro.Int},
"UNSIGNED MEDIUMINT": {Type: avro.Int},
"UNSIGNED INT": {Type: avro.Long},
"UNSIGNED BIGINT": {Type: avro.Long},
"FLOAT": {Type: avro.Float},
"DECIMAL": {Type: avro.Double},
"NUMERIC": {Type: avro.Double},
"DOUBLE": {Type: avro.Double},
"BIT": {Type: avro.Fixed, isBit: true},
// String types
"CHAR": {Type: avro.String},
"VARCHAR": {Type: avro.String},
"TINYTEXT": {Type: avro.String},
"TEXT": {Type: avro.String},
"MEDIUMTEXT": {Type: avro.String},
"LONGTEXT": {Type: avro.String},
// Binary types
"BINARY": {Type: avro.Bytes},
"VARBINARY": {Type: avro.Bytes},
"TINYBLOB": {Type: avro.Bytes},
"BLOB": {Type: avro.Bytes},
"MEDIUMBLOB": {Type: avro.Bytes},
"LONGBLOB": {Type: avro.Bytes},
// Date and type types
"DATE": {Type: avro.String, isDate: true},
"TIME": {Type: avro.String, isDate: true},
"DATETIME": {Type: avro.String, isDate: true},
"TIMESTAMP": {Type: avro.String, isDate: true},
"YEAR": {Type: avro.Int, isDate: true},
// Misc
"ENUM": {Type: avro.String},
"SET": {Type: avro.String},
"JSON": {Type: avro.String},
}
type avroNamedType struct {
avroType
Name string
}
func sqlxRowsToAvroCol(rows *sqlx.Rows) ([]*avroNamedType, error) {
colTypes, err := rows.ColumnTypes()
if err != nil {
return nil, fmt.Errorf("failed to retrieve column types: %w", err)
}
avroCols := make([]*avroNamedType, len(colTypes))
for i, colType := range colTypes {
avroType, ok := sqlColtypeToAvroTypeMap[colType.DatabaseTypeName()]
if !ok {
return nil, fmt.Errorf(
"failed to retrieve column type %s for %s",
colType.DatabaseTypeName(), colType.Name())
}
avroCol := &avroNamedType{avroType: avroType, Name: colType.Name()}
if colType.DatabaseTypeName() == "BIT" {
avroCol.isBit = true
}
avroCols[i] = avroCol
}
return avroCols, nil
}
var mysqlschemaTypeToAvroTypeMap = map[int]avroType{
// Numeric types
mysqlschema.TYPE_NUMBER: {Type: avro.Int},
mysqlschema.TYPE_FLOAT: {Type: avro.Float},
mysqlschema.TYPE_DECIMAL: {Type: avro.Double},
mysqlschema.TYPE_MEDIUM_INT: {Type: avro.Int},
// String types
mysqlschema.TYPE_STRING: {Type: avro.String},
mysqlschema.TYPE_ENUM: {Type: avro.String},
mysqlschema.TYPE_SET: {Type: avro.String},
// Binary types
mysqlschema.TYPE_BINARY: {Type: avro.Bytes},
mysqlschema.TYPE_BIT: {Type: avro.Fixed, isBit: true},
// Date and time types
mysqlschema.TYPE_DATETIME: {Type: avro.String, isDate: true},
mysqlschema.TYPE_TIMESTAMP: {Type: avro.String, isDate: true},
mysqlschema.TYPE_DATE: {Type: avro.String, isDate: true},
mysqlschema.TYPE_TIME: {Type: avro.String, isDate: true},
// Misc
mysqlschema.TYPE_JSON: {Type: avro.String},
mysqlschema.TYPE_POINT: {Type: avro.String},
}
var rawTypeToAvroTypeMap = map[string]avro.Type{
"bigint": avro.Long,
"bigint unsigned": avro.Long,
"tinyblob": avro.Bytes,
"blob": avro.Bytes,
"mediumblob": avro.Bytes,
"longblob": avro.Bytes,
}
func mysqlSchemaToAvroCol(tableCol mysqlschema.TableColumn) (*avroNamedType, error) {
avroType, ok := mysqlschemaTypeToAvroTypeMap[tableCol.Type]
if !ok {
return nil, fmt.Errorf("unsupported column type %s for column %s", tableCol.RawType, tableCol.Name)
}
if tableCol.RawType == "int unsigned" {
avroType.Type = avro.Long
}
if tableCol.Type == mysqlschema.TYPE_FLOAT && tableCol.RawType == "double" {
avroType.Type = avro.Double
}
avroColType := &avroNamedType{avroType: avroType, Name: tableCol.Name}
rawType, ok := rawTypeToAvroTypeMap[tableCol.RawType]
if ok {
avroColType.Type = rawType
}
return avroColType, nil
}
func colTypeToAvroField(avroCol *avroNamedType) (*avro.Field, error) {
if avroCol.isBit {
// Current limitations in the mysql driver that we use don't allow use
// to get the N from BIT(N) mysql columns. To track support for this
// feature refer to https://github.com/go-sql-driver/mysql/issues/1672
fixed8Size := 8
fixed, err := avro.NewFixedSchema(avroCol.Name+"_fixed", "", fixed8Size, nil)
if err != nil {
return nil, fmt.Errorf("failed to create fixed schema for bit column %s: %w", avroCol.Name, err)
}
field, err := avro.NewField(avroCol.Name, fixed)
if err != nil {
return nil, fmt.Errorf("failed to create avro field for bit column %s: %w", avroCol.Name, err)
}
return field, nil
}
primitive := avro.NewPrimitiveSchema(avroCol.Type, nil)
nameField, err := avro.NewField(avroCol.Name, primitive)
if err != nil {
return nil, fmt.Errorf("failed to create avro field for column %s: %w", avroCol.Name, err)
}
return nameField, nil
}
type schemaSubjectVersion struct {
subject string
version int
}
func (s *schemaMapper) createPayloadSchema(
ctx context.Context, table string, mysqlCols []*avroNamedType,
) (*schemaSubjectVersion, error) {
if s.schema != nil {
return s.schema, nil
}
fields := make([]*avro.Field, 0, len(mysqlCols))
for _, colType := range mysqlCols {
field, err := colTypeToAvroField(colType)
if err != nil {
return nil, fmt.Errorf("failed to create payload schema: %w", err)
}
fields = append(fields, field)
s.colTypes[colType.Name] = colType
}
recordSchema, err := avro.NewRecordSchema(table+"_payload", "mysql", fields)
if err != nil {
return nil, fmt.Errorf("failed to create payload schema: %w", err)
}
schema, err := schema.Create(ctx, schema.TypeAvro, recordSchema.Name(), []byte(recordSchema.String()))
if err != nil {
return nil, fmt.Errorf("failed to create payload schema: %w", err)
}
s.schema = &schemaSubjectVersion{
subject: schema.Subject,
version: schema.Version,
}
return s.schema, nil
}
func (s *schemaMapper) createKeySchema(
ctx context.Context, table string, colType *avroNamedType,
) (*schemaSubjectVersion, error) {
if s.schema != nil {
return s.schema, nil
}
field, err := colTypeToAvroField(colType)
if err != nil {
return nil, fmt.Errorf("failed to create key schema: %w", err)
}
recordSchema, err := avro.NewRecordSchema(table+"_key", "mysql", []*avro.Field{field})
if err != nil {
return nil, fmt.Errorf("failed to create key schema: %w", err)
}
s.colTypes[colType.Name] = colType
schema, err := schema.Create(ctx, schema.TypeAvro, recordSchema.Name(), []byte(recordSchema.String()))
if err != nil {
return nil, fmt.Errorf("failed to create key schema: %w", err)
}
s.schema = &schemaSubjectVersion{
subject: schema.Subject,
version: schema.Version,
}
return s.schema, nil
}
// formatValue uses the stored avro types to format the incoming value as an
// avro type. This way we can better control what the mysql driver returns. It
// should be called after creating the schema, otherwise it won't do anything.
func (s *schemaMapper) formatValue(ctx context.Context, column string, value any) any {
t, found := s.colTypes[column]
if !found {
// In snapshot mode, this should never happen.
// In CDC mode, to prevent getting into here we make sure to instantiate the
// schema mapper for each row event.
sdk.Logger(ctx).Warn().Msgf("column \"%v\" not found", column)
return value
}
// Each of the following branches handles different datatype parsing
// behaviour between database/sql and go-mysql-org/go-mysql/canal
// dependencies. We need this to make sure that a row emitted in snapshot mode
// and updated in cdc mode have the same schema.
// We manually convert nil values into the go zero value equivalent so that
// we don't need to handle NULL complexity into the schema.
// However, we might want to reflect nullability of the datatype in the future.
if value == nil {
return defaultValueForType(t.Type)
}
switch t.Type {
case avro.String:
switch v := value.(type) {
case []uint8:
return string(v)
case string:
if !t.isDate {
return v
}
t, err := time.Parse(time.DateOnly, v)
if err != nil {
return v
}
return t
}
case avro.Int:
switch v := value.(type) {
case int:
if v <= math.MaxInt32 && v >= math.MinInt32 {
return int32(v)
}
sdk.Logger(ctx).Warn().Msgf("value %v for column %s cannot be encoded in avro int", v, t.Name)
case int8:
return int32(v)
case int16:
return int32(v)
case int64:
if v >= math.MinInt32 && v <= math.MaxInt32 {
return int32(v)
}
sdk.Logger(ctx).Warn().Msgf("value %v for column %s cannot be encoded in avro int", v, t.Name)
case uint8:
return int32(v)
case uint16:
return int32(v)
case uint32:
if v <= math.MaxInt32 {
return int32(v)
}
sdk.Logger(ctx).Warn().Msgf("value %v for column %s cannot be encoded in avro int", v, t.Name)
case uint64:
if v <= math.MaxInt32 {
return int32(v)
}
sdk.Logger(ctx).Warn().Msgf("value %v for column %s cannot be encoded in avro int", v, t.Name)
}
return value
case avro.Long:
switch v := value.(type) {
case int:
return int64(v)
case []uint8:
// this handles the mysql bit datatype. When snapshotting will be
// represented as slice of bytes, so we manually convert it to the
// corresponding avro.Long datatype.
if len(v) > 0 {
var result int64
for i := 0; i < len(v); i++ {
result = result<<8 + int64(v[i])
}
return result
}
return int64(0)
case uint32:
return int64(v)
case uint64:
if v <= math.MaxInt64 {
return int64(v)
}
sdk.Logger(ctx).Warn().Msgf("value %v for column %s cannot be encoded in avro int", v, t.Name)
}
return value
case avro.Double:
switch v := value.(type) {
case string:
f, err := strconv.ParseFloat(v, 64)
if err != nil {
return v
}
return f
case []byte:
f, err := strconv.ParseFloat(string(v), 64)
if err != nil {
return v
}
return f
}
case avro.Boolean:
switch v := value.(type) {
case int8:
return v != 0
case uint8:
return v != 0
}
case avro.Fixed:
switch v := value.(type) {
case int64:
// canal.Canal parses mysql bit column as an int64, so to be
// consistent with snapshot mode we need to manually parse the int
// into a slice of bytes.
return int64ToBytes(v)
case []byte:
if t.isBit {
// Because of our current limitation at
// https://github.com/go-sql-driver/mysql/issues/1672
// we map BIT(N) columns to avro fixed[8] data type, so we need to
// do this.
byte8Table := [8]byte{}
// Should never happen, but just in case.
if len(v) > 8 {
v = v[len(v)-8:]
}
copy(byte8Table[8-len(v):], v)
return byte8Table[:]
}
}
case avro.Bytes:
if v, ok := value.(string); ok {
return []byte(v)
}
default:
return value
}
return value
}
func defaultValueForType(t avro.Type) any {
switch t {
case avro.Array:
return []any{}
case avro.Map:
return map[string]any{}
case avro.String:
return ""
case avro.Bytes:
return []byte{}
case avro.Int:
return int32(0)
case avro.Long:
return int64(0)
case avro.Float:
return float32(0)
case avro.Double:
return float64(0)
case avro.Boolean:
return false
case avro.Null:
return nil
case avro.Record, avro.Error, avro.Ref, avro.Enum, avro.Fixed, avro.Union:
return nil
default:
return nil
}
}
// int64ToBytes transforms an int64 to a slice of bytes without leading zeros.
func int64ToBytes(i int64) []byte {
bs := [8]byte{}
//nolint:gosec // the overflow that can happen here in this case is fine.
v := uint64(i)
binary.BigEndian.PutUint64(bs[:], v)
return bs[:]
}