Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Add engine column to the migration_history table and we will also record migration history if using UI workflow
天舟ed9f472d4f0c
diff --git a/api/instance.go b/api/instance.goindex 8874e1d30d..f952de48de 100644--- a/api/instance.go+++ b/api/instance.go@@ -122,12 +122,13 @@ type MigrationHistory struct {UpdatedTs int64 `jsonapi:"attr,updatedTs"`// Domain specific fields- Database string `jsonapi:"attr,database"`- Type db.MigrationType `jsonapi:"attr,type"`- Version string `jsonapi:"attr,version"`- Description string `jsonapi:"attr,description"`- Statement string `jsonapi:"attr,statement"`- ExecutionDuration int `jsonapi:"attr,executionDuration"`+ Database string `jsonapi:"attr,database"`+ Engine db.MigrationEngine `jsonapi:"attr,engine"`+ Type db.MigrationType `jsonapi:"attr,type"`+ Version string `jsonapi:"attr,version"`+ Description string `jsonapi:"attr,description"`+ Statement string `jsonapi:"attr,statement"`+ ExecutionDuration int `jsonapi:"attr,executionDuration"`// This is a string instead of int as the issue id may come from other issue tracking system in the futureIssueId string `jsonapi:"attr,issueId"`Payload string `jsonapi:"attr,payload"`diff --git a/db/driver.go b/db/driver.goindex 3f6519df32..d985f4a4a8 100644--- a/db/driver.go+++ b/db/driver.go@@ -58,6 +58,23 @@ type DriverConfig struct {type DriverFunc func(DriverConfig) Driver+type MigrationEngine string++const (+ UI MigrationEngine = "UI"+ VCS MigrationEngine = "VCS"+)++func (e MigrationEngine) String() string {+ switch e {+ case UI:+ return "UI"+ case VCS:+ return "VCS"+ }+ return "UNKNOWN"+}+type MigrationType stringconst (@@ -84,6 +101,7 @@ type MigrationInfo struct {Namespace stringDatabase stringEnvironment string+ Engine MigrationEngineType MigrationTypeDescription stringCreator string@@ -110,6 +128,7 @@ func ParseMigrationInfo(fullPath string, baseDir string) (*MigrationInfo, error)}mi := &MigrationInfo{+ Engine: VCS,Version: parts[0],Namespace: parts[1],Database: parts[1],@@ -154,6 +173,7 @@ type MigrationHistory struct {Namespace stringSequence int+ Engine MigrationEngineType MigrationTypeVersion stringDescription stringdiff --git a/db/mysql.go b/db/mysql.goindex 1ed0c399a1..880697c1bd 100644--- a/db/mysql.go+++ b/db/mysql.go@@ -224,7 +224,7 @@ func (driver *MySQLDriver) ExecuteMigration(ctx context.Context, m *MigrationInf// Phase 1 - Precheck before executing migration// Check if the same migration version has alraedy been applied- duplicate, err := checkDuplicateVersion(ctx, tx, m.Namespace, m.Version)+ duplicate, err := checkDuplicateVersion(ctx, tx, m.Namespace, m.Engine, m.Version)if err != nil {return err}@@ -233,7 +233,7 @@ func (driver *MySQLDriver) ExecuteMigration(ctx context.Context, m *MigrationInf}// Check if there is any higher version already been applied- version, err := checkOutofOrderVersion(ctx, tx, m.Namespace, m.Version)+ version, err := checkOutofOrderVersion(ctx, tx, m.Namespace, m.Engine, m.Version)if err != nil {return err}@@ -241,9 +241,9 @@ func (driver *MySQLDriver) ExecuteMigration(ctx context.Context, m *MigrationInfreturn fmt.Errorf("database '%s' has already applied version %s which is higher than %s", m.Database, *version, m.Version)}- // If the migration type is not baseline, then we can only proceed if there is existing baseline+ // If the migration engine is VCS and type is not baseline, then we can only proceed if there is existing baseline// This check is also wrapped in transaction to avoid edge case where two baselinings are running concurrently.- if m.Type != Baseline {+ if m.Engine == VCS && m.Type != Baseline {hasBaseline, err := findBaseline(ctx, tx, m.Namespace)if err != nil {return err@@ -254,13 +254,15 @@ func (driver *MySQLDriver) ExecuteMigration(ctx context.Context, m *MigrationInf}}- sequence, err := findNextSequence(ctx, tx, m.Namespace, m.Type == Baseline)+ // VCS based SQL migration requires existing baselining+ requireBaseline := m.Engine == VCS && m.Type == Sql+ sequence, err := findNextSequence(ctx, tx, m.Namespace, requireBaseline)if err != nil {return err}- // Phase 2 - Executing migration unless it's baselining- if m.Type != Baseline {+ // Phase 2 - Executing migration unless it's VCS baselining+ if m.Engine != VCS || m.Type != Baseline {_, err = tx.ExecContext(ctx, statement)if err != nil {return formatError(err)@@ -276,6 +278,7 @@ func (driver *MySQLDriver) ExecuteMigration(ctx context.Context, m *MigrationInfupdated_ts,namespace,sequence,+ `+"`engine`,"+``+"`type`,"+`version,description,@@ -284,12 +287,13 @@ func (driver *MySQLDriver) ExecuteMigration(ctx context.Context, m *MigrationInfissue_id,payload)- VALUES (?, unix_timestamp(), ?, unix_timestamp(), ?, ?, ?, ?, ?, ?, ?, ?, ?)+ VALUES (?, unix_timestamp(), ?, unix_timestamp(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,m.Creator,m.Creator,m.Namespace,sequence,+ m.Engine,m.Type,m.Version,m.Description,@@ -329,6 +333,7 @@ func (driver *MySQLDriver) FindMigrationHistoryList(ctx context.Context, find *Mupdated_ts,namespace,sequence,+ `+"`engine`,"+``+"`type`,"+`version,description,@@ -357,6 +362,7 @@ func (driver *MySQLDriver) FindMigrationHistoryList(ctx context.Context, find *M&history.UpdatedTs,&history.Namespace,&history.Sequence,+ &history.Engine,&history.Type,&history.Version,&history.Description,@@ -397,10 +403,10 @@ func findBaseline(ctx context.Context, tx *sql.Tx, namespace string) (bool, erroreturn true, nil}-func checkDuplicateVersion(ctx context.Context, tx *sql.Tx, namespace string, version string) (bool, error) {- args := []interface{}{namespace, version}+func checkDuplicateVersion(ctx context.Context, tx *sql.Tx, namespace string, engine MigrationEngine, version string) (bool, error) {+ args := []interface{}{namespace, engine.String(), version}row, err := tx.QueryContext(ctx, `- SELECT 1 FROM bytebase.migration_history WHERE namespace = ? AND version = ?+ SELECT 1 FROM bytebase.migration_history WHERE namespace = ? AND `+"`engine` = ? AND version = ?"+``,args...,)@@ -416,10 +422,10 @@ func checkDuplicateVersion(ctx context.Context, tx *sql.Tx, namespace string, vereturn false, nil}-func checkOutofOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, version string) (*string, error) {- args := []interface{}{namespace, version}+func checkOutofOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, engine MigrationEngine, version string) (*string, error) {+ args := []interface{}{namespace, engine.String(), version}row, err := tx.QueryContext(ctx, `- SELECT MIN(version) FROM bytebase.migration_history WHERE namespace = ? AND STRCMP(?, version) = -1+ SELECT MIN(version) FROM bytebase.migration_history WHERE namespace = ? AND `+"`engine` = ? AND STRCMP(?, version) = -1"+``,args...,)@@ -442,7 +448,7 @@ func checkOutofOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, vreturn nil, nil}-func findNextSequence(ctx context.Context, tx *sql.Tx, namespace string, baseline bool) (int, error) {+func findNextSequence(ctx context.Context, tx *sql.Tx, namespace string, requireBaseline bool) (int, error) {args := []interface{}{namespace}row, err := tx.QueryContext(ctx, `SELECT MAX(sequence) + 1 FROM bytebase.migration_history WHERE namespace = ?@@ -462,8 +468,8 @@ func findNextSequence(ctx context.Context, tx *sql.Tx, namespace string, baselin}if !sequence.Valid {- // Returns 1 if we are creating the first baseline- if baseline {+ // Returns 1 if we haven't applied any migration for this namespace and doesn't require baselining+ if !requireBaseline {return 1, nil}diff --git a/db/mysql_migration_schema.sql b/db/mysql_migration_schema.sqlindex 716c026672..1eb3ed98b3 100644--- a/db/mysql_migration_schema.sql+++ b/db/mysql_migration_schema.sql@@ -51,6 +51,8 @@ CREATE TABLE bytebase.migration_history (namespace TEXT NOT NULL,-- Used to detect out of order migration together with 'namespace' and 'version' column.sequence INTEGER UNSIGNED NOT NULL,+ -- We call it engine because maybe we could load history from other migration tool.+ `engine` ENUM('UI', 'VCS') NOT NULL,`type` ENUM('BASELINE', 'SQL', 'SQL_ROLLBACK') NOT NULL,version TEXT NOT NULL,description TEXT NOT NULL,@@ -63,6 +65,6 @@ CREATE TABLE bytebase.migration_history (CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_sequence ON bytebase.migration_history (namespace(256), sequence);-CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_version ON bytebase.migration_history (namespace(256), version(256));+CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_engine_version ON bytebase.migration_history (namespace(256), `engine`, version(256));-CREATE INDEX bytebase_idx_migration_history_namespace_type ON bytebase.migration_history(namespace(256), `type`);\ No newline at end of file+CREATE INDEX bytebase_idx_migration_history_namespace_engine_type ON bytebase.migration_history(namespace(256), `engine`, `type`);\ No newline at end of filediff --git a/frontend/src/components/MigrationHistoryTable.vue b/frontend/src/components/MigrationHistoryTable.vueindex 67ead2a36e..1c697590fd 100644--- a/frontend/src/components/MigrationHistoryTable.vue+++ b/frontend/src/components/MigrationHistoryTable.vue@@ -8,7 +8,10 @@:rowClickable="false"><template v-slot:body="{ rowData: history }">- <BBTableCell :leftPadding="4" class="w-16 table-cell">+ <BBTableCell :leftPadding="4" class="w-8 table-cell">+ {{ history.engine }}+ </BBTableCell>+ <BBTableCell class="w-16 table-cell">{{ history.version }}</BBTableCell><BBTableCell class="w-16 table-cell">@@ -43,6 +46,9 @@ import { MigrationHistory } from "../types";import { secondsToString } from "../utils";const COLUMN_LIST = [+ {+ title: "Workflow",+ },{title: "Version",},diff --git a/frontend/src/types/instance.ts b/frontend/src/types/instance.tsindex 4a99220d03..2bfedc0c72 100644--- a/frontend/src/types/instance.ts+++ b/frontend/src/types/instance.ts@@ -65,6 +65,8 @@ export type InstanceMigration = {error: string;};+export type MigrationEngine = "UI" | "VCS";+export type MigrationType = "BASELINE" | "SQL";export type MigrationHistoryPayload = {@@ -78,6 +80,7 @@ export type MigrationHistory = {updater: string;updatedTs: number;database: string;+ engine: MigrationEngine;type: MigrationType;version: string;description: string;diff --git a/server/instance.go b/server/instance.goindex a95e27bfa5..f1890761bc 100644--- a/server/instance.go+++ b/server/instance.go@@ -276,6 +276,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {Updater: entry.Updater,UpdatedTs: entry.UpdatedTs,Database: entry.Namespace,+ Engine: entry.Engine,Type: entry.Type,Version: entry.Version,Description: entry.Description,diff --git a/server/task_executor_schema_update.go b/server/task_executor_schema_update.goindex f1bc9a3ed4..f02b979515 100644--- a/server/task_executor_schema_update.go+++ b/server/task_executor_schema_update.go@@ -6,6 +6,7 @@ import ("fmt""strconv""strings"+ "time""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/db"@@ -35,6 +36,11 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serve}}()+ if task.Database == nil {+ return true, "", fmt.Errorf("missing database when updating schema")+ }+ databaseName := task.Database.Name+payload := &api.TaskDatabaseSchemaUpdatePayload{}if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {return true, "", fmt.Errorf("invalid database schema update payload: %w", err)@@ -43,7 +49,25 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Servemi := &db.MigrationInfo{Type: db.Sql,}- if payload.VCSPushEvent != nil {+ if payload.VCSPushEvent == nil {+ mi.Engine = db.UI+ creator, err := server.ComposePrincipalById(context.Background(), task.CreatorId)+ if err != nil {+ // If somehow we unable to find the principal, we just emit the error since it's not+ // critical enough to fail the entire operation.+ exec.l.Error("Failed to fetch creator for composing the migration info",+ zap.Int("task_id", task.ID),+ zap.Error(err),+ )+ } else {+ mi.Creator = creator.Name+ }+ // Use the concatenation of current time and the task id to guarantee uniqueness in an ascending way.+ mi.Version = strings.Join([]string{time.Now().Format("20060102150405"), strconv.Itoa(task.ID)}, ".")+ mi.Database = databaseName+ mi.Namespace = databaseName+ mi.Description = task.Name+ } else {mi, err = db.ParseMigrationInfo(payload.VCSPushEvent.FileCommit.Added, payload.VCSPushEvent.BaseDirectory)// This should not happen normally as we already check this when creating the issue. Just in case.if err != nil {@@ -66,7 +90,7 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serve}issue, err := server.IssueService.FindIssue(ctx, issueFind)if err != nil {- // If somehow we unable about to find the issue, we just emit the error since it's not+ // If somehow we unable to find the issue, we just emit the error since it's not// critical enough to fail the entire operation.exec.l.Error("Failed to fetch containing issue for composing the migration info",zap.Int("task_id", task.ID),@@ -87,10 +111,6 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serve}instance := task.Instance- databaseName := ""- if task.Database != nil {- databaseName = task.Database.Name- }driver, err := db.Open(instance.Engine, db.DriverConfig{Logger: exec.l}, db.ConnectionConfig{Username: instance.Username,Password: instance.Password,@@ -102,35 +122,24 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Servereturn true, "", fmt.Errorf("failed to connect instance: %v with user: %v. %w", instance.Name, instance.Username, err)}- if payload.VCSPushEvent == nil {- exec.l.Debug("Start executing sql...",- zap.String("instance", instance.Name),- zap.String("database", databaseName),- zap.String("sql", sql),- )+ exec.l.Debug("Start sql migration...",+ zap.String("instance", instance.Name),+ zap.String("database", databaseName),+ zap.String("engine", mi.Engine.String()),+ zap.String("type", mi.Type.String()),+ zap.String("sql", sql),+ )- if err := driver.Execute(ctx, sql); err != nil {- return true, "", err- }- } else {- exec.l.Debug("Start sql migration...",- zap.String("instance", instance.Name),- zap.String("database", databaseName),- zap.String("type", mi.Type.String()),- zap.String("sql", sql),- )-- setup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- return true, "", fmt.Errorf("failed to check migration setup for instance: %v, %w", instance.Name, err)- }- if setup {- return true, "", fmt.Errorf("missing migration schema for instance: %v", instance.Name)- }+ setup, err := driver.NeedsSetupMigration(ctx)+ if err != nil {+ return true, "", fmt.Errorf("failed to check migration setup for instance: %v, %w", instance.Name, err)+ }+ if setup {+ return true, "", fmt.Errorf("missing migration schema for instance: %v", instance.Name)+ }- if err := driver.ExecuteMigration(ctx, mi, sql); err != nil {- return true, "", err- }+ if err := driver.ExecuteMigration(ctx, mi, sql); err != nil {+ return true, "", err}detail = fmt.Sprintf("Applied migration version %s to database '%s'", mi.Version, databaseName)diff --git a/server/task_scheduler.go b/server/task_scheduler.goindex da94f927b0..9a16b11b77 100644--- a/server/task_scheduler.go+++ b/server/task_scheduler.go@@ -109,6 +109,17 @@ func (s *TaskScheduler) Run() error {continue}+ // This fetches quite a bit info and may cause performance issue if we have many ongoing tasks+ // We may optimize this in the future since only some relationship info is needed by the executor+ if err := s.server.ComposeTaskRelationship(context.Background(), task); err != nil {+ s.l.Error("Failed to fetch task relationship",+ zap.Int("id", task.ID),+ zap.String("name", task.Name),+ zap.String("type", string(task.Type)),+ )+ continue+ }+done, detail, err := executor.RunOnce(context.Background(), s.server, task)if done {if err != nil {