Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(gh-ost): gh-ost task executor implementation (phase 1) (#1244)

p0nyd68edd8c3879
diff --git a/.vscode/settings.json b/.vscode/settings.json
index a89e69ef43..e19f287980 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -41,5 +41,6 @@
"i18n-ally.enabledFrameworks": ["vue"],
"i18n-ally.parserOptions": {},
"go.lintOnSave": "workspace",
+ "go.buildFlags": ["-tags=mysql"],
"go.lintTool": "revive"
}
diff --git a/api/issue.go b/api/issue.go
index 593653a61a..8398829f3f 100644
--- a/api/issue.go
+++ b/api/issue.go
@@ -171,9 +171,9 @@ type UpdateSchemaGhostDetail struct {
// UpdateSchemaGhostContext is the issue create context for updating database schema using gh-ost.
type UpdateSchemaGhostContext struct {
- // UpdateSchemaDetail is the details of schema update.
+ // UpdateSchemaGhostDetail is the details of schema update.
// When a project is in tenant mode, there should be one item in the list.
- UpdateSchemaDetailList []*UpdateSchemaDetail `json:"updateSchemaDetailList"`
+ DetailList []*UpdateSchemaGhostDetail `json:"updateSchemaGhostDetailList"`
// VCSPushEvent is the event information for VCS push.
VCSPushEvent *vcs.PushEvent
}
diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.go
index 90e6f40339..1407f8a016 100644
--- a/plugin/db/util/driverutil.go
+++ b/plugin/db/util/driverutil.go
@@ -138,7 +138,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, executor MigrationExec
// Phase 1 - Precheck before executing migration
// Phase 2 - Record migration history as PENDING
- insertedID, err := beginMigration(ctx, executor, m, prevSchemaBuf.String(), statement, databaseName)
+ insertedID, err := BeginMigration(ctx, executor, m, prevSchemaBuf.String(), statement, databaseName)
if err != nil {
return -1, "", err
}
@@ -146,7 +146,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, executor MigrationExec
startedNs := time.Now().UnixNano()
defer func() {
- if err := endMigration(ctx, l, executor, startedNs, insertedID, updatedSchema, databaseName, resErr == nil /*isDone*/); err != nil {
+ if err := EndMigration(ctx, l, executor, startedNs, insertedID, updatedSchema, databaseName, resErr == nil /*isDone*/); err != nil {
l.Error("Failed to update migration history record",
zap.Error(err),
zap.Int64("migration_id", migrationHistoryID),
@@ -179,8 +179,8 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, executor MigrationExec
return insertedID, afterSchemaBuf.String(), nil
}
-// beginMigration checks before executing migration and inserts a migration history record with pending status.
-func beginMigration(ctx context.Context, executor MigrationExecutor, m *db.MigrationInfo, prevSchema string, statement string, databaseName string) (insertedID int64, err error) {
+// BeginMigration checks before executing migration and inserts a migration history record with pending status.
+func BeginMigration(ctx context.Context, executor MigrationExecutor, m *db.MigrationInfo, prevSchema string, statement string, databaseName string) (insertedID int64, err error) {
// Convert version to stored version.
storedVersion, err := ToStoredVersion(m.UseSemanticVersion, m.Version, m.SemanticVersionSuffix)
if err != nil {
@@ -246,8 +246,8 @@ func beginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migra
return insertedID, nil
}
-// endMigration updates the migration history record to DONE or FAILED depending on migration is done or not.
-func endMigration(ctx context.Context, l *zap.Logger, executor MigrationExecutor, startedNs int64, migrationHistoryID int64, updatedSchema string, databaseName string, isDone bool) (err error) {
+// EndMigration updates the migration history record to DONE or FAILED depending on migration is done or not.
+func EndMigration(ctx context.Context, l *zap.Logger, executor MigrationExecutor, startedNs int64, migrationHistoryID int64, updatedSchema string, databaseName string, isDone bool) (err error) {
migrationDurationNs := time.Now().UnixNano() - startedNs
sqldb, err := executor.GetDbConnection(ctx, databaseName)
diff --git a/server/issue.go b/server/issue.go
index 97ec53c596..b4d72e9b8b 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -665,7 +665,7 @@ func (s *Server) createPipelineFromIssue(ctx context.Context, issueCreate *api.I
return nil, err
}
if !s.feature(api.FeatureTaskScheduleTime) {
- for _, detail := range c.UpdateSchemaDetailList {
+ for _, detail := range c.DetailList {
if detail.EarliestAllowedTs != 0 {
return nil, echo.NewHTTPError(http.StatusForbidden, api.FeatureTaskScheduleTime.AccessErrorMessage())
}
@@ -681,7 +681,7 @@ func (s *Server) createPipelineFromIssue(ctx context.Context, issueCreate *api.I
if project.TenantMode == api.TenantModeTenant {
return nil, echo.NewHTTPError(http.StatusBadRequest, "not implemented yet")
}
- for _, d := range c.UpdateSchemaDetailList {
+ for _, d := range c.DetailList {
if d.Statement == "" {
return nil, echo.NewHTTPError(http.StatusBadRequest, "failed to create issue, sql statement missing")
}
@@ -819,7 +819,7 @@ func getUpdateTask(database *api.Database, migrationType db.MigrationType, vcsPu
}, nil
}
-func getUpdateGhostTaskList(database *api.Database, vcsPushEvent *vcs.PushEvent, d *api.UpdateSchemaDetail, schemaVersion string, taskStatus api.TaskStatus) ([]api.TaskCreate, []api.TaskIndexDAG, error) {
+func getUpdateGhostTaskList(database *api.Database, vcsPushEvent *vcs.PushEvent, d *api.UpdateSchemaGhostDetail, schemaVersion string, taskStatus api.TaskStatus) ([]api.TaskCreate, []api.TaskIndexDAG, error) {
var taskCreateList []api.TaskCreate
{
payload := api.TaskDatabaseSchemaUpdateGhostSyncPayload{}
diff --git a/server/server.go b/server/server.go
index 7d956f6766..baf8d7f200 100644
--- a/server/server.go
+++ b/server/server.go
@@ -176,11 +176,11 @@ func NewServer(ctx context.Context, prof Profile, logger *zap.Logger, loggerLeve
schemaUpdateGhostSyncExecutor := NewSchemaUpdateGhostSyncTaskExecutor(logger)
taskScheduler.Register(string(api.TaskDatabaseSchemaUpdateGhostSync), schemaUpdateGhostSyncExecutor)
- schemaUpdateTaskGhostCutoverExecutor := NewSchemaUpdateGhostCutoverTaskExecutor(logger)
- taskScheduler.Register(string(api.TaskDatabaseSchemaUpdateGhostCutover), schemaUpdateTaskGhostCutoverExecutor)
+ schemaUpdateGhostCutoverExecutor := NewSchemaUpdateGhostCutoverTaskExecutor(logger)
+ taskScheduler.Register(string(api.TaskDatabaseSchemaUpdateGhostCutover), schemaUpdateGhostCutoverExecutor)
- schemaUpdateTaskGhostDropOriginalTableExecutor := NewSchemaUpdateGhostDropOriginalTableTaskExecutor(logger)
- taskScheduler.Register(string(api.TaskDatabaseSchemaUpdateGhostDropOriginalTable), schemaUpdateTaskGhostDropOriginalTableExecutor)
+ schemaUpdateGhostDropOriginalTableExecutor := NewSchemaUpdateGhostDropOriginalTableTaskExecutor(logger)
+ taskScheduler.Register(string(api.TaskDatabaseSchemaUpdateGhostDropOriginalTable), schemaUpdateGhostDropOriginalTableExecutor)
s.TaskScheduler = taskScheduler
diff --git a/server/task_executor_schema_update_ghost_cutover.go b/server/task_executor_schema_update_ghost_cutover.go
index 099e52d714..f50857cd86 100644
--- a/server/task_executor_schema_update_ghost_cutover.go
+++ b/server/task_executor_schema_update_ghost_cutover.go
@@ -2,7 +2,6 @@ package server
import (
"context"
- "fmt"
"github.com/bytebase/bytebase/api"
"go.uber.org/zap"
@@ -10,17 +9,17 @@ import (
// NewSchemaUpdateGhostCutoverTaskExecutor creates a schema update (gh-ost) cutover task executor.
func NewSchemaUpdateGhostCutoverTaskExecutor(logger *zap.Logger) TaskExecutor {
- return &SchemaUpdateTaskExecutor{
+ return &SchemaUpdateGhostCutoverTaskExecutor{
l: logger,
}
}
-// SchemaUpdateGhostCutoverTaskExecutorExecutor is the schema update (gh-ost) cutover task executor.
-type SchemaUpdateGhostCutoverTaskExecutorExecutor struct {
+// SchemaUpdateGhostCutoverTaskExecutor is the schema update (gh-ost) cutover task executor.
+type SchemaUpdateGhostCutoverTaskExecutor struct {
l *zap.Logger //nolint
}
// RunOnce will run SchemaUpdateGhostCutover task once.
-func (exec *SchemaUpdateGhostCutoverTaskExecutorExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
- return true, nil, fmt.Errorf("not implemented yet")
+func (exec *SchemaUpdateGhostCutoverTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
+ return true, &api.TaskRunResultPayload{Detail: "not implemented yet"}, nil
}
diff --git a/server/task_executor_schema_update_ghost_drop_original_table.go b/server/task_executor_schema_update_ghost_drop_original_table.go
index 47ce11c805..660343ce98 100644
--- a/server/task_executor_schema_update_ghost_drop_original_table.go
+++ b/server/task_executor_schema_update_ghost_drop_original_table.go
@@ -2,7 +2,6 @@ package server
import (
"context"
- "fmt"
"github.com/bytebase/bytebase/api"
"go.uber.org/zap"
@@ -10,7 +9,7 @@ import (
// NewSchemaUpdateGhostDropOriginalTableTaskExecutor creates a schema update (gh-ost) drop original table task executor.
func NewSchemaUpdateGhostDropOriginalTableTaskExecutor(logger *zap.Logger) TaskExecutor {
- return &SchemaUpdateTaskExecutor{
+ return &SchemaUpdateGhostDropOriginalTableTaskExecutor{
l: logger,
}
}
@@ -22,5 +21,5 @@ type SchemaUpdateGhostDropOriginalTableTaskExecutor struct {
// RunOnce will run SchemaUpdateGhostDropOriginalTable task once.
func (exec *SchemaUpdateGhostDropOriginalTableTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
- return true, nil, fmt.Errorf("not implemented yet")
+ return true, &api.TaskRunResultPayload{Detail: "not implemented yet"}, nil
}
diff --git a/server/task_executor_schema_update_ghost_sync.go b/server/task_executor_schema_update_ghost_sync.go
index 1206142786..ae049dae1b 100644
--- a/server/task_executor_schema_update_ghost_sync.go
+++ b/server/task_executor_schema_update_ghost_sync.go
@@ -1,26 +1,229 @@
package server
import (
+ "bytes"
"context"
+ "encoding/json"
"fmt"
+ "strconv"
+ "strings"
+ "time"
"github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/common"
+ "github.com/bytebase/bytebase/plugin/db"
+ "github.com/bytebase/bytebase/plugin/db/util"
+ vcsPlugin "github.com/bytebase/bytebase/plugin/vcs"
+ "github.com/github/gh-ost/go/base"
+ "github.com/github/gh-ost/go/logic"
+ ghostsql "github.com/github/gh-ost/go/sql"
"go.uber.org/zap"
)
// NewSchemaUpdateGhostSyncTaskExecutor creates a schema update (gh-ost) sync task executor.
func NewSchemaUpdateGhostSyncTaskExecutor(logger *zap.Logger) TaskExecutor {
- return &SchemaUpdateTaskExecutor{
+ return &SchemaUpdateGhostSyncTaskExecutor{
l: logger,
}
}
// SchemaUpdateGhostSyncTaskExecutor is the schema update (gh-ost) sync task executor.
type SchemaUpdateGhostSyncTaskExecutor struct {
- l *zap.Logger //nolint
+ l *zap.Logger
+}
+
+type ghostConfig struct {
+ host string
+ port string
+ user string
+ password string
+ database string
+ table string
+ alterStatement string
+ noop bool
+}
+
+func newMigrationContext(config ghostConfig) (*base.MigrationContext, error) {
+ const (
+ allowedRunningOnMaster = true
+ concurrentCountTableRows = true
+ hooksStatusIntervalSec = 60
+ replicaServerID = 99999
+ heartbeatIntervalMilliseconds = 100
+ niceRatio = 0
+ chunkSize = 1000
+ dmlBatchSize = 10
+ maxLagMillisecondsThrottleThreshold = 1500
+ defaultNumRetries = 60
+ cutoverLockTimoutSeconds = 3
+ exponentialBackoffMaxInterval = 64
+ )
+ migrationContext := base.NewMigrationContext()
+ migrationContext.InspectorConnectionConfig.Key.Hostname = config.host
+ port := 3306
+ if config.port != "" {
+ configPort, err := strconv.Atoi(config.port)
+ if err != nil {
+ return nil, fmt.Errorf("failed to convert port from string to int, error: %w", err)
+ }
+ port = configPort
+ }
+ migrationContext.InspectorConnectionConfig.Key.Port = port
+ migrationContext.CliUser = config.user
+ migrationContext.CliPassword = config.password
+ migrationContext.DatabaseName = config.database
+ migrationContext.OriginalTableName = config.table
+ migrationContext.AlterStatement = config.alterStatement
+ migrationContext.Noop = config.noop
+ // set defaults
+ migrationContext.AllowedRunningOnMaster = allowedRunningOnMaster
+ migrationContext.ConcurrentCountTableRows = concurrentCountTableRows
+ migrationContext.HooksStatusIntervalSec = hooksStatusIntervalSec
+ migrationContext.ReplicaServerId = replicaServerID
+ migrationContext.CutOverType = base.CutOverAtomic
+
+ if migrationContext.AlterStatement == "" {
+ return nil, fmt.Errorf("alterStatement must be provided and must not be empty")
+ }
+ parser := ghostsql.NewParserFromAlterStatement(migrationContext.AlterStatement)
+ migrationContext.AlterStatementOptions = parser.GetAlterStatementOptions()
+
+ if migrationContext.DatabaseName == "" {
+ if !parser.HasExplicitSchema() {
+ return nil, fmt.Errorf("database must be provided and database name must not be empty, or alterStatement must specify database name")
+ }
+ migrationContext.DatabaseName = parser.GetExplicitSchema()
+ }
+ if migrationContext.OriginalTableName == "" {
+ if !parser.HasExplicitTable() {
+ return nil, fmt.Errorf("table must be provided and table name must not be empty, or alterStatement must specify table name")
+ }
+ migrationContext.OriginalTableName = parser.GetExplicitTable()
+ }
+ // TODO(p0ny): change file name according to design doc.
+ migrationContext.ServeSocketFile = fmt.Sprintf("/tmp/gh-ost.%s.%s.sock", migrationContext.DatabaseName, migrationContext.OriginalTableName)
+ // TODO(p0ny): set OkToDropTable to false and drop table in dropOriginalTable Task.
+ migrationContext.OkToDropTable = true
+ migrationContext.SetHeartbeatIntervalMilliseconds(heartbeatIntervalMilliseconds)
+ migrationContext.SetNiceRatio(niceRatio)
+ migrationContext.SetChunkSize(chunkSize)
+ migrationContext.SetDMLBatchSize(dmlBatchSize)
+ migrationContext.SetMaxLagMillisecondsThrottleThreshold(maxLagMillisecondsThrottleThreshold)
+ migrationContext.SetDefaultNumRetries(defaultNumRetries)
+ migrationContext.ApplyCredentials()
+ if err := migrationContext.SetCutOverLockTimeoutSeconds(cutoverLockTimoutSeconds); err != nil {
+ return nil, err
+ }
+ if err := migrationContext.SetExponentialBackoffMaxInterval(exponentialBackoffMaxInterval); err != nil {
+ return nil, err
+ }
+ return migrationContext, nil
}
// RunOnce will run SchemaUpdateGhostSync task once.
func (exec *SchemaUpdateGhostSyncTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
- return true, nil, fmt.Errorf("not implemented yet")
+ defer func() {
+ if r := recover(); r != nil {
+ panicErr, ok := r.(error)
+ if !ok {
+ panicErr = fmt.Errorf("%v", r)
+ }
+ exec.l.Error("SchemaUpdateGhostSyncTaskExecutor PANIC RECOVER", zap.Error(panicErr), zap.Stack("stack"))
+ terminated = true
+ err = fmt.Errorf("encounter internal error when executing migration using gh-ost")
+ }
+ }()
+
+ payload := &api.TaskDatabaseSchemaUpdateGhostSyncPayload{}
+ if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {
+ return true, nil, fmt.Errorf("invalid database schema update gh-ost sync payload: %w", err)
+ }
+ return runGhostMigration(ctx, exec.l, server, task, db.Migrate, payload.Statement, payload.SchemaVersion, payload.VCSPushEvent)
+}
+
+func runGhostMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.Task, migrationType db.MigrationType, statement, schemaVersion string, vcsPushEvent *vcsPlugin.PushEvent) (terminated bool, result *api.TaskRunResultPayload, err error) {
+ mi, err := preMigration(ctx, l, server, task, migrationType, statement, schemaVersion, vcsPushEvent)
+ if err != nil {
+ return true, nil, err
+ }
+ migrationID, schema, err := executeSync(ctx, l, task, mi, statement)
+ if err != nil {
+ return true, nil, err
+ }
+ return postMigration(ctx, l, server, task, vcsPushEvent, mi, migrationID, schema)
+}
+
+func executeSync(ctx context.Context, l *zap.Logger, task *api.Task, mi *db.MigrationInfo, statement string) (int64, string, error) {
+ statement = strings.TrimSpace(statement)
+
+ driver, err := getAdminDatabaseDriver(ctx, task.Instance, task.Database.Name, l)
+ if err != nil {
+ return -1, "", err
+ }
+ defer driver.Close(ctx)
+ setup, err := driver.NeedsSetupMigration(ctx)
+ if err != nil {
+ return -1, "", fmt.Errorf("failed to check migration setup for instance %q: %w", task.Instance.Name, err)
+ }
+ if setup {
+ return -1, "", common.Errorf(common.MigrationSchemaMissing, fmt.Errorf("missing migration schema for instance %q", task.Instance.Name))
+ }
+
+ executor := driver.(util.MigrationExecutor)
+
+ var prevSchemaBuf bytes.Buffer
+ if err := driver.Dump(ctx, mi.Database, &prevSchemaBuf, true); err != nil {
+ return -1, "", err
+ }
+
+ insertedID, err := util.BeginMigration(ctx, executor, mi, prevSchemaBuf.String(), statement, db.BytebaseDatabase)
+ if err != nil {
+ return -1, "", err
+ }
+ startedNs := time.Now().UnixNano()
+
+ err = executeGhost(task.Instance, task.Database.Name, statement)
+ if err != nil {
+ return -1, "", err
+ }
+
+ var afterSchemaBuf bytes.Buffer
+ if err := executor.Dump(ctx, mi.Database, &afterSchemaBuf, true); err != nil {
+ return -1, "", err
+ }
+
+ if err := util.EndMigration(ctx, l, executor, startedNs, insertedID, afterSchemaBuf.String(), mi.Database, true); err != nil {
+ l.Error("failed to update migration history record",
+ zap.Error(err),
+ zap.Int64("migration_id",
+ insertedID),
+ )
+ }
+ return insertedID, afterSchemaBuf.String(), nil
+}
+
+func executeGhost(instance *api.Instance, databaseName string, statement string) error {
+ adminDataSource := api.DataSourceFromInstanceWithType(instance, api.Admin)
+ if adminDataSource == nil {
+ return common.Errorf(common.Internal, fmt.Errorf("admin data source not found for instance %d", instance.ID))
+ }
+
+ migrationContext, err := newMigrationContext(ghostConfig{
+ host: instance.Host,
+ port: instance.Port,
+ user: adminDataSource.Username,
+ password: adminDataSource.Password,
+ database: databaseName,
+ alterStatement: statement,
+ noop: false,
+ })
+ if err != nil {
+ return fmt.Errorf("failed to init migrationContext for gh-ost, error: %w", err)
+ }
+
+ migrator := logic.NewMigrator(migrationContext)
+ if err = migrator.Migrate(); err != nil {
+ return fmt.Errorf("failed to run gh-ost, error: %w", err)
+ }
+ return nil
}
diff --git a/tests/ghost_test.go b/tests/ghost_test.go
index 6c6dd7a239..9ce9f178a3 100644
--- a/tests/ghost_test.go
+++ b/tests/ghost_test.go
@@ -4,149 +4,172 @@
package tests
import (
+ "context"
"database/sql"
+ "encoding/json"
"fmt"
+ "strconv"
"testing"
+ "github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/resources/mysql"
- "github.com/github/gh-ost/go/base"
- "github.com/github/gh-ost/go/logic"
- ghostsql "github.com/github/gh-ost/go/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/stretchr/testify/require"
)
-type config struct {
- host string
- port int
- user string
- password string
- database string
- table string
- alterStatement string
- noop bool
-}
-
-const (
- allowedRunningOnMaster = true
- concurrentCountTableRows = true
- hooksStatusIntervalSec = 60
- replicaServerID = 99999
- heartbeatIntervalMilliseconds = 100
- niceRatio = 0
- chunkSize = 1000
- dmlBatchSize = 10
- maxLagMillisecondsThrottleThreshold = 1500
- defaultNumRetries = 60
- cutoverLockTimoutSeconds = 3
- exponentialBackoffMaxInterval = 64
-)
-
-func newMigrationContext(config config) (*base.MigrationContext, error) {
- migrationContext := base.NewMigrationContext()
- migrationContext.InspectorConnectionConfig.Key.Hostname = config.host
- migrationContext.InspectorConnectionConfig.Key.Port = config.port
- migrationContext.CliUser = config.user
- migrationContext.CliPassword = config.password
- migrationContext.DatabaseName = config.database
- migrationContext.OriginalTableName = config.table
- migrationContext.AlterStatement = config.alterStatement
- migrationContext.Noop = config.noop
- // set defaults
- migrationContext.AllowedRunningOnMaster = allowedRunningOnMaster
- migrationContext.ConcurrentCountTableRows = concurrentCountTableRows
- migrationContext.HooksStatusIntervalSec = hooksStatusIntervalSec
- migrationContext.ReplicaServerId = replicaServerID
- migrationContext.CutOverType = base.CutOverAtomic
-
- if migrationContext.AlterStatement == "" {
- return nil, fmt.Errorf("alterStatement must be provided and must not be empty")
- }
- parser := ghostsql.NewParserFromAlterStatement(migrationContext.AlterStatement)
- migrationContext.AlterStatementOptions = parser.GetAlterStatementOptions()
-
- if migrationContext.DatabaseName == "" {
- if parser.HasExplicitSchema() {
- migrationContext.DatabaseName = parser.GetExplicitSchema()
- } else {
- return nil, fmt.Errorf("database must be provided and database name must not be empty, or alterStatement must specify database name")
- }
- }
- if migrationContext.OriginalTableName == "" {
- if parser.HasExplicitTable() {
- migrationContext.OriginalTableName = parser.GetExplicitTable()
- } else {
- return nil, fmt.Errorf("table must be provided and table name must not be empty, or alterStatement must specify table name")
- }
- }
- migrationContext.ServeSocketFile = fmt.Sprintf("/tmp/gh-ost.%s.%s.sock", migrationContext.DatabaseName, migrationContext.OriginalTableName)
- migrationContext.SetHeartbeatIntervalMilliseconds(heartbeatIntervalMilliseconds)
- migrationContext.SetNiceRatio(niceRatio)
- migrationContext.SetChunkSize(chunkSize)
- migrationContext.SetDMLBatchSize(dmlBatchSize)
- migrationContext.SetMaxLagMillisecondsThrottleThreshold(maxLagMillisecondsThrottleThreshold)
- migrationContext.SetDefaultNumRetries(defaultNumRetries)
- migrationContext.ApplyCredentials()
- if err := migrationContext.SetCutOverLockTimeoutSeconds(cutoverLockTimoutSeconds); err != nil {
- return nil, err
- }
- if err := migrationContext.SetExponentialBackoffMaxInterval(exponentialBackoffMaxInterval); err != nil {
- return nil, err
- }
- return migrationContext, nil
-}
+func TestGhostSchemaUpdate(t *testing.T) {
+ const (
+ databaseName = "testGhostSchemaUpdate"
+ mysqlMigrationStatement = `
+ CREATE TABLE book (
+ id INT PRIMARY KEY AUTO_INCREMENT,
+ name TEXT
+ );
+ `
+ mysqlGhostMigrationStatement = `
+ ALTER TABLE book ADD author VARCHAR(54)
+ `
+ mysqlQueryBookTable = `
+ SELECT * FROM INFORMATION_SCHEMA.COLUMNS
+ WHERE table_name = 'book'
+ ORDER BY ORDINAL_POSITION
+ `
+ mysqlBookSchema1 = `[["TABLE_CATALOG","TABLE_SCHEMA","TABLE_NAME","COLUMN_NAME","ORDINAL_POSITION","COLUMN_DEFAULT","IS_NULLABLE","DATA_TYPE","CHARACTER_MAXIMUM_LENGTH","CHARACTER_OCTET_LENGTH","NUMERIC_PRECISION","NUMERIC_SCALE","DATETIME_PRECISION","CHARACTER_SET_NAME","COLLATION_NAME","COLUMN_TYPE","COLUMN_KEY","EXTRA","PRIVILEGES","COLUMN_COMMENT","GENERATION_EXPRESSION","SRS_ID"],["VARCHAR","VARCHAR","VARCHAR","VARCHAR","INT","TEXT","VARCHAR","TEXT","BIGINT","BIGINT","BIGINT","BIGINT","INT","VARCHAR","VARCHAR","TEXT","CHAR","VARCHAR","VARCHAR","TEXT","TEXT","INT"],[["def","testGhostSchemaUpdate","book","id",1,null,"NO","int",null,null,"10","0",null,null,null,"int","PRI","auto_increment","select,insert,update,references","","",null],["def","testGhostSchemaUpdate","book","name",2,null,"YES","text","65535","65535",null,null,null,"utf8mb4","utf8mb4_general_ci","text","","","select,insert,update,references","","",null]]]`
+ mysqlBookSchema2 = `[["TABLE_CATALOG","TABLE_SCHEMA","TABLE_NAME","COLUMN_NAME","ORDINAL_POSITION","COLUMN_DEFAULT","IS_NULLABLE","DATA_TYPE","CHARACTER_MAXIMUM_LENGTH","CHARACTER_OCTET_LENGTH","NUMERIC_PRECISION","NUMERIC_SCALE","DATETIME_PRECISION","CHARACTER_SET_NAME","COLLATION_NAME","COLUMN_TYPE","COLUMN_KEY","EXTRA","PRIVILEGES","COLUMN_COMMENT","GENERATION_EXPRESSION","SRS_ID"],["VARCHAR","VARCHAR","VARCHAR","VARCHAR","INT","TEXT","VARCHAR","TEXT","BIGINT","BIGINT","BIGINT","BIGINT","INT","VARCHAR","VARCHAR","TEXT","CHAR","VARCHAR","VARCHAR","TEXT","TEXT","INT"],[["def","testGhostSchemaUpdate","book","id",1,null,"NO","int",null,null,"10","0",null,null,null,"int","PRI","auto_increment","select,insert,update,references","","",null],["def","testGhostSchemaUpdate","book","name",2,null,"YES","text","65535","65535",null,null,null,"utf8mb4","utf8mb4_general_ci","text","","","select,insert,update,references","","",null],["def","testGhostSchemaUpdate","book","author",3,null,"YES","varchar","54","216",null,null,null,"utf8mb4","utf8mb4_general_ci","varchar(54)","","","select,insert,update,references","","",null]]]`
+ )
-func TestGhostSimpleNoop(t *testing.T) {
+ port := getTestPort(t.Name()) + 3
t.Parallel()
a := require.New(t)
- var (
- localhost = "127.0.0.1"
- port = getTestPort(t.Name())
- user = "root"
- database = "gh_ost_test_db"
- table = "tbl"
- )
- _, stop := mysql.SetupTestInstance(t, port)
- defer stop()
+ ctx := context.Background()
+ ctl := &controller{}
+ dataDir := t.TempDir()
+ err := ctl.StartServer(ctx, dataDir, getTestPort(t.Name()))
+ a.NoError(err)
+ defer ctl.Close(ctx)
+ err = ctl.Login()
+ a.NoError(err)
+ err = ctl.setLicense()
+ a.NoError(err)
+
+ _, stopInstance := mysql.SetupTestInstance(t, port)
+ defer stopInstance()
+
+ mysqlDB, err := sql.Open("mysql", fmt.Sprintf("root@tcp(localhost:%d)/mysql", port))
+ a.NoError(err)
+ defer mysqlDB.Close()
+
+ _, err = mysqlDB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %v", databaseName))
+ a.NoError(err)
+
+ _, err = mysqlDB.Exec("DROP USER IF EXISTS bytebase")
+ a.NoError(err)
+ _, err = mysqlDB.Exec("CREATE USER 'bytebase' IDENTIFIED WITH mysql_native_password BY 'bytebase'")
+ a.NoError(err)
- db, err := sql.Open("mysql", fmt.Sprintf("root@tcp(localhost:%d)/mysql", port))
+ _, err = mysqlDB.Exec("GRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, DELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, SELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, REPLICATION CLIENT, REPLICATION SLAVE, LOCK TABLES ON *.* to bytebase")
a.NoError(err)
- defer db.Close()
- _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", database))
+ project, err := ctl.createProject(api.ProjectCreate{
+ Name: "Test Ghost Project",
+ Key: "TestGhostSchemaUpdate",
+ })
a.NoError(err)
- _, err = db.Exec(fmt.Sprintf("USE %s", database))
+ environments, err := ctl.getEnvironments()
+ a.NoError(err)
+ prodEnvironment, err := findEnvironment(environments, "Prod")
a.NoError(err)
- _, err = db.Exec(fmt.Sprintf("CREATE TABLE %s (id INT PRIMARY KEY, data INT)", table))
+ instance, err := ctl.addInstance(api.InstanceCreate{
+ EnvironmentID: prodEnvironment.ID,
+ Name: "mysqlInstance",
+ Engine: db.MySQL,
+ Host: "127.0.0.1",
+ Port: strconv.Itoa(port),
+ Username: "bytebase",
+ Password: "bytebase",
+ })
a.NoError(err)
- tx, err := db.Begin()
+ databases, err := ctl.getDatabases(api.DatabaseFind{
+ ProjectID: &project.ID,
+ })
+ a.NoError(err)
+ a.Zero(len(databases))
+ databases, err = ctl.getDatabases(api.DatabaseFind{
+ InstanceID: &instance.ID,
+ })
+ a.NoError(err)
+ a.Zero(len(databases))
+
+ err = ctl.createDatabase(project, instance, databaseName, nil)
a.NoError(err)
- defer tx.Rollback()
- const n = 100
- for i := 0; i < n; i++ {
- _, err = tx.Exec(fmt.Sprintf("INSERT INTO %s VALUES (%v, %v)", table, i, i))
- a.NoError(err)
- }
+ databases, err = ctl.getDatabases(api.DatabaseFind{
+ ProjectID: &project.ID,
+ })
- err = tx.Commit()
a.NoError(err)
+ a.Equal(1, len(databases))
+
+ database := databases[0]
+ a.Equal(database.Instance.ID, instance.ID)
+
+ createContext, err := json.Marshal(&api.UpdateSchemaContext{
+ MigrationType: db.Migrate,
+ UpdateSchemaDetailList: []*api.UpdateSchemaDetail{
+ {
+ DatabaseID: database.ID,
+ Statement: mysqlMigrationStatement,
+ },
+ },
+ })
+ a.NoError(err)
+ // Create an issue updating database schema.
+ issue, err := ctl.createIssue(api.IssueCreate{
+ ProjectID: project.ID,
+ Name: fmt.Sprintf("update schema for database %q", databaseName),
+ Type: api.IssueDatabaseSchemaUpdate,
+ Description: fmt.Sprintf("This updates the schema of database %q.", databaseName),
+ // Assign to self.
+ AssigneeID: project.Creator.ID,
+ CreateContext: string(createContext),
+ })
+ a.NoError(err)
+ status, err := ctl.waitIssuePipeline(issue.ID)
+ a.NoError(err)
+ a.Equal(api.TaskDone, status)
- migrationContext, err := newMigrationContext(config{
- host: localhost,
- port: port,
- user: user,
- database: database,
- table: table,
- alterStatement: "ALTER TABLE tbl ADD name VARCHAR(64)",
- noop: true,
+ result, err := ctl.query(instance, databaseName, mysqlQueryBookTable)
+ a.NoError(err)
+ a.Equal(mysqlBookSchema1, result)
+
+ createContext, err = json.Marshal(&api.UpdateSchemaGhostContext{
+ DetailList: []*api.UpdateSchemaGhostDetail{
+ {
+ DatabaseID: database.ID,
+ Statement: mysqlGhostMigrationStatement,
+ },
+ },
+ })
+ a.NoError(err)
+ issue, err = ctl.createIssue(api.IssueCreate{
+ ProjectID: project.ID,
+ Name: fmt.Sprintf("update schema for database %q", databaseName),
+ Type: api.IssueDatabaseSchemaUpdateGhost,
+ Description: fmt.Sprintf("This updates the schema of database %q using gh-ost", databaseName),
+ AssigneeID: project.Creator.ID,
+ CreateContext: string(createContext),
})
a.NoError(err)
+ // Status will be FAILED because not implemented
+ status, err = ctl.waitIssuePipeline(issue.ID)
+ a.NoError(err)
+ a.Equal(api.TaskDone, status)
- migrator := logic.NewMigrator(migrationContext)
- err = migrator.Migrate()
+ result, err = ctl.query(instance, databaseName, mysqlQueryBookTable)
a.NoError(err)
+ a.Equal(mysqlBookSchema2, result)
}
diff --git a/tests/tests.go b/tests/tests.go
index b78b13cc2a..fc8fa3409c 100644
--- a/tests/tests.go
+++ b/tests/tests.go
@@ -108,7 +108,7 @@ type controller struct {
}
func getTestPort(testName string) int {
- // The port should be incremented by 3 for bytebase, Postgres, and GitLab.
+ // The port should be incremented by 3 for bytebase, Postgres, and GitLab, unless documented otherwise.
switch testName {
case "TestServiceRestart":
return 1234
@@ -122,18 +122,19 @@ func getTestPort(testName string) int {
return 1246
case "TestTenantDatabaseNameTemplate":
return 1249
- case "TestGhostSimpleNoop":
+ // TestGhostSchemaUpdate uses 4 ports in total. The additional one is for a MySQL instance.
+ case "TestGhostSchemaUpdate":
return 1252
case "TestBackupRestoreBasic":
- return 1255
+ return 1256
case "TestPITR":
- return 1258
+ return 1259
case "TestTenantVCSDatabaseNameTemplate":
- return 1261
+ return 1262
case "TestBootWithExternalPg":
- return 1264
+ return 1265
case "NEXT": // TestBootWithExternalPg need 4 ports for test, modify here for your test.
- return 1268
+ return 1269
}
panic(fmt.Sprintf("test %q doesn't have assigned port, please set it in getTestPort()", testName))
}
@@ -884,6 +885,8 @@ func (ctl *controller) createDatabase(project *api.Project, instance *api.Instan
InstanceID: instance.ID,
DatabaseName: databaseName,
Labels: labels,
+ CharacterSet: "utf8mb4",
+ Collation: "utf8mb4_general_ci",
})
if err != nil {
return fmt.Errorf("failed to construct database creation issue CreateContext payload, error: %w", err)