Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

*: show PK name when decoding the clustered index row key #30623

Merged
merged 3 commits into from
Dec 10, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions ddl/ddl_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -1577,7 +1577,7 @@ func buildTableInfo(
tbInfo.CommonHandleVersion = 1
}
}
if tbInfo.PKIsHandle || tbInfo.IsCommonHandle {
if tbInfo.HasClusteredIndex() {
// Primary key cannot be invisible.
if constr.Option != nil && constr.Option.Visibility == ast.IndexVisibilityInvisible {
return nil, ErrPKIndexCantBeInvisible
Expand Down Expand Up @@ -2438,7 +2438,7 @@ func handleTableOptions(options []*ast.TableOption, tbInfo *model.TableInfo) err
case ast.TableOptionCompression:
tbInfo.Compression = op.StrValue
case ast.TableOptionShardRowID:
if op.UintValue > 0 && (tbInfo.PKIsHandle || tbInfo.IsCommonHandle) {
if op.UintValue > 0 && tbInfo.HasClusteredIndex() {
return errUnsupportedShardRowIDBits
}
tbInfo.ShardRowIDBits = op.UintValue
Expand Down Expand Up @@ -2946,7 +2946,7 @@ func (d *ddl) ShardRowID(ctx sessionctx.Context, tableIdent ast.Ident, uVal uint
// Nothing need to do.
return nil
}
if uVal > 0 && (t.Meta().PKIsHandle || t.Meta().IsCommonHandle) {
if uVal > 0 && t.Meta().HasClusteredIndex() {
return errUnsupportedShardRowIDBits
}
err = verifyNoOverflowShardBits(d.sessPool, t, uVal)
Expand Down
2 changes: 1 addition & 1 deletion executor/infoschema_reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ func (e *memtableRetriever) setDataFromTables(ctx context.Context, sctx sessionc
rowCount = 1
}
}
if table.PKIsHandle || table.IsCommonHandle {
if table.HasClusteredIndex() {
pkType = "CLUSTERED"
}
shardingInfo := infoschema.GetShardingInfo(schema, table)
Expand Down
2 changes: 1 addition & 1 deletion executor/show.go
Original file line number Diff line number Diff line change
Expand Up @@ -975,7 +975,7 @@ func ConstructResultOfShowCreateTable(ctx sessionctx.Context, tableInfo *model.T
fmt.Fprintf(buf, ` COMMENT '%s'`, format.OutputFormat(idxInfo.Comment))
}
if idxInfo.Primary {
if tableInfo.PKIsHandle || tableInfo.IsCommonHandle {
if tableInfo.HasClusteredIndex() {
buf.WriteString(" /*T![clustered_index] CLUSTERED */")
} else {
buf.WriteString(" /*T![clustered_index] NONCLUSTERED */")
Expand Down
2 changes: 1 addition & 1 deletion expression/builtin_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -746,7 +746,7 @@ func (b *builtinTiDBDecodeKeySig) Clone() builtinFunc {
return newSig
}

// evalInt evals a builtinTiDBIsDDLOwnerSig.
// evalInt evals a builtinTiDBDecodeKeySig.
func (b *builtinTiDBDecodeKeySig) evalString(row chunk.Row) (string, bool, error) {
s, isNull, err := b.args[0].EvalString(b.ctx, row)
if isNull || err != nil {
Expand Down
43 changes: 36 additions & 7 deletions expression/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2826,7 +2826,7 @@ func TestTiDBDecodePlanFunc(t *testing.T) {
tk.MustQuery("select tidb_decode_plan('xxx')").Check(testkit.Rows("xxx"))
}

func TestTiDBInternalFunc(t *testing.T) {
func TestTiDBDecodeKeyFunc(t *testing.T) {
t.Parallel()

store, clean := testkit.CreateMockStore(t)
Expand Down Expand Up @@ -2876,16 +2876,14 @@ func TestTiDBInternalFunc(t *testing.T) {
h, err := kv.NewCommonHandle(k)
require.NoError(t, err)
k = tablecodec.EncodeRowKeyWithHandle(tableID, h)
hexKey := hex.EncodeToString(codec.EncodeBytes(nil, k))
return hexKey
return hex.EncodeToString(codec.EncodeBytes(nil, k))
}
// split table t by ('bbbb', 10, '2020-01-01');
data := []types.Datum{types.NewStringDatum("bbbb"), types.NewIntDatum(10), types.NewTimeDatum(getTime(2020, 1, 1, mysql.TypeDatetime))}
hexKey := buildCommonKeyFromData(tbl.Meta().ID, data)
sql := fmt.Sprintf("select tidb_decode_key( '%s' )", hexKey)
result = tk.MustQuery(sql)
rs := fmt.Sprintf(`{"handle":{"a":"bbbb","b":"10","c":"2020-01-01 00:00:00"},"table_id":%d}`, tbl.Meta().ID)
result.Check(testkit.Rows(rs))
tk.MustQuery(sql).Check(testkit.Rows(rs))

// split table t by ('bbbb', 10, null);
data = []types.Datum{types.NewStringDatum("bbbb"), types.NewIntDatum(10), types.NewDatum(nil)}
Expand All @@ -2903,8 +2901,7 @@ func TestTiDBInternalFunc(t *testing.T) {
k, err := codec.EncodeKey(tk.Session().GetSessionVars().StmtCtx, nil, data...)
require.NoError(t, err)
k = tablecodec.EncodeIndexSeekKey(tableID, indexID, k)
hexKey := hex.EncodeToString(codec.EncodeBytes(nil, k))
return hexKey
return hex.EncodeToString(codec.EncodeBytes(nil, k))
}
// split table t index idx by ('aaaaa', 100, '2000-01-01');
data = []types.Datum{types.NewStringDatum("aaaaa"), types.NewIntDatum(100), types.NewTimeDatum(getTime(2000, 1, 1, mysql.TypeDatetime))}
Expand All @@ -2925,6 +2922,38 @@ func TestTiDBInternalFunc(t *testing.T) {
hexKey = "7480000000000000375F69800000000000000103800000000001D4C1023B6458"
sql = fmt.Sprintf("select tidb_decode_key( '%s' )", hexKey)
tk.MustQuery(sql).Check(testkit.Rows(hexKey))

// Test the table with the nonclustered index.
const rowID = 10
tk.MustExec("drop table if exists t;")
tk.MustExec("create table t (a int primary key nonclustered, b int, key bk (b));")
dom = domain.GetDomain(tk.Session())
is = dom.InfoSchema()
tbl, err = is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
require.NoError(t, err)
buildTableRowKey := func(tableID, rowID int64) string {
return hex.EncodeToString(
codec.EncodeBytes(
nil,
tablecodec.EncodeRowKeyWithHandle(tableID, kv.IntHandle(rowID)),
))
}
hexKey = buildTableRowKey(tbl.Meta().ID, rowID)
sql = fmt.Sprintf("select tidb_decode_key( '%s' )", hexKey)
rs = fmt.Sprintf(`{"_tidb_rowid":%d,"table_id":"%d"}`, rowID, tbl.Meta().ID)
tk.MustQuery(sql).Check(testkit.Rows(rs))

// Test the table with the clustered index.
tk.MustExec("drop table if exists t;")
tk.MustExec("create table t (a int primary key clustered, b int, key bk (b));")
dom = domain.GetDomain(tk.Session())
is = dom.InfoSchema()
tbl, err = is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
require.NoError(t, err)
hexKey = buildTableRowKey(tbl.Meta().ID, rowID)
sql = fmt.Sprintf("select tidb_decode_key( '%s' )", hexKey)
rs = fmt.Sprintf(`{"%s":%d,"table_id":"%d"}`, tbl.Meta().GetPkName().String(), rowID, tbl.Meta().ID)
tk.MustQuery(sql).Check(testkit.Rows(rs))
}

func TestTwoDecimalTruncate(t *testing.T) {
Expand Down
5 changes: 5 additions & 0 deletions parser/model/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,11 @@ func (t *TableInfo) ColumnIsInIndex(c *ColumnInfo) bool {
return false
}

// HasClusteredIndex checks whether the table has a clustered index.
func (t *TableInfo) HasClusteredIndex() bool {
return t.PKIsHandle || t.IsCommonHandle
}

// IsView checks if TableInfo is a view.
func (t *TableInfo) IsView() bool {
return t.View != nil
Expand Down
7 changes: 6 additions & 1 deletion planner/core/expression_rewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2030,7 +2030,12 @@ func decodeRecordKey(key []byte, tableID int64, tbl table.Table, loc *time.Locat
if handle.IsInt() {
ret := make(map[string]interface{})
ret["table_id"] = strconv.FormatInt(tableID, 10)
ret["_tidb_rowid"] = handle.IntValue()
// When the clustered index is enabled, we should show the PK name.
if tbl.Meta().HasClusteredIndex() {
ret[tbl.Meta().GetPkName().String()] = handle.IntValue()
} else {
ret["_tidb_rowid"] = handle.IntValue()
}
retStr, err := json.Marshal(ret)
if err != nil {
return "", errors.Trace(err)
Expand Down
4 changes: 2 additions & 2 deletions planner/core/planbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -960,7 +960,7 @@ func getPathByIndexName(paths []*util.AccessPath, idxName model.CIStr, tblInfo *
return path
}
}
if isPrimaryIndex(idxName) && (tblInfo.PKIsHandle || tblInfo.IsCommonHandle) {
if isPrimaryIndex(idxName) && tblInfo.HasClusteredIndex() {
return tablePath
}
return nil
Expand Down Expand Up @@ -1707,7 +1707,7 @@ func getColsInfo(tn *ast.TableName) (indicesInfo []*model.IndexInfo, colsInfo []
if col.IsGenerated() && !col.GeneratedStored {
continue
}
if mysql.HasPriKeyFlag(col.Flag) && (tbl.PKIsHandle || tbl.IsCommonHandle) {
if mysql.HasPriKeyFlag(col.Flag) && tbl.HasClusteredIndex() {
continue
}
colsInfo = append(colsInfo, col)
Expand Down