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: migrate spanner to instance change history (#5057)
p0nye3ebc876bece
diff --git a/backend/plugin/db/spanner/migrate.go b/backend/plugin/db/spanner/migrate.goindex 6b04944eab..094156c90e 100644--- a/backend/plugin/db/spanner/migrate.go+++ b/backend/plugin/db/spanner/migrate.go@@ -1,20 +1,16 @@package spannerimport (- "bytes""context""fmt""strings"- "time""cloud.google.com/go/spanner""cloud.google.com/go/spanner/admin/database/apiv1/databasepb""go.uber.org/zap"- "github.com/google/uuid""github.com/pkg/errors"- "github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/db/util"@@ -37,32 +33,13 @@ func (d *Driver) notFoundDatabase(ctx context.Context, databaseName string) (boo}// NeedsSetupMigration checks if it needs to set up migration.-func (d *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {- notFound, err := d.notFoundDatabase(ctx, db.BytebaseDatabase)- if err != nil {- return false, err- }- return notFound, nil+func (*Driver) NeedsSetupMigration(context.Context) (bool, error) {+ return false, nil}// SetupMigrationIfNeeded sets up migration if needed.-func (d *Driver) SetupMigrationIfNeeded(ctx context.Context) error {- setup, err := d.NeedsSetupMigration(ctx)- if err != nil {- return err- }- if !setup {- return nil- }- log.Info("Bytebase migration schema not found, creating schema...",- zap.String("environment", d.connCtx.EnvironmentID),- zap.String("instance", d.connCtx.InstanceID),- )- statements, err := sanitizeSQL(migrationSchema)- if err != nil {- return err- }- return d.creataDatabase(ctx, createBytebaseDatabaseStatement, statements)+func (*Driver) SetupMigrationIfNeeded(context.Context) error {+ return nil}func (d *Driver) creataDatabase(ctx context.Context, createStatement string, extraStatement []string) error {@@ -82,177 +59,32 @@ func (d *Driver) creataDatabase(ctx context.Context, createStatement string, ext// ExecuteMigration executes a migration.// ExecuteMigration will execute the database migration.-// Returns the created migration history id and the updated schema on success.func (d *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (migrationHistoryID string, updatedSchema string, resErr error) {- var prevSchemaBuf bytes.Buffer- // Don't record schema if the database hasn't existed yet or is schemaless (e.g. Mongo).+ if statement == "" || m.Type == db.Baseline {+ return "", "", nil+ }+if !m.CreateDatabase {- // For baseline migration, we also record the live schema to detect the schema drift.- // See https://bytebase.com/blog/what-is-database-schema-drift- if _, err := d.Dump(ctx, m.Database, &prevSchemaBuf, true /*schemaOnly*/); err != nil {+ if _, err := d.Execute(ctx, statement, m.CreateDatabase); err != nil {return "", "", util.FormatError(err)}- }-- // Switch to the database where the migration_history table resides.- if err := d.switchDatabase(ctx, db.BytebaseDatabase); err != nil {- return "", "", err- }-- // Phase 1 - Pre-check before executing migration- // Phase 2 - Record migration history as PENDING- insertedID, err := d.beginMigration(ctx, m, prevSchemaBuf.String(), statement)- if err != nil {- if common.ErrorCode(err) == common.MigrationAlreadyApplied {- return insertedID, prevSchemaBuf.String(), nil+ } else {+ stmts, err := sanitizeSQL(statement)+ if err != nil {+ return "", "", errors.Wrapf(err, "failed to sanitize %v", statement)}- return "", "", errors.Wrapf(err, "failed to begin migration for issue %s", m.IssueID)- }-- startedNs := time.Now().UnixNano()-- defer func() {- if err := d.endMigration(ctx, startedNs, insertedID, updatedSchema, db.BytebaseDatabase, resErr == nil /*isDone*/); err != nil {- log.Error("Failed to update migration history record",- zap.Error(err),- zap.String("migration_id", migrationHistoryID),- )+ if len(stmts) == 0 {+ return "", "", errors.Errorf("expect sanitized SQLs to have at least one entry, original statement: %v", statement)}- }()-- // Phase 3 - Executing migration- // Branch migration type always has empty sql.- // Baseline migration type could has non-empty sql but will not execute.- // https://github.com/bytebase/bytebase/issues/394- doMigrate := true- if statement == "" {- doMigrate = false- }- if m.Type == db.Baseline {- doMigrate = false- }- if doMigrate {- // Switch back to the target database.- if !m.CreateDatabase {- if err := d.switchDatabase(ctx, m.Database); err != nil {- return "", "", errors.Wrap(err, "failed to switch database")- }- if _, err := d.Execute(ctx, statement, m.CreateDatabase); err != nil {- return "", "", util.FormatError(err)- }- } else {- stmts, err := sanitizeSQL(statement)- if err != nil {- return "", "", errors.Wrapf(err, "failed to sanitize %v", statement)- }- if len(stmts) == 0 {- return "", "", errors.Errorf("expect sanitized SQLs to have at least one entry, original statement: %v", statement)- }- if !strings.HasPrefix(stmts[0], "CREATE DATABASE") {- return "", "", errors.Errorf("expect the first entry of the sanitized SQLs to start with 'CREATE DATABASE', sql %v", stmts[0])- }- if err := d.creataDatabase(ctx, stmts[0], stmts[1:]); err != nil {- return "", "", errors.Wrap(err, "failed to create database")- }+ if !strings.HasPrefix(stmts[0], "CREATE DATABASE") {+ return "", "", errors.Errorf("expect the first entry of the sanitized SQLs to start with 'CREATE DATABASE', sql %v", stmts[0])}- }-- // Phase 4 - Dump the schema after migration- var afterSchemaBuf bytes.Buffer- if _, err := d.Dump(ctx, m.Database, &afterSchemaBuf, true /*schemaOnly*/); err != nil {- return "", "", util.FormatError(err)- }-- return insertedID, afterSchemaBuf.String(), nil-}--// BeginMigration checks before executing migration and inserts a migration history record with pending status.-func (d *Driver) beginMigration(ctx context.Context, m *db.MigrationInfo, prevSchema string, statement string) (insertedID string, err error) {- // Convert version to stored version.- storedVersion, err := util.ToStoredVersion(m.UseSemanticVersion, m.Version, m.SemanticVersionSuffix)- if err != nil {- return "", errors.Wrap(err, "failed to convert to stored version")- }- // Phase 1 - Pre-check before executing migration- // Check if the same migration version has already been applied.- if list, err := d.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{- Database: &m.Namespace,- Version: &m.Version,- }); err != nil {- return "", errors.Wrap(err, "failed to check duplicate version")- } else if len(list) > 0 {- migrationHistory := list[0]- switch migrationHistory.Status {- case db.Done:- if migrationHistory.IssueID != m.IssueID {- return migrationHistory.ID, common.Errorf(common.MigrationFailed, "database %q has already applied version %s by issue %s", m.Database, m.Version, migrationHistory.IssueID)- }- return migrationHistory.ID, common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s", m.Database, m.Version)- case db.Pending:- err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version)- log.Debug(err.Error())- // For force migration, we will ignore the existing migration history and continue to migration.- if m.Force {- return migrationHistory.ID, nil- }- return "", common.Wrap(err, common.MigrationPending)- case db.Failed:- err := errors.Errorf("database %q version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version ", m.Database, m.Version)- log.Debug(err.Error())- // For force migration, we will ignore the existing migration history and continue to migration.- if m.Force {- return migrationHistory.ID, nil- }- return "", common.Wrap(err, common.MigrationFailed)+ if err := d.creataDatabase(ctx, stmts[0], stmts[1:]); err != nil {+ return "", "", errors.Wrap(err, "failed to create database")}}- // Get largestSequence, largestVersionSinceBaseline in a transaction.- tx := d.client.ReadOnlyTransaction()- defer tx.Close()-- largestSequence, err := d.findLargestSequence(ctx, tx, m.Namespace, false /* baseline */)- if err != nil {- return "", err- }-- // Check if there is any higher version already been applied since the last baseline or branch.- if version, err := d.findLargestVersionSinceBaseline(ctx, tx, m.Namespace); err != nil {- return "", err- } else if version != nil && len(*version) > 0 && *version >= m.Version {- return "", common.Errorf(common.MigrationOutOfOrder, "database %q has already applied version %s which >= %s", m.Database, *version, m.Version)- }-- // Phase 2 - Record migration history as PENDING.- // MySQL runs DDL in its own transaction, so we can't commit migration history together with DDL in a single transaction.- // Thus we sort of doing a 2-phase commit, where we first write a PENDING migration record, and after migration completes, we then- // update the record to DONE together with the updated schema.- statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)- if insertedID, err = d.insertPendingHistory(ctx, largestSequence+1, prevSchema, m, storedVersion, statementRecord); err != nil {- return "", err- }-- return insertedID, nil-}--// EndMigration updates the migration history record to DONE or FAILED depending on migration is done or not.-func (d *Driver) endMigration(ctx context.Context, startedNs int64, migrationHistoryID string, updatedSchema string, databaseName string, isDone bool) (err error) {- migrationDurationNs := time.Now().UnixNano() - startedNs- if err := d.switchDatabase(ctx, databaseName); err != nil {- return err- }-- if isDone {- // Upon success, update the migration history as 'DONE', execution_duration_ns, updated schema.- err = d.updateHistoryAsDone(ctx, migrationDurationNs, updatedSchema, migrationHistoryID)- } else {- // Otherwise, update the migration history as 'FAILED', execution_duration.- err = d.updateHistoryAsFailed(ctx, migrationDurationNs, migrationHistoryID)- }- if err != nil {- return err- }- return nil+ return "", "", nil}// FindMigrationHistoryList finds the migration history list.@@ -372,214 +204,3 @@ func (d *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migratioreturn migrationHistoryList, nil}--func (d *Driver) findLargestVersionSinceBaseline(ctx context.Context, tx *spanner.ReadOnlyTransaction, namespace string) (*string, error) {- largestBaselineSequence, err := d.findLargestSequence(ctx, tx, namespace, true /* baseline */)- if err != nil {- return nil, err- }- query := `- SELECT- MAX(version)- FROM migration_history- WHERE namespace = @namespace AND sequence >= @sequence- `- params := map[string]interface{}{- "namespace": namespace,- "sequence": largestBaselineSequence,- }- stmt := spanner.Statement{SQL: query, Params: params}- iter := tx.Query(ctx, stmt)- var versions []spanner.NullString- for {- row, err := iter.Next()- if err == iterator.Done {- break- }- if err != nil {- return nil, err- }- var version spanner.NullString- if err := row.Columns(&version); err != nil {- return nil, err- }- versions = append(versions, version)- }- if len(versions) != 1 {- return nil, errors.New("expect to get 1 row")- }- if versions[0].Valid {- version := versions[0].StringVal- return &version, nil- }- return nil, nil-}--func (*Driver) findLargestSequence(ctx context.Context, tx *spanner.ReadOnlyTransaction, namespace string, baseline bool) (int, error) {- query := `- SELECT- MAX(sequence)- FROM migration_history- WHERE namespace = @namespace- `- if baseline {- query = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", query, db.Baseline, db.Branch)- }- params := map[string]interface{}{"namespace": namespace}- stmt := spanner.Statement{SQL: query, Params: params}- iter := tx.Query(ctx, stmt)- var sequences []spanner.NullInt64- for {- row, err := iter.Next()- if err == iterator.Done {- break- }- if err != nil {- return 0, err- }- var sequence spanner.NullInt64- if err := row.Columns(&sequence); err != nil {- return 0, err- }- sequences = append(sequences, sequence)- }- if len(sequences) != 1 {- return 0, errors.New("expect to get 1 row")- }- if sequences[0].Valid {- return int(sequences[0].Int64), nil- }-- return 0, nil-}--func (d *Driver) insertPendingHistory(ctx context.Context, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (string, error) {- id := uuid.NewString()- query := `- INSERT INTO migration_history (- id,- created_by,- created_ts,- updated_by,- updated_ts,- release_version,- namespace,- sequence,- source,- type,- status,- version,- description,- statement,- schema,- schema_prev,- execution_duration_ns,- issue_id,- payload- )- VALUES (- @id,- @creator,- UNIX_SECONDS(CURRENT_TIMESTAMP()),- @creator,- UNIX_SECONDS(CURRENT_TIMESTAMP()),- @release_version,- @namespace,- @sequence,- @source,- @type,- @status,- @version,- @description,- @statement,- @schema,- @schema_prev,- 0,- @issue_id,- @payload)- `- params := map[string]interface{}{- "id": id,- "creator": m.Creator,- "release_version": m.ReleaseVersion,- "namespace": m.Namespace,- "sequence": sequence,- "source": m.Source,- "type": m.Type,- "status": db.Pending,- "version": storedVersion,- "description": m.Description,- "statement": statement,- "schema": prevSchema,- "schema_prev": prevSchema,- "issue_id": m.IssueID,- "payload": m.Payload,- }- stmt := spanner.Statement{SQL: query, Params: params}- if _, err := d.client.ReadWriteTransaction(ctx, func(ctx context.Context, rwt *spanner.ReadWriteTransaction) error {- if _, err := rwt.Update(ctx, stmt); err != nil {- return err- }- return nil- }); err != nil {- return "", err- }-- return id, nil-}--func (d *Driver) updateHistoryAsDone(ctx context.Context, migrationDurationNs int64, updatedSchema string, insertedID string) error {- query := `- UPDATE- migration_history- SET- status = @status,- execution_duration_ns = @execution_duration_ns,- schema = @schema- WHERE id = @id- `- params := map[string]interface{}{- "status": db.Done,- "execution_duration_ns": migrationDurationNs,- "schema": updatedSchema,- "id": insertedID,- }- stmt := spanner.Statement{SQL: query, Params: params}-- if _, err := d.client.ReadWriteTransaction(ctx, func(ctx context.Context, rwt *spanner.ReadWriteTransaction) error {- if _, err := rwt.Update(ctx, stmt); err != nil {- return err- }- return nil- }); err != nil {- return err- }- return nil-}--func (d *Driver) updateHistoryAsFailed(ctx context.Context, migrationDurationNs int64, insertedID string) error {- query := `- UPDATE- migration_history- SET- status = @status,- execution_duration_ns = @execution_duration_ns- WHERE id = @id- `- params := map[string]interface{}{- "status": db.Failed,- "execution_duration_ns": migrationDurationNs,- "id": insertedID,- }- stmt := spanner.Statement{SQL: query, Params: params}-- if _, err := d.client.ReadWriteTransaction(ctx, func(ctx context.Context, rwt *spanner.ReadWriteTransaction) error {- if _, err := rwt.Update(ctx, stmt); err != nil {- return err- }- return nil- }); err != nil {- return err- }- return nil-}diff --git a/backend/plugin/db/spanner/spanner.go b/backend/plugin/db/spanner/spanner.goindex bcda6dd0c2..e0082575e5 100644--- a/backend/plugin/db/spanner/spanner.go+++ b/backend/plugin/db/spanner/spanner.go@@ -4,7 +4,6 @@ package spannerimport ("context""database/sql"- _ "embed""fmt""regexp""strings"@@ -27,15 +26,10 @@ import ()var (- //go:embed spanner_migration_schema.sql- migrationSchema string-excludedDatabaseList = map[string]bool{"bytebase": true,}- createBytebaseDatabaseStatement = `CREATE DATABASE bytebase`-dsnRegExp = regexp.MustCompile("projects/(?P<PROJECTGROUP>([a-z]|[-.:]|[0-9])+)/instances/(?P<INSTANCEGROUP>([a-z]|[-]|[0-9])+)/databases/(?P<DATABASEGROUP>([a-z]|[-]|[_]|[0-9])+)")_ db.Driver = (*Driver)(nil)diff --git a/backend/runner/taskrun/database_create_executor.go b/backend/runner/taskrun/database_create_executor.goindex 845ecb2286..f017c7e53e 100644--- a/backend/runner/taskrun/database_create_executor.go+++ b/backend/runner/taskrun/database_create_executor.go@@ -171,7 +171,13 @@ func (exec *DatabaseCreateExecutor) RunOnce(ctx context.Context, task *store.Tasmi.IssueID = strconv.Itoa(issue.UID)}- migrationID, _, err := driver.ExecuteMigration(ctx, mi, statement)+ // TODO(p0ny): migrate to instance change history+ var migrationID string+ if instance.Engine == db.Spanner {+ migrationID, _, err = utils.ExecuteMigration(ctx, exec.store, driver, mi, statement)+ } else {+ migrationID, _, err = driver.ExecuteMigration(ctx, mi, statement)+ }if err != nil {return true, nil, err}diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.goindex 4725a95c6e..ed3bfd58ea 100644--- a/backend/runner/taskrun/executor.go+++ b/backend/runner/taskrun/executor.go@@ -187,7 +187,8 @@ func executeMigration(ctx context.Context, stores *store.Store, dbFactory *dbfactask = updatedTask}- if instance.Engine == db.Redis || instance.Engine == db.Oracle {+ // TODO(p0ny): migrate to instance change history+ if instance.Engine == db.Redis || instance.Engine == db.Oracle || instance.Engine == db.Spanner {migrationID, schema, err = utils.ExecuteMigration(ctx, stores, driver, mi, statement)if err != nil {return "", "", errdiff --git a/backend/runner/taskrun/pitr_cutover_executor.go b/backend/runner/taskrun/pitr_cutover_executor.goindex 014e77ef37..579dad1dd0 100644--- a/backend/runner/taskrun/pitr_cutover_executor.go+++ b/backend/runner/taskrun/pitr_cutover_executor.go@@ -151,6 +151,7 @@ func (exec *PITRCutoverExecutor) pitrCutover(ctx context.Context, dbFactory *dbfIssueID: strconv.Itoa(issue.UID),}+ // TODO(p0ny): migrate to instance change historyif _, _, err := driver.ExecuteMigration(ctx, m, "/* pitr cutover */"); err != nil {log.Error("Failed to add migration history record", zap.Error(err))return true, nil, errors.Wrap(err, "failed to add migration history record")diff --git a/backend/runner/taskrun/pitr_restore_executor.go b/backend/runner/taskrun/pitr_restore_executor.goindex 93a534e8cb..248c79c297 100644--- a/backend/runner/taskrun/pitr_restore_executor.go+++ b/backend/runner/taskrun/pitr_restore_executor.go@@ -548,6 +548,7 @@ func createBranchMigrationHistory(ctx context.Context, stores *store.Store, dbFareturn "", "", err}defer targetDriver.Close(ctx)+ // TODO(p0ny): migrate to instance change historymigrationID, _, err := targetDriver.ExecuteMigration(ctx, m, "")if err != nil {return "", "", errors.Wrap(err, "failed to create migration history")diff --git a/backend/store/pg_engine.go b/backend/store/pg_engine.goindex 867b23ab27..7a1361de45 100644--- a/backend/store/pg_engine.go+++ b/backend/store/pg_engine.go@@ -355,6 +355,7 @@ func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, modcreateDatabase = true}+ // TODO(p0ny): migrate to instance change historyif _, _, err := d.ExecuteMigration(ctx,&dbdriver.MigrationInfo{@@ -418,6 +419,7 @@ func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, modcontinue}log.Info(fmt.Sprintf("Migrating %s...", pv.version))+ // TODO(p0ny): migrate to instance change historyif _, _, err := d.ExecuteMigration(ctx,&dbdriver.MigrationInfo{@@ -509,6 +511,7 @@ func migrateDev(ctx context.Context, d dbdriver.Driver, serverVersion, databaseNfor _, m := range migrations {log.Info(fmt.Sprintf("Migrating dev %s...", m.filename))// We expect to use semantic versioning for dev environment too because getLatestVersion() always expect to get the latest version in semantic format.+ // TODO(p0ny): migrate to instance change historyif _, _, err := d.ExecuteMigration(ctx,&dbdriver.MigrationInfo{diff --git a/backend/utils/utils.go b/backend/utils/utils.goindex e0ba53b354..2f6c836c7a 100644--- a/backend/utils/utils.go+++ b/backend/utils/utils.go@@ -532,6 +532,7 @@ func ExecuteMigration(ctx context.Context, store *store.Store, driver db.Driver,doMigrate = false}if doMigrate {+ // TODO(p0ny): migrate to instance change historyif _, _, err := driver.ExecuteMigration(ctx, m, statement); err != nil {return "", "", err}