Skip to content

Commit

Permalink
sessionctx, executor: add session var to control explicit insertion o…
Browse files Browse the repository at this point in the history
…n auto_random column (#17102) (#18508)
  • Loading branch information
tangenta authored Jul 13, 2020
1 parent 9848ee7 commit 89e34b7
Show file tree
Hide file tree
Showing 12 changed files with 41 additions and 1 deletion.
17 changes: 17 additions & 0 deletions ddl/serial_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -962,6 +962,23 @@ func (s *testSerialSuite) TestAutoRandom(c *C) {
assertShowWarningCorrect("create table t (a int auto_random(30) primary key)", 1)
assertShowWarningCorrect("create table t (a int auto_random(29) primary key)", 3)

// Test insert into auto_random column explicitly is not allowed by default.
assertExplicitInsertDisallowed := func(sql string) {
assertInvalidAutoRandomErr(sql, autoid.AutoRandomExplicitInsertDisabledErrMsg)
}
tk.MustExec("set @@allow_auto_random_explicit_insert = false")
mustExecAndDrop("create table t (a bigint auto_random primary key)", func() {
assertExplicitInsertDisallowed("insert into t values (1)")
assertExplicitInsertDisallowed("insert into t values (3)")
tk.MustExec("insert into t values()")
})
tk.MustExec("set @@allow_auto_random_explicit_insert = true")
mustExecAndDrop("create table t (a bigint auto_random primary key)", func() {
tk.MustExec("insert into t values(1)")
tk.MustExec("insert into t values(3)")
tk.MustExec("insert into t values()")
})

// Disallow using it when allow-auto-random is not enabled.
config.GetGlobalConfig().Experimental.AllowAutoRandom = false
assertExperimentDisabled("create table auto_random_table (a int primary key auto_random(3))")
Expand Down
1 change: 1 addition & 0 deletions executor/ddl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@ func (s *testAutoRandomSuite) TestAutoRandomBitsData(c *C) {
c.Assert(err, IsNil)
return allHds
}
tk.MustExec("set @@allow_auto_random_explicit_insert = true")

tk.MustExec("create table t (a bigint primary key auto_random(15), b int)")
for i := 0; i < 100; i++ {
Expand Down
4 changes: 4 additions & 0 deletions executor/insert_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/ddl"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/meta/autoid"
Expand Down Expand Up @@ -847,6 +848,9 @@ func (e *InsertValues) adjustAutoRandomDatum(ctx context.Context, d types.Datum,
}
// Use the value if it's not null and not 0.
if recordID != 0 {
if !e.ctx.GetSessionVars().AllowAutoRandExplicitInsert {
return types.Datum{}, ddl.ErrInvalidAutoRandom.GenWithStackByArgs(autoid.AutoRandomExplicitInsertDisabledErrMsg)
}
err = e.rebaseAutoRandomID(recordID, &c.FieldType)
if err != nil {
return types.Datum{}, err
Expand Down
2 changes: 2 additions & 0 deletions executor/insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1106,6 +1106,8 @@ func (s *testSuite9) TestAutoRandomIDExplicit(c *C) {
}

tk := testkit.NewTestKit(c, s.store)
tk.MustExec("set @@allow_auto_random_explicit_insert = true")

tk.MustExec(`use test`)
tk.MustExec(`drop table if exists ar`)
tk.MustExec(`create table ar (id int key auto_random, name char(10))`)
Expand Down
1 change: 1 addition & 0 deletions executor/show_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,7 @@ func (s *testAutoRandomSuite) TestAutoRandomBase(c *C) {
}()

tk := testkit.NewTestKit(c, s.store)
tk.MustExec("set @@allow_auto_random_explicit_insert = true")
tk.MustExec("use test")

tk.MustExec("drop table if exists t")
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,7 @@ github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sasha-s/go-deadlock v0.2.0/go.mod h1:StQn567HiB1fF2yJ44N9au7wOhrPS3iZqiDbRupzT10=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/sergi/go-diff v1.0.1-0.20180205163309-da645544ed44 h1:tB9NOR21++IjLyVx3/PCPhWMwqGNCMQEH96A6dMZ/gc=
github.com/sergi/go-diff v1.0.1-0.20180205163309-da645544ed44/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/shirou/gopsutil v2.19.10+incompatible h1:lA4Pi29JEVIQIgATSeftHSY0rMGI9CLrl2ZvDLiahto=
github.com/shirou/gopsutil v2.19.10+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
Expand Down
1 change: 1 addition & 0 deletions session/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -1963,6 +1963,7 @@ var builtinGlobalVariable = []string{
variable.TiDBEvolvePlanBaselines,
variable.TiDBIsolationReadEngines,
variable.TiDBStoreLimit,
variable.TiDBAllowAutoRandExplicitInsert,
variable.TiDBSlowLogMasking,
variable.TiDBEnableTelemetry,
}
Expand Down
6 changes: 6 additions & 0 deletions sessionctx/variable/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,9 @@ type SessionVars struct {
// If value is set to 2 , which means to force to send batch cop for any query. Value is set to 0 means never use batch cop.
AllowBatchCop int

// TiDBAllowAutoRandExplicitInsert indicates whether explicit insertion on auto_random column is allowed.
AllowAutoRandExplicitInsert bool

// CorrelationThreshold is the guard to enable row count estimation using column order correlation.
CorrelationThreshold float64

Expand Down Expand Up @@ -693,6 +696,7 @@ func NewSessionVars() *SessionVars {
PrevFoundInPlanCache: DefTiDBFoundInPlanCache,
FoundInPlanCache: DefTiDBFoundInPlanCache,
SelectLimit: math.MaxUint64,
AllowAutoRandExplicitInsert: DefTiDBAllowAutoRandExplicitInsert,
EnableSlowLogMasking: DefTiDBSlowLogMasking,
}
vars.KVVars = kv.NewVariables(&vars.Killed)
Expand Down Expand Up @@ -1284,6 +1288,8 @@ func (s *SessionVars) SetSystemVar(name string, val string) error {
s.EnableSlowLogMasking = TiDBOptOn(val)
case TiDBEnableCollectExecutionInfo:
config.GetGlobalConfig().EnableCollectExecutionInfo = TiDBOptOn(val)
case TiDBAllowAutoRandExplicitInsert:
s.AllowAutoRandExplicitInsert = TiDBOptOn(val)
}
s.systems[name] = val
return nil
Expand Down
1 change: 1 addition & 0 deletions sessionctx/variable/sysvar.go
Original file line number Diff line number Diff line change
Expand Up @@ -722,6 +722,7 @@ var defaultSysVars = []*SysVar{
{ScopeSession, TiDBFoundInPlanCache, BoolToIntStr(DefTiDBFoundInPlanCache)},
{ScopeGlobal, TiDBSlowLogMasking, BoolToIntStr(DefTiDBSlowLogMasking)},
{ScopeSession, TiDBEnableCollectExecutionInfo, BoolToIntStr(DefTiDBEnableCollectExecutionInfo)},
{ScopeSession, TiDBAllowAutoRandExplicitInsert, boolToOnOff(DefTiDBAllowAutoRandExplicitInsert)},
{ScopeGlobal, TiDBEnableTelemetry, BoolToIntStr(DefTiDBEnableTelemetry)},
}

Expand Down
4 changes: 4 additions & 0 deletions sessionctx/variable/tidb_vars.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,9 @@ const (

// TiDBFoundInPlanCache indicates whether the last statement was found in plan cache
TiDBFoundInPlanCache = "last_plan_from_cache"

// TiDBAllowAutoRandExplicitInsert indicates whether explicit insertion on auto_random column is allowed.
TiDBAllowAutoRandExplicitInsert = "allow_auto_random_explicit_insert"
)

// TiDB system variable names that both in session and global scope.
Expand Down Expand Up @@ -494,6 +497,7 @@ const (
DefTiDBFoundInPlanCache = false
DefTiDBSlowLogMasking = false
DefTiDBEnableCollectExecutionInfo = false
DefTiDBAllowAutoRandExplicitInsert = false
DefTiDBEnableTelemetry = true
)

Expand Down
3 changes: 2 additions & 1 deletion sessionctx/variable/varsutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,8 @@ func ValidateSetSystemVar(vars *SessionVars, name string, value string, scope Sc
TiDBLowResolutionTSO, TiDBEnableIndexMerge, TiDBEnableNoopFuncs,
TiDBCheckMb4ValueInUTF8, TiDBEnableSlowLog, TiDBRecordPlanInSlowLog,
TiDBScatterRegion, TiDBGeneralLog, TiDBConstraintCheckInPlace,
TiDBEnableVectorizedExpression, TiDBFoundInPlanCache, TiDBEnableCollectExecutionInfo, TiDBEnableTelemetry:
TiDBEnableVectorizedExpression, TiDBFoundInPlanCache, TiDBEnableCollectExecutionInfo,
TiDBAllowAutoRandExplicitInsert, TiDBEnableTelemetry:
fallthrough
case GeneralLog, AvoidTemporalUpgrade, BigTables, CheckProxyUsers, LogBin,
CoreFile, EndMakersInJSON, SQLLogBin, OfflineMode, PseudoSlaveMode, LowPriorityUpdates,
Expand Down
1 change: 1 addition & 0 deletions sessionctx/variable/varsutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ func (s *testVarsutilSuite) TestNewSessionVars(c *C) {
c.Assert(vars.TiDBOptJoinReorderThreshold, Equals, DefTiDBOptJoinReorderThreshold)
c.Assert(vars.EnableFastAnalyze, Equals, DefTiDBUseFastAnalyze)
c.Assert(vars.FoundInPlanCache, Equals, DefTiDBFoundInPlanCache)
c.Assert(vars.AllowAutoRandExplicitInsert, Equals, DefTiDBAllowAutoRandExplicitInsert)

assertFieldsGreaterThanZero(c, reflect.ValueOf(vars.Concurrency))
assertFieldsGreaterThanZero(c, reflect.ValueOf(vars.MemQuota))
Expand Down

0 comments on commit 89e34b7

Please sign in to comment.