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

ddl: Drop a local temporary table #26063

Merged
merged 21 commits into from
Jul 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
e6583f7
drop local temp table
Howie59 Jul 8, 2021
3233fef
Merge branch 'master' into drop-local-temp-table
Howie59 Jul 8, 2021
8e5596d
add check
Howie59 Jul 9, 2021
656002b
Merge branch 'drop-local-temp-table' of https://github.jparrowsec.cn.cnpmjs.org…
Howie59 Jul 9, 2021
7963dfd
Merge branch 'master' into drop-local-temp-table
Howie59 Jul 9, 2021
b20380a
Merge branch 'master' of https://github.jparrowsec.cn.cnpmjs.org/pingcap/tidb i…
Howie59 Jul 13, 2021
a326f5a
opt drop operation
Howie59 Jul 13, 2021
035ff97
remove data in membuffer
Howie59 Jul 13, 2021
7a5d2e6
Merge branch 'master' of https://github.jparrowsec.cn.cnpmjs.org/pingcap/tidb i…
Howie59 Jul 13, 2021
a47e711
move package pos
Howie59 Jul 13, 2021
01191e4
add tests
Howie59 Jul 16, 2021
b029036
Merge branch 'master' into drop-local-temp-table
lcwangchao Jul 16, 2021
92d248b
opt code
Howie59 Jul 17, 2021
ceccea1
Merge branch 'drop-local-temp-table' of https://github.jparrowsec.cn.cnpmjs.org…
Howie59 Jul 17, 2021
b6302ca
add err
Howie59 Jul 17, 2021
affe6da
Merge branch 'master' into drop-local-temp-table
Howie59 Jul 17, 2021
fee7f0c
fix tests
Howie59 Jul 20, 2021
7bfc433
Merge branch 'drop-local-temp-table' of https://github.jparrowsec.cn.cnpmjs.org…
Howie59 Jul 20, 2021
dcffa61
Merge branch 'master' into drop-local-temp-table
Howie59 Jul 20, 2021
ccdd722
Merge branch 'master' into drop-local-temp-table
lcwangchao Jul 20, 2021
166ef1f
Merge branch 'master' into drop-local-temp-table
ti-chi-bot Jul 20, 2021
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
125 changes: 124 additions & 1 deletion ddl/db_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
package ddl_test

