forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tablecodec.go
445 lines (406 loc) · 11.7 KB
/
tablecodec.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
// Copyright 2016 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package tablecodec
import (
"bytes"
"time"
"github.com/juju/errors"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/terror"
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/types"
)
var (
errInvalidRecordKey = terror.ClassXEval.New(codeInvalidRecordKey, "invalid record key")
errInvalidColumnCount = terror.ClassXEval.New(codeInvalidColumnCount, "invalid column count")
)
var (
tablePrefix = []byte{'t'}
recordPrefixSep = []byte("_r")
indexPrefixSep = []byte("_i")
)
const (
idLen = 8
prefixLen = 1 + idLen /*tableID*/ + 2
recordRowKeyLen = prefixLen + idLen /*handle*/
)
// EncodeRowKey encodes the table id and record handle into a kv.Key
func EncodeRowKey(tableID int64, encodedHandle []byte) kv.Key {
buf := make([]byte, 0, recordRowKeyLen)
buf = appendTableRecordPrefix(buf, tableID)
buf = append(buf, encodedHandle...)
return buf
}
// EncodeRowKeyWithHandle encodes the table id, row handle into a kv.Key
func EncodeRowKeyWithHandle(tableID int64, handle int64) kv.Key {
buf := make([]byte, 0, recordRowKeyLen+idLen)
buf = appendTableRecordPrefix(buf, tableID)
buf = codec.EncodeInt(buf, handle)
return buf
}
// EncodeRecordKey encodes the recordPrefix, row handle into a kv.Key.
func EncodeRecordKey(recordPrefix kv.Key, h int64) kv.Key {
buf := make([]byte, 0, len(recordPrefix)+16)
buf = append(buf, recordPrefix...)
buf = codec.EncodeInt(buf, h)
return buf
}
// DecodeRecordKey decodes the key and gets the tableID, handle.
func DecodeRecordKey(key kv.Key) (tableID int64, handle int64, err error) {
k := key
if !key.HasPrefix(tablePrefix) {
return 0, 0, errInvalidRecordKey.Gen("invalid record key - %q", k)
}
key = key[len(tablePrefix):]
key, tableID, err = codec.DecodeInt(key)
if err != nil {
return 0, 0, errors.Trace(err)
}
if !key.HasPrefix(recordPrefixSep) {
return 0, 0, errInvalidRecordKey.Gen("invalid record key - %q", k)
}
key = key[len(recordPrefixSep):]
key, handle, err = codec.DecodeInt(key)
if err != nil {
return 0, 0, errors.Trace(err)
}
return
}
// DecodeRowKey decodes the key and gets the handle.
func DecodeRowKey(key kv.Key) (int64, error) {
_, handle, err := DecodeRecordKey(key)
return handle, errors.Trace(err)
}
// EncodeValue encodes a go value to bytes.
func EncodeValue(raw types.Datum) ([]byte, error) {
v, err := flatten(raw)
if err != nil {
return nil, errors.Trace(err)
}
b, err := codec.EncodeValue(nil, v)
return b, errors.Trace(err)
}
// EncodeRow encode row data and column ids into a slice of byte.
// Row layout: colID1, value1, colID2, value2, .....
func EncodeRow(row []types.Datum, colIDs []int64) ([]byte, error) {
if len(row) != len(colIDs) {
return nil, errors.Errorf("EncodeRow error: data and columnID count not match %d vs %d", len(row), len(colIDs))
}
values := make([]types.Datum, 2*len(row))
for i, c := range row {
id := colIDs[i]
idv := types.NewIntDatum(id)
values[2*i] = idv
fc, err := flatten(c)
if err != nil {
return nil, errors.Trace(err)
}
values[2*i+1] = fc
}
if len(values) == 0 {
// We could not set nil value into kv.
return []byte{codec.NilFlag}, nil
}
return codec.EncodeValue(nil, values...)
}
func flatten(data types.Datum) (types.Datum, error) {
switch data.Kind() {
case types.KindMysqlTime:
// for mysql datetime, timestamp and date type
return types.NewUintDatum(data.GetMysqlTime().ToPackedUint()), nil
case types.KindMysqlDuration:
// for mysql time type
data.SetInt64(int64(data.GetMysqlDuration().Duration))
return data, nil
case types.KindMysqlEnum:
data.SetUint64(data.GetMysqlEnum().Value)
return data, nil
case types.KindMysqlSet:
data.SetUint64(data.GetMysqlSet().Value)
return data, nil
case types.KindMysqlBit:
data.SetUint64(data.GetMysqlBit().Value)
return data, nil
case types.KindMysqlHex:
data.SetInt64(data.GetMysqlHex().Value)
return data, nil
default:
return data, nil
}
}
// DecodeValues decodes a byte slice into datums with column types.
func DecodeValues(data []byte, fts []*types.FieldType, inIndex bool) ([]types.Datum, error) {
if len(data) == 0 {
return nil, nil
}
values, err := codec.Decode(data, len(fts))
if err != nil {
return nil, errors.Trace(err)
}
if len(values) > len(fts) {
return nil, errInvalidColumnCount.Gen("invalid column count %d is less than value count %d", len(fts), len(values))
}
for i := range values {
values[i], err = Unflatten(values[i], fts[i], inIndex)
if err != nil {
return nil, errors.Trace(err)
}
}
return values, nil
}
// DecodeColumnValue decodes data to a Datum according to the column info.
func DecodeColumnValue(data []byte, ft *types.FieldType) (types.Datum, error) {
_, d, err := codec.DecodeOne(data)
if err != nil {
return types.Datum{}, errors.Trace(err)
}
colDatum, err := Unflatten(d, ft, false)
if err != nil {
return types.Datum{}, errors.Trace(err)
}
return colDatum, nil
}
// DecodeRow decodes a byte slice into datums.
// Row layout: colID1, value1, colID2, value2, .....
func DecodeRow(b []byte, cols map[int64]*types.FieldType) (map[int64]types.Datum, error) {
if b == nil {
return nil, nil
}
if len(b) == 1 && b[0] == codec.NilFlag {
return nil, nil
}
row := make(map[int64]types.Datum, len(cols))
cnt := 0
var (
data []byte
err error
)
for len(b) > 0 {
// Get col id.
data, b, err = codec.CutOne(b)
if err != nil {
return nil, errors.Trace(err)
}
_, cid, err := codec.DecodeOne(data)
if err != nil {
return nil, errors.Trace(err)
}
// Get col value.
data, b, err = codec.CutOne(b)
if err != nil {
return nil, errors.Trace(err)
}
id := cid.GetInt64()
ft, ok := cols[id]
if ok {
_, v, err := codec.DecodeOne(data)
if err != nil {
return nil, errors.Trace(err)
}
v, err = Unflatten(v, ft, false)
if err != nil {
return nil, errors.Trace(err)
}
row[id] = v
cnt++
if cnt == len(cols) {
// Get enough data.
break
}
}
}
return row, nil
}
// CutRow cut encoded row into byte slices and return interested columns' byte slice.
// Row layout: colID1, value1, colID2, value2, .....
func CutRow(data []byte, cols map[int64]*types.FieldType) (map[int64][]byte, error) {
if data == nil {
return nil, nil
}
if len(data) == 1 && data[0] == codec.NilFlag {
return nil, nil
}
row := make(map[int64][]byte, len(cols))
cnt := 0
var (
b []byte
err error
)
for len(data) > 0 && cnt < len(cols) {
// Get col id.
b, data, err = codec.CutOne(data)
if err != nil {
return nil, errors.Trace(err)
}
_, cid, err := codec.DecodeOne(b)
if err != nil {
return nil, errors.Trace(err)
}
// Get col value.
b, data, err = codec.CutOne(data)
if err != nil {
return nil, errors.Trace(err)
}
id := cid.GetInt64()
_, ok := cols[id]
if ok {
row[id] = b
cnt++
}
}
return row, nil
}
// Unflatten converts a raw datum to a column datum.
func Unflatten(datum types.Datum, ft *types.FieldType, inIndex bool) (types.Datum, error) {
if datum.IsNull() {
return datum, nil
}
switch ft.Tp {
case mysql.TypeFloat:
datum.SetFloat32(float32(datum.GetFloat64()))
return datum, nil
case mysql.TypeTiny, mysql.TypeShort, mysql.TypeYear, mysql.TypeInt24,
mysql.TypeLong, mysql.TypeLonglong, mysql.TypeDouble, mysql.TypeTinyBlob,
mysql.TypeMediumBlob, mysql.TypeBlob, mysql.TypeLongBlob, mysql.TypeVarchar,
mysql.TypeString:
return datum, nil
case mysql.TypeDate, mysql.TypeDatetime, mysql.TypeTimestamp:
var t mysql.Time
t.Type = ft.Tp
t.Fsp = ft.Decimal
var err error
err = t.FromPackedUint(datum.GetUint64())
if err != nil {
return datum, errors.Trace(err)
}
datum.SetMysqlTime(t)
return datum, nil
case mysql.TypeDuration:
dur := mysql.Duration{Duration: time.Duration(datum.GetInt64())}
datum.SetValue(dur)
return datum, nil
case mysql.TypeEnum:
enum, err := mysql.ParseEnumValue(ft.Elems, datum.GetUint64())
if err != nil {
return datum, errors.Trace(err)
}
datum.SetValue(enum)
return datum, nil
case mysql.TypeSet:
set, err := mysql.ParseSetValue(ft.Elems, datum.GetUint64())
if err != nil {
return datum, errors.Trace(err)
}
datum.SetValue(set)
return datum, nil
case mysql.TypeBit:
bit := mysql.Bit{Value: datum.GetUint64(), Width: ft.Flen}
datum.SetValue(bit)
return datum, nil
}
return datum, nil
}
// EncodeIndexSeekKey encodes an index value to kv.Key.
func EncodeIndexSeekKey(tableID int64, idxID int64, encodedValue []byte) kv.Key {
key := make([]byte, 0, prefixLen+len(encodedValue))
key = appendTableIndexPrefix(key, tableID)
key = codec.EncodeInt(key, idxID)
key = append(key, encodedValue...)
return key
}
// DecodeIndexKey decodes datums from an index key.
func DecodeIndexKey(key kv.Key) ([]types.Datum, error) {
b := key[prefixLen+idLen:]
return codec.Decode(b, 1)
}
// CutIndexKey cuts encoded index key into colIDs to bytes slices map.
// The returned value b is the remaining bytes of the key which would be empty if it is unique index or handle data
// if it is non-unique index.
func CutIndexKey(key kv.Key, colIDs []int64) (values map[int64][]byte, b []byte, err error) {
b = key[prefixLen+idLen:]
values = make(map[int64][]byte)
for _, id := range colIDs {
var val []byte
val, b, err = codec.CutOne(b)
if err != nil {
return nil, nil, errors.Trace(err)
}
values[id] = val
}
return
}
// EncodeTableIndexPrefix encodes index prefix with tableID and idxID.
func EncodeTableIndexPrefix(tableID, idxID int64) kv.Key {
key := make([]byte, 0, prefixLen)
key = appendTableIndexPrefix(key, tableID)
key = codec.EncodeInt(key, idxID)
return key
}
// EncodeTablePrefix encodes table prefix with table ID.
func EncodeTablePrefix(tableID int64) kv.Key {
var key kv.Key
key = append(key, tablePrefix...)
key = codec.EncodeInt(key, tableID)
return key
}
// Record prefix is "t[tableID]_r".
func appendTableRecordPrefix(buf []byte, tableID int64) []byte {
buf = append(buf, tablePrefix...)
buf = codec.EncodeInt(buf, tableID)
buf = append(buf, recordPrefixSep...)
return buf
}
// Index prefix is "t[tableID]_i".
func appendTableIndexPrefix(buf []byte, tableID int64) []byte {
buf = append(buf, tablePrefix...)
buf = codec.EncodeInt(buf, tableID)
buf = append(buf, indexPrefixSep...)
return buf
}
// GenTableRecordPrefix composes record prefix with tableID: "t[tableID]_r".
func GenTableRecordPrefix(tableID int64) kv.Key {
buf := make([]byte, 0, len(tablePrefix)+8+len(recordPrefixSep))
return appendTableRecordPrefix(buf, tableID)
}
// GenTableIndexPrefix composes index prefix with tableID: "t[tableID]_i".
func GenTableIndexPrefix(tableID int64) kv.Key {
buf := make([]byte, 0, len(tablePrefix)+8+len(indexPrefixSep))
return appendTableIndexPrefix(buf, tableID)
}
// TruncateToRowKeyLen truncates the key to row key length if the key is longer than row key.
func TruncateToRowKeyLen(key kv.Key) kv.Key {
if len(key) > recordRowKeyLen {
return key[:recordRowKeyLen]
}
return key
}
type keyRangeSorter struct {
ranges []kv.KeyRange
}
func (r *keyRangeSorter) Len() int {
return len(r.ranges)
}
func (r *keyRangeSorter) Less(i, j int) bool {
a := r.ranges[i]
b := r.ranges[j]
cmp := bytes.Compare(a.StartKey, b.StartKey)
return cmp < 0
}
func (r *keyRangeSorter) Swap(i, j int) {
r.ranges[i], r.ranges[j] = r.ranges[j], r.ranges[i]
}
const (
codeInvalidRecordKey = 4
codeInvalidColumnCount = 5
)