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: get latest old table ID before replace view (#53720) #56891

Merged
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 ddl/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,7 @@ go_test(
"@io_etcd_go_etcd_client_v3//:client",
"@org_golang_google_grpc//:grpc",
"@org_golang_x_exp//slices",
"@org_golang_x_sync//errgroup",
"@org_uber_go_atomic//:atomic",
"@org_uber_go_goleak//:goleak",
"@org_uber_go_zap//:zap",
Expand Down
52 changes: 52 additions & 0 deletions ddl/ddl_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import (
"github.com/pingcap/tidb/util/cmp"
"github.com/stretchr/testify/require"
"golang.org/x/exp/slices"
"golang.org/x/sync/errgroup"
)

func TestGetDDLJobs(t *testing.T) {
Expand Down Expand Up @@ -153,6 +154,57 @@ func enQueueDDLJobs(t *testing.T, sess session.Session, txn kv.Transaction, jobT
}
}

func TestCreateViewConcurrently(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")

tk.MustExec("create table t (a int);")
tk.MustExec("create view v as select * from t;")
tk.MustExec("set global tidb_enable_metadata_lock = 1;")
var (
counterErr error
counter int
)
ddl.OnCreateViewForTest = func(job *model.Job) {
counter++
if counter > 1 {
counterErr = fmt.Errorf("create view job should not run concurrently")
return
}
}
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/ddl/onDDLCreateView", "return"))
defer func() {
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/ddl/onDDLCreateView"))
}()

ddl.AfterDelivery2WorkerForTest = func(job *model.Job) {
if job.Type == model.ActionCreateView {
counter--
}
}
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/ddl/afterDelivery2Worker", "return"))
defer func() {
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/ddl/afterDelivery2Worker"))
}()

var eg errgroup.Group
for i := 0; i < 5; i++ {
eg.Go(func() error {
newTk := testkit.NewTestKit(t, store)
_, err := newTk.Exec("use test")
if err != nil {
return err
}
_, err = newTk.Exec("create or replace view v as select * from t;")
return err
})
}
err := eg.Wait()
require.NoError(t, err)
require.NoError(t, counterErr)
}

func TestCreateDropCreateTable(t *testing.T) {
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
Expand Down
6 changes: 6 additions & 0 deletions ddl/job_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -351,13 +351,19 @@ func (d *ddl) loadDDLJobAndRun(se *sess.Session, pool *workerPool, getJob func(*
d.delivery2worker(wk, pool, job)
}

// AfterDelivery2WorkerForTest is only used for test.
var AfterDelivery2WorkerForTest func(*model.Job)

// delivery2worker owns the worker, need to put it back to the pool in this function.
func (d *ddl) delivery2worker(wk *worker, pool *workerPool, job *model.Job) {
injectFailPointForGetJob(job)
d.runningJobs.add(job)
d.wg.Run(func() {
metrics.DDLRunningJobCount.WithLabelValues(pool.tp().String()).Inc()
defer func() {
failpoint.Inject("afterDelivery2Worker", func() {
AfterDelivery2WorkerForTest(job)
})
d.runningJobs.remove(job)
asyncNotify(d.ddlJobCh)
metrics.DDLRunningJobCount.WithLabelValues(pool.tp().String()).Dec()
Expand Down
4 changes: 2 additions & 2 deletions ddl/placement_policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ func getPlacementPolicyByName(d *ddlCtx, t *meta.Meta, policyName model.CIStr) (
}

is := d.infoCache.GetLatest()
if is.SchemaMetaVersion() == currVer {
if is != nil && is.SchemaMetaVersion() == currVer {
// Use cached policy.
policy, ok := is.PolicyByName(policyName)
if ok {
Expand Down Expand Up @@ -319,7 +319,7 @@ func checkPlacementPolicyNotInUse(d *ddlCtx, t *meta.Meta, policy *model.PolicyI
return err
}
is := d.infoCache.GetLatest()
if is.SchemaMetaVersion() == currVer {
if is != nil && is.SchemaMetaVersion() == currVer {
return CheckPlacementPolicyNotInUseFromInfoSchema(is, policy)
}

Expand Down
2 changes: 1 addition & 1 deletion ddl/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func checkSchemaNotExists(d *ddlCtx, t *meta.Meta, schemaID int64, dbInfo *model
return err
}
is := d.infoCache.GetLatest()
if is.SchemaMetaVersion() == currVer {
if is != nil && is.SchemaMetaVersion() == currVer {
return checkSchemaNotExistsFromInfoSchema(is, schemaID, dbInfo)
}
return checkSchemaNotExistsFromStore(t, schemaID, dbInfo)
Expand Down
66 changes: 59 additions & 7 deletions ddl/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,18 +270,28 @@
return t.UpdateTable(schemaID, tbInfo)
}

// OnCreateViewForTest is only used for test.
var OnCreateViewForTest func(*model.Job)

func onCreateView(d *ddlCtx, t *meta.Meta, job *model.Job) (ver int64, _ error) {
schemaID := job.SchemaID
tbInfo := &model.TableInfo{}
var orReplace bool
var oldTbInfoID int64
if err := job.DecodeArgs(tbInfo, &orReplace, &oldTbInfoID); err != nil {
var _placeholder int64 // oldTblInfoID
if err := job.DecodeArgs(tbInfo, &orReplace, &_placeholder); err != nil {
// Invalid arguments, cancel this job.
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
tbInfo.State = model.StateNone
err := checkTableNotExists(d, t, schemaID, tbInfo.Name.L)

oldTableID, err := findTableIDByName(d, t, schemaID, tbInfo.Name.L)
if infoschema.ErrTableNotExists.Equal(err) {
err = nil
}
failpoint.Inject("onDDLCreateView", func() {
OnCreateViewForTest(job)
})
if err != nil {
if infoschema.ErrDatabaseNotExists.Equal(err) {
job.State = model.JobStateCancelled
Expand All @@ -304,13 +314,13 @@
// none -> public
tbInfo.State = model.StatePublic
tbInfo.UpdateTS = t.StartTS
if oldTbInfoID > 0 && orReplace {
err = t.DropTableOrView(schemaID, oldTbInfoID)
if oldTableID > 0 && orReplace {
err = t.DropTableOrView(schemaID, oldTableID)
if err != nil {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
err = t.GetAutoIDAccessors(schemaID, oldTbInfoID).Del()
err = t.GetAutoIDAccessors(schemaID, oldTableID).Del()
if err != nil {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
Expand Down Expand Up @@ -1468,7 +1478,7 @@
return err
}
is := d.infoCache.GetLatest()
if is.SchemaMetaVersion() == currVer {
if is != nil && is.SchemaMetaVersion() == currVer {
return checkTableNotExistsFromInfoSchema(is, schemaID, tableName)
}

Expand Down Expand Up @@ -1521,6 +1531,48 @@
return nil
}

func findTableIDByName(d *ddlCtx, t *meta.Meta, schemaID int64, tableName string) (int64, error) {
// Try to use memory schema info to check first.
currVer, err := t.GetSchemaVersion()
if err != nil {
return 0, err
}

Check warning on line 1539 in ddl/table.go

View check run for this annotation

Codecov / codecov/patch

ddl/table.go#L1538-L1539

Added lines #L1538 - L1539 were not covered by tests
is := d.infoCache.GetLatest()
if is != nil && is.SchemaMetaVersion() == currVer {
return findTableIDFromInfoSchema(is, schemaID, tableName)
}

return findTableIDFromStore(t, schemaID, tableName)

Check warning on line 1545 in ddl/table.go

View check run for this annotation

Codecov / codecov/patch

ddl/table.go#L1545

Added line #L1545 was not covered by tests
}

func findTableIDFromInfoSchema(is infoschema.InfoSchema, schemaID int64, tableName string) (int64, error) {
schema, ok := is.SchemaByID(schemaID)
if !ok {
return 0, infoschema.ErrDatabaseNotExists.GenWithStackByArgs("")
}

Check warning on line 1552 in ddl/table.go

View check run for this annotation

Codecov / codecov/patch

ddl/table.go#L1551-L1552

Added lines #L1551 - L1552 were not covered by tests
tbl, err := is.TableByName(schema.Name, model.NewCIStr(tableName))
if err != nil {
return 0, err
}
return tbl.Meta().ID, nil
}

func findTableIDFromStore(t *meta.Meta, schemaID int64, tableName string) (int64, error) {
tbls, err := t.ListTables(schemaID)
if err != nil {
if meta.ErrDBNotExists.Equal(err) {
return 0, infoschema.ErrDatabaseNotExists.GenWithStackByArgs("")
}
return 0, errors.Trace(err)

Check warning on line 1566 in ddl/table.go

View check run for this annotation

Codecov / codecov/patch

ddl/table.go#L1560-L1566

Added lines #L1560 - L1566 were not covered by tests
}
for _, tbl := range tbls {
if tbl.Name.L == tableName {
return tbl.ID, nil
}

Check warning on line 1571 in ddl/table.go

View check run for this annotation

Codecov / codecov/patch

ddl/table.go#L1568-L1571

Added lines #L1568 - L1571 were not covered by tests
}
return 0, infoschema.ErrTableNotExists.FastGenByArgs(tableName)

Check warning on line 1573 in ddl/table.go

View check run for this annotation

Codecov / codecov/patch

ddl/table.go#L1573

Added line #L1573 was not covered by tests
}

// updateVersionAndTableInfoWithCheck checks table info validate and updates the schema version and the table information
func updateVersionAndTableInfoWithCheck(d *ddlCtx, t *meta.Meta, job *model.Job, tblInfo *model.TableInfo, shouldUpdateVer bool, multiInfos ...schemaIDAndTableInfo) (
ver int64, err error) {
Expand Down
3 changes: 2 additions & 1 deletion ddl/table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,8 @@ func TestCreateView(t *testing.T) {
}
ctx.SetValue(sessionctx.QueryString, "skip")
err = d.DoDDLJob(ctx, job)
require.Error(t, err)
// The non-existing table id in job args will not be considered anymore.
require.NoError(t, err)
}

func checkTableCacheTest(t *testing.T, store kv.Storage, dbInfo *model.DBInfo, tblInfo *model.TableInfo) {
Expand Down