import (
"bytes"
"context"
"fmt"
"math"
Expand Down Expand Up @@ -2917,7 +2918,7 @@ func (s *testIntegrationSuite3) TestCreateTemporaryTable(c *C) {
tk.MustExec("begin")
tk.MustExec("insert into check_data values (1)")
tk.MustExec("create temporary table a_local_temp_table (id int)")
// Although "begin" take a infoschem snapshot, local temporary table inside txn should be always visible.
// Although "begin" take a infoschema snapshot, local temporary table inside txn should be always visible.
tk.MustExec("show create table tmp_db.a_local_temp_table")
tk.MustExec("rollback")
tk.MustQuery("select * from check_data").Check(testkit.Rows())
Expand Down Expand Up @@ -3022,3 +3023,125 @@ func (s *testIntegrationSuite3) TestAvoidCreateViewOnLocalTemporaryTable(c *C) {
tk.MustExec("create view vv as select * from v0")
checkCreateView()
}

func (s *testIntegrationSuite3) TestDropTemporaryTable(c *C) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Try this: drop table normal_table, temp_table;
Where the normal_table doesn't exist, which leads to rollback.
I assume it's both OK that temp_table exists or not.

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

// Check drop temporary table(include meta data and real data.
tk.MustExec("create temporary table if not exists b_local_temp_table (id int)")
tk.MustQuery("select * from b_local_temp_table").Check(testkit.Rows())
tk.MustExec("drop table b_local_temp_table")
_, err := tk.Exec("select * from b_local_temp_table")
c.Assert(err.Error(), Equals, "[schema:1146]Table 'test.b_local_temp_table' doesn't exist")
// TODO: test drop real data

// Check if we have a normal and local temporary table in the same db with the same name,
// local temporary table should be dropped instead of the normal table.
tk.MustExec("drop table if exists b_table_local_and_normal")
tk.MustExec("create table if not exists b_table_local_and_normal (id int)")
tk.MustExec("create temporary table if not exists b_table_local_and_normal (id int)")
tk.MustQuery("select * from b_table_local_and_normal").Check(testkit.Rows())
tk.MustExec("drop table b_table_local_and_normal")
sequenceTable := testGetTableByName(c, tk.Se, "test", "b_table_local_and_normal")
c.Assert(sequenceTable.Meta().TempTableType, Equals, model.TempTableNone)
tk.MustExec("drop table if exists b_table_local_and_normal")
_, err = tk.Exec("select * from b_table_local_and_normal")
c.Assert(err.Error(), Equals, "[schema:1146]Table 'test.b_table_local_and_normal' doesn't exist")

// Check dropping local temporary tables should not commit current transaction implicitly.
tk.MustExec("drop table if exists check_data_normal_table")
tk.MustExec("create table check_data_normal_table (id int)")
defer tk.MustExec("drop table if exists check_data_normal_table")
tk.MustExec("begin")
tk.MustExec("insert into check_data_normal_table values (1)")
tk.MustExec("create temporary table a_local_temp_table (id int)")
tk.MustExec("create temporary table a_local_temp_table_1 (id int)")
tk.MustExec("create temporary table a_local_temp_table_2 (id int)")
tk.MustExec("show create table a_local_temp_table")
tk.MustExec("show create table a_local_temp_table_1")
tk.MustExec("show create table a_local_temp_table_2")
tk.MustExec("drop table a_local_temp_table, a_local_temp_table_1, a_local_temp_table_2")
tk.MustExec("rollback")
tk.MustQuery("select * from check_data_normal_table").Check(testkit.Rows())

// Check dropping local temporary and normal tables should commit current transaction implicitly.
tk.MustExec("drop table if exists check_data_normal_table_1")
tk.MustExec("create table check_data_normal_table_1 (id int)")
defer tk.MustExec("drop table if exists check_data_normal_table_1")
tk.MustExec("begin")
tk.MustExec("insert into check_data_normal_table_1 values (1)")
tk.MustExec("create temporary table a_local_temp_table (id int)")
tk.MustExec("create temporary table a_local_temp_table_1 (id int)")
tk.MustExec("create temporary table a_local_temp_table_2 (id int)")
tk.MustExec("drop table if exists a_normal_table")
tk.MustExec("create table a_normal_table (id int)")
defer tk.MustExec("drop table if exists a_normal_table")
tk.MustExec("show create table a_local_temp_table")
tk.MustExec("show create table a_local_temp_table_1")
tk.MustExec("show create table a_local_temp_table_2")
tk.MustExec("show create table a_normal_table")
tk.MustExec("drop table a_local_temp_table, a_local_temp_table_1, a_local_temp_table_2, a_normal_table")
tk.MustExec("rollback")
tk.MustQuery("select * from check_data_normal_table_1").Check(testkit.Rows("1"))

// Check drop not exists table.
tk.MustExec("create temporary table a_local_temp_table_3 (id int)")
tk.MustExec("create temporary table a_local_temp_table_4 (id int)")
tk.MustExec("create temporary table a_local_temp_table_5 (id int)")
tk.MustExec("drop table if exists a_normal_table_2")
tk.MustExec("create table a_normal_table_2 (id int)")
defer tk.MustExec("drop table if exists a_normal_table_2")
_, err = tk.Exec("drop table a_local_temp_table_3, a_local_temp_table_4, a_local_temp_table_5, a_normal_table_2, a_local_temp_table_6")
c.Assert(err.Error(), Equals, "[schema:1051]Unknown table 'test.a_local_temp_table_6'")

tk.MustExec("drop table if exists check_data_normal_table_3")
tk.MustExec("create table check_data_normal_table_3 (id int)")
defer tk.MustExec("drop table if exists check_data_normal_table_3")
tk.MustExec("create temporary table a_local_temp_table_6 (id int)")
_, err = tk.Exec("drop table check_data_normal_table_3, check_data_normal_table_7, a_local_temp_table_6")
c.Assert(err.Error(), Equals, "[schema:1051]Unknown table 'test.check_data_normal_table_7'")

// Check filter out data from removed local temp tables
tk.MustExec("create temporary table a_local_temp_table_7 (id int)")
ctx := s.ctx
c.Assert(ctx.NewTxn(context.Background()), IsNil)
txn, err := ctx.Txn(true)
c.Assert(err, IsNil)
defer func() {
err := txn.Rollback()
c.Assert(err, IsNil)
}()
sessionVars := tk.Se.GetSessionVars()
sessVarsTempTable := sessionVars.LocalTemporaryTables
localTemporaryTable := sessVarsTempTable.(*infoschema.LocalTemporaryTables)
tbl, exist := localTemporaryTable.TableByName(model.NewCIStr("test"), model.NewCIStr("a_local_temp_table_7"))
c.Assert(exist, IsTrue)
tblInfo := tbl.Meta()
tablePrefix := tablecodec.EncodeTablePrefix(tblInfo.ID)
endTablePrefix := tablecodec.EncodeTablePrefix(tblInfo.ID + 1)

tk.MustExec("insert into a_local_temp_table_7 values (0)")
tk.MustExec("insert into a_local_temp_table_7 values (2)")
tk.MustExec("begin")
tk.MustExec("insert into a_local_temp_table_7 values (1)")
tk.MustExec("drop table if exists a_local_temp_table_7")
tk.MustExec("commit")

_, err = tk.Exec("select * from a_local_temp_table_7")
c.Assert(err.Error(), Equals, "[schema:1146]Table 'test.a_local_temp_table_7' doesn't exist")
memData := sessionVars.TemporaryTableData
iter, err := memData.Iter(tablePrefix, endTablePrefix)
c.Assert(err, IsNil)
for iter.Valid() {
key := iter.Key()
if !bytes.HasPrefix(key, tablePrefix) {
break
}
value := iter.Value()
c.Assert(len(value), Equals, 0)
_ = iter.Next()
}
c.Assert(iter.Valid(), IsFalse)
}
87 changes: 82 additions & 5 deletions executor/ddl.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
package executor

import (
"bytes"
"context"
"fmt"
"strings"
Expand All @@ -33,6 +34,7 @@ import (
"github.com/pingcap/tidb/planner/core"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/util/admin"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/gcutil"
Expand Down Expand Up @@ -69,6 +71,39 @@ func (e *DDLExec) toErr(err error) error {
return err
}

// deleteTemporaryTableRecords delete temporary table data.
func deleteTemporaryTableRecords(memData kv.MemBuffer, tblID int64) error {
if memData == nil {
return kv.ErrNotExist
}

tblPrefix := tablecodec.EncodeTablePrefix(tblID)
endKey := tablecodec.EncodeTablePrefix(tblID + 1)

iter, err := memData.Iter(tblPrefix, endKey)
if err != nil {
return err
}
for iter.Valid() {
key := iter.Key()
if !bytes.HasPrefix(key, tblPrefix) {
break
}

err = memData.Delete(key)
if err != nil {
return err
}

err = iter.Next()
if err != nil {
return err
}
}

return nil
}

// Next implements the Executor Next interface.
func (e *DDLExec) Next(ctx context.Context, req *chunk.Chunk) (err error) {
if e.done {
Expand All @@ -77,12 +112,37 @@ func (e *DDLExec) Next(ctx context.Context, req *chunk.Chunk) (err error) {
e.done = true

// For each DDL, we should commit the previous transaction and create a new transaction.
// An exception is create local temporary table.
if s, ok := e.stmt.(*ast.CreateTableStmt); ok {
// Following cases are exceptions
var localTempTablesToDrop []*model.TableInfo
switch s := e.stmt.(type) {
case *ast.CreateTableStmt:
if s.TemporaryKeyword == ast.TemporaryLocal {
return e.createSessionTemporaryTable(s)
}
case *ast.DropTableStmt:
if s.IsView {
break
}
sessVars := e.ctx.GetSessionVars()
sessVarsTempTable := sessVars.LocalTemporaryTables
if sessVarsTempTable == nil {
break
}
localTemporaryTables := sessVarsTempTable.(*infoschema.LocalTemporaryTables)
for tbIdx := len(s.Tables) - 1; tbIdx >= 0; tbIdx-- {
tb := s.Tables[tbIdx]
if tableInfo, ok := localTemporaryTables.TableByName(s.Tables[tbIdx].Schema, s.Tables[tbIdx].Name); ok {
localTempTablesToDrop = append(localTempTablesToDrop, tableInfo.Meta())
localTemporaryTables.RemoveTable(tb.Schema, tb.Name)
s.Tables = append(s.Tables[:tbIdx], s.Tables[tbIdx+1:]...)
}
}
// if all tables are local temporary, directly drop those tables.
if len(s.Tables) == 0 {
return e.dropLocalTemporaryTables(localTempTablesToDrop)
}
}

if err = e.ctx.NewTxn(ctx); err != nil {
return err
}
Expand Down Expand Up @@ -111,6 +171,9 @@ func (e *DDLExec) Next(ctx context.Context, req *chunk.Chunk) (err error) {
err = e.executeDropView(x)
} else {
err = e.executeDropTable(x)
if err == nil {
err = e.dropLocalTemporaryTables(localTempTablesToDrop)
}
}
case *ast.RecoverTableStmt:
err = e.executeRecoverTable(x)
Expand Down Expand Up @@ -143,7 +206,6 @@ func (e *DDLExec) Next(ctx context.Context, req *chunk.Chunk) (err error) {
return e.toErr(err)
}
return err

}

dom := domain.GetDomain(e.ctx)
Expand Down Expand Up @@ -372,6 +434,7 @@ func (e *DDLExec) executeDropSequence(s *ast.DropSequenceStmt) error {
// dropTableObject actually applies to `tableObject`, `viewObject` and `sequenceObject`.
func (e *DDLExec) dropTableObject(objects []*ast.TableName, obt objectType, ifExists bool) error {
var notExistTables []string
sessVars := e.ctx.GetSessionVars()
for _, tn := range objects {
fullti := ast.Ident{Schema: tn.Schema, Name: tn.Name}
_, ok := e.is.SchemaByName(tn.Schema)
Expand Down Expand Up @@ -438,15 +501,29 @@ func (e *DDLExec) dropTableObject(objects []*ast.TableName, obt objectType, ifEx
if len(notExistTables) > 0 && ifExists {
for _, table := range notExistTables {
if obt == sequenceObject {
e.ctx.GetSessionVars().StmtCtx.AppendNote(infoschema.ErrSequenceDropExists.GenWithStackByArgs(table))
sessVars.StmtCtx.AppendNote(infoschema.ErrSequenceDropExists.GenWithStackByArgs(table))
} else {
e.ctx.GetSessionVars().StmtCtx.AppendNote(infoschema.ErrTableDropExists.GenWithStackByArgs(table))
sessVars.StmtCtx.AppendNote(infoschema.ErrTableDropExists.GenWithStackByArgs(table))
}
}
}
return nil
}

func (e *DDLExec) dropLocalTemporaryTables(localTempTables []*model.TableInfo) error {
if len(localTempTables) == 0 {
return nil
}
sessVars := e.ctx.GetSessionVars()
for _, tb := range localTempTables {
err := deleteTemporaryTableRecords(sessVars.TemporaryTableData, tb.ID)
if err != nil {
return err
}
}
return nil
}

func (e *DDLExec) executeDropIndex(s *ast.DropIndexStmt) error {
ti := ast.Ident{Schema: s.Table.Schema, Name: s.Table.Name}
err := domain.GetDomain(e.ctx).DDL().DropIndex(e.ctx, ti, model.NewCIStr(s.IndexName), s.IfExists)
Expand Down
21 changes: 17 additions & 4 deletions session/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ import (
"github.com/pingcap/tidb/plugin"
"github.com/pingcap/tidb/privilege"
"github.com/pingcap/tidb/privilege/privileges"
txninfo "github.com/pingcap/tidb/session/txninfo"
"github.com/pingcap/tidb/session/txninfo"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/binloginfo"
"github.com/pingcap/tidb/sessionctx/stmtctx"
Expand Down Expand Up @@ -555,13 +555,23 @@ func (s *session) doCommit(ctx context.Context) error {
}

func (s *session) commitTxnWithTemporaryData(ctx context.Context, txn kv.Transaction) error {
txnTempTables := s.sessionVars.TxnCtx.TemporaryTables
sessVars := s.sessionVars
txnTempTables := sessVars.TxnCtx.TemporaryTables
if len(txnTempTables) == 0 {
return txn.Commit(ctx)
}

sessionData := s.sessionVars.TemporaryTableData
var stage kv.StagingHandle
sessionData := sessVars.TemporaryTableData
var (
stage kv.StagingHandle
localTempTables *infoschema.LocalTemporaryTables
)

if sessVars.LocalTemporaryTables != nil {
localTempTables = sessVars.LocalTemporaryTables.(*infoschema.LocalTemporaryTables)
} else {
localTempTables = new(infoschema.LocalTemporaryTables)
}

defer func() {
// stage != kv.InvalidStagingHandle means error occurs, we need to cleanup sessionData
Expand All @@ -578,6 +588,9 @@ func (s *session) commitTxnWithTemporaryData(ctx context.Context, txn kv.Transac
if tbl.GetMeta().TempTableType != model.TempTableLocal {
continue
}
if _, ok := localTempTables.TableByID(tblID); !ok {
continue
}

if stage == kv.InvalidStagingHandle {
stage = sessionData.Staging()
Expand Down