-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
tables.go
1904 lines (1755 loc) · 58.2 KB
/
tables.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
// Copyright 2015 PingCAP, 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.
// Copyright 2013 The ql Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSES/QL-LICENSE file.
package tables
import (
"context"
"math"
"strconv"
"strings"
"sync"
"time"
"github.com/opentracing/opentracing-go"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/meta"
"github.com/pingcap/tidb/meta/autoid"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/binloginfo"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/statistics"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/collate"
"github.com/pingcap/tidb/util/generatedexpr"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/stringutil"
"github.com/pingcap/tidb/util/tableutil"
"github.com/pingcap/tipb/go-binlog"
"github.com/pingcap/tipb/go-tipb"
"go.uber.org/zap"
)
// TableCommon is shared by both Table and partition.
type TableCommon struct {
tableID int64
// physicalTableID is a unique int64 to identify a physical table.
physicalTableID int64
Columns []*table.Column
PublicColumns []*table.Column
VisibleColumns []*table.Column
HiddenColumns []*table.Column
WritableColumns []*table.Column
FullHiddenColsAndVisibleColumns []*table.Column
indices []table.Index
meta *model.TableInfo
allocs autoid.Allocators
sequence *sequenceCommon
// recordPrefix and indexPrefix are generated using physicalTableID.
recordPrefix kv.Key
indexPrefix kv.Key
}
// MockTableFromMeta only serves for test.
func MockTableFromMeta(tblInfo *model.TableInfo) table.Table {
columns := make([]*table.Column, 0, len(tblInfo.Columns))
for _, colInfo := range tblInfo.Columns {
col := table.ToColumn(colInfo)
columns = append(columns, col)
}
var t TableCommon
initTableCommon(&t, tblInfo, tblInfo.ID, columns, nil)
if tblInfo.TableCacheStatusType != model.TableCacheStatusDisable {
ret, err := newCachedTable(&t)
if err != nil {
return nil
}
return ret
}
if tblInfo.GetPartitionInfo() == nil {
if err := initTableIndices(&t); err != nil {
return nil
}
return &t
}
ret, err := newPartitionedTable(&t, tblInfo)
if err != nil {
return nil
}
return ret
}
// TableFromMeta creates a Table instance from model.TableInfo.
func TableFromMeta(allocs autoid.Allocators, tblInfo *model.TableInfo) (table.Table, error) {
if tblInfo.State == model.StateNone {
return nil, table.ErrTableStateCantNone.GenWithStackByArgs(tblInfo.Name)
}
colsLen := len(tblInfo.Columns)
columns := make([]*table.Column, 0, colsLen)
for i, colInfo := range tblInfo.Columns {
if colInfo.State == model.StateNone {
return nil, table.ErrColumnStateCantNone.GenWithStackByArgs(colInfo.Name)
}
// Print some information when the column's offset isn't equal to i.
if colInfo.Offset != i {
logutil.BgLogger().Error("wrong table schema", zap.Any("table", tblInfo), zap.Any("column", colInfo), zap.Int("index", i), zap.Int("offset", colInfo.Offset), zap.Int("columnNumber", colsLen))
}
col := table.ToColumn(colInfo)
if col.IsGenerated() {
expr, err := generatedexpr.ParseExpression(colInfo.GeneratedExprString)
if err != nil {
return nil, err
}
expr, err = generatedexpr.SimpleResolveName(expr, tblInfo)
if err != nil {
return nil, err
}
col.GeneratedExpr = expr
}
// default value is expr.
if col.DefaultIsExpr {
expr, err := generatedexpr.ParseExpression(colInfo.DefaultValue.(string))
if err != nil {
return nil, err
}
col.DefaultExpr = expr
}
columns = append(columns, col)
}
var t TableCommon
initTableCommon(&t, tblInfo, tblInfo.ID, columns, allocs)
if tblInfo.GetPartitionInfo() == nil {
if err := initTableIndices(&t); err != nil {
return nil, err
}
if tblInfo.TableCacheStatusType != model.TableCacheStatusDisable {
return newCachedTable(&t)
}
return &t, nil
}
return newPartitionedTable(&t, tblInfo)
}
// initTableCommon initializes a TableCommon struct.
func initTableCommon(t *TableCommon, tblInfo *model.TableInfo, physicalTableID int64, cols []*table.Column, allocs autoid.Allocators) {
t.tableID = tblInfo.ID
t.physicalTableID = physicalTableID
t.allocs = allocs
t.meta = tblInfo
t.Columns = cols
t.PublicColumns = t.Cols()
t.VisibleColumns = t.VisibleCols()
t.HiddenColumns = t.HiddenCols()
t.WritableColumns = t.WritableCols()
t.FullHiddenColsAndVisibleColumns = t.FullHiddenColsAndVisibleCols()
t.recordPrefix = tablecodec.GenTableRecordPrefix(physicalTableID)
t.indexPrefix = tablecodec.GenTableIndexPrefix(physicalTableID)
if tblInfo.IsSequence() {
t.sequence = &sequenceCommon{meta: tblInfo.Sequence}
}
}
// initTableIndices initializes the indices of the TableCommon.
func initTableIndices(t *TableCommon) error {
tblInfo := t.meta
for _, idxInfo := range tblInfo.Indices {
if idxInfo.State == model.StateNone {
return table.ErrIndexStateCantNone.GenWithStackByArgs(idxInfo.Name)
}
// Use partition ID for index, because TableCommon may be table or partition.
idx := NewIndex(t.physicalTableID, tblInfo, idxInfo)
t.indices = append(t.indices, idx)
}
return nil
}
func initTableCommonWithIndices(t *TableCommon, tblInfo *model.TableInfo, physicalTableID int64, cols []*table.Column, allocs autoid.Allocators) error {
initTableCommon(t, tblInfo, physicalTableID, cols, allocs)
return initTableIndices(t)
}
// Indices implements table.Table Indices interface.
func (t *TableCommon) Indices() []table.Index {
return t.indices
}
// GetWritableIndexByName gets the index meta from the table by the index name.
func GetWritableIndexByName(idxName string, t table.Table) table.Index {
for _, idx := range t.Indices() {
if !IsIndexWritable(idx) {
continue
}
if idxName == idx.Meta().Name.L {
return idx
}
}
return nil
}
// deletableIndices implements table.Table deletableIndices interface.
func (t *TableCommon) deletableIndices() []table.Index {
// All indices are deletable because we don't need to check StateNone.
return t.indices
}
// Meta implements table.Table Meta interface.
func (t *TableCommon) Meta() *model.TableInfo {
return t.meta
}
// GetPhysicalID implements table.Table GetPhysicalID interface.
func (t *TableCommon) GetPhysicalID() int64 {
return t.physicalTableID
}
type getColsMode int64
const (
_ getColsMode = iota
visible
hidden
full
)
func (t *TableCommon) getCols(mode getColsMode) []*table.Column {
columns := make([]*table.Column, 0, len(t.Columns))
for _, col := range t.Columns {
if col.State != model.StatePublic {
continue
}
if (mode == visible && col.Hidden) || (mode == hidden && !col.Hidden) {
continue
}
columns = append(columns, col)
}
return columns
}
// Cols implements table.Table Cols interface.
func (t *TableCommon) Cols() []*table.Column {
if len(t.PublicColumns) > 0 {
return t.PublicColumns
}
return t.getCols(full)
}
// VisibleCols implements table.Table VisibleCols interface.
func (t *TableCommon) VisibleCols() []*table.Column {
if len(t.VisibleColumns) > 0 {
return t.VisibleColumns
}
return t.getCols(visible)
}
// HiddenCols implements table.Table HiddenCols interface.
func (t *TableCommon) HiddenCols() []*table.Column {
if len(t.HiddenColumns) > 0 {
return t.HiddenColumns
}
return t.getCols(hidden)
}
// WritableCols implements table WritableCols interface.
func (t *TableCommon) WritableCols() []*table.Column {
if len(t.WritableColumns) > 0 {
return t.WritableColumns
}
writableColumns := make([]*table.Column, 0, len(t.Columns))
for _, col := range t.Columns {
if col.State == model.StateDeleteOnly || col.State == model.StateDeleteReorganization {
continue
}
writableColumns = append(writableColumns, col)
}
return writableColumns
}
// DeletableCols implements table DeletableCols interface.
func (t *TableCommon) DeletableCols() []*table.Column {
return t.Columns
}
// FullHiddenColsAndVisibleCols implements table FullHiddenColsAndVisibleCols interface.
func (t *TableCommon) FullHiddenColsAndVisibleCols() []*table.Column {
if len(t.FullHiddenColsAndVisibleColumns) > 0 {
return t.FullHiddenColsAndVisibleColumns
}
cols := make([]*table.Column, 0, len(t.Columns))
for _, col := range t.Columns {
if col.Hidden || col.State == model.StatePublic {
cols = append(cols, col)
}
}
return cols
}
// RecordPrefix implements table.Table interface.
func (t *TableCommon) RecordPrefix() kv.Key {
return t.recordPrefix
}
// RecordKey implements table.Table interface.
func (t *TableCommon) RecordKey(h kv.Handle) kv.Key {
return tablecodec.EncodeRecordKey(t.recordPrefix, h)
}
// UpdateRecord implements table.Table UpdateRecord interface.
// `touched` means which columns are really modified, used for secondary indices.
// Length of `oldData` and `newData` equals to length of `t.WritableCols()`.
func (t *TableCommon) UpdateRecord(ctx context.Context, sctx sessionctx.Context, h kv.Handle, oldData, newData []types.Datum, touched []bool) error {
txn, err := sctx.Txn(true)
if err != nil {
return err
}
memBuffer := txn.GetMemBuffer()
sh := memBuffer.Staging()
defer memBuffer.Cleanup(sh)
if m := t.Meta(); m.TempTableType != model.TempTableNone {
if tmpTable := addTemporaryTable(sctx, m); tmpTable != nil {
if err := checkTempTableSize(sctx, tmpTable, m); err != nil {
return err
}
defer handleTempTableSize(tmpTable, txn.Size(), txn)
}
}
var colIDs, binlogColIDs []int64
var row, binlogOldRow, binlogNewRow []types.Datum
numColsCap := len(newData) + 1 // +1 for the extra handle column that we may need to append.
colIDs = make([]int64, 0, numColsCap)
row = make([]types.Datum, 0, numColsCap)
if shouldWriteBinlog(sctx, t.meta) {
binlogColIDs = make([]int64, 0, numColsCap)
binlogOldRow = make([]types.Datum, 0, numColsCap)
binlogNewRow = make([]types.Datum, 0, numColsCap)
}
for _, col := range t.Columns {
var value types.Datum
if col.State == model.StateDeleteOnly || col.State == model.StateDeleteReorganization {
if col.ChangeStateInfo != nil {
// TODO: Check overflow or ignoreTruncate.
value, err = table.CastValue(sctx, oldData[col.DependencyColumnOffset], col.ColumnInfo, false, false)
if err != nil {
logutil.BgLogger().Info("update record cast value failed", zap.Any("col", col), zap.Uint64("txnStartTS", txn.StartTS()),
zap.String("handle", h.String()), zap.Any("val", oldData[col.DependencyColumnOffset]), zap.Error(err))
return err
}
oldData = append(oldData, value)
touched = append(touched, touched[col.DependencyColumnOffset])
}
continue
}
if col.State != model.StatePublic {
// If col is in write only or write reorganization state we should keep the oldData.
// Because the oldData must be the original data(it's changed by other TiDBs.) or the original default value.
// TODO: Use newData directly.
value = oldData[col.Offset]
if col.ChangeStateInfo != nil {
// TODO: Check overflow or ignoreTruncate.
value, err = table.CastValue(sctx, newData[col.DependencyColumnOffset], col.ColumnInfo, false, false)
if err != nil {
return err
}
newData[col.Offset] = value
touched[col.Offset] = touched[col.DependencyColumnOffset]
}
} else {
value = newData[col.Offset]
}
if !t.canSkip(col, &value) {
colIDs = append(colIDs, col.ID)
row = append(row, value)
}
if shouldWriteBinlog(sctx, t.meta) && !t.canSkipUpdateBinlog(col, value) {
binlogColIDs = append(binlogColIDs, col.ID)
binlogOldRow = append(binlogOldRow, oldData[col.Offset])
binlogNewRow = append(binlogNewRow, value)
}
}
sessVars := sctx.GetSessionVars()
// rebuild index
if !sessVars.InTxn() {
savePresumeKeyNotExist := sessVars.PresumeKeyNotExists
if !sessVars.ConstraintCheckInPlace && sessVars.TxnCtx.IsPessimistic {
sessVars.PresumeKeyNotExists = true
}
err = t.rebuildIndices(sctx, txn, h, touched, oldData, newData, table.WithCtx(ctx))
sessVars.PresumeKeyNotExists = savePresumeKeyNotExist
if err != nil {
return err
}
} else {
err = t.rebuildIndices(sctx, txn, h, touched, oldData, newData, table.WithCtx(ctx))
if err != nil {
return err
}
}
key := t.RecordKey(h)
sc, rd := sessVars.StmtCtx, &sessVars.RowEncoder
value, err := tablecodec.EncodeRow(sc, row, colIDs, nil, nil, rd)
if err != nil {
return err
}
if err = memBuffer.Set(key, value); err != nil {
return err
}
memBuffer.Release(sh)
if shouldWriteBinlog(sctx, t.meta) {
if !t.meta.PKIsHandle && !t.meta.IsCommonHandle {
binlogColIDs = append(binlogColIDs, model.ExtraHandleID)
binlogOldRow = append(binlogOldRow, types.NewIntDatum(h.IntValue()))
binlogNewRow = append(binlogNewRow, types.NewIntDatum(h.IntValue()))
}
err = t.addUpdateBinlog(sctx, binlogOldRow, binlogNewRow, binlogColIDs)
if err != nil {
return err
}
}
colSize := make(map[int64]int64, len(t.Cols()))
for id, col := range t.Cols() {
size, err := codec.EstimateValueSize(sc, newData[id])
if err != nil {
continue
}
newLen := size - 1
size, err = codec.EstimateValueSize(sc, oldData[id])
if err != nil {
continue
}
oldLen := size - 1
colSize[col.ID] = int64(newLen - oldLen)
}
sessVars.TxnCtx.UpdateDeltaForTable(t.physicalTableID, 0, 1, colSize)
return nil
}
func (t *TableCommon) rebuildIndices(ctx sessionctx.Context, txn kv.Transaction, h kv.Handle, touched []bool, oldData []types.Datum, newData []types.Datum, opts ...table.CreateIdxOptFunc) error {
for _, idx := range t.deletableIndices() {
if t.meta.IsCommonHandle && idx.Meta().Primary {
continue
}
for _, ic := range idx.Meta().Columns {
if !touched[ic.Offset] {
continue
}
oldVs, err := idx.FetchValues(oldData, nil)
if err != nil {
return err
}
if err = t.removeRowIndex(ctx.GetSessionVars().StmtCtx, h, oldVs, idx, txn); err != nil {
return err
}
break
}
}
for _, idx := range t.Indices() {
if !IsIndexWritable(idx) {
continue
}
if t.meta.IsCommonHandle && idx.Meta().Primary {
continue
}
untouched := true
for _, ic := range idx.Meta().Columns {
if !touched[ic.Offset] {
continue
}
untouched = false
break
}
// If txn is auto commit and index is untouched, no need to write index value.
if untouched && !ctx.GetSessionVars().InTxn() {
continue
}
newVs, err := idx.FetchValues(newData, nil)
if err != nil {
return err
}
if err := t.buildIndexForRow(ctx, h, newVs, newData, idx, txn, untouched, opts...); err != nil {
return err
}
}
return nil
}
// adjustRowValuesBuf adjust writeBufs.AddRowValues length, AddRowValues stores the inserting values that is used
// by tablecodec.EncodeRow, the encoded row format is `id1, colval, id2, colval`, so the correct length is rowLen * 2. If
// the inserting row has null value, AddRecord will skip it, so the rowLen will be different, so we need to adjust it.
func adjustRowValuesBuf(writeBufs *variable.WriteStmtBufs, rowLen int) {
adjustLen := rowLen * 2
if writeBufs.AddRowValues == nil || cap(writeBufs.AddRowValues) < adjustLen {
writeBufs.AddRowValues = make([]types.Datum, adjustLen)
}
writeBufs.AddRowValues = writeBufs.AddRowValues[:adjustLen]
}
// FindPrimaryIndex uses to find primary index in tableInfo.
func FindPrimaryIndex(tblInfo *model.TableInfo) *model.IndexInfo {
var pkIdx *model.IndexInfo
for _, idx := range tblInfo.Indices {
if idx.Primary {
pkIdx = idx
break
}
}
return pkIdx
}
// CommonAddRecordCtx is used in `AddRecord` to avoid memory malloc for some temp slices.
// This is useful in lightning parse row data to key-values pairs. This can gain upto 5% performance
// improvement in lightning's local mode.
type CommonAddRecordCtx struct {
colIDs []int64
row []types.Datum
}
// commonAddRecordKey is used as key in `sessionctx.Context.Value(key)`
type commonAddRecordKey struct{}
// String implement `stringer.String` for CommonAddRecordKey
func (c commonAddRecordKey) String() string {
return "_common_add_record_context_key"
}
// addRecordCtxKey is key in `sessionctx.Context` for CommonAddRecordCtx
var addRecordCtxKey = commonAddRecordKey{}
// SetAddRecordCtx set a CommonAddRecordCtx to session context
func SetAddRecordCtx(ctx sessionctx.Context, r *CommonAddRecordCtx) {
ctx.SetValue(addRecordCtxKey, r)
}
// ClearAddRecordCtx remove `CommonAddRecordCtx` from session context
func ClearAddRecordCtx(ctx sessionctx.Context) {
ctx.ClearValue(addRecordCtxKey)
}
// NewCommonAddRecordCtx create a context used for `AddRecord`
func NewCommonAddRecordCtx(size int) *CommonAddRecordCtx {
return &CommonAddRecordCtx{
colIDs: make([]int64, 0, size),
row: make([]types.Datum, 0, size),
}
}
// TryGetCommonPkColumnIds get the IDs of primary key column if the table has common handle.
func TryGetCommonPkColumnIds(tbl *model.TableInfo) []int64 {
if !tbl.IsCommonHandle {
return nil
}
pkIdx := FindPrimaryIndex(tbl)
pkColIds := make([]int64, 0, len(pkIdx.Columns))
for _, idxCol := range pkIdx.Columns {
pkColIds = append(pkColIds, tbl.Columns[idxCol.Offset].ID)
}
return pkColIds
}
// PrimaryPrefixColumnIDs get prefix column ids in primary key.
func PrimaryPrefixColumnIDs(tbl *model.TableInfo) (prefixCols []int64) {
for _, idx := range tbl.Indices {
if !idx.Primary {
continue
}
for _, col := range idx.Columns {
if col.Length > 0 && tbl.Columns[col.Offset].Flen > col.Length {
prefixCols = append(prefixCols, tbl.Columns[col.Offset].ID)
}
}
}
return
}
// TryGetCommonPkColumns get the primary key columns if the table has common handle.
func TryGetCommonPkColumns(tbl table.Table) []*table.Column {
if !tbl.Meta().IsCommonHandle {
return nil
}
pkIdx := FindPrimaryIndex(tbl.Meta())
cols := tbl.Cols()
pkCols := make([]*table.Column, 0, len(pkIdx.Columns))
for _, idxCol := range pkIdx.Columns {
pkCols = append(pkCols, cols[idxCol.Offset])
}
return pkCols
}
func addTemporaryTable(sctx sessionctx.Context, tblInfo *model.TableInfo) tableutil.TempTable {
tempTable := sctx.GetSessionVars().GetTemporaryTable(tblInfo)
tempTable.SetModified(true)
return tempTable
}
// The size of a temporary table is calculated by accumulating the transaction size delta.
func handleTempTableSize(t tableutil.TempTable, txnSizeBefore int, txn kv.Transaction) {
txnSizeNow := txn.Size()
delta := txnSizeNow - txnSizeBefore
oldSize := t.GetSize()
newSize := oldSize + int64(delta)
t.SetSize(newSize)
}
func checkTempTableSize(ctx sessionctx.Context, tmpTable tableutil.TempTable, tblInfo *model.TableInfo) error {
tmpTableSize := tmpTable.GetSize()
if tempTableData := ctx.GetSessionVars().TemporaryTableData; tempTableData != nil {
tmpTableSize += tempTableData.GetTableSize(tblInfo.ID)
}
if tmpTableSize > ctx.GetSessionVars().TMPTableSize {
return table.ErrTempTableFull.GenWithStackByArgs(tblInfo.Name.O)
}
return nil
}
// AddRecord implements table.Table AddRecord interface.
func (t *TableCommon) AddRecord(sctx sessionctx.Context, r []types.Datum, opts ...table.AddRecordOption) (recordID kv.Handle, err error) {
txn, err := sctx.Txn(true)
if err != nil {
return nil, err
}
var opt table.AddRecordOpt
for _, fn := range opts {
fn.ApplyOn(&opt)
}
if m := t.Meta(); m.TempTableType != model.TempTableNone {
if tmpTable := addTemporaryTable(sctx, m); tmpTable != nil {
if err := checkTempTableSize(sctx, tmpTable, m); err != nil {
return nil, err
}
defer handleTempTableSize(tmpTable, txn.Size(), txn)
}
}
var ctx context.Context
if opt.Ctx != nil {
ctx = opt.Ctx
if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {
span1 := span.Tracer().StartSpan("table.AddRecord", opentracing.ChildOf(span.Context()))
defer span1.Finish()
ctx = opentracing.ContextWithSpan(ctx, span1)
}
} else {
ctx = context.Background()
}
var hasRecordID bool
cols := t.Cols()
// opt.IsUpdate is a flag for update.
// If handle ID is changed when update, update will remove the old record first, and then call `AddRecord` to add a new record.
// Currently, only insert can set _tidb_rowid, update can not update _tidb_rowid.
if len(r) > len(cols) && !opt.IsUpdate {
// The last value is _tidb_rowid.
recordID = kv.IntHandle(r[len(r)-1].GetInt64())
hasRecordID = true
} else {
tblInfo := t.Meta()
txn.CacheTableInfo(t.physicalTableID, tblInfo)
if tblInfo.PKIsHandle {
recordID = kv.IntHandle(r[tblInfo.GetPkColInfo().Offset].GetInt64())
hasRecordID = true
} else if tblInfo.IsCommonHandle {
pkIdx := FindPrimaryIndex(tblInfo)
pkDts := make([]types.Datum, 0, len(pkIdx.Columns))
for _, idxCol := range pkIdx.Columns {
pkDts = append(pkDts, r[idxCol.Offset])
}
tablecodec.TruncateIndexValues(tblInfo, pkIdx, pkDts)
var handleBytes []byte
handleBytes, err = codec.EncodeKey(sctx.GetSessionVars().StmtCtx, nil, pkDts...)
if err != nil {
return
}
recordID, err = kv.NewCommonHandle(handleBytes)
if err != nil {
return
}
hasRecordID = true
}
}
if !hasRecordID {
if opt.ReserveAutoID > 0 {
// Reserve a batch of auto ID in the statement context.
// The reserved ID could be used in the future within this statement, by the
// following AddRecord() operation.
// Make the IDs continuous benefit for the performance of TiKV.
stmtCtx := sctx.GetSessionVars().StmtCtx
stmtCtx.BaseRowID, stmtCtx.MaxRowID, err = allocHandleIDs(ctx, sctx, t, uint64(opt.ReserveAutoID))
if err != nil {
return nil, err
}
}
recordID, err = AllocHandle(ctx, sctx, t)
if err != nil {
return nil, err
}
}
var colIDs, binlogColIDs []int64
var row, binlogRow []types.Datum
if recordCtx, ok := sctx.Value(addRecordCtxKey).(*CommonAddRecordCtx); ok {
colIDs = recordCtx.colIDs[:0]
row = recordCtx.row[:0]
} else {
colIDs = make([]int64, 0, len(r))
row = make([]types.Datum, 0, len(r))
}
memBuffer := txn.GetMemBuffer()
sh := memBuffer.Staging()
defer memBuffer.Cleanup(sh)
sessVars := sctx.GetSessionVars()
for _, col := range t.WritableCols() {
var value types.Datum
// In column type change, since we have set the origin default value for changing col, but
// for the new insert statement, we should use the casted value of relative column to insert.
if col.ChangeStateInfo != nil && col.State != model.StatePublic {
// TODO: Check overflow or ignoreTruncate.
value, err = table.CastValue(sctx, r[col.DependencyColumnOffset], col.ColumnInfo, false, false)
if err != nil {
return nil, err
}
if len(r) < len(t.WritableCols()) {
r = append(r, value)
} else {
r[col.Offset] = value
}
row = append(row, value)
colIDs = append(colIDs, col.ID)
continue
}
if col.State != model.StatePublic &&
// Update call `AddRecord` will already handle the write only column default value.
// Only insert should add default value for write only column.
!opt.IsUpdate {
// If col is in write only or write reorganization state, we must add it with its default value.
value, err = table.GetColOriginDefaultValue(sctx, col.ToInfo())
if err != nil {
return nil, err
}
// add value to `r` for dirty db in transaction.
// Otherwise when update will panic cause by get value of column in write only state from dirty db.
if col.Offset < len(r) {
r[col.Offset] = value
} else {
r = append(r, value)
}
} else {
value = r[col.Offset]
}
if !t.canSkip(col, &value) {
colIDs = append(colIDs, col.ID)
row = append(row, value)
}
}
writeBufs := sessVars.GetWriteStmtBufs()
adjustRowValuesBuf(writeBufs, len(row))
key := t.RecordKey(recordID)
logutil.BgLogger().Debug("addRecord",
zap.Stringer("key", key))
sc, rd := sessVars.StmtCtx, &sessVars.RowEncoder
writeBufs.RowValBuf, err = tablecodec.EncodeRow(sc, row, colIDs, writeBufs.RowValBuf, writeBufs.AddRowValues, rd)
if err != nil {
return nil, err
}
value := writeBufs.RowValBuf
var setPresume bool
if !sctx.GetSessionVars().StmtCtx.BatchCheck {
if t.meta.TempTableType != model.TempTableNone {
// Always check key for temporary table because it does not write to TiKV
_, err = txn.Get(ctx, key)
} else if sctx.GetSessionVars().LazyCheckKeyNotExists() {
var v []byte
v, err = txn.GetMemBuffer().Get(ctx, key)
if err != nil {
setPresume = true
}
if err == nil && len(v) == 0 {
err = kv.ErrNotExist
}
} else {
_, err = txn.Get(ctx, key)
}
if err == nil {
handleStr := getDuplicateErrorHandleString(t, recordID, r)
return recordID, kv.ErrKeyExists.FastGenByArgs(handleStr, "PRIMARY")
} else if !kv.ErrNotExist.Equal(err) {
return recordID, err
}
}
if setPresume {
err = memBuffer.SetWithFlags(key, value, kv.SetPresumeKeyNotExists)
} else {
err = memBuffer.Set(key, value)
}
if err != nil {
return nil, err
}
var createIdxOpts []table.CreateIdxOptFunc
if len(opts) > 0 {
createIdxOpts = make([]table.CreateIdxOptFunc, 0, len(opts))
for _, fn := range opts {
if raw, ok := fn.(table.CreateIdxOptFunc); ok {
createIdxOpts = append(createIdxOpts, raw)
}
}
}
// Insert new entries into indices.
h, err := t.addIndices(sctx, recordID, r, txn, createIdxOpts)
if err != nil {
return h, err
}
memBuffer.Release(sh)
if shouldWriteBinlog(sctx, t.meta) {
// For insert, TiDB and Binlog can use same row and schema.
binlogRow = row
binlogColIDs = colIDs
err = t.addInsertBinlog(sctx, recordID, binlogRow, binlogColIDs)
if err != nil {
return nil, err
}
}
if sessVars.TxnCtx == nil {
return recordID, nil
}
colSize := make(map[int64]int64, len(r))
for id, col := range t.Cols() {
size, err := codec.EstimateValueSize(sc, r[id])
if err != nil {
continue
}
colSize[col.ID] = int64(size) - 1
}
sessVars.TxnCtx.UpdateDeltaForTable(t.physicalTableID, 1, 1, colSize)
return recordID, nil
}
// genIndexKeyStr generates index content string representation.
func genIndexKeyStr(colVals []types.Datum) (string, error) {
// Pass pre-composed error to txn.
strVals := make([]string, 0, len(colVals))
for _, cv := range colVals {
cvs := "NULL"
var err error
if !cv.IsNull() {
cvs, err = types.ToString(cv.GetValue())
if err != nil {
return "", err
}
}
strVals = append(strVals, cvs)
}
return strings.Join(strVals, "-"), nil
}
// addIndices adds data into indices. If any key is duplicated, returns the original handle.
func (t *TableCommon) addIndices(sctx sessionctx.Context, recordID kv.Handle, r []types.Datum, txn kv.Transaction, opts []table.CreateIdxOptFunc) (kv.Handle, error) {
writeBufs := sctx.GetSessionVars().GetWriteStmtBufs()
indexVals := writeBufs.IndexValsBuf
skipCheck := sctx.GetSessionVars().StmtCtx.BatchCheck
for _, v := range t.Indices() {
if !IsIndexWritable(v) {
continue
}
if t.meta.IsCommonHandle && v.Meta().Primary {
continue
}
indexVals, err := v.FetchValues(r, indexVals)
if err != nil {
return nil, err
}
var dupErr error
if !skipCheck && v.Meta().Unique {
entryKey, err := genIndexKeyStr(indexVals)
if err != nil {
return nil, err
}
idxMeta := v.Meta()
dupErr = kv.ErrKeyExists.FastGenByArgs(entryKey, idxMeta.Name.String())
}
rsData := TryGetHandleRestoredDataWrapper(t, r, nil, v.Meta())
if dupHandle, err := v.Create(sctx, txn, indexVals, recordID, rsData, opts...); err != nil {
if kv.ErrKeyExists.Equal(err) {
return dupHandle, dupErr
}
return nil, err
}
}
// save the buffer, multi rows insert can use it.
writeBufs.IndexValsBuf = indexVals
return nil, nil
}
// RowWithCols is used to get the corresponding column datum values with the given handle.
func RowWithCols(t table.Table, ctx sessionctx.Context, h kv.Handle, cols []*table.Column) ([]types.Datum, error) {
// Get raw row data from kv.
key := tablecodec.EncodeRecordKey(t.RecordPrefix(), h)
txn, err := ctx.Txn(true)
if err != nil {
return nil, err
}
value, err := txn.Get(context.TODO(), key)
if err != nil {
return nil, err
}
v, _, err := DecodeRawRowData(ctx, t.Meta(), h, cols, value)
if err != nil {
return nil, err
}
return v, nil
}
func containFullColInHandle(meta *model.TableInfo, col *table.Column) (containFullCol bool, idxInHandle int) {
pkIdx := FindPrimaryIndex(meta)
for i, idxCol := range pkIdx.Columns {
if meta.Columns[idxCol.Offset].ID == col.ID {
idxInHandle = i
containFullCol = idxCol.Length == types.UnspecifiedLength
return
}
}
return
}
// DecodeRawRowData decodes raw row data into a datum slice and a (columnID:columnValue) map.
func DecodeRawRowData(ctx sessionctx.Context, meta *model.TableInfo, h kv.Handle, cols []*table.Column,
value []byte) ([]types.Datum, map[int64]types.Datum, error) {
v := make([]types.Datum, len(cols))
colTps := make(map[int64]*types.FieldType, len(cols))
prefixCols := make(map[int64]struct{})
for i, col := range cols {
if col == nil {
continue
}
if col.IsPKHandleColumn(meta) {
if mysql.HasUnsignedFlag(col.Flag) {
v[i].SetUint64(uint64(h.IntValue()))
} else {
v[i].SetInt64(h.IntValue())
}
continue
}
if col.IsCommonHandleColumn(meta) && !types.NeedRestoredData(&col.FieldType) {
if containFullCol, idxInHandle := containFullColInHandle(meta, col); containFullCol {
dtBytes := h.EncodedCol(idxInHandle)
_, dt, err := codec.DecodeOne(dtBytes)
if err != nil {
return nil, nil, err
}
dt, err = tablecodec.Unflatten(dt, &col.FieldType, ctx.GetSessionVars().Location())
if err != nil {
return nil, nil, err
}
v[i] = dt
continue
}
prefixCols[col.ID] = struct{}{}
}
colTps[col.ID] = &col.FieldType
}
rowMap, err := tablecodec.DecodeRowToDatumMap(value, colTps, ctx.GetSessionVars().Location())
if err != nil {
return nil, rowMap, err
}
defaultVals := make([]types.Datum, len(cols))