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: cleanup non-pg migrator code (#5427)
Danny Xu74a232e72a78
diff --git a/backend/bin/bb/cmd/migrate.go b/backend/bin/bb/cmd/migrate.goindex 9b4967b719..68aa794579 100644--- a/backend/bin/bb/cmd/migrate.go+++ b/backend/bin/bb/cmd/migrate.go@@ -70,10 +70,6 @@ func migrateDatabase(ctx context.Context, u *dburl.URL, description, issueID str}defer driver.Close(ctx)- if err := driver.SetupMigrationIfNeeded(ctx); err != nil {- return errors.Wrap(err, "failed to setup migration")- }-migrationCreator := "bb-unknown-creator"if currentUser, err := user.Current(); err == nil {migrationCreator = currentUser.Usernamediff --git a/backend/plugin/db/clickhouse/clickhouse_migration_schema.sql b/backend/plugin/db/clickhouse/clickhouse_migration_schema.sqldeleted file mode 100644index 20dca62835..0000000000--- a/backend/plugin/db/clickhouse/clickhouse_migration_schema.sql+++ /dev/null@@ -1,45 +0,0 @@--- This is the bytebase schema to track migration info for MySQL--- Create a database called bytebase-CREATE DATABASE bytebase;---- Create migration_history table--- Note, we don't create trigger to update created_ts and updated_ts because that may causes error:--- ERROR 1419 (HY000): You do not have the SUPER privilege and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)-CREATE TABLE bytebase.migration_history (- id BIGINT,- created_by TEXT NOT NULL,- created_ts BIGINT NOT NULL,- updated_by TEXT NOT NULL,- updated_ts BIGINT NOT NULL,- -- Record the client version creating this migration history. For Bytebase, we use its binary release version. Different Bytebase release might- -- record different history info and thie field helps to handle such situation properly. Moreover, it helps debugging.- release_version TEXT 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 each database migration history.- namespace TEXT NOT NULL,- -- Used to detect out of order migration together with 'namespace' and 'version' column.- sequence BIGINT UNSIGNED NOT NULL,- -- 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, 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.- -- Thus, we create a "PENDING" record before applying the DDL and update that record to "DONE" after applying the DDL.- status TEXT NOT NULL,- -- Record the migration version.- version TEXT NOT NULL,- description TEXT NOT NULL,- -- Record the migration statement- statement TEXT NOT NULL,- -- Record the schema after migration- `schema` TEXT NOT NULL,- -- Record the schema before migration. Though we could also fetch it from the previous migration history, it would complicate fetching logic.- -- Besides, by storing the schema_prev, we can perform consistency check to see if the migration history has any gaps.- schema_prev TEXT NOT NULL,- execution_duration_ns BIGINT NOT NULL,- issue_id TEXT NOT NULL,- payload TEXT NOT NULL-) ENGINE = MergeTree()-PRIMARY KEY id;diff --git a/backend/plugin/db/clickhouse/migrate.go b/backend/plugin/db/clickhouse/migrate.goindex 03c8b0af31..86a56a06d6 100644--- a/backend/plugin/db/clickhouse/migrate.go+++ b/backend/plugin/db/clickhouse/migrate.go@@ -2,219 +2,12 @@ package clickhouseimport ("context"- "database/sql""fmt"- "time"- // embed will embeds the migration schema.- _ "embed"-- "go.uber.org/zap"-- "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")-var (- //go:embed clickhouse_migration_schema.sql- migrationSchema string-- _ util.MigrationExecutor = (*Driver)(nil)-)--// NeedsSetupMigration returns whether it needs to setup migration.-func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {- const query = `- SELECT- 1- FROM system.tables- WHERE database = 'bytebase' AND name = 'migration_history'- `- return util.NeedsSetupMigrationSchema(ctx, driver.db, query)-}--// SetupMigrationIfNeeded sets up migration if needed.-func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {- setup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- return err- }-- if setup {- log.Info("Bytebase migration schema not found, creating schema...",- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- if _, err := driver.Execute(ctx, migrationSchema, true /* createDatabase */); err != nil {- log.Error("Failed to initialize migration schema.",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- return util.FormatErrorWithQuery(err, migrationSchema)- }- log.Info("Successfully created migration schema.",- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- }-- return nil-}--// FindLargestVersionSinceBaseline will find the largest version since last baseline or branch.-func (driver Driver) FindLargestVersionSinceBaseline(ctx context.Context, tx *sql.Tx, namespace string) (*string, error) {- largestBaselineSequence, err := driver.FindLargestSequence(ctx, tx, namespace, true /* baseline */)- if err != nil {- return nil, err- }- const getLargestVersionSinceLastBaselineQuery = `- SELECT MAX(version) FROM bytebase.migration_history- WHERE namespace = $1 AND sequence >= $2- `- var version sql.NullString- if err := tx.QueryRowContext(ctx, getLargestVersionSinceLastBaselineQuery,- namespace, largestBaselineSequence,- ).Scan(&version); err != nil {- if err == sql.ErrNoRows {- return nil, common.FormatDBErrorEmptyRowWithQuery(getLargestVersionSinceLastBaselineQuery)- }- return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)- }- if version.Valid {- return &version.String, nil- }- return nil, nil-}--// FindLargestSequence will return the largest sequence number.-func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace string, baseline bool) (int, error) {- findLargestSequenceQuery := `- SELECT MAX(sequence) FROM bytebase.migration_history- WHERE namespace = $1`- if baseline {- findLargestSequenceQuery = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", findLargestSequenceQuery, db.Baseline, db.Branch)- }- var sequence sql.NullInt32- if err := tx.QueryRowContext(ctx, findLargestSequenceQuery,- namespace,- ).Scan(&sequence); err != nil {- if err == sql.ErrNoRows {- return -1, common.FormatDBErrorEmptyRowWithQuery(findLargestSequenceQuery)- }- return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)- }- if sequence.Valid {- return int(sequence.Int32), nil- }- // Returns 0 if we haven't applied any migration for this namespace.- return 0, nil-}--// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.-func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (string, error) {- const insertHistoryQuery = `- INSERT INTO bytebase.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 ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)- `- var insertedID string- maxIDQuery := "SELECT MAX(id)+1 FROM bytebase.migration_history"- rows, err := tx.QueryContext(ctx, maxIDQuery)- if err != nil {- return "", util.FormatErrorWithQuery(err, maxIDQuery)- }- defer rows.Close()- for rows.Next() {- if err := rows.Scan(- &insertedID,- ); err != nil {- return "", util.FormatErrorWithQuery(err, maxIDQuery)- }- }- if err := rows.Err(); err != nil {- return "", util.FormatErrorWithQuery(err, maxIDQuery)- }- // Clickhouse sql driver doesn't support taking now() as prepared value.- now := time.Now().Unix()- _, err = tx.ExecContext(ctx, insertHistoryQuery,- insertedID,- m.Creator,- now,- m.Creator,- now,- m.ReleaseVersion,- m.Namespace,- sequence,- m.Source,- m.Type,- db.Pending,- storedVersion,- m.Description,- statement,- prevSchema,- prevSchema,- 0,- m.IssueID,- m.Payload,- )- if err != nil {- return "", util.FormatErrorWithQuery(err, insertHistoryQuery)- }-- return insertedID, nil-}--// UpdateHistoryAsDone will update the migration record as done.-func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID string) error {- const updateHistoryAsDoneQuery = `- ALTER TABLE- bytebase.migration_history- UPDATE- status = $1,- execution_duration_ns = $2,- ` + "`schema` = $3" + `- WHERE id = $4- `- _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, db.Done, migrationDurationNs, updatedSchema, insertedID)- return err-}--// UpdateHistoryAsFailed will update the migration record as failed.-func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID string) error {- const updateHistoryAsFailedQuery = `- ALTER TABLE- bytebase.migration_history- UPDATE- status = $1,- execution_duration_ns = $2- WHERE id = $3- `- _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, db.Failed, migrationDurationNs, insertedID)- return err-}-// ExecuteMigration will execute the migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {_, err := driver.Execute(ctx, statement, m.CreateDatabase)diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.goindex 54ee0faa71..76a56725d8 100644--- a/backend/plugin/db/driver.go+++ b/backend/plugin/db/driver.go@@ -480,11 +480,6 @@ type Driver interface {// DeleteRole deletes the role by name.DeleteRole(ctx context.Context, roleName 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.// The migration type is determined by m.Type. Note, it can also perform data migration (DML) in addition to schema migration (DDL).ExecuteMigration(ctx context.Context, m *MigrationInfo, statement string) (string, string, error)diff --git a/backend/plugin/db/mongodb/collmod_migrationHistory_collection_command.json b/backend/plugin/db/mongodb/collmod_migrationHistory_collection_command.jsondeleted file mode 100644index c551f72337..0000000000--- a/backend/plugin/db/mongodb/collmod_migrationHistory_collection_command.json+++ /dev/null@@ -1,88 +0,0 @@-{- "collMod": "migration_history",- "validator": {- "$jsonSchema": {- "title": "Bytebase Migration History Object Validation",- "required": [- "_id",- "id",- "created_by",- "created_ts",- "updated_by",- "updated_ts",- "release_version",- "namespace",- "sequence",- "source",- "type",- "status",- "version",- "description",- "statement",- "execution_duration_ns",- "issue_id",- "payload"- ],- "properties": {- "_id": {- "bsonType": "objectId"- },- "id": {- "bsonType": "long",- "minimum": 0- },- "created_by": {- "bsonType": "string"- },- "created_ts": {- "bsonType": "timestamp"- },- "updated_by": {- "bsonType": "string"- },- "updated_ts": {- "bsonType": "timestamp"- },- "release_version": {- "bsonType": "string"- },- "namespace": {- "bsonType": "string"- },- "sequence": {- "bsonType": "long",- "minimum": 0- },- "source": {- "bsonType": "string"- },- "type": {- "bsonType": "string"- },- "status": {- "bsonType": "string"- },- "version": {- "bsonType": "string"- },- "description": {- "bsonType": "string"- },- "statement": {- "bsonType": "string"- },- "execution_duration_ns": {- "bsonType": "long"- },- "issue_id": {- "bsonType": "string"- },- "payload": {- "bsonType": "string"- }- },- "additionalProperties": false- }- },- "writeConcern": { "w": "majority" }-}diff --git a/backend/plugin/db/mongodb/create_index_on_migrationHistory_collection_command.json b/backend/plugin/db/mongodb/create_index_on_migrationHistory_collection_command.jsondeleted file mode 100644index c64f95cf6a..0000000000--- a/backend/plugin/db/mongodb/create_index_on_migrationHistory_collection_command.json+++ /dev/null@@ -1,44 +0,0 @@-{- "createIndexes": "migration_history",- "indexes": [- {- "key": {- "id": 1- },- "name": "bytebase_idx_unique_migration_history_id",- "unique": true- },- {- "key": {- "namespace": 1,- "sequence": 1- },- "name": "bytebase_idx_unique_migration_history_namespace_sequence",- "unique": true- },- {- "key": {- "namespace": 1,- "version": 1- },- "name": "bytebase_idx_unique_migration_history_namespace_version",- "unique": true- },- {- "key": {- "namespace": 1,- "source": 1,- "type": 1- },- "name": "bytebase_idx_migration_history_namespace_source_type"- },- {- "key": {- "namespace": 1,- "created_ts": 1- },- "name": "bytebase_idx_migration_history_namespace_created"- }- ],- "writeConcern": { "w": "majority" }-}diff --git a/backend/plugin/db/mongodb/migrate.go b/backend/plugin/db/mongodb/migrate.goindex 993e98c80a..1016e7a4cb 100644--- a/backend/plugin/db/mongodb/migrate.go+++ b/backend/plugin/db/mongodb/migrate.go@@ -5,20 +5,13 @@ import ("database/sql""fmt""strconv"- "time"-- // embed will embeds the migration schema.- _ "embed""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/bson/primitive"- "go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options"- "go.uber.org/zap""github.com/pkg/errors"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/db/util")@@ -30,15 +23,6 @@ const (migrationHistoryDefaultCollection = "migration_history")-var (- //go:embed collmod_migrationHistory_collection_command.json- collmodMigrationHistoryCollectionCommand string- //go:embed create_index_on_migrationHistory_collection_command.json- createIndexOnMigrationHistoryCollectionCommand string-- _ util.MigrationExecutor = (*Driver)(nil)-)-// MigrationHistory is the migration history record in MongoDB.type MigrationHistory struct {ID int64 `bson:"id"`@@ -60,61 +44,6 @@ type MigrationHistory struct {Payload string `bson:"payload"`}-// NeedsSetupMigration returns whether the driver needs to setup migration.-func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {- database := driver.client.Database(migrationHistoryDefaultDatabase)- collectionNames, err := database.ListCollectionNames(ctx, bson.M{})- if err != nil {- return false, errors.Wrapf(err, "failed to list collection names for database %q", migrationHistoryDefaultDatabase)- }- for _, collectionName := range collectionNames {- if collectionName == migrationHistoryDefaultCollection {- return false, nil- }- }- return true, nil-}--// SetupMigrationIfNeeded sets up migration if needed.-func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {- setup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- return err- }- if !setup {- return nil- }- log.Info("Bytebase migration schema not found, creating schema for mongodb...",- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- database := driver.client.Database(migrationHistoryDefaultDatabase)- if err := database.CreateCollection(ctx, migrationHistoryDefaultCollection); err != nil {- return errors.Wrapf(err, "failed to create collection %q in mongodb database %q for instance named %q", migrationHistoryDefaultCollection, migrationHistoryDefaultDatabase, driver.connectionCtx.InstanceID)- }-- var b any- if err := bson.UnmarshalExtJSON([]byte(collmodMigrationHistoryCollectionCommand), true, &b); err != nil {- return errors.Wrap(err, "failed to unmarshal collmod command")- }- var result any- if err := database.RunCommand(context.Background(), b).Decode(&result); err != nil {- return errors.Wrap(err, "failed to run collmod command")- }-- if err := bson.UnmarshalExtJSON([]byte(createIndexOnMigrationHistoryCollectionCommand), true, &b); err != nil {- return errors.Wrap(err, "failed to unmarshal create index command")- }- if err := database.RunCommand(context.Background(), b).Decode(&result); err != nil {- return errors.Wrap(err, "failed to run create index command")- }- log.Info("Successfully created migration schema for mongodb.",- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- return nil-}-// ExecuteMigration executes a migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {_, err := driver.Execute(ctx, statement, m.CreateDatabase)@@ -251,203 +180,3 @@ func (driver *Driver) FindLargestSequence(ctx context.Context, _ *sql.Tx, namesp}return 0, nil}--// FindLargestVersionSinceBaseline will find the largest version since last baseline or branch.-func (driver *Driver) FindLargestVersionSinceBaseline(ctx context.Context, tx *sql.Tx, namespace string) (*string, error) {- collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)- largestBaselineSeuqence, err := driver.FindLargestSequence(ctx, tx, namespace, true /* baseline */)- if err != nil {- return nil, err- }- filter := bson.M{- "namespace": namespace,- "sequence": bson.M{"$gte": largestBaselineSeuqence},- }- // Set up MAX(version) aggregation.- aggregation := []bson.M{- {- "$match": filter,- },- {- "$group": bson.M{- "_id": nil,- "version": bson.M{"$max": "$version"},- },- },- }- cursor, err := collection.Aggregate(ctx, aggregation)- if err != nil {- return nil, errors.Wrapf(err, "failed to aggregate migration history list to find largest version since baseline")- }- defer cursor.Close(ctx)-- if cursor.Next(ctx) {- var result bson.M- if err := cursor.Decode(&result); err != nil {- return nil, errors.Wrapf(err, "failed to decode find largest version since baseline aggregation result")- }- if version, ok := result["version"]; ok {- if versionStr, ok := version.(string); ok {- return &versionStr, nil- }- }- return nil, errors.Errorf("failed to get version from find largest version since baseline aggregation result: %v", result)- }- // If cursor contains no data, we check the err, if err is nil, it means that the query is successful, but there is no data.- if err := cursor.Err(); err != nil {- return nil, errors.Wrapf(err, "failed to find largest version since baseline")- }- return nil, nil-}--// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.-func (driver *Driver) InsertPendingHistory(ctx context.Context, _ *sql.Tx, sequence int, _ string, m *db.MigrationInfo, storedVersion, statement string) (insertedID string, err error) {- collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)-- retryTimes := 3- for i := 0; i < retryTimes; i++ {- currentTimestamp := getMongoTimestamp()- nextID, err := driver.getMigrationHistoryNextID(ctx)- if err != nil {- return "", errors.Wrapf(err, "failed to get next migration history ID")- }-- document := bson.M{- "id": nextID,- "created_by": m.Creator,- "created_ts": currentTimestamp,- "updated_by": m.Creator,- "updated_ts": currentTimestamp,- "release_version": m.ReleaseVersion,- "namespace": m.Namespace,- "sequence": int64(sequence),- "source": m.Source,- "type": m.Type,- "status": db.Pending,- "version": storedVersion,- "description": m.Description,- "statement": statement,- "execution_duration_ns": int64(0),- "issue_id": m.IssueID,- "payload": m.Payload,- }- if _, err = collection.InsertOne(ctx, document); err != nil {- // Detect if it's a duplicate key error.- if driverErr, ok := err.(mongo.WriteException); ok {- find := false- for _, writeErr := range driverErr.WriteErrors {- if writeErr.Code == 121 {- log.Info("Duplicate key error with migration_history id: %d, retrying...", zap.Int64("id", nextID))- find = true- break- }- }- if find {- continue- }- }- return "", errors.Wrapf(err, "failed to insert a pending migration history record")- }- return fmt.Sprintf("%d", nextID), nil- }- return "", errors.Errorf("failed to insert a pending migration history record because of the duplidate id after %d retries", retryTimes)-}--// UpdateHistoryAsDone will update the migration record as done.-func (driver *Driver) UpdateHistoryAsDone(ctx context.Context, _ *sql.Tx, migrationDurationNs int64, _ string, insertedID string) error {- collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)- longMigrationHistoryID, err := strconv.ParseInt(insertedID, 10, 64)- if err != nil {- return errors.Wrapf(err, "failed to parse inserted ID %s to int64", insertedID)- }-- filter := bson.M{- "id": longMigrationHistoryID,- }- update := bson.M{- "$set": bson.M{- "status": db.Done,- "execution_duration_ns": migrationDurationNs,- },- }-- updateResult, err := collection.UpdateOne(ctx, filter, update)- if err != nil {- return errors.Wrapf(err, "failed to update a migration history as done")- }- if updateResult.MatchedCount == 0 {- return errors.Errorf("failed to find a migration history record to mark as done with ID %s", insertedID)- }- return nil-}--// UpdateHistoryAsFailed will update the migration record as failed.-func (driver *Driver) UpdateHistoryAsFailed(ctx context.Context, _ *sql.Tx, migrationDurationNs int64, insertedID string) error {- collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)- longMigrationHistoryID, err := strconv.ParseInt(insertedID, 10, 64)- if err != nil {- return errors.Wrapf(err, "failed to parse inserted ID %s to int64", insertedID)- }- filter := bson.M{- "id": longMigrationHistoryID,- }- update := bson.M{- "$set": bson.M{- "status": db.Failed,- "execution_duration_ns": migrationDurationNs,- },- }- updateResult, err := collection.UpdateOne(ctx, filter, update)- if err != nil {- return errors.Wrapf(err, "failed to update a migration history as failed")- }- if updateResult.MatchedCount == 0 {- return errors.Errorf("failed to find a migration history record to mark as failed with ID %s", insertedID)- }- return nil-}--func getMongoTimestamp() primitive.Timestamp {- return primitive.Timestamp{T: uint32(time.Now().Unix()), I: 1}-}--// getMigrationHistoryNextID will get the next ID for the migration history.-// In RDBMS, it is usually auto-increment, but in MongoDB, we need to maintain the ID by ourselves.-// Multiple goroutines may call this function at the same time and the ID may be duplicated.-// It's caller's responsibility to handle the duplicated ID, likes retry.-func (driver *Driver) getMigrationHistoryNextID(ctx context.Context) (int64, error) {- collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)- // Set up MAX(id) aggregation.- aggregation := []bson.M{- {- "$group": bson.M{- "_id": nil,- "id": bson.M{"$max": "$id"},- },- },- }- cursor, err := collection.Aggregate(ctx, aggregation)- if err != nil {- return 0, errors.Wrapf(err, "failed to aggregate migration history list to find largest ID")- }- defer cursor.Close(ctx)-- if cursor.Next(ctx) {- var result bson.M- if err := cursor.Decode(&result); err != nil {- return 0, errors.Wrapf(err, "failed to decode find largest ID aggregation result")- }- if resultID, ok := result["id"]; ok {- if id, ok := resultID.(int64); ok {- return id + 1, nil- }- }- return 0, errors.Errorf("failed to get ID from find largest ID aggregation result: %v", result)- }- // If cursor contains no data, we check the err, if err is nil, it means that the query is successful, but there is no data.- if err := cursor.Err(); err != nil {- return 0, errors.Wrapf(err, "failed to find largest ID")- }- // Return 1 if there is no data.- return 1, nil-}diff --git a/backend/plugin/db/mssql/migrate.go b/backend/plugin/db/mssql/migrate.goindex 93bf5542c0..3b2d321de5 100644--- a/backend/plugin/db/mssql/migrate.go+++ b/backend/plugin/db/mssql/migrate.go@@ -8,18 +8,6 @@ import ("github.com/bytebase/bytebase/backend/plugin/db/util")-// Migration related.--// NeedsSetupMigration checks whether we need to setup migration (e.g. creating/upgrading the migration related tables).-func (*Driver) NeedsSetupMigration(context.Context) (bool, error) {- return false, nil-}--// SetupMigrationIfNeeded create or upgrade migration related tables.-func (*Driver) SetupMigrationIfNeeded(context.Context) error {- return nil-}-// ExecuteMigration executes a migration.// ExecuteMigration will execute the database migration.// Returns the created migration history id and the updated schema on success.diff --git a/backend/plugin/db/mysql/migrate.go b/backend/plugin/db/mysql/migrate.goindex d03f4284b7..9e69b10df2 100644--- a/backend/plugin/db/mysql/migrate.go+++ b/backend/plugin/db/mysql/migrate.go@@ -2,201 +2,12 @@ package mysqlimport ("context"- "database/sql""fmt"- // embed will embeds the migration schema.- _ "embed"-- "go.uber.org/zap"-- "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")-var (- //go:embed mysql_migration_schema.sql- migrationSchema string-- _ util.MigrationExecutor = (*Driver)(nil)-)--// NeedsSetupMigration returns whether it needs to setup migration.-func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {- const query = `- SELECT- 1- FROM information_schema.TABLES- WHERE TABLE_SCHEMA = 'bytebase' AND TABLE_NAME = 'migration_history'- `- return util.NeedsSetupMigrationSchema(ctx, driver.db, query)-}--// SetupMigrationIfNeeded sets up migration if needed.-func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {- setup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- return err- }-- if setup {- log.Info("Bytebase migration schema not found, creating schema...",- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- // Do not wrap it in a single transaction here because:- // 1. For MySQL, each DDL is in its own transaction. See https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html- // 2. For TiDB, the created database/table is not visible to the followup statements from the same transaction.- if _, err := driver.db.ExecContext(ctx, migrationSchema); err != nil {- log.Error("Failed to initialize migration schema.",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- return util.FormatErrorWithQuery(err, migrationSchema)- }- log.Info("Successfully created migration schema.",- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- }-- return nil-}--// FindLargestVersionSinceBaseline will find the largest version since last baseline or branch.-func (driver Driver) FindLargestVersionSinceBaseline(ctx context.Context, tx *sql.Tx, namespace string) (*string, error) {- largestBaselineSequence, err := driver.FindLargestSequence(ctx, tx, namespace, true /* baseline */)- if err != nil {- return nil, err- }- const getLargestVersionSinceLastBaselineQuery = `- SELECT MAX(version) FROM bytebase.migration_history- WHERE namespace = ? AND sequence >= ?- `- var version sql.NullString- if err := tx.QueryRowContext(ctx, getLargestVersionSinceLastBaselineQuery,- namespace, largestBaselineSequence,- ).Scan(&version); err != nil {- if err == sql.ErrNoRows {- return nil, common.FormatDBErrorEmptyRowWithQuery(getLargestVersionSinceLastBaselineQuery)- }- return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)- }- if version.Valid {- return &version.String, nil- }- return nil, nil-}--// FindLargestSequence will return the largest sequence number.-func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace string, baseline bool) (int, error) {- findLargestSequenceQuery := `- SELECT MAX(sequence) FROM bytebase.migration_history- WHERE namespace = ?`- if baseline {- findLargestSequenceQuery = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", findLargestSequenceQuery, db.Baseline, db.Branch)- }- var sequence sql.NullInt32- if err := tx.QueryRowContext(ctx, findLargestSequenceQuery,- namespace,- ).Scan(&sequence); err != nil {- if err == sql.ErrNoRows {- return -1, common.FormatDBErrorEmptyRowWithQuery(findLargestSequenceQuery)- }- return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)- }- if sequence.Valid {- return int(sequence.Int32), nil- }- // Returns 0 if we haven't applied any migration for this namespace.- return 0, nil-}--// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.-func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (string, error) {- const insertHistoryQuery = `- INSERT INTO bytebase.migration_history (- 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 (?, unix_timestamp(), ?, unix_timestamp(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)- `- res, err := tx.ExecContext(ctx, insertHistoryQuery,- m.Creator,- m.Creator,- m.ReleaseVersion,- m.Namespace,- sequence,- m.Source,- m.Type,- db.Pending,- storedVersion,- m.Description,- statement,- prevSchema,- prevSchema,- m.IssueID,- m.Payload,- )- if err != nil {- return "", util.FormatErrorWithQuery(err, insertHistoryQuery)- }-- insertedID, err := res.LastInsertId()- if err != nil {- return "", util.FormatErrorWithQuery(err, insertHistoryQuery)- }- return fmt.Sprintf("%d", insertedID), nil-}--// UpdateHistoryAsDone will update the migration record as done.-func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID string) error {- const updateHistoryAsDoneQuery = `- UPDATE- bytebase.migration_history- SET- status = ?,- execution_duration_ns = ?,- ` + "`schema` = ?" + `- WHERE id = ?- `- _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, db.Done, migrationDurationNs, updatedSchema, insertedID)- return err-}--// UpdateHistoryAsFailed will update the migration record as failed.-func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID string) error {- const updateHistoryAsFailedQuery = `- UPDATE- bytebase.migration_history- SET- status = ?,- execution_duration_ns = ?- WHERE id = ?- `- _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, db.Failed, migrationDurationNs, insertedID)- return err-}-// ExecuteMigration will execute the migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {_, err := driver.Execute(ctx, statement, m.CreateDatabase)diff --git a/backend/plugin/db/mysql/mysql_migration_schema.sql b/backend/plugin/db/mysql/mysql_migration_schema.sqldeleted file mode 100644index e4e0487422..0000000000--- a/backend/plugin/db/mysql/mysql_migration_schema.sql+++ /dev/null@@ -1,52 +0,0 @@--- This is the bytebase schema to track migration info for MySQL--- Create a database called bytebase-CREATE DATABASE bytebase CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_general_ci';---- Create migration_history table--- Note, we don't create trigger to update created_ts and updated_ts because that may causes error:--- ERROR 1419 (HY000): You do not have the SUPER privilege and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)-CREATE TABLE bytebase.migration_history (- id BIGINT PRIMARY KEY AUTO_INCREMENT,- created_by TEXT NOT NULL,- created_ts BIGINT NOT NULL,- updated_by TEXT NOT NULL,- updated_ts BIGINT NOT NULL,- -- Record the client version creating this migration history. For Bytebase, we use its binary release version. Different Bytebase release might- -- record different history info and thie field helps to handle such situation properly. Moreover, it helps debugging.- release_version TEXT 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 each database migration history.- namespace TEXT NOT NULL,- -- Used to detect out of order migration together with 'namespace' and 'version' column.- sequence BIGINT UNSIGNED NOT NULL,- -- 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, 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.- -- Thus, we create a "PENDING" record before applying the DDL and update that record to "DONE" after applying the DDL.- status TEXT NOT NULL,- -- Record the migration version.- version TEXT NOT NULL,- description TEXT NOT NULL,- -- Record the migration statement- statement TEXT NOT NULL,- -- Record the schema after migration- `schema` MEDIUMTEXT NOT NULL,- -- Record the schema before migration. Though we could also fetch it from the previous migration history, it would complicate fetching logic.- -- Besides, by storing the schema_prev, we can perform consistency check to see if the migration history has any gaps.- schema_prev MEDIUMTEXT NOT NULL,- execution_duration_ns BIGINT NOT NULL,- issue_id TEXT NOT NULL,- payload TEXT NOT NULL-);--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 INDEX bytebase_idx_migration_history_namespace_source_type ON bytebase.migration_history(namespace(256), source(256), type(256));--CREATE INDEX bytebase_idx_migration_history_namespace_created ON bytebase.migration_history(namespace(256), created_ts);diff --git a/backend/plugin/db/oracle/migrate.go b/backend/plugin/db/oracle/migrate.goindex 08601feff9..b5533b990d 100644--- a/backend/plugin/db/oracle/migrate.go+++ b/backend/plugin/db/oracle/migrate.go@@ -9,18 +9,6 @@ import ("github.com/bytebase/bytebase/backend/plugin/db/util")-// Migration related.--// NeedsSetupMigration checks whether we need to setup migration (e.g. creating/upgrading the migration related tables).-func (*Driver) NeedsSetupMigration(context.Context) (bool, error) {- return false, nil-}--// SetupMigrationIfNeeded create or upgrade migration related tables.-func (*Driver) SetupMigrationIfNeeded(context.Context) error {- return nil-}-// ExecuteMigration executes a migration.// ExecuteMigration will execute the database migration.// Returns the created migration history id and the updated schema on success.diff --git a/backend/plugin/db/redis/migrate.go b/backend/plugin/db/redis/migrate.goindex 18160cef41..d7fc12c66b 100644--- a/backend/plugin/db/redis/migrate.go+++ b/backend/plugin/db/redis/migrate.go@@ -9,20 +9,6 @@ import ("github.com/bytebase/bytebase/backend/plugin/db/util")-// Migration related.--// NeedsSetupMigration checks whether we need to setup migration (e.g. creating/upgrading the migration related tables).-// No need because redis uses bytebase metaDB InstanceChangeHistory.-func (*Driver) NeedsSetupMigration(context.Context) (bool, error) {- return false, nil-}--// SetupMigrationIfNeeded create or upgrade migration related tables.-// No need for redis because it uses bytebase metaDB InstanceChangeHistory.-func (*Driver) SetupMigrationIfNeeded(context.Context) error {- return nil-}-// ExecuteMigration executes a migration.// ExecuteMigration will execute the database migration.// Returns the created migration history id and the updated schema on success.diff --git a/backend/plugin/db/redshift/migrate.go b/backend/plugin/db/redshift/migrate.goindex 269ab75832..381f34ca3f 100644--- a/backend/plugin/db/redshift/migrate.go+++ b/backend/plugin/db/redshift/migrate.go@@ -8,18 +8,6 @@ import ("github.com/bytebase/bytebase/backend/plugin/db/util")-// Migration related.--// NeedsSetupMigration checks whether we need to setup migration (e.g. creating/upgrading the migration related tables).-func (*Driver) NeedsSetupMigration(context.Context) (bool, error) {- return false, nil-}--// SetupMigrationIfNeeded create or upgrade migration related tables.-func (*Driver) SetupMigrationIfNeeded(context.Context) error {- return nil-}-// ExecuteMigration executes a migration.// ExecuteMigration will execute the database migration.// Returns the created migration history id and the updated schema on success.diff --git a/backend/plugin/db/snowflake/migrate.go b/backend/plugin/db/snowflake/migrate.goindex 30230fcfed..665a5c3f0a 100644--- a/backend/plugin/db/snowflake/migrate.go+++ b/backend/plugin/db/snowflake/migrate.go@@ -2,226 +2,12 @@ package snowflakeimport ("context"- "database/sql""fmt"- // embed will embeds the migration schema.- _ "embed"-- "go.uber.org/zap"-- "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")-var (- //go:embed snowflake_migration_schema.sql- migrationSchema string-- _ util.MigrationExecutor = (*Driver)(nil)-)--// NeedsSetupMigration returns whether it needs to setup migration.-func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {- exist, err := driver.hasBytebaseDatabase(ctx)- if err != nil {- return false, err- }- if !exist {- return true, nil- }-- const query = `- SELECT- 1- FROM BYTEBASE.INFORMATION_SCHEMA.TABLES- WHERE TABLE_SCHEMA='PUBLIC' AND TABLE_NAME = 'MIGRATION_HISTORY'- `- return util.NeedsSetupMigrationSchema(ctx, driver.db, query)-}--// SetupMigrationIfNeeded sets up migration if needed.-func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {- setup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- return err- }-- if setup {- log.Info("Bytebase migration schema not found, creating schema...",- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- // Should use role SYSADMIN.- if _, err := driver.Execute(ctx, migrationSchema, true /* createDatabase */); err != nil {- log.Error("Failed to initialize migration schema.",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- return util.FormatErrorWithQuery(err, migrationSchema)- }- log.Info("Successfully created migration schema.",- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- }-- return nil-}--// FindLargestVersionSinceBaseline will find the largest version since last baseline or branch.-func (driver Driver) FindLargestVersionSinceBaseline(ctx context.Context, tx *sql.Tx, namespace string) (*string, error) {- largestBaselineSequence, err := driver.FindLargestSequence(ctx, tx, namespace, true /* baseline */)- if err != nil {- return nil, err- }- const getLargestVersionSinceLastBaselineQuery = `- SELECT MAX(version) FROM bytebase.public.migration_history- WHERE namespace = ? AND sequence >= ?- `- var version sql.NullString- if err := tx.QueryRowContext(ctx, getLargestVersionSinceLastBaselineQuery,- namespace, largestBaselineSequence,- ).Scan(&version); err != nil {- if err == sql.ErrNoRows {- return nil, common.FormatDBErrorEmptyRowWithQuery(getLargestVersionSinceLastBaselineQuery)- }- return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)- }- if version.Valid {- return &version.String, nil- }- return nil, nil-}--// FindLargestSequence will return the largest sequence number.-func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace string, baseline bool) (int, error) {- findLargestSequenceQuery := `- SELECT MAX(sequence) FROM bytebase.public.migration_history- WHERE namespace = ?`- if baseline {- findLargestSequenceQuery = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", findLargestSequenceQuery, db.Baseline, db.Branch)- }- var sequence sql.NullInt32- if err := tx.QueryRowContext(ctx, findLargestSequenceQuery,- namespace,- ).Scan(&sequence); err != nil {- if err == sql.ErrNoRows {- return -1, common.FormatDBErrorEmptyRowWithQuery(findLargestSequenceQuery)- }- return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)- }- if sequence.Valid {- return int(sequence.Int32), nil- }- // Returns 0 if we haven't applied any migration for this namespace.- return 0, nil-}--// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.-func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (string, error) {- const insertHistoryQuery = `- INSERT INTO bytebase.public.migration_history (- 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 (?, DATE_PART(EPOCH_SECOND, CURRENT_TIMESTAMP()), ?, DATE_PART(EPOCH_SECOND, CURRENT_TIMESTAMP()), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)- `- var insertedID string- maxIDQuery := "SELECT MAX(id)+1 FROM bytebase.public.migration_history"- rows, err := tx.QueryContext(ctx, maxIDQuery)- if err != nil {- return "", util.FormatErrorWithQuery(err, maxIDQuery)- }- defer rows.Close()- var id sql.NullString- for rows.Next() {- if err := rows.Scan(- &id,- ); err != nil {- return "", util.FormatErrorWithQuery(err, maxIDQuery)- }- }- if err := rows.Err(); err != nil {- return "", util.FormatErrorWithQuery(err, maxIDQuery)- }- if id.Valid {- insertedID = id.String- } else {- insertedID = "1"- }-- _, err = tx.ExecContext(ctx, insertHistoryQuery,- m.Creator,- m.Creator,- m.ReleaseVersion,- m.Namespace,- sequence,- m.Source,- m.Type,- db.Pending,- storedVersion,- m.Description,- statement,- prevSchema,- prevSchema,- m.IssueID,- m.Payload,- )- if err != nil {- return "", util.FormatErrorWithQuery(err, insertHistoryQuery)- }- return insertedID, nil-}--// UpdateHistoryAsDone will update the migration record as done.-func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID string) error {- const updateHistoryAsDoneQuery = `- UPDATE- bytebase.public.migration_history- SET- status = ?,- execution_duration_ns = ?,- schema = ?- WHERE id = ?- `- _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, db.Done, migrationDurationNs, updatedSchema, insertedID)- return err-}--// UpdateHistoryAsFailed will update the migration record as failed.-func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID string) error {- const updateHistoryAsFailedQuery = `- UPDATE- bytebase.public.migration_history- SET- status = ?,- execution_duration_ns = ?- WHERE id = ?- `- _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, db.Failed, migrationDurationNs, insertedID)- return err-}-// ExecuteMigration will execute the migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {_, err := driver.Execute(ctx, statement, m.CreateDatabase)@@ -281,18 +67,3 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Mig}return util.FindMigrationHistoryList(ctx, query, params, driver, bytebaseDatabase)}--func (driver *Driver) hasBytebaseDatabase(ctx context.Context) (bool, error) {- databases, err := driver.getDatabases(ctx)- if err != nil {- return false, err- }- exist := false- for _, database := range databases {- if database == bytebaseDatabase {- exist = true- break- }- }- return exist, nil-}diff --git a/backend/plugin/db/snowflake/snowflake_migration_schema.sql b/backend/plugin/db/snowflake/snowflake_migration_schema.sqldeleted file mode 100644index 79c4db2b46..0000000000--- a/backend/plugin/db/snowflake/snowflake_migration_schema.sql+++ /dev/null@@ -1,44 +0,0 @@--- This is the bytebase schema to track migration info for Snowflake--- Create a database called bytebase-CREATE DATABASE bytebase;---- Create migration_history table--- Note, we don't create trigger to update created_ts and updated_ts because that may causes error:--- ERROR 1419 (HY000): You do not have the SUPER privilege and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)-CREATE TABLE bytebase.public.migration_history (- id BIGINT PRIMARY KEY AUTOINCREMENT,- created_by TEXT NOT NULL,- created_ts BIGINT NOT NULL,- updated_by TEXT NOT NULL,- updated_ts BIGINT NOT NULL,- -- Record the client version creating this migration history. For Bytebase, we use its binary release version. Different Bytebase release might- -- record different history info and thie field helps to handle such situation properly. Moreover, it helps debugging.- release_version TEXT 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 each database migration history.- namespace TEXT NOT NULL,- -- Used to detect out of order migration together with 'namespace' and 'version' column.- sequence BIGINT NOT NULL,- -- 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, 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.- -- Thus, we create a "PENDING" record before applying the DDL and update that record to "DONE" after applying the DDL.- status TEXT NOT NULL,- -- Record the migration version.- version TEXT NOT NULL,- description TEXT NOT NULL,- -- Record the migration statement- statement TEXT NOT NULL,- -- Record the schema after migration- schema TEXT NOT NULL,- -- Record the schema before migration. Though we could also fetch it from the previous migration history, it would complicate fetching logic.- -- Besides, by storing the schema_prev, we can perform consistency check to see if the migration history has any gaps.- schema_prev TEXT NOT NULL,- execution_duration_ns BIGINT NOT NULL,- issue_id TEXT NOT NULL,- payload TEXT NOT NULL-);diff --git a/backend/plugin/db/spanner/migrate.go b/backend/plugin/db/spanner/migrate.goindex 82b49b6ea4..be27d55f41 100644--- a/backend/plugin/db/spanner/migrate.go+++ b/backend/plugin/db/spanner/migrate.go@@ -32,16 +32,6 @@ func (d *Driver) notFoundDatabase(ctx context.Context, databaseName string) (booreturn false, nil}-// NeedsSetupMigration checks if it needs to set up migration.-func (*Driver) NeedsSetupMigration(context.Context) (bool, error) {- return false, nil-}--// SetupMigrationIfNeeded sets up migration if needed.-func (*Driver) SetupMigrationIfNeeded(context.Context) error {- return nil-}-func (d *Driver) creataDatabase(ctx context.Context, createStatement string, extraStatement []string) error {op, err := d.dbClient.CreateDatabase(ctx, &databasepb.CreateDatabaseRequest{Parent: d.config.Host,diff --git a/backend/plugin/db/spanner/spanner_migration_schema.sql b/backend/plugin/db/spanner/spanner_migration_schema.sqldeleted file mode 100644index 21adb3df1e..0000000000--- a/backend/plugin/db/spanner/spanner_migration_schema.sql+++ /dev/null@@ -1,51 +0,0 @@--- This is the bytebase schema to track migration info for Spanner--- Create a database called bytebase in the driver.--- CREATE DATABASE bytebase;---- Create migration_history table-CREATE TABLE migration_history (- -- id is UUIDv4. See https://cloud.google.com/spanner/docs/schema-design#uuid_primary_key- id STRING(MAX) NOT NULL,- created_by STRING(MAX) NOT NULL,- created_ts INT64 NOT NULL,- updated_by STRING(MAX) NOT NULL,- updated_ts INT64 NOT NULL,- -- Record the client version creating this migration history. For Bytebase, we use its binary release version. Different Bytebase release might- -- record different history info and this field helps to handle such situation properly. Moreover, it helps debugging.- release_version STRING(MAX) 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 each database migration history.- namespace STRING(MAX) NOT NULL,- -- Used to detect out of order migration together with 'namespace' and 'version' column.- sequence INT64 NOT NULL,- CONSTRAINT sequence_is_non_negative CHECK (sequence >= 0),- -- We call it source because maybe we could load history from other migration tool.- -- Current allowed values are UI, VCS, LIBRARY.- source STRING(MAX) NOT NULL,- -- Current allowed values are BASELINE, MIGRATE, MIGRATE_SDL, BRANCH, DATA.- type STRING(MAX) 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.- status STRING(MAX) NOT NULL,- -- Record the migration version.- version STRING(MAX) NOT NULL,- description STRING(MAX) NOT NULL,- -- Record the migration statement- statement STRING(MAX) NOT NULL,- -- Record the schema after migration- schema STRING(MAX) NOT NULL,- -- Record the schema before migration. Though we could also fetch it from the previous migration history, it would complicate fetching logic.- -- Besides, by storing the schema_prev, we can perform consistency check to see if the migration history has any gaps.- schema_prev STRING(MAX) NOT NULL,- execution_duration_ns INT64 NOT NULL,- issue_id STRING(MAX) NOT NULL,- payload STRING(MAX) NOT NULL-) PRIMARY KEY(id);--CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_sequence ON migration_history (namespace, sequence);--CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_version ON migration_history (namespace, version);--CREATE INDEX bytebase_idx_migration_history_namespace_source_type ON migration_history(namespace, source, type);--CREATE INDEX bytebase_idx_migration_history_namespace_created ON migration_history(namespace, created_ts);diff --git a/backend/plugin/db/sqlite/migrate.go b/backend/plugin/db/sqlite/migrate.goindex 3e5a615366..23360c9f92 100644--- a/backend/plugin/db/sqlite/migrate.go+++ b/backend/plugin/db/sqlite/migrate.go@@ -2,222 +2,12 @@ package sqliteimport ("context"- "database/sql""fmt"- "strconv"- // embed will embeds the migration schema.- _ "embed"-- "github.com/pkg/errors"- "go.uber.org/zap"-- "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")-var (- //go:embed sqlite_migration_schema.sql- migrationSchema string-- _ util.MigrationExecutor = (*Driver)(nil)-)--// NeedsSetupMigration returns whether it needs to setup migration.-func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {- exist, err := driver.hasBytebaseDatabase()- if err != nil {- return false, err- }- if !exist {- return true, nil- }- if _, err := driver.GetDBConnection(ctx, bytebaseDatabase); err != nil {- return false, err- }-- const query = `- SELECT- 1- FROM sqlite_master- WHERE type='table' AND name = 'bytebase_migration_history'- `- return util.NeedsSetupMigrationSchema(ctx, driver.db, query)-}--// SetupMigrationIfNeeded sets up migration if needed.-func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {- setup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- return err- }-- if setup {- log.Info("Bytebase migration schema not found, creating schema...",- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )-- if _, err := driver.GetDBConnection(ctx, bytebaseDatabase); err != nil {- log.Error("Failed to switch to database \"bytebase\".",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- return errors.Wrap(err, "failed to switch to database \"bytebase\"")- }-- if _, err := driver.db.ExecContext(ctx, migrationSchema); err != nil {- log.Error("Failed to initialize migration schema.",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- return util.FormatErrorWithQuery(err, migrationSchema)- }- log.Info("Successfully created migration schema.",- zap.String("environment", driver.connectionCtx.EnvironmentID),- zap.String("instance", driver.connectionCtx.InstanceID),- )- }-- return nil-}--// FindLargestVersionSinceBaseline will find the largest version since last baseline or branch.-func (driver Driver) FindLargestVersionSinceBaseline(ctx context.Context, tx *sql.Tx, namespace string) (*string, error) {- largestBaselineSequence, err := driver.FindLargestSequence(ctx, tx, namespace, true /* baseline */)- if err != nil {- return nil, err- }- const getLargestVersionSinceLastBaselineQuery = `- SELECT MAX(version) FROM bytebase_migration_history- WHERE namespace = ? AND sequence >= ?- `- var version sql.NullString- if err := tx.QueryRowContext(ctx, getLargestVersionSinceLastBaselineQuery,- namespace, largestBaselineSequence,- ).Scan(- &version,- ); err != nil {- if err == sql.ErrNoRows {- return nil, common.FormatDBErrorEmptyRowWithQuery(getLargestVersionSinceLastBaselineQuery)- }- return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)- }- if version.Valid {- return &version.String, nil- }- return nil, nil-}--// FindLargestSequence will return the largest sequence number.-func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace string, baseline bool) (int, error) {- findLargestSequenceQuery := `- SELECT MAX(sequence) FROM bytebase_migration_history- WHERE namespace = ?`- if baseline {- findLargestSequenceQuery = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", findLargestSequenceQuery, db.Baseline, db.Branch)- }- var sequence sql.NullInt32- if err := tx.QueryRowContext(ctx, findLargestSequenceQuery,- namespace,- ).Scan(- &sequence,- ); err != nil {- return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)- }- if sequence.Valid {- return int(sequence.Int32), nil- }- // Returns 0 if we haven't applied any migration for this namespace.- return 0, nil-}--// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.-func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (string, error) {- const insertHistoryQuery = `- INSERT INTO bytebase_migration_history (- 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 (?, strftime('%s', 'now'), ?, strftime('%s', 'now'), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)- `- res, err := tx.ExecContext(ctx, insertHistoryQuery,- m.Creator,- m.Creator,- m.ReleaseVersion,- m.Namespace,- sequence,- m.Source,- m.Type,- db.Pending,- storedVersion,- m.Description,- statement,- prevSchema,- prevSchema,- m.IssueID,- m.Payload,- )- if err != nil {- return "", util.FormatErrorWithQuery(err, insertHistoryQuery)- }-- insertedID, err := res.LastInsertId()- if err != nil {- return "", util.FormatErrorWithQuery(err, insertHistoryQuery)- }- return strconv.FormatInt(insertedID, 10), nil-}--// UpdateHistoryAsDone will update the migration record as done.-func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID string) error {- const updateHistoryAsDoneQuery = `- UPDATE- bytebase_migration_history- SET- status = ?,- execution_duration_ns = ?,- schema = ?- WHERE id = ?- `- _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, db.Done, migrationDurationNs, updatedSchema, insertedID)- return err-}--// UpdateHistoryAsFailed will update the migration record as failed.-func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID string) error {- const updateHistoryAsFailedQuery = `- UPDATE- bytebase_migration_history- SET- status = ?,- execution_duration_ns = ?- WHERE id = ?- `- _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, db.Failed, migrationDurationNs, insertedID)- return err-}-// ExecuteMigration will execute the migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {_, err := driver.Execute(ctx, statement, m.CreateDatabase)diff --git a/backend/plugin/db/sqlite/sqlite.go b/backend/plugin/db/sqlite/sqlite.goindex 0e2062f493..7562649705 100644--- a/backend/plugin/db/sqlite/sqlite.go+++ b/backend/plugin/db/sqlite/sqlite.go@@ -116,19 +116,6 @@ func (driver *Driver) getDatabases() ([]string, error) {return databases, nil}-func (driver *Driver) hasBytebaseDatabase() (bool, error) {- databases, err := driver.getDatabases()- if err != nil {- return false, err- }- for _, database := range databases {- if database == bytebaseDatabase {- return true, nil- }- }- return false, nil-}-// Execute executes a SQL statement.func (driver *Driver) Execute(ctx context.Context, statement string, _ bool) (int64, error) {var remainingStmts []stringdiff --git a/backend/store/pg_engine.go b/backend/store/pg_engine.goindex 8e6cc40379..a286274749 100644--- a/backend/store/pg_engine.go+++ b/backend/store/pg_engine.go@@ -133,11 +133,12 @@ func (db *DB) Open(ctx context.Context) (schemaVersion *semver.Version, err erro}return ver, nil}+ pgDriver := d.(*pg.Driver)// We are also using our own migration core to manage our own schema's migration history.// So here we will create a "bytebase" database to store the migration history if the target// db instance does not have one yet.- if err := d.SetupMigrationIfNeeded(ctx); err != nil {+ if err := pgDriver.SetupMigrationIfNeeded(ctx); err != nil {return nil, err}@@ -146,7 +147,6 @@ func (db *DB) Open(ctx context.Context) (schemaVersion *semver.Version, err erroreturn nil, errors.Wrap(err, "failed to get current schema version")}- pgDriver := d.(*pg.Driver)if err := migrate(ctx, pgDriver, verBefore, db.mode, db.connCfg.StrictUseDb, db.serverVersion, databaseName); err != nil {return nil, errors.Wrap(err, "failed to migrate")}