Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: move sdl to a new type of task (#2983)
Danny Xu72f62524944e
diff --git a/api/task.go b/api/task.goindex b66d8fb535..20317466e9 100644--- a/api/task.go+++ b/api/task.go@@ -36,6 +36,8 @@ const (TaskDatabaseCreate TaskType = "bb.task.database.create"// TaskDatabaseSchemaUpdate is the task type for updating database schemas.TaskDatabaseSchemaUpdate TaskType = "bb.task.database.schema.update"+ // TaskDatabaseSchemaUpdateSDL is the task type for updating database schemas via state-based migration.+ TaskDatabaseSchemaUpdateSDL TaskType = "bb.task.database.schema.update-sdl"// TaskDatabaseSchemaUpdateGhostSync is the task type for gh-ost syncing ghost table.TaskDatabaseSchemaUpdateGhostSync TaskType = "bb.task.database.schema.update.ghost.sync"// TaskDatabaseSchemaUpdateGhostCutover is the task type for gh-ost switching the original table and the ghost table.diff --git a/plugin/db/clickhouse/clickhouse_migration_schema.sql b/plugin/db/clickhouse/clickhouse_migration_schema.sqlindex 04211d6354..20dca62835 100644--- a/plugin/db/clickhouse/clickhouse_migration_schema.sql+++ b/plugin/db/clickhouse/clickhouse_migration_schema.sql@@ -22,7 +22,7 @@ CREATE TABLE bytebase.migration_history (-- We call it source because maybe we could load history from other migration tool.-- Current allowed values are UI, VCS, LIBRARY.source TEXT NOT NULL,- -- Current allowed values are BASELINE, MIGRATE, BRANCH, DATA.+ -- Current allowed values are BASELINE, MIGRATE, MIGRATE_SDL, BRANCH, DATA.type TEXT NOT NULL,-- Current allowed values are PENDING, DONE, FAILED.-- MySQL runs DDL in its own transaction, so we can't record DDL and migration_history into a single transaction.diff --git a/plugin/db/driver.go b/plugin/db/driver.goindex e876f89ac5..8f31077123 100644--- a/plugin/db/driver.go+++ b/plugin/db/driver.go@@ -189,6 +189,9 @@ const (// Migrate is the migration type for MIGRATE.// Used for DDL change including CREATE DATABASE.Migrate MigrationType = "MIGRATE"+ // MigrateSDL is the migration type via state-based schema migration.+ // Used for schema change including CREATE DATABASE.+ MigrateSDL MigrationType = "MIGRATE_SDL"// Branch is the migration type for BRANCH.// Used when restoring from a backup (the restored database branched from the original backup).Branch MigrationType = "BRANCH"diff --git a/plugin/db/mysql/mysql_migration_schema.sql b/plugin/db/mysql/mysql_migration_schema.sqlindex 835652e565..e4e0487422 100644--- a/plugin/db/mysql/mysql_migration_schema.sql+++ b/plugin/db/mysql/mysql_migration_schema.sql@@ -22,7 +22,7 @@ CREATE TABLE bytebase.migration_history (-- We call it source because maybe we could load history from other migration tool.-- Current allowed values are UI, VCS, LIBRARY.source TEXT NOT NULL,- -- Current allowed values are BASELINE, MIGRATE, BRANCH, DATA.+ -- Current allowed values are BASELINE, MIGRATE, MIGRATE_SDL, BRANCH, DATA.type TEXT NOT NULL,-- Current allowed values are PENDING, DONE, FAILED.-- MySQL runs DDL in its own transaction, so we can't record DDL and migration_history into a single transaction.diff --git a/plugin/db/pg/pg_migration_schema.sql b/plugin/db/pg/pg_migration_schema.sqlindex 69c579ce00..20a6498250 100644--- a/plugin/db/pg/pg_migration_schema.sql+++ b/plugin/db/pg/pg_migration_schema.sql@@ -22,7 +22,7 @@ CREATE TABLE migration_history (-- We call it source because maybe we could load history from other migration tool.-- Current allowed values are UI, VCS, LIBRARY.source TEXT NOT NULL,- -- Current allowed values are BASELINE, MIGRATE, BRANCH, DATA.+ -- Current allowed values are BASELINE, MIGRATE, MIGRATE_SDL, BRANCH, DATA.type TEXT NOT NULL,-- Current allowed values are PENDING, DONE, FAILED.-- PostgreSQL can't do cross database transaction, so we can't record DDL and migration_history into a single transaction.diff --git a/plugin/db/snowflake/snowflake_migration_schema.sql b/plugin/db/snowflake/snowflake_migration_schema.sqlindex dd643049ce..79c4db2b46 100644--- a/plugin/db/snowflake/snowflake_migration_schema.sql+++ b/plugin/db/snowflake/snowflake_migration_schema.sql@@ -22,7 +22,7 @@ CREATE TABLE bytebase.public.migration_history (-- We call it source because maybe we could load history from other migration tool.-- Current allowed values are UI, VCS, LIBRARY.source TEXT NOT NULL,- -- Current allowed values are BASELINE, MIGRATE, BRANCH, DATA.+ -- Current allowed values are BASELINE, MIGRATE, MIGRATE_SDL, BRANCH, DATA.type TEXT NOT NULL,-- Current allowed values are PENDING, DONE, FAILED.-- Snowflake runs DDL in its own transaction, so we can't record DDL and migration_history into a single transaction.diff --git a/plugin/db/sqlite/sqlite_migration_schema.sql b/plugin/db/sqlite/sqlite_migration_schema.sqlindex 42e80d339c..c56b2191df 100644--- a/plugin/db/sqlite/sqlite_migration_schema.sql+++ b/plugin/db/sqlite/sqlite_migration_schema.sql@@ -16,7 +16,7 @@ CREATE TABLE bytebase_migration_history (-- We call it source because maybe we could load history from other migration tool.-- Current allowed values are UI, VCS, LIBRARY.source TEXT NOT NULL,- -- Current allowed values are BASELINE, MIGRATE, BRANCH, DATA.+ -- Current allowed values are BASELINE, MIGRATE, MIGRATE_SDL, BRANCH, DATA.type TEXT NOT NULL,-- Current allowed values are PENDING, DONE, FAILED.-- We create a "PENDING" record before applying the DDL and update that record to "DONE" after applying the DDL.diff --git a/server/issue.go b/server/issue.goindex d379cd4855..bfedb2eba5 100644--- a/server/issue.go+++ b/server/issue.go@@ -839,6 +839,8 @@ func getUpdateTask(database *api.Database, vcsPushEvent *vcs.PushEvent, d *api.Mswitch d.MigrationType {case db.Migrate:taskName = fmt.Sprintf("DDL(schema) for %q", database.Name)+ case db.MigrateSDL:+ taskName = fmt.Sprintf("SDL for %q", database.Name)case db.Data:taskName = fmt.Sprintf("DML(data) for %q", database.Name)}@@ -861,6 +863,8 @@ func getUpdateTask(database *api.Database, vcsPushEvent *vcs.PushEvent, d *api.MtaskType := api.TaskDatabaseSchemaUpdateif d.MigrationType == db.Data {taskType = api.TaskDatabaseDataUpdate+ } else if d.MigrationType == db.MigrateSDL {+ taskType = api.TaskDatabaseSchemaUpdateSDL}return &api.TaskCreate{Name: taskName,diff --git a/server/server.go b/server/server.goindex 3539fb2b42..71cc54dfef 100644--- a/server/server.go+++ b/server/server.go@@ -230,6 +230,8 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {taskScheduler.Register(api.TaskDatabaseSchemaUpdate, NewSchemaUpdateTaskExecutor)+ taskScheduler.Register(api.TaskDatabaseSchemaUpdateSDL, NewSchemaUpdateSDLTaskExecutor)+taskScheduler.Register(api.TaskDatabaseDataUpdate, NewDataUpdateTaskExecutor)taskScheduler.Register(api.TaskDatabaseBackup, NewDatabaseBackupTaskExecutor)diff --git a/server/task.go b/server/task.goindex 9652ca3126..2a965907d1 100644--- a/server/task.go+++ b/server/task.go@@ -159,7 +159,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project with ID: %d", issue.ProjectID)).SetInternal(err)}- if project.TenantMode == api.TenantModeTenant && task.Type == api.TaskDatabaseSchemaUpdate {+ if project.TenantMode == api.TenantModeTenant && (task.Type == api.TaskDatabaseSchemaUpdate || task.Type == api.TaskDatabaseSchemaUpdateSDL) {return echo.NewHTTPError(http.StatusBadRequest, "cannot update SQL statement of a single task for projects in tenant mode")}}@@ -285,6 +285,27 @@ func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.T}payloadStr := string(bytes)taskPatch.Payload = &payloadStr+ case api.TaskDatabaseSchemaUpdateSDL:+ payload := &api.TaskDatabaseSchemaUpdatePayload{}+ if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {+ return nil, echo.NewHTTPError(http.StatusBadRequest, "Malformed database schema update payload").SetInternal(err)+ }+ oldStatement = payload.Statement+ payload.Statement = *taskPatch.Statement+ // 1. For VCS workflows, patchTask only happens when we modify the same file.+ // In that case, we want to use the same schema version parsed from the file name.+ // The task executor will force retry using the new SQL statement.+ // 2. We should update the schema version if we've updated the SQL in the UI workflow, otherwise we will+ // get migration history version conflict if the previous task has been attempted.+ if issue.Project.WorkflowType == api.UIWorkflow {+ payload.SchemaVersion = common.DefaultMigrationVersion()+ }+ bytes, err := json.Marshal(payload)+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct updated task payload").SetInternal(err)+ }+ payloadStr := string(bytes)+ taskPatch.Payload = &payloadStrcase api.TaskDatabaseDataUpdate:payload := &api.TaskDatabaseDataUpdatePayload{}if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {@@ -347,7 +368,7 @@ func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.T}// create an activity and trigger task check for statement update- if taskPatched.Type == api.TaskDatabaseSchemaUpdate || taskPatched.Type == api.TaskDatabaseDataUpdate || taskPatched.Type == api.TaskDatabaseSchemaUpdateGhostSync {+ if taskPatched.Type == api.TaskDatabaseSchemaUpdate || taskPatched.Type == api.TaskDatabaseSchemaUpdateSDL || taskPatched.Type == api.TaskDatabaseDataUpdate || taskPatched.Type == api.TaskDatabaseSchemaUpdateGhostSync {if oldStatement != newStatement {if issue == nil {err := errors.Errorf("issue not found with pipeline ID %v", task.PipelineID)@@ -728,7 +749,7 @@ func (s *Server) patchTaskStatus(ctx context.Context, task *api.Task, taskStatus}// If create database, schema update and gh-ost cutover task completes, we sync the corresponding instance schema immediately.- if (taskPatched.Type == api.TaskDatabaseCreate || taskPatched.Type == api.TaskDatabaseSchemaUpdate || taskPatched.Type == api.TaskDatabaseSchemaUpdateGhostCutover) && taskPatched.Status == api.TaskDone {+ if (taskPatched.Type == api.TaskDatabaseCreate || taskPatched.Type == api.TaskDatabaseSchemaUpdate || taskPatched.Type == api.TaskDatabaseSchemaUpdateSDL || taskPatched.Type == api.TaskDatabaseSchemaUpdateGhostCutover) && taskPatched.Status == api.TaskDone {instance, err := s.store.GetInstanceByID(ctx, task.InstanceID)if err != nil {return nil, errors.Wrap(err, "failed to sync instance schema after completing task")diff --git a/server/task_check_executor_statement_type.go b/server/task_check_executor_statement_type.goindex f66f818338..3d6856faef 100644--- a/server/task_check_executor_statement_type.go+++ b/server/task_check_executor_statement_type.go@@ -113,7 +113,7 @@ func mysqlStatementTypeCheck(statement string, charset string, collation string,})}}- case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseSchemaUpdateGhostSync:+ case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseSchemaUpdateSDL, api.TaskDatabaseSchemaUpdateGhostSync:for _, node := range stmts {_, isDML := node.(tidbast.DMLNode)_, isExplain := node.(*tidbast.ExplainStmt)@@ -165,7 +165,7 @@ func postgresqlStatementTypeCheck(statement string, taskType api.TaskType) (resu})}}- case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseSchemaUpdateGhostSync:+ case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseSchemaUpdateSDL, api.TaskDatabaseSchemaUpdateGhostSync:for _, node := range stmts {_, isDML := node.(ast.DMLNode)_, isSelect := node.(*ast.SelectStmt)diff --git a/server/task_check_scheduler.go b/server/task_check_scheduler.goindex e87a3f2095..3adcba41eb 100644--- a/server/task_check_scheduler.go+++ b/server/task_check_scheduler.go@@ -188,7 +188,7 @@ func (s *TaskCheckScheduler) ScheduleCheckIfNeeded(ctx context.Context, task *apreturn nil, errors.Wrap(err, "failed to schedule backup/PITR task check")}- if task.Type != api.TaskDatabaseSchemaUpdate && task.Type != api.TaskDatabaseDataUpdate && task.Type != api.TaskDatabaseSchemaUpdateGhostSync {+ if task.Type != api.TaskDatabaseSchemaUpdate && task.Type != api.TaskDatabaseSchemaUpdateSDL && task.Type != api.TaskDatabaseDataUpdate && task.Type != api.TaskDatabaseSchemaUpdateGhostSync {return task, nil}@@ -244,6 +244,12 @@ func (*TaskCheckScheduler) getStatement(task *api.Task) (string, error) {return "", errors.Wrap(err, "invalid TaskDatabaseSchemaUpdatePayload")}return taskPayload.Statement, nil+ case api.TaskDatabaseSchemaUpdateSDL:+ taskPayload := &api.TaskDatabaseSchemaUpdatePayload{}+ if err := json.Unmarshal([]byte(task.Payload), taskPayload); err != nil {+ return "", errors.Wrap(err, "invalid TaskDatabaseSchemaUpdatePayload")+ }+ return taskPayload.Statement, nilcase api.TaskDatabaseDataUpdate:taskPayload := &api.TaskDatabaseDataUpdatePayload{}if err := json.Unmarshal([]byte(task.Payload), taskPayload); err != nil {diff --git a/server/task_executor_schema_update_sdl.go b/server/task_executor_schema_update_sdl.gonew file mode 100644index 0000000000..a03e7c27b4--- /dev/null+++ b/server/task_executor_schema_update_sdl.go@@ -0,0 +1,85 @@+package server++import (+ "bytes"+ "context"+ "encoding/json"+ "sync/atomic"++ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/bytebase/bytebase/plugin/parser"+ "github.com/bytebase/bytebase/plugin/parser/differ"+)++// NewSchemaUpdateSDLTaskExecutor creates a schema update (SDL) task executor.+func NewSchemaUpdateSDLTaskExecutor() TaskExecutor {+ return &SchemaUpdateSDLTaskExecutor{}+}++// SchemaUpdateSDLTaskExecutor is the schema update (SDL) task executor.+type SchemaUpdateSDLTaskExecutor struct {+ completed int32+}++// RunOnce will run the schema update (SDL) task executor once.+func (exec *SchemaUpdateSDLTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {+ defer atomic.StoreInt32(&exec.completed, 1)+ payload := &api.TaskDatabaseSchemaUpdatePayload{}+ if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {+ return true, nil, errors.Wrap(err, "invalid database schema update payload")+ }++ ddl, err := server.computeDatabaseSchemaDiff(ctx, task.Database, payload.Statement)+ if err != nil {+ return true, nil, errors.Wrap(err, "invalid database schema diff")+ }+ return runMigration(ctx, server, task, payload.MigrationType, ddl, payload.SchemaVersion, payload.VCSPushEvent)+}++// IsCompleted tells the scheduler if the task execution has completed.+func (exec *SchemaUpdateSDLTaskExecutor) IsCompleted() bool {+ return atomic.LoadInt32(&exec.completed) == 1+}++// GetProgress returns the task progress.+func (*SchemaUpdateSDLTaskExecutor) GetProgress() api.Progress {+ return api.Progress{}+}++// computeDatabaseSchemaDiff computes the diff between current database schema+// and the given schema. It returns an empty string if there is no applicable+// diff.+func (s *Server) computeDatabaseSchemaDiff(ctx context.Context, database *api.Database, newSchemaStr string) (string, error) {+ driver, err := s.getAdminDatabaseDriver(ctx, database.Instance, database.Name)+ if err != nil {+ return "", errors.Wrap(err, "get admin driver")+ }+ defer func() {+ _ = driver.Close(ctx)+ }()++ var schema bytes.Buffer+ _, err = driver.Dump(ctx, database.Name, &schema, true /* schemaOnly */)+ if err != nil {+ return "", errors.Wrap(err, "dump old schema")+ }++ var engine parser.EngineType+ switch database.Instance.Engine {+ case db.Postgres:+ engine = parser.Postgres+ case db.MySQL:+ engine = parser.MySQL+ default:+ return "", errors.Errorf("unsupported database engine %q", database.Instance.Engine)+ }++ diff, err := differ.SchemaDiff(engine, schema.String(), newSchemaStr)+ if err != nil {+ return "", errors.New("compute schema diff")+ }+ return diff, nil+}diff --git a/server/task_scheduler.go b/server/task_scheduler.goindex 7ec3e17453..92ff9034a1 100644--- a/server/task_scheduler.go+++ b/server/task_scheduler.go@@ -361,7 +361,7 @@ func (s *TaskScheduler) ClearRunningTasks(ctx context.Context) error {func (s *TaskScheduler) passAllCheck(ctx context.Context, task *api.Task, allowedStatus api.TaskCheckStatus) (bool, error) {// schema update, data update and gh-ost sync task have required task check.- if task.Type == api.TaskDatabaseSchemaUpdate || task.Type == api.TaskDatabaseDataUpdate || task.Type == api.TaskDatabaseSchemaUpdateGhostSync {+ if task.Type == api.TaskDatabaseSchemaUpdate || task.Type == api.TaskDatabaseSchemaUpdateSDL || task.Type == api.TaskDatabaseDataUpdate || task.Type == api.TaskDatabaseSchemaUpdateGhostSync {pass, err := s.server.passCheck(ctx, task, api.TaskCheckDatabaseConnect, allowedStatus)if err != nil {return false, errdiff --git a/server/webhook.go b/server/webhook.goindex d06b63689b..40423f3176 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -1,7 +1,6 @@package serverimport (- "bytes""context""crypto/hmac""crypto/sha256"@@ -24,8 +23,6 @@ import ("github.com/bytebase/bytebase/common/log""github.com/bytebase/bytebase/plugin/advisor""github.com/bytebase/bytebase/plugin/db"- "github.com/bytebase/bytebase/plugin/parser"- "github.com/bytebase/bytebase/plugin/parser/differ""github.com/bytebase/bytebase/plugin/vcs""github.com/bytebase/bytebase/plugin/vcs/github""github.com/bytebase/bytebase/plugin/vcs/gitlab"@@ -661,21 +658,19 @@ func (s *Server) prepareIssueFromSDLFile(ctx context.Context, repo *api.Repositoreturn nil, nil}- statement, err := s.readFileContent(ctx, pushEvent, repo, file)+ sdl, err := s.readFileContent(ctx, pushEvent, repo, file)if err != nil {activityCreate := getIgnoredFileActivityCreate(repo.ProjectID, pushEvent, file, errors.Wrap(err, "Failed to read file content"))return nil, []*api.ActivityCreate{activityCreate}}- activityCreateList := []*api.ActivityCreate{}var migrationDetailList []*api.MigrationDetailif repo.Project.TenantMode == api.TenantModeTenant {migrationDetailList = append(migrationDetailList,&api.MigrationDetail{- // TODO(d): make it to SDL migration.- MigrationType: db.Migrate,+ MigrationType: db.MigrateSDL,DatabaseName: dbName,- Statement: statement,+ Statement: sdl,},)return migrationDetailList, nil@@ -689,24 +684,16 @@ func (s *Server) prepareIssueFromSDLFile(ctx context.Context, repo *api.Reposito}for _, database := range databases {- diff, err := s.computeDatabaseSchemaDiff(ctx, database, statement)- if err != nil {- activityCreate := getIgnoredFileActivityCreate(repo.ProjectID, pushEvent, file, errors.Wrap(err, "Failed to compute database schema diff"))- activityCreateList = append(activityCreateList, activityCreate)- continue- }-migrationDetailList = append(migrationDetailList,&api.MigrationDetail{- // TODO(d): make it to SDL migration.- MigrationType: db.Migrate,+ MigrationType: db.MigrateSDL,DatabaseID: database.ID,- Statement: diff,+ Statement: sdl,},)}- return migrationDetailList, activityCreateList+ return migrationDetailList, nil}// prepareIssueFromFile returns a list of update schema details derived@@ -806,41 +793,6 @@ func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases [return nil}-// computeDatabaseSchemaDiff computes the diff between current database schema-// and the given schema. It returns an empty string if there is no applicable-// diff.-func (s *Server) computeDatabaseSchemaDiff(ctx context.Context, database *api.Database, newSchemaStr string) (string, error) {- driver, err := s.getAdminDatabaseDriver(ctx, database.Instance, database.Name)- if err != nil {- return "", errors.Wrap(err, "get admin driver")- }- defer func() {- _ = driver.Close(ctx)- }()-- var schema bytes.Buffer- _, err = driver.Dump(ctx, database.Name, &schema, true /* schemaOnly */)- if err != nil {- return "", errors.Wrap(err, "dump old schema")- }-- var engine parser.EngineType- switch database.Instance.Engine {- case db.Postgres:- engine = parser.Postgres- case db.MySQL:- engine = parser.MySQL- default:- return "", errors.Errorf("unsupported database engine %q", database.Instance.Engine)- }-- diff, err := differ.SchemaDiff(engine, schema.String(), newSchemaStr)- if err != nil {- return "", errors.New("compute schema diff")- }- return diff, nil-}-// convertSQLAdviceToGitLabCIResult will convert SQL advice map to GitLab test output format.// GitLab test report: https://docs.gitlab.com/ee/ci/testing/unit_test_reports.html// junit XML format: https://llg.cubic.org/docs/junit/diff --git a/tests/schema_update_test.go b/tests/schema_update_test.goindex 142c4e613b..f79a686428 100644--- a/tests/schema_update_test.go+++ b/tests/schema_update_test.go@@ -906,7 +906,7 @@ ALTER TABLE ONLY public.users{Database: databaseName,Source: db.VCS,- Type: db.Migrate,+ Type: db.MigrateSDL,Status: db.Done,Schema: updatedSchema,SchemaPrev: initialSchema,