Skip to content

Commit

Permalink
Merge branch 'master' into fix_per_reg
Browse files Browse the repository at this point in the history
  • Loading branch information
rebelice authored Mar 11, 2021
2 parents cefbe00 + c1b8347 commit 0a2f723
Show file tree
Hide file tree
Showing 145 changed files with 3,194 additions and 1,645 deletions.
18 changes: 18 additions & 0 deletions bindinfo/bind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2061,3 +2061,21 @@ func (s *testSuite) TestExplainTableStmts(c *C) {
tk.MustExec("explain table t")
tk.MustExec("desc table t")
}

func (s *testSuite) TestSPMWithoutUseDatabase(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk1 := testkit.NewTestKit(c, s.store)
s.cleanBindingEnv(tk)
s.cleanBindingEnv(tk1)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int, b int, key(a))")
tk.MustExec("create global binding for select * from t using select * from t force index(a)")

err := tk1.ExecToErr("select * from t")
c.Assert(err, ErrorMatches, "*No database selected")
tk1.MustQuery(`select @@last_plan_from_binding;`).Check(testkit.Rows("0"))
c.Assert(tk1.MustUseIndex("select * from test.t", "a"), IsTrue)
tk1.MustExec("select * from test.t")
tk1.MustQuery(`select @@last_plan_from_binding;`).Check(testkit.Rows("1"))
}
18 changes: 9 additions & 9 deletions cmd/explaintest/r/partition_pruning.result
Original file line number Diff line number Diff line change
Expand Up @@ -2276,7 +2276,7 @@ TableReader 250.00 root partition:dual data:Selection
└─TableFullScan 10000.00 cop[tikv] table:t1 keep order:false, stats:pseudo
explain format = 'brief' select * from t2 where a > 0xFE AND a <= 0xFF;
id estRows task access object operator info
TableReader 250.00 root partition:all data:Selection
TableReader 250.00 root partition:dual data:Selection
└─Selection 250.00 cop[tikv] gt(test.t2.a, 254), le(test.t2.a, 255)
└─TableFullScan 10000.00 cop[tikv] table:t2 keep order:false, stats:pseudo
explain format = 'brief' select * from t1 where a >= 0xFE AND a <= 0xFF;
Expand All @@ -2286,7 +2286,7 @@ TableReader 250.00 root partition:p2 data:Selection
└─TableFullScan 10000.00 cop[tikv] table:t1 keep order:false, stats:pseudo
explain format = 'brief' select * from t2 where a >= 0xFE AND a <= 0xFF;
id estRows task access object operator info
TableReader 250.00 root partition:all data:Selection
TableReader 250.00 root partition:p2 data:Selection
└─Selection 250.00 cop[tikv] ge(test.t2.a, 254), le(test.t2.a, 255)
└─TableFullScan 10000.00 cop[tikv] table:t2 keep order:false, stats:pseudo
explain format = 'brief' select * from t1 where a < 64 AND a >= 63;
Expand All @@ -2296,7 +2296,7 @@ TableReader 250.00 root partition:p0 data:Selection
└─TableFullScan 10000.00 cop[tikv] table:t1 keep order:false, stats:pseudo
explain format = 'brief' select * from t2 where a < 64 AND a >= 63;
id estRows task access object operator info
TableReader 250.00 root partition:all data:Selection
TableReader 250.00 root partition:p0 data:Selection
└─Selection 250.00 cop[tikv] ge(test.t2.a, 63), lt(test.t2.a, 64)
└─TableFullScan 10000.00 cop[tikv] table:t2 keep order:false, stats:pseudo
explain format = 'brief' select * from t1 where a <= 64 AND a >= 63;
Expand All @@ -2306,7 +2306,7 @@ TableReader 250.00 root partition:p0,p1 data:Selection
└─TableFullScan 10000.00 cop[tikv] table:t1 keep order:false, stats:pseudo
explain format = 'brief' select * from t2 where a <= 64 AND a >= 63;
id estRows task access object operator info
TableReader 250.00 root partition:all data:Selection
TableReader 250.00 root partition:p0,p1 data:Selection
└─Selection 250.00 cop[tikv] ge(test.t2.a, 63), le(test.t2.a, 64)
└─TableFullScan 10000.00 cop[tikv] table:t2 keep order:false, stats:pseudo
drop table t1;
Expand All @@ -2322,13 +2322,13 @@ insert into t1 values (9),(19),(0xFFFF0000FFFF000-1), (0xFFFF0000FFFFFFF-1);
explain format = 'brief' select * from t1 where
a >= 2305561538531885056-10 and a <= 2305561538531885056-8;
id estRows task access object operator info
TableReader 250.00 root partition:all data:Selection
TableReader 250.00 root partition:p3 data:Selection
└─Selection 250.00 cop[tikv] ge(test.t1.a, 2305561538531885046), le(test.t1.a, 2305561538531885048)
└─TableFullScan 10000.00 cop[tikv] table:t1 keep order:false, stats:pseudo
explain format = 'brief' select * from t1 where
a > 0xFFFFFFFFFFFFFFEC and a < 0xFFFFFFFFFFFFFFEE;
id estRows task access object operator info
TableReader 250.00 root partition:all data:Selection
TableReader 250.00 root partition:dual data:Selection
└─Selection 250.00 cop[tikv] gt(test.t1.a, 18446744073709551596), lt(test.t1.a, 18446744073709551598)
└─TableFullScan 10000.00 cop[tikv] table:t1 keep order:false, stats:pseudo
explain format = 'brief' select * from t1 where a>=0 and a <= 0xFFFFFFFFFFFFFFFF;
Expand All @@ -2346,7 +2346,7 @@ partition p4 values less than (1000)
insert into t1 values (-15),(-5),(5),(15),(-15),(-5),(5),(15);
explain format = 'brief' select * from t1 where a>-2 and a <=0;
id estRows task access object operator info
TableReader 250.00 root partition:all data:Selection
TableReader 250.00 root partition:p3 data:Selection
└─Selection 250.00 cop[tikv] gt(test.t1.a, -2), le(test.t1.a, 0)
└─TableFullScan 10000.00 cop[tikv] table:t1 keep order:false, stats:pseudo
drop table t1;
Expand Down Expand Up @@ -2391,12 +2391,12 @@ partition p2 values less than (255)
insert into t1 select A.a + 10*B.a from t0 A, t0 B;
explain format = 'brief' select * from t1 where a between 10 and 13;
id estRows task access object operator info
TableReader 250.00 root partition:all data:Selection
TableReader 250.00 root partition:p0 data:Selection
└─Selection 250.00 cop[tikv] ge(test.t1.a, 10), le(test.t1.a, 13)
└─TableFullScan 10000.00 cop[tikv] table:t1 keep order:false, stats:pseudo
explain format = 'brief' select * from t1 where a between 10 and 10+33;
id estRows task access object operator info
TableReader 250.00 root partition:all data:Selection
TableReader 250.00 root partition:p0 data:Selection
└─Selection 250.00 cop[tikv] ge(test.t1.a, 10), le(test.t1.a, 43)
└─TableFullScan 10000.00 cop[tikv] table:t1 keep order:false, stats:pseudo
drop table t0, t1;
Expand Down
1 change: 1 addition & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,7 @@ var deprecatedConfig = map[string]struct{}{
"max-txn-time-use": {},
"experimental.allow-auto-random": {},
"enable-redact-log": {}, // use variable tidb_redact_log instead
"tikv-client.copr-cache.enable": {},
}

