Skip to content

Commit

Permalink
*: reduce the allocation of error constructing in DecodeTableID (#4…
Browse files Browse the repository at this point in the history
  • Loading branch information
iosmanthus authored Feb 11, 2023
1 parent 01f8f6a commit 7352d7b
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 6 deletions.
1 change: 1 addition & 0 deletions tablecodec/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ go_test(
"//util/rowcodec",
"@com_github_pingcap_failpoint//:failpoint",
"@com_github_stretchr_testify//require",
"@com_github_tikv_client_go_v2//tikv",
"@org_uber_go_goleak//:goleak",
],
)
16 changes: 10 additions & 6 deletions tablecodec/tablecodec.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,13 +278,17 @@ func DecodeKeyHead(key kv.Key) (tableID int64, indexID int64, isRecordKey bool,

// DecodeTableID decodes the table ID of the key, if the key is not table key, returns 0.
func DecodeTableID(key kv.Key) int64 {
// If the key is in API V2, then ignore the prefix
_, k, err := tikv.DecodeKey(key, kvrpcpb.APIVersion_V2)
if err == nil {
key = k
}
if !key.HasPrefix(tablePrefix) {
return 0
// If the key is in API V2, then ignore the prefix
_, k, err := tikv.DecodeKey(key, kvrpcpb.APIVersion_V2)
if err != nil {
terror.Log(errors.Trace(err))
return 0
}
key = k
if !key.HasPrefix(tablePrefix) {
return 0
}
}
key = key[len(tablePrefix):]
_, tableID, err := codec.DecodeInt(key)
Expand Down
19 changes: 19 additions & 0 deletions tablecodec/tablecodec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
"github.com/pingcap/tidb/util/collate"
"github.com/pingcap/tidb/util/rowcodec"
"github.com/stretchr/testify/require"
"github.com/tikv/client-go/v2/tikv"
)

// TestTableCodec tests some functions in package tablecodec
Expand Down Expand Up @@ -698,3 +699,21 @@ func TestTempIndexValueCodec(t *testing.T) {
require.Equal(t, result[1].Handle.IntValue(), int64(100))
require.Equal(t, result[2].Handle.IntValue(), int64(101))
}

func TestV2TableCodec(t *testing.T) {
const tableID int64 = 31415926
key := EncodeTablePrefix(tableID)
c, err := tikv.NewCodecV2(tikv.ModeTxn, 271828)
require.NoError(t, err)
key = c.EncodeKey(key)
tbid := DecodeTableID(key)
require.Equal(t, tableID, tbid)

key = []byte("x001HelloWorld")
tbid = DecodeTableID(key)
require.Equal(t, int64(0), tbid)

key = []byte("x001x001t123")
tbid = DecodeTableID(key)
require.Equal(t, int64(0), tbid)
}

0 comments on commit 7352d7b

Please sign in to comment.