diff --git a/pkg/restore/db.go b/pkg/restore/db.go index 876f0fb63..81f43bff7 100644 --- a/pkg/restore/db.go +++ b/pkg/restore/db.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + "strings" "github.com/pingcap/errors" "github.com/pingcap/log" @@ -86,6 +87,22 @@ func (db *DB) CreateTable(ctx context.Context, table *utils.Table) error { return errors.Trace(err) } createSQL := buf.String() + // Insert `IF NOT EXISTS` statement to skip the created tables + words := strings.Split(createSQL, " ") + if len(words) > 2 && strings.ToUpper(words[0]) == "CREATE" && strings.ToUpper(words[1]) == "TABLE" { + resWords := append([]string{}, words[:2]...) + resWords = append(resWords, "IF NOT EXISTS") + resWords = append(resWords, words[2:]...) + createSQL = strings.Join(resWords, " ") + } else { + log.Error( + "build create table SQL error", + zap.Stringer("db", table.Db.Name), + zap.Stringer("table", schema.Name), + zap.String("SQL", createSQL), + zap.Error(err)) + return errors.New("build create table SQL failed") + } _, err = db.se.Execute(ctx, createSQL) if err != nil { log.Error("create table failed", diff --git a/pkg/restore/db_test.go b/pkg/restore/db_test.go index aa015d640..045cdf4d8 100644 --- a/pkg/restore/db_test.go +++ b/pkg/restore/db_test.go @@ -34,7 +34,7 @@ func (s *testRestoreSchemaSuite) TearDownSuite(c *C) { testleak.AfterTest(c)() } -func (s *testRestoreSchemaSuite) TestRestoreAutoIncID(c *C) { +func (s *testRestoreSchemaSuite) TestRestoreTableSchema(c *C) { c.Assert(s.mock.Start(), IsNil) defer s.mock.Stop() @@ -86,6 +86,8 @@ func (s *testRestoreSchemaSuite) TestRestoreAutoIncID(c *C) { c.Assert(err, IsNil, Commentf("Error create empty charset db: %s %s", err, s.mock.DSN)) err = db.CreateTable(context.Background(), &table) c.Assert(err, IsNil, Commentf("Error create table: %s %s", err, s.mock.DSN)) + err = db.CreateTable(context.Background(), &table) + c.Assert(err, IsNil, Commentf("Error create existed table: %s %s", err, s.mock.DSN)) tk.MustExec("use test") // Check if AutoIncID is altered successfully autoIncID, err = strconv.ParseUint(tk.MustQuery("admin show t next_row_id").Rows()[0][3].(string), 10, 64)