func isAllDeprecatedConfigItems(items []string) bool {
Expand Down
13 changes: 1 addition & 12 deletions config/config.toml.example
Original file line number Diff line number Diff line change
Expand Up @@ -418,20 +418,9 @@ store-liveness-timeout = "5s"
ttl-refreshed-txn-size = 33554432

[tikv-client.copr-cache]
# Whether to enable the copr cache. The copr cache saves the result from TiKV Coprocessor in the memory and
# reuses the result when corresponding data in TiKV is unchanged, on a region basis.
enable = true

# The capacity in MB of the cache.
# The capacity in MB of the cache. Zero means disable coprocessor cache.
capacity-mb = 1000.0

# Only cache small requests. Zero means no limits for requests.
admission-max-ranges = 500
# Only cache requests whose result set is small.
admission-max-result-mb = 10.0
# Only cache requests takes notable time to process.
admission-min-process-ms = 5

[binlog]
# enable to write binlog.
# NOTE: If binlog is enabled with Kafka (e.g. arbiter cluster),
Expand Down
3 changes: 2 additions & 1 deletion ddl/db_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2225,7 +2225,7 @@ func (s *testIntegrationSuite7) TestAddExpressionIndex(c *C) {
}

func (s *testIntegrationSuite7) TestCreateExpressionIndexError(c *C) {
defer config.RestoreFunc()
defer config.RestoreFunc()()
config.UpdateGlobal(func(conf *config.Config) {
conf.Experimental.AllowsExpressionIndex = true
conf.AlterPrimaryKey = true
Expand Down Expand Up @@ -2640,6 +2640,7 @@ func (s *testIntegrationSuite7) TestDuplicateErrorMessage(c *C) {
restoreConfig := config.RestoreFunc()
config.UpdateGlobal(func(conf *config.Config) {
conf.EnableGlobalIndex = globalIndex
conf.AlterPrimaryKey = false
})
for _, clusteredIndex := range []bool{false, true} {
tk.Se.GetSessionVars().EnableClusteredIndex = clusteredIndex
Expand Down
28 changes: 13 additions & 15 deletions ddl/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ import (
"github.com/pingcap/tidb/util/domainutil"
"github.com/pingcap/tidb/util/israce"
"github.com/pingcap/tidb/util/mock"
"github.com/pingcap/tidb/util/rowcodec"
"github.com/pingcap/tidb/util/testkit"
"github.com/pingcap/tidb/util/testutil"
)
Expand Down Expand Up @@ -1141,7 +1140,11 @@ func (s *testDBSuite4) TestAddIndex4(c *C) {
partition p4 values less than maxvalue)`, "")
}

func (s *testDBSuite5) TestAddIndex5(c *C) {
func (s *testSerialDBSuite) TestAddIndex5(c *C) {
defer config.RestoreFunc()()
config.UpdateGlobal(func(conf *config.Config) {
conf.AlterPrimaryKey = false
})
testAddIndex(c, s.store, s.lease, testClusteredIndex,
`create table test_add_index (c1 bigint, c2 bigint, c3 bigint, primary key(c2, c3))`, "")
}
Expand Down Expand Up @@ -1303,7 +1306,7 @@ LOOP:

c.Assert(err, IsNil)
_, ok := handles.Get(h)
c.Assert(ok, IsTrue)
c.Assert(ok, IsTrue, Commentf("handle: %v", h.String()))
handles.Delete(h)
}
c.Assert(handles.Len(), Equals, 0)
Expand Down Expand Up @@ -1903,15 +1906,6 @@ func checkGlobalIndexRow(c *C, ctx sessionctx.Context, tblInfo *model.TableInfo,
for _, col := range tblInfo.Columns {
tblColMap[col.ID] = &col.FieldType
}
idxColInfos := make([]rowcodec.ColInfo, 0, len(indexInfo.Columns))
for _, idxCol := range indexInfo.Columns {
col := tblInfo.Columns[idxCol.Offset]
idxColInfos = append(idxColInfos, rowcodec.ColInfo{
ID: col.ID,
IsPKHandle: tblInfo.PKIsHandle && mysql.HasPriKeyFlag(col.Flag),
Ft: rowcodec.FieldTypeFromModelColumn(col),
})
}

// Check local index entry does not exist.
localPrefix := tablecodec.EncodeTableIndexPrefix(pid, indexInfo.ID)
Expand All @@ -1928,6 +1922,7 @@ func checkGlobalIndexRow(c *C, ctx sessionctx.Context, tblInfo *model.TableInfo,
c.Assert(err, IsNil)
value, err := txn.Get(context.Background(), key)
c.Assert(err, IsNil)
idxColInfos := tables.BuildRowcodecColInfoForIndexColumns(indexInfo, tblInfo)
colVals, err := tablecodec.DecodeIndexKV(key, value, len(indexInfo.Columns), tablecodec.HandleDefault, idxColInfos)
c.Assert(err, IsNil)
c.Assert(colVals, HasLen, len(idxVals)+2)
Expand Down Expand Up @@ -1955,8 +1950,10 @@ func checkGlobalIndexRow(c *C, ctx sessionctx.Context, tblInfo *model.TableInfo,
}

func (s *testSerialDBSuite) TestAddGlobalIndex(c *C) {
defer config.RestoreFunc()()
config.UpdateGlobal(func(conf *config.Config) {
conf.EnableGlobalIndex = true
conf.AlterPrimaryKey = true
})
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test_db")
Expand Down Expand Up @@ -2024,9 +2021,6 @@ func (s *testSerialDBSuite) TestAddGlobalIndex(c *C) {

err = txn.Commit(context.Background())
c.Assert(err, IsNil)
config.UpdateGlobal(func(conf *config.Config) {
conf.EnableGlobalIndex = false
})
}

func (s *testDBSuite) showColumns(tk *testkit.TestKit, c *C, tableName string) [][]interface{} {
Expand Down Expand Up @@ -2678,6 +2672,10 @@ func (s *testSerialDBSuite) TestRepairTable(c *C) {
defer func() {
c.Assert(failpoint.Disable("github.com/pingcap/tidb/infoschema/repairFetchCreateTable"), IsNil)
}()
defer config.RestoreFunc()()
config.UpdateGlobal(func(conf *config.Config) {
conf.AlterPrimaryKey = true
})
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t, other_table, origin")
Expand Down
69 changes: 16 additions & 53 deletions ddl/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
package ddl

import (
"bytes"
"context"
"strings"
"sync/atomic"
Expand All @@ -40,10 +39,8 @@ import (
"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/logutil"
decoder "github.com/pingcap/tidb/util/rowDecoder"
"github.com/pingcap/tidb/util/rowcodec"
"github.com/pingcap/tidb/util/timeutil"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
Expand Down Expand Up @@ -1026,68 +1023,34 @@ func (w *addIndexWorker) initBatchCheckBufs(batchCount int) {
func (w *addIndexWorker) checkHandleExists(key kv.Key, value []byte, handle kv.Handle) error {
idxInfo := w.index.Meta()
tblInfo := w.table.Meta()
name := w.index.Meta().Name.String()

colInfo := make([]rowcodec.ColInfo, 0, len(idxInfo.Columns))
for _, idxCol := range idxInfo.Columns {
col := tblInfo.Columns[idxCol.Offset]
colInfo = append(colInfo, rowcodec.ColInfo{
ID: col.ID,
IsPKHandle: tblInfo.PKIsHandle && mysql.HasPriKeyFlag(col.Flag),
Ft: rowcodec.FieldTypeFromModelColumn(col),
})
idxColLen := len(idxInfo.Columns)
h, err := tablecodec.DecodeIndexHandle(key, value, idxColLen)
if err != nil {
return errors.Trace(err)
}

values, err := tablecodec.DecodeIndexKV(key, value, len(idxInfo.Columns), tablecodec.HandleDefault, colInfo)
hasBeenBackFilled := h.Equal(handle)
if hasBeenBackFilled {
return nil
}
colInfos := tables.BuildRowcodecColInfoForIndexColumns(idxInfo, tblInfo)
values, err := tablecodec.DecodeIndexKV(key, value, idxColLen, tablecodec.HandleNotNeeded, colInfos)
if err != nil {
return err
}

if !w.table.Meta().IsCommonHandle {
_, d, err := codec.DecodeOne(values[len(colInfo)])
if err != nil {
return errors.Trace(err)
}
if d.GetInt64() == handle.IntValue() {
return nil
}
} else {
// We expect the two handle have the same number of columns, because they come from a same table.
// But we still need to check it explicitly, otherwise we will encounter undesired index out of range panic,
// or undefined behavior if someone change the format of the value returned by tablecodec.DecodeIndexKV.
colsOfHandle := len(values) - len(colInfo)
if w.index.Meta().Global {
colsOfHandle--
}
if colsOfHandle != handle.NumCols() {
// We can claim these two handle are different, because they have different length.
// But we'd better report an error at here to detect compatibility problem introduced in other package during tests.
return errors.New("number of columns in two handle is different")
}

for i := 0; i < handle.NumCols(); i++ {
if bytes.Equal(values[i+len(colInfo)], handle.EncodedCol(i)) {
colsOfHandle--
}
}
if colsOfHandle == 0 {
return nil
}
}

valueStr := make([]string, 0, len(colInfo))
for i, val := range values[:len(colInfo)] {
d, err := tablecodec.DecodeColumnValue(val, colInfo[i].Ft, time.Local)
indexName := w.index.Meta().Name.String()
valueStr := make([]string, 0, idxColLen)
for i, val := range values[:idxColLen] {
d, err := tablecodec.DecodeColumnValue(val, colInfos[i].Ft, time.Local)
if err != nil {
return kv.ErrKeyExists.FastGenByArgs(key.String(), name)
return kv.ErrKeyExists.FastGenByArgs(key.String(), indexName)
}
str, err := d.ToString()
if err != nil {
str = string(val)
}
valueStr = append(valueStr, str)
}
return kv.ErrKeyExists.FastGenByArgs(strings.Join(valueStr, "-"), name)
return kv.ErrKeyExists.FastGenByArgs(strings.Join(valueStr, "-"), indexName)
}

func (w *addIndexWorker) batchCheckUniqueKey(txn kv.Transaction, idxRecords []*indexRecord) error {
Expand Down
5 changes: 4 additions & 1 deletion ddl/partition.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
"github.com/pingcap/parser/format"
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/ddl/placement"
"github.com/pingcap/tidb/ddl/util"
"github.com/pingcap/tidb/domain/infosync"
Expand Down Expand Up @@ -1501,7 +1502,9 @@ func checkPartitioningKeysConstraints(sctx sessionctx.Context, s *ast.CreateTabl
if index.Primary {
return ErrUniqueKeyNeedAllFieldsInPf.GenWithStackByArgs("PRIMARY KEY")
}
return ErrUniqueKeyNeedAllFieldsInPf.GenWithStackByArgs("UNIQUE INDEX")
if !config.GetGlobalConfig().EnableGlobalIndex {
return ErrUniqueKeyNeedAllFieldsInPf.GenWithStackByArgs("UNIQUE INDEX")
}
}
}
// when PKIsHandle, tblInfo.Indices will not contain the primary key.
Expand Down
10 changes: 10 additions & 0 deletions distsql/request_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"sort"

"github.com/pingcap/errors"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/tidb/ddl/placement"
"github.com/pingcap/tidb/infoschema"
Expand Down Expand Up @@ -235,6 +236,15 @@ func (builder *RequestBuilder) SetFromSessionVars(sv *variable.SessionVars) *Req
builder.Request.SchemaVar = sv.TxnCtx.SchemaVersion
}
builder.txnScope = sv.TxnCtx.TxnScope
builder.IsStaleness = sv.TxnCtx.IsStaleness
if builder.IsStaleness && builder.txnScope != oracle.GlobalTxnScope {
builder.MatchStoreLabels = []*metapb.StoreLabel{
{
Key: placement.DCLabelKey,
Value: builder.txnScope,
},
}
}
return builder
}

Expand Down
2 changes: 1 addition & 1 deletion distsql/select_result.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ func (s *selectResultRuntimeStats) String() string {
buf.WriteString(", rpc_time: ")
buf.WriteString(execdetails.FormatDuration(time.Duration(copRPC.Consume)))
}
if config.GetGlobalConfig().TiKVClient.CoprCache.Enable {
if config.GetGlobalConfig().TiKVClient.CoprCache.CapacityMB > 0 {
buf.WriteString(fmt.Sprintf(", copr_cache_hit_ratio: %v",
strconv.FormatFloat(float64(s.CoprCacheHitNum)/float64(len(s.copRespTime)), 'f', 2, 64)))
} else {
Expand Down
2 changes: 1 addition & 1 deletion docs/design/2018-10-08-online-DDL.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,4 @@ This operation requires writing the corresponding column data in the table to th
To reduce the impact on other read and write operations, its default priority is low.

## Compatibility
About specific compatibility, you can view [MySQL’s compatibility](https://github.com/pingcap/docs/blob/master/sql/mysql-compatibility.md#ddl).
About specific compatibility, you can view [MySQL’s compatibility](https://github.com/pingcap/docs/blob/master/mysql-compatibility.md#ddl).
Loading

0 comments on commit 0a2f723

Please sign in to comment.