-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathrow_event.go
1597 lines (1363 loc) · 38.6 KB
/
row_event.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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package replication
import (
"encoding/binary"
"encoding/hex"
"fmt"
"io"
"strconv"
"strings"
"time"
"github.com/pingcap/errors"
"github.com/shopspring/decimal"
"github.com/siddontang/go-log/log"
"github.com/siddontang/go/hack"
. "github.com/go-mysql-org/go-mysql/mysql"
)
var errMissingTableMapEvent = errors.New("invalid table id, no corresponding table map event")
type TableMapEvent struct {
flavor string
tableIDSize int
TableID uint64
Flags uint16
Schema []byte
Table []byte
ColumnCount uint64
ColumnType []byte
ColumnMeta []uint16
//len = (ColumnCount + 7) / 8
NullBitmap []byte
/*
The following are available only after MySQL-8.0.1 or MariaDB-10.5.0
By default MySQL and MariaDB do not log the full row metadata.
see:
- https://dev.mysql.com/doc/refman/8.0/en/replication-options-binary-log.html#sysvar_binlog_row_metadata
- https://mariadb.com/kb/en/replication-and-binary-log-system-variables/#binlog_row_metadata
*/
// SignednessBitmap stores signedness info for numeric columns.
SignednessBitmap []byte
// DefaultCharset/ColumnCharset stores collation info for character columns.
// DefaultCharset[0] is the default collation of character columns.
// For character columns that have different charset,
// (character column index, column collation) pairs follows
DefaultCharset []uint64
// ColumnCharset contains collation sequence for all character columns
ColumnCharset []uint64
// SetStrValue stores values for set columns.
SetStrValue [][][]byte
setStrValueString [][]string
// EnumStrValue stores values for enum columns.
EnumStrValue [][][]byte
enumStrValueString [][]string
// ColumnName list all column names.
ColumnName [][]byte
columnNameString []string // the same as ColumnName in string type, just for reuse
// GeometryType stores real type for geometry columns.
GeometryType []uint64
// PrimaryKey is a sequence of column indexes of primary key.
PrimaryKey []uint64
// PrimaryKeyPrefix is the prefix length used for each column of primary key.
// 0 means that the whole column length is used.
PrimaryKeyPrefix []uint64
// EnumSetDefaultCharset/EnumSetColumnCharset is similar to DefaultCharset/ColumnCharset but for enum/set columns.
EnumSetDefaultCharset []uint64
EnumSetColumnCharset []uint64
}
func (e *TableMapEvent) Decode(data []byte) error {
pos := 0
e.TableID = FixedLengthInt(data[0:e.tableIDSize])
pos += e.tableIDSize
e.Flags = binary.LittleEndian.Uint16(data[pos:])
pos += 2
schemaLength := data[pos]
pos++
e.Schema = data[pos : pos+int(schemaLength)]
pos += int(schemaLength)
//skip 0x00
pos++
tableLength := data[pos]
pos++
e.Table = data[pos : pos+int(tableLength)]
pos += int(tableLength)
//skip 0x00
pos++
var n int
e.ColumnCount, _, n = LengthEncodedInt(data[pos:])
pos += n
e.ColumnType = data[pos : pos+int(e.ColumnCount)]
pos += int(e.ColumnCount)
var err error
var metaData []byte
if metaData, _, n, err = LengthEncodedString(data[pos:]); err != nil {
return errors.Trace(err)
}
if err = e.decodeMeta(metaData); err != nil {
return errors.Trace(err)
}
pos += n
nullBitmapSize := bitmapByteSize(int(e.ColumnCount))
if len(data[pos:]) < nullBitmapSize {
return io.EOF
}
e.NullBitmap = data[pos : pos+nullBitmapSize]
pos += nullBitmapSize
if err = e.decodeOptionalMeta(data[pos:]); err != nil {
return err
}
return nil
}
func bitmapByteSize(columnCount int) int {
return (columnCount + 7) / 8
}
// see mysql sql/log_event.h
/*
0 byte
MYSQL_TYPE_DECIMAL
MYSQL_TYPE_TINY
MYSQL_TYPE_SHORT
MYSQL_TYPE_LONG
MYSQL_TYPE_NULL
MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_LONGLONG
MYSQL_TYPE_INT24
MYSQL_TYPE_DATE
MYSQL_TYPE_TIME
MYSQL_TYPE_DATETIME
MYSQL_TYPE_YEAR
1 byte
MYSQL_TYPE_FLOAT
MYSQL_TYPE_DOUBLE
MYSQL_TYPE_BLOB
MYSQL_TYPE_GEOMETRY
//maybe
MYSQL_TYPE_TIME2
MYSQL_TYPE_DATETIME2
MYSQL_TYPE_TIMESTAMP2
2 byte
MYSQL_TYPE_VARCHAR
MYSQL_TYPE_BIT
MYSQL_TYPE_NEWDECIMAL
MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_STRING
This enumeration value is only used internally and cannot exist in a binlog.
MYSQL_TYPE_NEWDATE
MYSQL_TYPE_ENUM
MYSQL_TYPE_SET
MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_MEDIUM_BLOB
MYSQL_TYPE_LONG_BLOB
*/
func (e *TableMapEvent) decodeMeta(data []byte) error {
pos := 0
e.ColumnMeta = make([]uint16, e.ColumnCount)
for i, t := range e.ColumnType {
switch t {
case MYSQL_TYPE_STRING:
var x = uint16(data[pos]) << 8 //real type
x += uint16(data[pos+1]) //pack or field length
e.ColumnMeta[i] = x
pos += 2
case MYSQL_TYPE_NEWDECIMAL:
var x = uint16(data[pos]) << 8 //precision
x += uint16(data[pos+1]) //decimals
e.ColumnMeta[i] = x
pos += 2
case MYSQL_TYPE_VAR_STRING,
MYSQL_TYPE_VARCHAR,
MYSQL_TYPE_BIT:
e.ColumnMeta[i] = binary.LittleEndian.Uint16(data[pos:])
pos += 2
case MYSQL_TYPE_BLOB,
MYSQL_TYPE_DOUBLE,
MYSQL_TYPE_FLOAT,
MYSQL_TYPE_GEOMETRY,
MYSQL_TYPE_JSON:
e.ColumnMeta[i] = uint16(data[pos])
pos++
case MYSQL_TYPE_TIME2,
MYSQL_TYPE_DATETIME2,
MYSQL_TYPE_TIMESTAMP2:
e.ColumnMeta[i] = uint16(data[pos])
pos++
case MYSQL_TYPE_NEWDATE,
MYSQL_TYPE_ENUM,
MYSQL_TYPE_SET,
MYSQL_TYPE_TINY_BLOB,
MYSQL_TYPE_MEDIUM_BLOB,
MYSQL_TYPE_LONG_BLOB:
return errors.Errorf("unsupport type in binlog %d", t)
default:
e.ColumnMeta[i] = 0
}
}
return nil
}
func (e *TableMapEvent) decodeOptionalMeta(data []byte) (err error) {
pos := 0
for pos < len(data) {
// optional metadata fields are stored in Type, Length, Value(TLV) format
// Type takes 1 byte. Length is a packed integer value. Values takes Length bytes
t := data[pos]
pos++
l, _, n := LengthEncodedInt(data[pos:])
pos += n
v := data[pos : pos+int(l)]
pos += int(l)
switch t {
case TABLE_MAP_OPT_META_SIGNEDNESS:
e.SignednessBitmap = v
case TABLE_MAP_OPT_META_DEFAULT_CHARSET:
e.DefaultCharset, err = e.decodeDefaultCharset(v)
if err != nil {
return err
}
case TABLE_MAP_OPT_META_COLUMN_CHARSET:
e.ColumnCharset, err = e.decodeIntSeq(v)
if err != nil {
return err
}
case TABLE_MAP_OPT_META_COLUMN_NAME:
if err = e.decodeColumnNames(v); err != nil {
return err
}
case TABLE_MAP_OPT_META_SET_STR_VALUE:
e.SetStrValue, err = e.decodeStrValue(v)
if err != nil {
return err
}
case TABLE_MAP_OPT_META_ENUM_STR_VALUE:
e.EnumStrValue, err = e.decodeStrValue(v)
if err != nil {
return err
}
case TABLE_MAP_OPT_META_GEOMETRY_TYPE:
e.GeometryType, err = e.decodeIntSeq(v)
if err != nil {
return err
}
case TABLE_MAP_OPT_META_SIMPLE_PRIMARY_KEY:
if err = e.decodeSimplePrimaryKey(v); err != nil {
return err
}
case TABLE_MAP_OPT_META_PRIMARY_KEY_WITH_PREFIX:
if err = e.decodePrimaryKeyWithPrefix(v); err != nil {
return err
}
case TABLE_MAP_OPT_META_ENUM_AND_SET_DEFAULT_CHARSET:
e.EnumSetDefaultCharset, err = e.decodeDefaultCharset(v)
if err != nil {
return err
}
case TABLE_MAP_OPT_META_ENUM_AND_SET_COLUMN_CHARSET:
e.EnumSetColumnCharset, err = e.decodeIntSeq(v)
if err != nil {
return err
}
default:
// Ignore for future extension
}
}
return nil
}
func (e *TableMapEvent) decodeIntSeq(v []byte) (ret []uint64, err error) {
p := 0
for p < len(v) {
i, _, n := LengthEncodedInt(v[p:])
p += n
ret = append(ret, i)
}
return
}
func (e *TableMapEvent) decodeDefaultCharset(v []byte) (ret []uint64, err error) {
ret, err = e.decodeIntSeq(v)
if err != nil {
return
}
if len(ret)%2 != 1 {
return nil, errors.Errorf("Expect odd item in DefaultCharset but got %d", len(ret))
}
return
}
func (e *TableMapEvent) decodeColumnNames(v []byte) error {
p := 0
e.ColumnName = make([][]byte, 0, e.ColumnCount)
for p < len(v) {
n := int(v[p])
p++
e.ColumnName = append(e.ColumnName, v[p:p+n])
p += n
}
if len(e.ColumnName) != int(e.ColumnCount) {
return errors.Errorf("Expect %d column names but got %d", e.ColumnCount, len(e.ColumnName))
}
return nil
}
func (e *TableMapEvent) decodeStrValue(v []byte) (ret [][][]byte, err error) {
p := 0
for p < len(v) {
nVal, _, n := LengthEncodedInt(v[p:])
p += n
vals := make([][]byte, 0, int(nVal))
for i := 0; i < int(nVal); i++ {
val, _, n, err := LengthEncodedString(v[p:])
if err != nil {
return nil, err
}
p += n
vals = append(vals, val)
}
ret = append(ret, vals)
}
return
}
func (e *TableMapEvent) decodeSimplePrimaryKey(v []byte) error {
p := 0
for p < len(v) {
i, _, n := LengthEncodedInt(v[p:])
e.PrimaryKey = append(e.PrimaryKey, i)
e.PrimaryKeyPrefix = append(e.PrimaryKeyPrefix, 0)
p += n
}
return nil
}
func (e *TableMapEvent) decodePrimaryKeyWithPrefix(v []byte) error {
p := 0
for p < len(v) {
i, _, n := LengthEncodedInt(v[p:])
e.PrimaryKey = append(e.PrimaryKey, i)
p += n
i, _, n = LengthEncodedInt(v[p:])
e.PrimaryKeyPrefix = append(e.PrimaryKeyPrefix, i)
p += n
}
return nil
}
func (e *TableMapEvent) Dump(w io.Writer) {
fmt.Fprintf(w, "TableID: %d\n", e.TableID)
fmt.Fprintf(w, "TableID size: %d\n", e.tableIDSize)
fmt.Fprintf(w, "Flags: %d\n", e.Flags)
fmt.Fprintf(w, "Schema: %s\n", e.Schema)
fmt.Fprintf(w, "Table: %s\n", e.Table)
fmt.Fprintf(w, "Column count: %d\n", e.ColumnCount)
fmt.Fprintf(w, "Column type: \n%s", hex.Dump(e.ColumnType))
fmt.Fprintf(w, "NULL bitmap: \n%s", hex.Dump(e.NullBitmap))
fmt.Fprintf(w, "Signedness bitmap: \n%s", hex.Dump(e.SignednessBitmap))
fmt.Fprintf(w, "Default charset: %v\n", e.DefaultCharset)
fmt.Fprintf(w, "Column charset: %v\n", e.ColumnCharset)
fmt.Fprintf(w, "Set str value: %v\n", e.SetStrValueString())
fmt.Fprintf(w, "Enum str value: %v\n", e.EnumStrValueString())
fmt.Fprintf(w, "Column name: %v\n", e.ColumnNameString())
fmt.Fprintf(w, "Geometry type: %v\n", e.GeometryType)
fmt.Fprintf(w, "Primary key: %v\n", e.PrimaryKey)
fmt.Fprintf(w, "Primary key prefix: %v\n", e.PrimaryKeyPrefix)
fmt.Fprintf(w, "Enum/set default charset: %v\n", e.EnumSetDefaultCharset)
fmt.Fprintf(w, "Enum/set column charset: %v\n", e.EnumSetColumnCharset)
unsignedMap := e.UnsignedMap()
fmt.Fprintf(w, "UnsignedMap: %#v\n", unsignedMap)
collationMap := e.CollationMap()
fmt.Fprintf(w, "CollationMap: %#v\n", collationMap)
enumSetCollationMap := e.EnumSetCollationMap()
fmt.Fprintf(w, "EnumSetCollationMap: %#v\n", enumSetCollationMap)
enumStrValueMap := e.EnumStrValueMap()
fmt.Fprintf(w, "EnumStrValueMap: %#v\n", enumStrValueMap)
setStrValueMap := e.SetStrValueMap()
fmt.Fprintf(w, "SetStrValueMap: %#v\n", setStrValueMap)
geometryTypeMap := e.GeometryTypeMap()
fmt.Fprintf(w, "GeometryTypeMap: %#v\n", geometryTypeMap)
nameMaxLen := 0
for _, name := range e.ColumnName {
if len(name) > nameMaxLen {
nameMaxLen = len(name)
}
}
nameFmt := " %s"
if nameMaxLen > 0 {
nameFmt = fmt.Sprintf(" %%-%ds", nameMaxLen)
}
primaryKey := map[int]struct{}{}
for _, pk := range e.PrimaryKey {
primaryKey[int(pk)] = struct{}{}
}
fmt.Fprintf(w, "Columns: \n")
for i := 0; i < int(e.ColumnCount); i++ {
if len(e.ColumnName) == 0 {
fmt.Fprintf(w, nameFmt, "<n/a>")
} else {
fmt.Fprintf(w, nameFmt, e.ColumnName[i])
}
fmt.Fprintf(w, " type=%-3d", e.realType(i))
if e.IsNumericColumn(i) {
if len(unsignedMap) == 0 {
fmt.Fprintf(w, " unsigned=<n/a>")
} else if unsignedMap[i] {
fmt.Fprintf(w, " unsigned=yes")
} else {
fmt.Fprintf(w, " unsigned=no ")
}
}
if e.IsCharacterColumn(i) {
if len(collationMap) == 0 {
fmt.Fprintf(w, " collation=<n/a>")
} else {
fmt.Fprintf(w, " collation=%d ", collationMap[i])
}
}
if e.IsEnumColumn(i) {
if len(enumSetCollationMap) == 0 {
fmt.Fprintf(w, " enum_collation=<n/a>")
} else {
fmt.Fprintf(w, " enum_collation=%d", enumSetCollationMap[i])
}
if len(enumStrValueMap) == 0 {
fmt.Fprintf(w, " enum=<n/a>")
} else {
fmt.Fprintf(w, " enum=%v", enumStrValueMap[i])
}
}
if e.IsSetColumn(i) {
if len(enumSetCollationMap) == 0 {
fmt.Fprintf(w, " set_collation=<n/a>")
} else {
fmt.Fprintf(w, " set_collation=%d", enumSetCollationMap[i])
}
if len(setStrValueMap) == 0 {
fmt.Fprintf(w, " set=<n/a>")
} else {
fmt.Fprintf(w, " set=%v", setStrValueMap[i])
}
}
if e.IsGeometryColumn(i) {
if len(geometryTypeMap) == 0 {
fmt.Fprintf(w, " geometry_type=<n/a>")
} else {
fmt.Fprintf(w, " geometry_type=%v", geometryTypeMap[i])
}
}
available, nullable := e.Nullable(i)
if !available {
fmt.Fprintf(w, " null=<n/a>")
} else if nullable {
fmt.Fprintf(w, " null=yes")
} else {
fmt.Fprintf(w, " null=no ")
}
if _, ok := primaryKey[i]; ok {
fmt.Fprintf(w, " pri")
}
fmt.Fprintf(w, "\n")
}
fmt.Fprintln(w)
}
// Nullable returns the nullablity of the i-th column.
// If null bits are not available, available is false.
// i must be in range [0, ColumnCount).
func (e *TableMapEvent) Nullable(i int) (available, nullable bool) {
if len(e.NullBitmap) == 0 {
return
}
return true, e.NullBitmap[i/8]&(1<<uint(i%8)) != 0
}
// SetStrValueString returns values for set columns as string slices.
// nil is returned if not available or no set columns at all.
func (e *TableMapEvent) SetStrValueString() [][]string {
if e.setStrValueString == nil {
if len(e.SetStrValue) == 0 {
return nil
}
e.setStrValueString = make([][]string, 0, len(e.SetStrValue))
for _, vals := range e.SetStrValue {
e.setStrValueString = append(
e.setStrValueString,
e.bytesSlice2StrSlice(vals),
)
}
}
return e.setStrValueString
}
// EnumStrValueString returns values for enum columns as string slices.
// nil is returned if not available or no enum columns at all.
func (e *TableMapEvent) EnumStrValueString() [][]string {
if e.enumStrValueString == nil {
if len(e.EnumStrValue) == 0 {
return nil
}
e.enumStrValueString = make([][]string, 0, len(e.EnumStrValue))
for _, vals := range e.EnumStrValue {
e.enumStrValueString = append(
e.enumStrValueString,
e.bytesSlice2StrSlice(vals),
)
}
}
return e.enumStrValueString
}
// ColumnNameString returns column names as string slice.
// nil is returned if not available.
func (e *TableMapEvent) ColumnNameString() []string {
if e.columnNameString == nil {
e.columnNameString = e.bytesSlice2StrSlice(e.ColumnName)
}
return e.columnNameString
}
func (e *TableMapEvent) bytesSlice2StrSlice(src [][]byte) []string {
if src == nil {
return nil
}
ret := make([]string, 0, len(src))
for _, item := range src {
ret = append(ret, string(item))
}
return ret
}
// UnsignedMap returns a map: column index -> unsigned.
// Note that only numeric columns will be returned.
// nil is returned if not available or no numeric columns at all.
func (e *TableMapEvent) UnsignedMap() map[int]bool {
if len(e.SignednessBitmap) == 0 {
return nil
}
p := 0
ret := make(map[int]bool)
for i := 0; i < int(e.ColumnCount); i++ {
if !e.IsNumericColumn(i) {
continue
}
ret[i] = e.SignednessBitmap[p/8]&(1<<uint(7-p%8)) != 0
p++
}
return ret
}
// CollationMap returns a map: column index -> collation id.
// Note that only character columns will be returned.
// nil is returned if not available or no character columns at all.
func (e *TableMapEvent) CollationMap() map[int]uint64 {
return e.collationMap(e.IsCharacterColumn, e.DefaultCharset, e.ColumnCharset)
}
// EnumSetCollationMap returns a map: column index -> collation id.
// Note that only enum or set columns will be returned.
// nil is returned if not available or no enum/set columns at all.
func (e *TableMapEvent) EnumSetCollationMap() map[int]uint64 {
return e.collationMap(e.IsEnumOrSetColumn, e.EnumSetDefaultCharset, e.EnumSetColumnCharset)
}
func (e *TableMapEvent) collationMap(includeType func(int) bool, defaultCharset, columnCharset []uint64) map[int]uint64 {
if len(defaultCharset) != 0 {
defaultCollation := defaultCharset[0]
// character column index -> collation
collations := make(map[int]uint64)
for i := 1; i < len(defaultCharset); i += 2 {
collations[int(defaultCharset[i])] = defaultCharset[i+1]
}
p := 0
ret := make(map[int]uint64)
for i := 0; i < int(e.ColumnCount); i++ {
if !includeType(i) {
continue
}
if collation, ok := collations[p]; ok {
ret[i] = collation
} else {
ret[i] = defaultCollation
}
p++
}
return ret
}
if len(columnCharset) != 0 {
p := 0
ret := make(map[int]uint64)
for i := 0; i < int(e.ColumnCount); i++ {
if !includeType(i) {
continue
}
ret[i] = columnCharset[p]
p++
}
return ret
}
return nil
}
// EnumStrValueMap returns a map: column index -> enum string value.
// Note that only enum columns will be returned.
// nil is returned if not available or no enum columns at all.
func (e *TableMapEvent) EnumStrValueMap() map[int][]string {
return e.strValueMap(e.IsEnumColumn, e.EnumStrValueString())
}
// SetStrValueMap returns a map: column index -> set string value.
// Note that only set columns will be returned.
// nil is returned if not available or no set columns at all.
func (e *TableMapEvent) SetStrValueMap() map[int][]string {
return e.strValueMap(e.IsSetColumn, e.SetStrValueString())
}
func (e *TableMapEvent) strValueMap(includeType func(int) bool, strValue [][]string) map[int][]string {
if len(strValue) == 0 {
return nil
}
p := 0
ret := make(map[int][]string)
for i := 0; i < int(e.ColumnCount); i++ {
if !includeType(i) {
continue
}
ret[i] = strValue[p]
p++
}
return ret
}
// GeometryTypeMap returns a map: column index -> geometry type.
// Note that only geometry columns will be returned.
// nil is returned if not available or no geometry columns at all.
func (e *TableMapEvent) GeometryTypeMap() map[int]uint64 {
if len(e.GeometryType) == 0 {
return nil
}
p := 0
ret := make(map[int]uint64)
for i := 0; i < int(e.ColumnCount); i++ {
if !e.IsGeometryColumn(i) {
continue
}
ret[i] = e.GeometryType[p]
p++
}
return ret
}
// Below realType and IsXXXColumn are base from:
// table_def::type in sql/rpl_utility.h
// Table_map_log_event::print_columns in mysql-8.0/sql/log_event.cc and mariadb-10.5/sql/log_event_client.cc
func (e *TableMapEvent) realType(i int) byte {
typ := e.ColumnType[i]
switch typ {
case MYSQL_TYPE_STRING:
rtyp := byte(e.ColumnMeta[i] >> 8)
if rtyp == MYSQL_TYPE_ENUM || rtyp == MYSQL_TYPE_SET {
return rtyp
}
case MYSQL_TYPE_DATE:
return MYSQL_TYPE_NEWDATE
}
return typ
}
func (e *TableMapEvent) IsNumericColumn(i int) bool {
switch e.realType(i) {
case MYSQL_TYPE_TINY,
MYSQL_TYPE_SHORT,
MYSQL_TYPE_INT24,
MYSQL_TYPE_LONG,
MYSQL_TYPE_LONGLONG,
MYSQL_TYPE_NEWDECIMAL,
MYSQL_TYPE_FLOAT,
MYSQL_TYPE_DOUBLE:
return true
default:
return false
}
}
// IsCharacterColumn returns true if the column type is considered as character type.
// Note that JSON/GEOMETRY types are treated as character type in mariadb.
// (JSON is an alias for LONGTEXT in mariadb: https://mariadb.com/kb/en/json-data-type/)
func (e *TableMapEvent) IsCharacterColumn(i int) bool {
switch e.realType(i) {
case MYSQL_TYPE_STRING,
MYSQL_TYPE_VAR_STRING,
MYSQL_TYPE_VARCHAR,
MYSQL_TYPE_BLOB:
return true
case MYSQL_TYPE_GEOMETRY:
if e.flavor == "mariadb" {
return true
}
return false
default:
return false
}
}
func (e *TableMapEvent) IsEnumColumn(i int) bool {
return e.realType(i) == MYSQL_TYPE_ENUM
}
func (e *TableMapEvent) IsSetColumn(i int) bool {
return e.realType(i) == MYSQL_TYPE_SET
}
func (e *TableMapEvent) IsGeometryColumn(i int) bool {
return e.realType(i) == MYSQL_TYPE_GEOMETRY
}
func (e *TableMapEvent) IsEnumOrSetColumn(i int) bool {
rtyp := e.realType(i)
return rtyp == MYSQL_TYPE_ENUM || rtyp == MYSQL_TYPE_SET
}
// RowsEventStmtEndFlag is set in the end of the statement.
const RowsEventStmtEndFlag = 0x01
type RowsEvent struct {
//0, 1, 2
Version int
tableIDSize int
tables map[uint64]*TableMapEvent
needBitmap2 bool
Table *TableMapEvent
TableID uint64
Flags uint16
//if version == 2
ExtraData []byte
//lenenc_int
ColumnCount uint64
/*
By default MySQL and MariaDB log the full row image.
see
- https://dev.mysql.com/doc/refman/8.0/en/replication-options-binary-log.html#sysvar_binlog_row_image
- https://mariadb.com/kb/en/replication-and-binary-log-system-variables/#binlog_row_image
ColumnBitmap1, ColumnBitmap2 and SkippedColumns are not set on the full row image.
*/
//len = (ColumnCount + 7) / 8
ColumnBitmap1 []byte
//if UPDATE_ROWS_EVENTv1 or v2
//len = (ColumnCount + 7) / 8
ColumnBitmap2 []byte
//rows: invalid: int64, float64, bool, []byte, string
Rows [][]interface{}
SkippedColumns [][]int
parseTime bool
timestampStringLocation *time.Location
useDecimal bool
ignoreJSONDecodeErr bool
}
func (e *RowsEvent) Decode(data []byte) (err2 error) {
pos := 0
e.TableID = FixedLengthInt(data[0:e.tableIDSize])
pos += e.tableIDSize
e.Flags = binary.LittleEndian.Uint16(data[pos:])
pos += 2
if e.Version == 2 {
dataLen := binary.LittleEndian.Uint16(data[pos:])
pos += 2
e.ExtraData = data[pos : pos+int(dataLen-2)]
pos += int(dataLen - 2)
}
var n int
e.ColumnCount, _, n = LengthEncodedInt(data[pos:])
pos += n
bitCount := bitmapByteSize(int(e.ColumnCount))
e.ColumnBitmap1 = data[pos : pos+bitCount]
pos += bitCount
if e.needBitmap2 {
e.ColumnBitmap2 = data[pos : pos+bitCount]
pos += bitCount
}
var ok bool
e.Table, ok = e.tables[e.TableID]
if !ok {
if len(e.tables) > 0 {
return errors.Errorf("invalid table id %d, no corresponding table map event", e.TableID)
} else {
return errors.Annotatef(errMissingTableMapEvent, "table id %d", e.TableID)
}
}
var err error
// ... repeat rows until event-end
defer func() {
if r := recover(); r != nil {
errStr := fmt.Sprintf("parse rows event panic %v, data %q, parsed rows %#v, table map %#v", r, data, e, e.Table)
log.Errorf("%s\n%s", errStr, Pstack())
err2 = errors.Trace(errors.New(errStr))
}
}()
// Pre-allocate memory for rows.
rowsLen := e.ColumnCount
if e.needBitmap2 {
rowsLen += e.ColumnCount
}
e.SkippedColumns = make([][]int, 0, rowsLen)
e.Rows = make([][]interface{}, 0, rowsLen)
for pos < len(data) {
if n, err = e.decodeRows(data[pos:], e.Table, e.ColumnBitmap1); err != nil {
return errors.Trace(err)
}
pos += n
if e.needBitmap2 {
if n, err = e.decodeRows(data[pos:], e.Table, e.ColumnBitmap2); err != nil {
return errors.Trace(err)
}
pos += n
}
}
return nil
}
func isBitSet(bitmap []byte, i int) bool {
return bitmap[i>>3]&(1<<(uint(i)&7)) > 0
}
func (e *RowsEvent) decodeRows(data []byte, table *TableMapEvent, bitmap []byte) (int, error) {
row := make([]interface{}, e.ColumnCount)
skips := make([]int, 0)
pos := 0
// refer: https://github.com/alibaba/canal/blob/c3e38e50e269adafdd38a48c63a1740cde304c67/dbsync/src/main/java/com/taobao/tddl/dbsync/binlog/event/RowsLogBuffer.java#L63
count := 0
for i := 0; i < int(e.ColumnCount); i++ {
if isBitSet(bitmap, i) {
count++
}
}
count = (count + 7) / 8
nullBitmap := data[pos : pos+count]
pos += count
nullbitIndex := 0
var n int
var err error
for i := 0; i < int(e.ColumnCount); i++ {
if !isBitSet(bitmap, i) {
skips = append(skips, i)
continue
}
isNull := (uint32(nullBitmap[nullbitIndex/8]) >> uint32(nullbitIndex%8)) & 0x01
nullbitIndex++
if isNull > 0 {
row[i] = nil
continue
}
row[i], n, err = e.decodeValue(data[pos:], table.ColumnType[i], table.ColumnMeta[i])
if err != nil {
return 0, err
}
pos += n
}
e.Rows = append(e.Rows, row)
e.SkippedColumns = append(e.SkippedColumns, skips)
return pos, nil
}
func (e *RowsEvent) parseFracTime(t interface{}) interface{} {
v, ok := t.(fracTime)
if !ok {
return t
}
if !e.parseTime {
// Don't parse time, return string directly
return v.String()
}
// return Golang time directly
return v.Time