Skip to content

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

Implement ExecuteMigrate

天舟2e186812b156
diff --git a/backend/api/task.go b/backend/api/task.go
index 66cdd2d9c6..9e5434d676 100644
--- a/backend/api/task.go
+++ b/backend/api/task.go
@@ -45,9 +45,9 @@ const (
// So we annotate with json tag using camelCase naming which is consistent with normal
// json naming convention
type TaskDatabaseSchemaUpdatePayload struct {
- Statement string `json:"statement,omitempty"`
- RollbackStatement string `json:"rollbackStatement,omitempty"`
- VCSPushEvent VCSPushEvent `json:"pushEvent,omitempty"`
+ Statement string `json:"statement,omitempty"`
+ RollbackStatement string `json:"rollbackStatement,omitempty"`
+ VCSPushEvent *VCSPushEvent `json:"pushEvent,omitempty"`
}
type Task struct {
diff --git a/backend/db/driver.go b/backend/db/driver.go
index febb55730e..05924bad34 100644
--- a/backend/db/driver.go
+++ b/backend/db/driver.go
@@ -2,8 +2,8 @@ package db
import (
"context"
- "database/sql"
"fmt"
+ "strings"
"sync"
"go.uber.org/zap"
@@ -52,17 +52,87 @@ type DriverConfig struct {
type DriverFunc func(DriverConfig) Driver
+type MigrationType string
+
+const (
+ Baseline MigrationType = "BASELINE"
+ Sql MigrationType = "SQL"
+)
+
+func (e MigrationType) String() string {
+ switch e {
+ case Baseline:
+ return "BASELINE"
+ case Sql:
+ return "SQL"
+ }
+ return "UNKNOWN"
+}
+
+type MigrationInfo struct {
+ Version string
+ Namespace string
+ Database string
+ Type MigrationType
+ Description string
+ Creator string
+}
+
+// Expected filename example, {{version}} can be arbitrary string without "_"
+// - {{version}}_db1 (a normal migration without description)
+// - {{version}}_db1_create_t1 (a normal migration with "create t1" as description)
+// - {{version}}_db1_baseline (a baseline migration without description)
+// - {{version}}_db1_baseline_create_t1 (a baseline migration with "create t1" as description)
+func ParseMigrationInfo(filename string) (*MigrationInfo, error) {
+ parts := strings.Split(strings.TrimSuffix(filename, ".sql"), "_")
+ if len(parts) < 2 {
+ return nil, fmt.Errorf("invalid filename format, got %v, want {{version}}_{{dbname}}[_{{type}}][_{{description}}].sql", filename)
+ }
+ mi := &MigrationInfo{
+ Version: parts[0],
+ Namespace: parts[1],
+ Database: parts[1],
+ }
+
+ migrationType := Sql
+ description := ""
+ if len(parts) > 2 {
+ if parts[2] == "baseline" {
+ migrationType = Baseline
+ if len(parts) > 3 {
+ description = strings.Join(parts[3:], " ")
+ }
+ } else {
+ description = strings.Join(parts[2:], " ")
+ }
+ }
+ if description == "" {
+ if migrationType == Baseline {
+ description = fmt.Sprintf("Create %s baseline", mi.Database)
+ } else {
+ description = fmt.Sprintf("Create %s migration", mi.Database)
+ }
+ }
+ mi.Type = migrationType
+ // Capitalize first letter
+ mi.Description = strings.ToUpper(description[:1]) + description[1:]
+
+ return mi, nil
+}
+
type Driver interface {
open(config ConnectionConfig) (Driver, error)
Ping(ctx context.Context) error
SyncSchema(ctx context.Context) ([]*DBSchema, error)
- Execute(ctx context.Context, sql string) (sql.Result, error)
+ Execute(ctx context.Context, statement string) error
// Migration related
// Check whether we need to setup migration (e.g. creating/upgrading the migration related tables)
NeedsSetupMigration(ctx context.Context) (bool, error)
// Create or upgrade migration related tables
SetupMigrationIfNeeded(ctx context.Context) error
+ // Execute migration will apply the statement and record the migration history on success.
+ ExecuteMigration(ctx context.Context, m *MigrationInfo, statement string) error
}
type ConnectionConfig struct {
diff --git a/backend/db/mysql.go b/backend/db/mysql.go
index e9908e1009..41b6936c19 100644
--- a/backend/db/mysql.go
+++ b/backend/db/mysql.go
@@ -6,6 +6,7 @@ import (
_ "embed"
"fmt"
"strings"
+ "time"
_ "github.com/go-sql-driver/mysql"
"go.uber.org/zap"
@@ -152,14 +153,15 @@ func (driver *MySQLDriver) SyncSchema(ctx context.Context) ([]*DBSchema, error)
return list, err
}
-func (driver *MySQLDriver) Execute(ctx context.Context, sql string) (sql.Result, error) {
+func (driver *MySQLDriver) Execute(ctx context.Context, statement string) error {
tx, err := driver.db.BeginTx(ctx, nil)
if err != nil {
- return nil, err
+ return err
}
defer tx.Rollback()
- return tx.ExecContext(ctx, sql)
+ _, err = tx.ExecContext(ctx, statement)
+ return err
}
func (driver *MySQLDriver) NeedsSetupMigration(ctx context.Context) (bool, error) {
@@ -189,12 +191,213 @@ func (driver *MySQLDriver) SetupMigrationIfNeeded(ctx context.Context) error {
if setup {
driver.l.Info("Bytebase migration schema not found, creating schema...")
- if _, err := driver.Execute(ctx, migrationSchema); err != nil {
+ if err := driver.Execute(ctx, migrationSchema); err != nil {
driver.l.Error("Failed to initialize migration schema.", zap.Error(err))
- return err
+ return formatError(err)
}
driver.l.Info("Successfully created migration schema.")
}
return nil
}
+
+func (driver *MySQLDriver) ExecuteMigration(ctx context.Context, m *MigrationInfo, statement string) error {
+ tx, err := driver.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ startedTs := time.Now().Unix()
+
+ // 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)
+ if err != nil {
+ return err
+ }
+ if duplicate {
+ return fmt.Errorf("%s has already applied version %s", m.Database, m.Version)
+ }
+
+ // Check if there is any higher version already been applied
+ version, err := checkOutofOrderVersion(ctx, tx, m.Namespace, m.Version)
+ if err != nil {
+ return err
+ }
+ if version != nil {
+ return fmt.Errorf("%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
+ // This check is also wrapped in transaction to avoid edge case where two baselings are running concurrently.
+ if m.Type != Baseline {
+ hasBaseline, err := findBaseline(ctx, tx, m.Namespace)
+ if err != nil {
+ return err
+ }
+
+ if !hasBaseline {
+ return fmt.Errorf("%s has not created migration baseline yet", m.Database)
+ }
+ }
+
+ sequence, err := findNextSequence(ctx, tx, m.Namespace, m.Type == Baseline)
+ if err != nil {
+ return err
+ }
+
+ // Phase 2 - Executing migration unless it's baselining and has empty statement
+ // Baseline can have empty statement
+ if !(m.Type == Baseline && statement == "") {
+ _, err = tx.ExecContext(ctx, statement)
+ if err != nil {
+ return formatError(err)
+ }
+ }
+
+ // Phase 3 - Record migration
+ _, err = tx.ExecContext(ctx, `
+ INSERT INTO bytebase.migration_history (
+ created_by,
+ updated_by,
+ namespace,
+ sequence,
+ `+"`type`,"+`
+ version,
+ description,
+ statement,
+ execution_duration
+ )
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `,
+ m.Creator,
+ m.Creator,
+ m.Namespace,
+ sequence,
+ m.Type,
+ m.Version,
+ m.Description,
+ statement,
+ time.Now().Unix()-startedTs,
+ )
+
+ if err != nil {
+ return formatError(err)
+ }
+
+ tx.Commit()
+
+ return nil
+}
+
+func findBaseline(ctx context.Context, tx *sql.Tx, namespace string) (bool, error) {
+ args := []interface{}{namespace}
+ row, err := tx.QueryContext(ctx, `
+ SELECT 1 FROM bytebase.migration_history WHERE namespace = ? AND `+"`type` = 'BASELINE'"+`
+ `,
+ args...,
+ )
+
+ if err != nil {
+ return false, err
+ }
+ defer row.Close()
+
+ if !row.Next() {
+ return false, nil
+ }
+
+ return true, nil
+}
+
+func checkDuplicateVersion(ctx context.Context, tx *sql.Tx, namespace string, version string) (bool, error) {
+ args := []interface{}{namespace, version}
+ row, err := tx.QueryContext(ctx, `
+ SELECT 1 FROM bytebase.migration_history WHERE namespace = ? AND version = ?
+ `,
+ args...,
+ )
+
+ if err != nil {
+ return false, err
+ }
+ defer row.Close()
+
+ if row.Next() {
+ return true, nil
+ }
+ return false, nil
+}
+
+func checkOutofOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, version string) (*string, error) {
+ args := []interface{}{namespace, version}
+ row, err := tx.QueryContext(ctx, `
+ SELECT MIN(version) FROM bytebase.migration_history WHERE namespace = ? AND STRCMP(?, version) = -1
+ `,
+ args...,
+ )
+
+ if err != nil {
+ return nil, err
+ }
+ defer row.Close()
+
+ var minVersion sql.NullString
+ row.Next()
+ if err := row.Scan(&minVersion); err != nil {
+ return nil, err
+ }
+
+ if minVersion.Valid {
+ return &minVersion.String, nil
+ }
+
+ return nil, nil
+}
+
+func findNextSequence(ctx context.Context, tx *sql.Tx, namespace string, baseline bool) (int, error) {
+ args := []interface{}{namespace}
+ row, err := tx.QueryContext(ctx, `
+ SELECT MAX(sequence) + 1 FROM bytebase.migration_history WHERE namespace = ?
+ `,
+ args...,
+ )
+
+ if err != nil {
+ return -1, err
+ }
+ defer row.Close()
+
+ var sequence sql.NullInt32
+ row.Next()
+ if err := row.Scan(&sequence); err != nil {
+ return -1, err
+ }
+
+ if !sequence.Valid {
+ // Returns 1 if we are creating the first baseline
+ if baseline {
+ return 1, nil
+ }
+
+ // This should not happen normally since we already check the baselining exist beforehand. Just in case.
+ return -1, fmt.Errorf("unable to generate next migration_sequence, no migration hisotry found for '%s', do you forget to baselining?", namespace)
+ }
+
+ return int(sequence.Int32), nil
+}
+
+func formatError(err error) error {
+ if err == nil {
+ return nil
+ }
+
+ if strings.Contains(err.Error(), "bytebase_idx_unique_migration_history_namespace_version") {
+ return fmt.Errorf("version has already been applied")
+ } else if strings.Contains(err.Error(), "bytebase_idx_unique_migration_history_namespace_sequence") {
+ return fmt.Errorf("concurrent migration")
+ }
+
+ return err
+}
diff --git a/backend/db/mysql_migration_schema.sql b/backend/db/mysql_migration_schema.sql
index 3aa668638d..4bc38a7b78 100644
--- a/backend/db/mysql_migration_schema.sql
+++ b/backend/db/mysql_migration_schema.sql
@@ -4,28 +4,29 @@ CREATE DATABASE bytebase CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_0900_ai_ci';
-- Create migration_history table
CREATE TABLE bytebase.migration_history (
- -- Can be used to detect out of order migration together with 'version' column.
id INTEGER PRIMARY KEY AUTO_INCREMENT,
created_by TEXT NOT NULL,
created_ts BIGINT NOT NULL,
updated_by TEXT NOT NULL,
updated_ts BIGINT NOT NULL,
-- Allows granular tracking of migration history (e.g If an application manages schemas for a multi-tenant service and each tenant has its own schema, that application can use namespace to record the tenant name to track the per-tenant schema migration)
- -- Since bytebase also manages different application databases from an instance, it leverages this field to track different databases using bytebase.{{dbname}} format.
+ -- Since bytebase also manages different application databases from an instance, it leverages this field to track each database migration history.
namespace TEXT NOT NULL,
- `type` ENUM('BASELINE', "SQL", "SQL_ROLLBACK", "DELETED") NOT NULL,
+ -- Used to detect out of order migration together with 'namespace' and 'version' column.
+ sequence INTEGER UNSIGNED NOT NULL,
+ `type` ENUM('BASELINE', 'SQL', 'SQL_ROLLBACK', 'DELETED') NOT NULL,
version TEXT NOT NULL,
description TEXT NOT NULL,
- -- Recorded the migration sql
- `sql` TEXT NOT NULL,
- execution_duration INTEGER NOT NULL,
- execution_status ENUM('RUNNING', 'DONE', 'FAILED') NOT NULL,
- execution_detail TEXT NOT NULL
+ -- Recorded the migration statement
+ statement TEXT NOT NULL,
+ execution_duration INTEGER NOT NULL
);
-CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_version ON bytebase.migration_history (version(256));
+CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_sequence ON bytebase.migration_history (namespace(256), sequence);
-CREATE INDEX bytebase_idx_migration_history_namespace ON bytebase.migration_history(namespace(256));
+CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_version ON bytebase.migration_history (namespace(256), version(256));
+
+CREATE INDEX bytebase_idx_migration_history_namespace_type ON bytebase.migration_history(namespace(256), `type`);
CREATE TRIGGER bytebase.trigger_update_migration_history_creation_time BEFORE
INSERT
diff --git a/backend/server/issue.go b/backend/server/issue.go
index 3a52a2f90b..e07cd43156 100644
--- a/backend/server/issue.go
+++ b/backend/server/issue.go
@@ -387,7 +387,7 @@ func (s *Server) CreateIssue(ctx context.Context, issueCreate *api.IssueCreate,
payload.RollbackStatement = taskCreate.RollbackStatement
}
if taskCreate.VCSPushEvent != nil {
- payload.VCSPushEvent = *taskCreate.VCSPushEvent
+ payload.VCSPushEvent = taskCreate.VCSPushEvent
}
bytes, err := json.Marshal(payload)
if err != nil {
diff --git a/backend/server/task_executor_sql.go b/backend/server/task_executor_sql.go
index 94a842f2bb..0adf1744bb 100644
--- a/backend/server/task_executor_sql.go
+++ b/backend/server/task_executor_sql.go
@@ -4,6 +4,8 @@ import (
"context"
"encoding/json"
"fmt"
+ "path/filepath"
+ "strings"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/db"
@@ -26,18 +28,31 @@ func (exec *SqlTaskExecutor) RunOnce(ctx context.Context, server *Server, task *
return true, fmt.Errorf("invalid schema update payload: %w", err)
}
- if payload.Statement == "" {
- return true, fmt.Errorf("missing sql statement")
+ mi := &db.MigrationInfo{
+ Type: db.Sql,
+ }
+ if payload.VCSPushEvent != nil {
+ filename := filepath.Base(payload.VCSPushEvent.FileCommit.Added)
+ mi, err = db.ParseMigrationInfo(filename)
+ // This should not happen normally as we already check this when creating the issue. Just in case.
+ if err != nil {
+ return true, fmt.Errorf("failed to start schema migration, error: %w", err)
+ }
+ mi.Creator = payload.VCSPushEvent.FileCommit.AuthorName
}
- exec.l.Info(fmt.Sprintf("sql executor: run %v", payload.Statement))
+ sql := strings.TrimSpace(payload.Statement)
+ // Only baseline can have empty sql statement, which indicates empty database.
+ if mi.Type != db.Baseline && sql == "" {
+ return true, fmt.Errorf("empty sql statement")
+ }
if err := server.ComposeTaskRelationship(ctx, task, []string{SECRET_KEY}); err != nil {
return true, err
}
instance := task.Database.Instance
- db, err := db.Open(instance.Engine, db.DriverConfig{Logger: exec.l}, db.ConnectionConfig{
+ driver, err := db.Open(instance.Engine, db.DriverConfig{Logger: exec.l}, db.ConnectionConfig{
Username: instance.Username,
Password: instance.Password,
Host: instance.Host,
@@ -48,9 +63,33 @@ func (exec *SqlTaskExecutor) RunOnce(ctx context.Context, server *Server, task *
return true, fmt.Errorf("failed to connect instance: %v with user: %v. %w", instance.Name, instance.Username, err)
}
- _, err = db.Execute(ctx, payload.Statement)
- if err != nil {
- return true, err
+ if payload.VCSPushEvent == nil {
+ exec.l.Debug("Start executing sql...",
+ zap.String("database", task.Database.Name),
+ zap.String("sql", sql),
+ )
+
+ if err := driver.Execute(ctx, sql); err != nil {
+ return true, err
+ }
+ } else {
+ exec.l.Debug("Start sql migration...",
+ zap.String("database", task.Database.Name),
+ 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)
+ }
+
+ if err := driver.ExecuteMigration(ctx, mi, sql); err != nil {
+ return true, err
+ }
}
return true, nil
diff --git a/backend/server/webhook.go b/backend/server/webhook.go
index 31f1140743..663e4a1c21 100644
--- a/backend/server/webhook.go
+++ b/backend/server/webhook.go
@@ -14,6 +14,7 @@ import (
"github.com/bytebase/bytebase"
"github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/db"
"github.com/bytebase/bytebase/external/gitlab"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
@@ -40,7 +41,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
// This shouldn't happen as we only setup webhook to receive push event, just in case.
if pushEvent.ObjectKind != gitlab.WebhookPush {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid webhook event type. Expect push, got %s", pushEvent.ObjectKind))
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid webhook event type, got %s, want push", pushEvent.ObjectKind))
}
webhookEndpointId := c.Param("id")
@@ -64,7 +65,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
}
if strconv.Itoa(pushEvent.Project.ID) != repository.ExternalId {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project mismatch. Expect %s, got %d", repository.ExternalId, pushEvent.Project.ID))
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project mismatch, got %d, want %s", pushEvent.Project.ID, repository.ExternalId))
}
createdMessageList := []string{}
@@ -72,20 +73,11 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
for _, added := range commit.AddedList {
if strings.HasPrefix(added, repository.BaseDirectory) && filepath.Ext(added) == ".sql" {
filename := filepath.Base(added)
-
- // We expect filename in the {{version}}_{{dbname}}[_{{description}}]
- // The description part is optional
- parts := strings.Split(strings.TrimSuffix(filename, filepath.Ext(added)), "_")
- if len(parts) < 2 {
- s.l.Warn("Added SQL file name does not conform to the expected format. Ignored", zap.String("filename", filename))
+ mi, err := db.ParseMigrationInfo(filename)
+ if err != nil {
+ s.l.Warn("invalid migration filename. Ignored", zap.Error(err))
continue
}
- //version := parts[0]
- dbName := parts[1]
- description := ""
- if len(parts) > 2 {
- description = strings.Join(parts[2:], " ")
- }
// Retrieve sql by reading the file content
resp, err := gitlab.GET(
@@ -107,12 +99,12 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
// Find matching database
databaseFind := &api.DatabaseFind{
ProjectId: &repository.ProjectId,
- Name: &dbName,
+ Name: &mi.Database,
}
database, err := s.ComposeDatabaseByFind(context.Background(), databaseFind, []string{})
if err != nil {
if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
- s.l.Warn(fmt.Sprintf("Project ID %d does not contain database %s. Ignored", repository.ProjectId, dbName),
+ s.l.Warn(fmt.Sprintf("Project ID %d does not contain database %s. Ignored", repository.ProjectId, mi.Database),
zap.Int("project_id", repository.ProjectId),
zap.String("filename", filename),
)
@@ -147,7 +139,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
task := &api.TaskCreate{
InstanceId: database.InstanceId,
DatabaseId: database.ID,
- Name: description,
+ Name: mi.Description,
Status: "PENDING",
Type: api.TaskDatabaseSchemaUpdate,
Statement: string(b),