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

*: support select for update of tables #27861

Merged
merged 2 commits into from
Oct 14, 2021
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
1 change: 1 addition & 0 deletions executor/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,7 @@ func (a *ExecStmt) handlePessimisticDML(ctx context.Context, e Executor) error {
}
keys = filterTemporaryTableKeys(sctx.GetSessionVars(), keys)
seVars := sctx.GetSessionVars()
keys = filterLockTableKeys(seVars.StmtCtx, keys)
lockCtx := newLockCtx(seVars, seVars.LockWaitTimeout)
var lockKeyStats *util.LockKeysDetails
ctx = context.WithValue(ctx, util.LockKeysDetailCtxKey, &lockKeyStats)
Expand Down
16 changes: 16 additions & 0 deletions executor/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -1009,6 +1009,7 @@ func doLockKeys(ctx context.Context, se sessionctx.Context, lockCtx *tikvstore.L
// Skip the temporary table keys.
keys = filterTemporaryTableKeys(sessVars, keys)

keys = filterLockTableKeys(sessVars.StmtCtx, keys)
var lockKeyStats *tikvutil.LockKeysDetails
ctx = context.WithValue(ctx, tikvutil.LockKeysDetailCtxKey, &lockKeyStats)
err = txn.LockKeys(tikvutil.SetSessionID(ctx, se.GetSessionVars().ConnectionID), lockCtx, keys...)
Expand All @@ -1034,6 +1035,20 @@ func filterTemporaryTableKeys(vars *variable.SessionVars, keys []kv.Key) []kv.Ke
return newKeys
}

func filterLockTableKeys(stmtCtx *stmtctx.StatementContext, keys []kv.Key) []kv.Key {
if len(stmtCtx.LockTableIDs) == 0 {
return keys
}
newKeys := keys[:0:len(keys)]
for _, key := range keys {
tblID := tablecodec.DecodeTableID(key)
if _, ok := stmtCtx.LockTableIDs[tblID]; ok {
newKeys = append(newKeys, key)
}
}
return newKeys
}

// LimitExec represents limit executor
// It ignores 'Offset' rows from src, then returns 'Count' rows at maximum.
type LimitExec struct {
Expand Down Expand Up @@ -1666,6 +1681,7 @@ func ResetContextOfStmt(ctx sessionctx.Context, s ast.StmtNode) (err error) {
sc.TaskID = stmtctx.AllocateTaskID()
sc.CTEStorageMap = map[int]*CTEStorages{}
sc.IsStaleness = false
sc.LockTableIDs = make(map[int64]struct{})

sc.InitMemTracker(memory.LabelForSQLText, vars.MemQuotaQuery)
sc.InitDiskTracker(memory.LabelForSQLText, -1)
Expand Down
32 changes: 32 additions & 0 deletions executor/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import (
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/statistics"
"github.com/pingcap/tidb/store/copr"
error2 "github.com/pingcap/tidb/store/driver/error"
"github.com/pingcap/tidb/store/mockstore"
"github.com/pingcap/tidb/store/mockstore/unistore"
"github.com/pingcap/tidb/table"
Expand Down Expand Up @@ -3243,6 +3244,37 @@ func (s *testSuite) TestSelectForUpdate(c *C) {

}

func (s *testSuite) TestSelectForUpdateOf(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk1 := testkit.NewTestKit(c, s.store)
tk1.MustExec("use test")

tk.MustExec("drop table if exists t, t1")
tk.MustExec("create table t (i int)")
tk.MustExec("create table t1 (i int)")
tk.MustExec("insert t values (1)")
tk.MustExec("insert t1 values (1)")

tk.MustExec("begin pessimistic")
tk.MustQuery("select * from t, t1 where t.i = t1.i for update of t").Check(testkit.Rows("1 1"))

tk1.MustExec("begin pessimistic")

// no lock for t
tk1.MustQuery("select * from t1 for update").Check(testkit.Rows("1"))

// meet lock for t1
err := tk1.ExecToErr("select * from t for update nowait")
c.Assert(terror.ErrorEqual(err, error2.ErrLockAcquireFailAndNoWaitSet), IsTrue, Commentf("error: ", err))

// t1 rolled back, tk1 acquire the lock
tk.MustExec("rollback")
tk1.MustQuery("select * from t for update nowait").Check(testkit.Rows("1"))

tk1.MustExec("rollback")
}

func (s *testSuite) TestEmptyEnum(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
Expand Down
10 changes: 7 additions & 3 deletions planner/core/logical_plan_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -3583,16 +3583,20 @@ func (b *PlanBuilder) buildSelect(ctx context.Context, sel *ast.SelectStmt) (p L
return nil, err
}
}
if sel.LockInfo != nil && sel.LockInfo.LockType != ast.SelectLockNone {
if sel.LockInfo.LockType == ast.SelectLockForShare && noopFuncsMode != variable.OnInt {
l := sel.LockInfo
if l != nil && l.LockType != ast.SelectLockNone {
if l.LockType == ast.SelectLockForShare && noopFuncsMode != variable.OnInt {
err = expression.ErrFunctionsNoopImpl.GenWithStackByArgs("LOCK IN SHARE MODE")
if noopFuncsMode == variable.OffInt {
return nil, err
}
// NoopFuncsMode is Warn, append an error
b.ctx.GetSessionVars().StmtCtx.AppendWarning(err)
}
p, err = b.buildSelectLock(p, sel.LockInfo)
for _, tName := range l.Tables {
b.ctx.GetSessionVars().StmtCtx.LockTableIDs[tName.TableInfo.ID] = struct{}{}
}
p, err = b.buildSelectLock(p, l)
if err != nil {
return nil, err
}
Expand Down
1 change: 1 addition & 0 deletions sessionctx/stmtctx/stmtctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ type StatementContext struct {
PessimisticLockWaited int32
LockKeysDuration int64
LockKeysCount int32
LockTableIDs map[int64]struct{} // table IDs need to be locked, empty for lock all tables
TblInfo2UnionScan map[*model.TableInfo]bool
TaskID uint64 // unique ID for an execution of a statement
TaskMapBakTS uint64 // counter for
Expand Down