Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
test: add tests for backup&restore (#1050)
Yilong Li9065b48a1070
diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex 4b0a3ddbfe..1d7f5577a6 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -358,7 +358,8 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.User, []*db.Schema,return nil, nil, err}- if table.Type == baseTableType {+ switch table.Type {+ case baseTableType:if tableCollation.Valid {table.Collation = tableCollation.String}@@ -372,7 +373,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.User, []*db.Schema,} else {tableMap[dbName] = []db.Table{table}}- } else if table.Type == viewTableType {+ case viewTableType:viewInfoMap[fmt.Sprintf("%s/%s", dbName, table.Name)] = ViewInfo{createdTs: table.CreatedTs,updatedTs: table.UpdatedTs,@@ -920,14 +921,14 @@ func (driver *Driver) Restore(ctx context.Context, sc *bufio.Scanner) (err error}defer txn.Rollback()- f := func(stmt string) error {+ fnExecuteStmt := func(stmt string) error {if _, err := txn.Exec(stmt); err != nil {return err}return nil}- if err := util.ApplyMultiStatements(sc, f); err != nil {+ if err := util.ApplyMultiStatements(sc, fnExecuteStmt); err != nil {return err}diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.goindex 7882dbe8b7..6c0ab3ec62 100644--- a/plugin/db/pg/pg.go+++ b/plugin/db/pg/pg.go@@ -193,7 +193,7 @@ func (driver *Driver) GetVersion(ctx context.Context) (string, error) {return version, nil}-// SyncSchema synces the schema.+// SyncSchema syncs the schema.func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.User, []*db.Schema, error) {excludedDatabaseList := map[string]bool{// Skip our internal "bytebase" databasediff --git a/server/task_executor_database_restore.go b/server/task_executor_database_restore.goindex 1a3fa5877f..744292f134 100644--- a/server/task_executor_database_restore.go+++ b/server/task_executor_database_restore.go@@ -12,6 +12,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/db"+"go.uber.org/zap")diff --git a/tests/backup_restore_test.go b/tests/backup_restore_test.gonew file mode 100644index 0000000000..cd858414c0--- /dev/null+++ b/tests/backup_restore_test.go@@ -0,0 +1,288 @@+//go:build mysql+// +build mysql++package tests++import (+ "bufio"+ "bytes"+ "context"+ "database/sql"+ "fmt"+ "testing"+ "time"++ dbPlugin "github.com/bytebase/bytebase/plugin/db"+ "go.uber.org/zap"++ "github.com/bytebase/bytebase/resources/mysql"+ "github.com/stretchr/testify/require"+)++// TestBackupRestoreBasic tests basic backup and restore behavior+// The test plan is:+// 1. create schema with index and constraint and populate data (TODO(dragonly): add routine/event/trigger)+// 2. create a full backup+// 3. clear data+// 4. restore data+// 5. validate+func TestBackupRestoreBasic(t *testing.T) {+ t.Parallel()+ a := require.New(t)++ localhost := "127.0.0.1"+ port := getTestPort(t.Name())+ username := "root"+ database := "backup_restore"+ table := "backup_restore"++ _, stop := mysql.SetupTestInstance(t, port)+ defer stop()++ db, err := sql.Open("mysql", fmt.Sprintf("%s@tcp(%s:%d)/mysql", username, localhost, port))+ a.NoError(err)+ defer db.Close()++ _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", database))+ a.NoError(err)++ _, err = db.Exec(fmt.Sprintf("USE %s", database))+ a.NoError(err)++ _, err = db.Exec(fmt.Sprintf(`+ CREATE TABLE %s (+ id INT,+ PRIMARY KEY (id),+ CHECK (id >= 0)+ );+ `, table))+ a.NoError(err)++ const numRecords = 100+ tx, err := db.Begin()+ a.NoError(err)+ defer tx.Rollback()+ for i := 0; i < numRecords; i++ {+ _, err = tx.Exec(fmt.Sprintf("INSERT INTO %s VALUES (%d)", table, i))+ a.NoError(err)+ }+ err = tx.Commit()+ a.NoError(err)++ // make a full backup+ driver := getDbDriver(a, localhost, fmt.Sprintf("%d", port), username, database)+ defer func() {+ err := driver.Close(context.TODO())+ a.NoError(err)+ }()++ buf := backup(a, driver, database)+ // t.Logf("dump:\n%s", buf.String())++ // drop all tables+ _, err = db.Exec(fmt.Sprintf("DROP TABLE %s", table))+ a.NoError(err)++ // restore+ err = driver.Restore(context.TODO(), bufio.NewScanner(buf))+ a.NoError(err)++ // validate data+ rows, err := db.Query(fmt.Sprintf("SELECT * FROM %s ORDER BY id ASC", table))+ a.NoError(err)+ i := 0+ for rows.Next() {+ var col int+ err := rows.Scan(&col)+ a.NoError(err)+ a.Equal(col, i)+ i+++ }+ a.NoError(rows.Err())+ a.Equal(numRecords, i)+}++// TestPITR tests the PITR behavior+// The test plan is:+// 0. prepare tables with foreign key constraints dependencies+// 1. insert data and make a full backup (denoted as t0), which defines the checkpoint+// 2. insert more data, and this is the point-in-time (denoted as t1) that we want to recover+// 3. keep inserting data into the original tables+// 4.1. set foreign_key_checks=OFF+// 4.2. restore full backup at t0 to ghost tables+// 4.3. apply binlog from t0 to t1 to ghost tables+// 4.4. foreign_key_checks=ON+// 5. lock tables and atomically swap original and ghost tables+func TestPITR(t *testing.T) {+ t.Parallel()+ a := require.New(t)++ localhost := "127.0.0.1"+ port := getTestPort(t.Name())+ username := "root"+ database := "backup_restore"++ insertData := func(db *sql.DB, a *require.Assertions, begin, end int) {+ tx, err := db.Begin()+ a.NoError(err)+ defer tx.Rollback()++ for i := begin; i < end; i++ {+ _, err := tx.Exec(fmt.Sprintf("INSERT INTO t0 VALUES (%d)", i))+ a.NoError(err)+ _, err = tx.Exec(fmt.Sprintf("INSERT INTO t1 VALUES (%d, %d)", i, i))+ a.NoError(err)+ }++ err = tx.Commit()+ a.NoError(err)+ }++ _, stop := mysql.SetupTestInstance(t, port)+ defer stop()++ db, err := sql.Open("mysql", fmt.Sprintf("%s@tcp(%s:%d)/mysql", username, localhost, port))+ a.NoError(err)+ defer db.Close()++ _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", database))+ a.NoError(err)++ _, err = db.Exec(fmt.Sprintf("USE %s", database))+ a.NoError(err)++ _, err = db.Exec(`+ CREATE TABLE t0 (+ id INT,+ PRIMARY KEY (id),+ CHECK (id >= 0)+ );+ `)+ a.NoError(err)+ _, err = db.Exec(`+ CREATE TABLE t1 (+ id INT,+ pid INT,+ PRIMARY KEY (id),+ UNIQUE INDEX (pid),+ CONSTRAINT FOREIGN KEY (pid) REFERENCES t0(id) ON DELETE NO ACTION+ );+ `)+ a.NoError(err)++ // insert data to make time point t0+ insertData(db, a, 0, 10)++ // make a full backup of t0+ driverBackup := getDbDriver(a, localhost, fmt.Sprintf("%d", port), username, database)+ defer func() {+ err := driverBackup.Close(context.TODO())+ a.NoError(err)+ }()++ buf := backup(a, driverBackup, database)+ t.Log(buf.String())++ // insert more data to make time point t1+ insertData(db, a, 10, 20)++ // concurrently update data+ stopChan := make(chan bool)+ go updateRow(t, username, localhost, database, port, stopChan)+ defer func() { stopChan <- true }()++ // restore to ghost database+ _, err = db.Exec("SET foreign_key_checks=OFF")+ a.NoError(err)++ _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s_ghost", database))+ a.NoError(err)+ _, err = db.Exec(fmt.Sprintf("USE %s_ghost", database))+ a.NoError(err)++ driverRestore := getDbDriver(a, localhost, fmt.Sprintf("%d", port), username, fmt.Sprintf("%s_ghost", database))+ defer func() {+ err := driverRestore.Close(context.TODO())+ a.NoError(err)+ }()+ err = driverRestore.Restore(context.TODO(), bufio.NewScanner(buf))+ a.NoError(err)++ // TODO(dragonly): validate ghost table data and schema++ // TODO(dragonly): apply binlog from full backup to+ // need to use binlog package from gh-ost or go-mysql++ _, err = db.Exec("SET foreign_key_checks=ON")+ a.NoError(err)++ // the user can inspect the ghost table for now, and decide whether to execute the cut over+ // cut over stage, swap tables+ _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s_old", database))+ a.NoError(err)+ queryRename := fmt.Sprintf("RENAME TABLE"++ " `%s`.`t0` TO `%s_old`.`t0`, `%s`.`t1` TO `%s_old`.`t1`,"++ " `%s_ghost`.`t0` TO `%s`.`t0`, `%s_ghost`.`t1` TO `%s`.`t1`",+ database, database, database, database, database, database, database, database)+ t.Log(queryRename)+ _, err = db.Exec(queryRename)+ a.NoError(err)+}++func getDbDriver(a *require.Assertions, host, port, username, database string) dbPlugin.Driver {+ logger, err := zap.NewDevelopment()+ a.NoError(err)+ driver, err := dbPlugin.Open(+ context.TODO(),+ dbPlugin.MySQL,+ dbPlugin.DriverConfig{Logger: logger},+ dbPlugin.ConnectionConfig{+ Host: host,+ Port: port,+ Username: username,+ Password: "",+ Database: database,+ TLSConfig: dbPlugin.TLSConfig{},+ },+ dbPlugin.ConnectionContext{},+ )+ a.NoError(err)+ return driver+}++func backup(a *require.Assertions, driver dbPlugin.Driver, database string) *bytes.Buffer {+ var buf bytes.Buffer+ err := driver.Dump(context.TODO(), database, &buf, false)+ a.NoError(err)++ return &buf+}++func updateRow(t *testing.T, username, localhost, database string, port int, stopChan chan bool) {+ a := require.New(t)+ db, err := sql.Open("mysql", fmt.Sprintf("%s@tcp(%s:%d)/mysql", username, localhost, port))+ a.NoError(err)+ defer db.Close()++ _, err = db.Exec(fmt.Sprintf("USE %s", database))+ a.NoError(err)++ t.Log("Start updating data")+ _, err = db.Exec("CREATE TABLE IF NOT EXISTS _update_row_ (id INT PRIMARY KEY)")+ a.NoError(err)+ _, err = db.Exec("REPLACE INTO _update_row_ VALUES (0)")+ a.NoError(err)+ i := 0+ for {+ select {+ case <-stopChan:+ t.Log("Stop updating data")+ return+ default:+ }+ _, err = db.Exec(fmt.Sprintf("UPDATE _update_row_ SET id = %d", i))+ a.NoError(err)+ i+++ time.Sleep(10 * time.Millisecond)+ }+}diff --git a/tests/ghost_test.go b/tests/ghost_test.goindex 11c85a346a..6c6dd7a239 100644--- a/tests/ghost_test.go+++ b/tests/ghost_test.go@@ -97,9 +97,11 @@ func newMigrationContext(config config) (*base.MigrationContext, error) {}func TestGhostSimpleNoop(t *testing.T) {- const (+ t.Parallel()+ a := require.New(t)+ var (localhost = "127.0.0.1"- port = 13306+ port = getTestPort(t.Name())user = "root"database = "gh_ost_test_db"table = "tbl"@@ -108,30 +110,30 @@ func TestGhostSimpleNoop(t *testing.T) {defer stop()db, err := sql.Open("mysql", fmt.Sprintf("root@tcp(localhost:%d)/mysql", port))- require.NoError(t, err)+ a.NoError(err)defer db.Close()_, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", database))- require.NoError(t, err)+ a.NoError(err)_, err = db.Exec(fmt.Sprintf("USE %s", database))- require.NoError(t, err)+ a.NoError(err)_, err = db.Exec(fmt.Sprintf("CREATE TABLE %s (id INT PRIMARY KEY, data INT)", table))- require.NoError(t, err)+ a.NoError(err)tx, err := db.Begin()- require.NoError(t, err)+ a.NoError(err)defer tx.Rollback()const n = 100- for i := 1; i <= n; i++ {+ for i := 0; i < n; i++ {_, err = tx.Exec(fmt.Sprintf("INSERT INTO %s VALUES (%v, %v)", table, i, i))- require.NoError(t, err)+ a.NoError(err)}err = tx.Commit()- require.NoError(t, err)+ a.NoError(err)migrationContext, err := newMigrationContext(config{host: localhost,@@ -142,9 +144,9 @@ func TestGhostSimpleNoop(t *testing.T) {alterStatement: "ALTER TABLE tbl ADD name VARCHAR(64)",noop: true,})- require.NoError(t, err)+ a.NoError(err)migrator := logic.NewMigrator(migrationContext)err = migrator.Migrate()- require.NoError(t, err)+ a.NoError(err)}diff --git a/tests/tests.go b/tests/tests.goindex fa61eba76c..2e04df367e 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -118,8 +118,14 @@ func getTestPort(testName string) int {return 1246case "TestTenantDatabaseNameTemplate":return 1249- case "TestTenantVCSDatabaseNameTemplate":+ case "TestGhostSimpleNoop":return 1252+ case "TestBackupRestoreBasic":+ return 1255+ case "TestPITR":+ return 1258+ case "TestTenantVCSDatabaseNameTemplate":+ return 1261}panic(fmt.Sprintf("test %q doesn't have assigned port, please set it in getTestPort()", testName))}