Skip to content

Commit

Permalink
session, ddl: rollback txn for prepare statement (#39433)
Browse files Browse the repository at this point in the history
close #39432
  • Loading branch information
wjhuang2016 committed Nov 29, 2022
1 parent 37bd052 commit 3c3a9d0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
13 changes: 13 additions & 0 deletions ddl/metadatalocktest/mdl_test.go
Expand Up @@ -1105,3 +1105,16 @@ func TestMDLRenameTable(t *testing.T) {
tk.MustGetErrCode("select * from test2.t1;", mysql.ErrNoSuchTable)
tk.MustExec("commit")
}

func TestMDLPrepareFail(t *testing.T) {
store := testkit.CreateMockStore(t)

tk := testkit.NewTestKit(t, store)
tk2 := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("create table t(a int);")
_, _, _, err := tk.Session().PrepareStmt("select b from t")
require.Error(t, err)

tk2.MustExec("alter table test.t add column c int")
}
8 changes: 3 additions & 5 deletions session/session.go
Expand Up @@ -2450,7 +2450,6 @@ func (s *session) PrepareStmt(sql string) (stmtID uint32, paramCount int, fields
}

ctx := context.Background()
inTxn := s.GetSessionVars().InTxn()
// NewPrepareExec may need startTS to build the executor, for example prepare statement has subquery in int.
// So we have to call PrepareTxnCtx here.
if err = s.PrepareTxnCtx(ctx); err != nil {
Expand All @@ -2467,13 +2466,12 @@ func (s *session) PrepareStmt(sql string) (stmtID uint32, paramCount int, fields
}
prepareExec := executor.NewPrepareExec(s, sql)
err = prepareExec.Next(ctx, nil)
// Rollback even if err is nil.
s.rollbackOnError(ctx)

if err != nil {
return
}
if !inTxn {
// We could start a transaction to build the prepare executor before, we should rollback it here.
s.RollbackTxn(ctx)
}
return prepareExec.ID, prepareExec.ParamCount, prepareExec.Fields, nil
}

Expand Down

0 comments on commit 3c3a9d0

Please sign in to comment.