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

sessionctx, executor: add session var to control explicit insertion on auto_random column #17102

Merged
merged 6 commits into from
May 26, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
17 changes: 17 additions & 0 deletions ddl/serial_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -940,6 +940,23 @@ func (s *testSerialSuite) TestAutoRandom(c *C) {
assertShowWarningCorrect("create table t (a bigint auto_random(15) primary key)", 281474976710655)
assertShowWarningCorrect("create table t (a bigint unsigned auto_random(15) primary key)", 562949953421311)

// 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 @@ -844,6 +844,7 @@ func (s *testAutoRandomSuite) TestAutoRandomBitsData(c *C) {

testutil.ConfigTestUtils.SetupAutoRandomTestConfig()
defer testutil.ConfigTestUtils.RestoreAutoRandomTestConfig()
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 bigint key auto_random, name char(10))`)
Expand Down
1 change: 1 addition & 0 deletions executor/seqtest/seq_executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -832,6 +832,7 @@ func HelperTestAdminShowNextID(c *C, s *seqTestSuite, str string) {

oldAutoRandom := config.GetGlobalConfig().Experimental.AllowAutoRandom
config.GetGlobalConfig().Experimental.AllowAutoRandom = true
tk.MustExec("set @@allow_auto_random_explicit_insert = true")
defer func() {
config.GetGlobalConfig().Experimental.AllowAutoRandom = oldAutoRandom
}()
Expand Down
2 changes: 2 additions & 0 deletions meta/autoid/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ const (
AutoRandomNonPositive = "the value of auto_random should be positive"
// AutoRandomAvailableAllocTimesNote is reported when a table containing auto_random is created.
AutoRandomAvailableAllocTimesNote = "Available implicit allocation times: %d"
// AutoRandomExplicitInsertDisabledErrMsg is reported when auto_random column value is explicitly specified, but the session var 'allow_auto_random_explicit_insert' is false.
AutoRandomExplicitInsertDisabledErrMsg = "Explicit insertion on auto_random column is disabled. Try to set @@allow_auto_random_explicit_insert = true."
// AutoRandomOnNonBigIntColumn is reported when define auto random to non bigint column
AutoRandomOnNonBigIntColumn = "auto_random option must be defined on `bigint` column, but not on `%s` column"
)
1 change: 1 addition & 0 deletions session/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -2053,6 +2053,7 @@ var builtinGlobalVariable = []string{
variable.TiDBEvolvePlanBaselines,
variable.TiDBIsolationReadEngines,
variable.TiDBStoreLimit,
variable.TiDBAllowAutoRandExplicitInsert,
}

var (
Expand Down
6 changes: 6 additions & 0 deletions sessionctx/variable/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,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 @@ -690,6 +693,7 @@ func NewSessionVars() *SessionVars {
WindowingUseHighPrecision: true,
PrevFoundInPlanCache: DefTiDBFoundInPlanCache,
FoundInPlanCache: DefTiDBFoundInPlanCache,
AllowAutoRandExplicitInsert: DefTiDBAllowAutoRandExplicitInsert,
}
vars.KVVars = kv.NewVariables(&vars.Killed)
vars.Concurrency = Concurrency{
Expand Down Expand Up @@ -1290,6 +1294,8 @@ func (s *SessionVars) SetSystemVar(name string, val string) error {
s.FoundInPlanCache = 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 @@ -721,6 +721,7 @@ var defaultSysVars = []*SysVar{
{ScopeSession, TiDBCheckMb4ValueInUTF8, BoolToIntStr(config.GetGlobalConfig().CheckMb4ValueInUTF8)},
{ScopeSession, TiDBFoundInPlanCache, BoolToIntStr(DefTiDBFoundInPlanCache)},
{ScopeSession, TiDBEnableCollectExecutionInfo, BoolToIntStr(logutil.DefaultTiDBEnableSlowLog)},
{ScopeSession, TiDBAllowAutoRandExplicitInsert, boolToOnOff(DefTiDBAllowAutoRandExplicitInsert)},
}

// SynonymsSysVariables is synonyms of system variables.
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 @@ -487,6 +490,7 @@ const (
DefTiDBMetricSchemaRangeDuration = 60 // 60s
DefTiDBFoundInPlanCache = false
DefTidbEnableCollectExecutionInfo = false
DefTiDBAllowAutoRandExplicitInsert = false
)

// Process global variables.
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:
TiDBEnableVectorizedExpression, TiDBFoundInPlanCache, TiDBEnableCollectExecutionInfo,
TiDBAllowAutoRandExplicitInsert:
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