Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: move migration related functions to migrate.go in the driver (#1617)
Danny Xu0024bc621195
diff --git a/plugin/db/clickhouse/clickhouse.go b/plugin/db/clickhouse/clickhouse.goindex 1a2e9acc33..7add0626a5 100644--- a/plugin/db/clickhouse/clickhouse.go+++ b/plugin/db/clickhouse/clickhouse.go@@ -9,9 +9,6 @@ import ("strings""time"- // embed will embeds the migration schema.- _ "embed"-clickhouse "github.com/ClickHouse/clickhouse-go/v2""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/common/log"@@ -20,9 +17,6 @@ import ("go.uber.org/zap")-//go:embed clickhouse_migration_schema.sql-var migrationSchema string-var (systemDatabases = map[string]bool{"system": true,@@ -30,8 +24,7 @@ var ("INFORMATION_SCHEMA": true,}- _ db.Driver = (*Driver)(nil)- _ util.MigrationExecutor = (*Driver)(nil)+ _ db.Driver = (*Driver)(nil))func init() {@@ -153,322 +146,6 @@ func (driver *Driver) Query(ctx context.Context, statement string, limit int) ([return util.Query(ctx, driver.db, statement, limit)}-// 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 nil- }-- if setup {- log.Info("Bytebase migration schema not found, creating schema...",- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- if err := driver.Execute(ctx, migrationSchema); err != nil {- log.Error("Failed to initialize migration schema.",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- return util.FormatErrorWithQuery(err, migrationSchema)- }- log.Info("Successfully created migration schema.",- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- }-- 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- `- row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,- namespace, largestBaselineSequence,- )- if err != nil {- return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)- }- defer row.Close()-- var version sql.NullString- row.Next()- if err := row.Scan(&version); err != nil {- return nil, err- }-- 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)- }- row, err := tx.QueryContext(ctx, findLargestSequenceQuery,- namespace,- )- if err != nil {- return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)- }- defer row.Close()-- var sequence sql.NullInt32- row.Next()- if err := row.Scan(&sequence); err != nil {- return -1, err- }-- if !sequence.Valid {- // Returns 0 if we haven't applied any migration for this namespace.- return 0, nil- }-- return int(sequence.Int32), 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) (int64, 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 int64- maxIDQuery := "SELECT MAX(id)+1 FROM bytebase.migration_history"- rows, err := tx.QueryContext(ctx, maxIDQuery)- if err != nil {- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)- }- defer rows.Close()- for rows.Next() {- if err := rows.Scan(- &insertedID,- ); err != nil {- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)- }- }- if err := rows.Err(); err != nil {- return int64(0), 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,- "PENDING",- storedVersion,- m.Description,- statement,- prevSchema,- prevSchema,- 0,- m.IssueID,- m.Payload,- )- if err != nil {- return int64(0), 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 int64) error {- const updateHistoryAsDoneQuery = `- ALTER TABLE- bytebase.migration_history- UPDATE- status = 'DONE',- execution_duration_ns = $1,- ` + "`schema` = $2" + `- WHERE id = $3- `- _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, 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 int64) error {- const updateHistoryAsFailedQuery = `- ALTER TABLE- bytebase.migration_history- UPDATE- status = 'FAILED',- execution_duration_ns = $1- WHERE id = $2- `- _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)- return err-}--// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {- return util.ExecuteMigration(ctx, driver, m, statement, db.BytebaseDatabase)-}--// FindMigrationHistoryList finds the migration history.-func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {- baseQuery := `- SELECT- 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- FROM bytebase.migration_history `- paramNames, params := []string{}, []interface{}{}- if v := find.ID; v != nil {- paramNames, params = append(paramNames, "id"), append(params, *v)- }- if v := find.Database; v != nil {- paramNames, params = append(paramNames, "namespace"), append(params, *v)- }- if v := find.Version; v != nil {- // TODO(d): support semantic versioning.- storedVersion, err := util.ToStoredVersion(false, *v, "")- if err != nil {- return nil, err- }- paramNames, params = append(paramNames, "version"), append(params, storedVersion)- }- if v := find.Source; v != nil {- paramNames, params = append(paramNames, "source"), append(params, *v)- }- var query = baseQuery +- db.FormatParamNameInNumberedPosition(paramNames) +- `ORDER BY created_ts DESC`- if v := find.Limit; v != nil {- query += fmt.Sprintf(" LIMIT %d", *v)- }- // TODO(zp): modified param database of `util.FindMigrationHistoryList` when we support *clickhouse* database level.- history, err := util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase, find, baseQuery)- // TODO(d): remove this block once all existing customers all migrated to semantic versioning.- if err != nil {- if !strings.Contains(err.Error(), "invalid stored version") {- return nil, err- }- if err := driver.updateMigrationHistoryStorageVersion(ctx); err != nil {- return nil, err- }- return util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase, find, baseQuery)- }- return history, err-}--func (driver *Driver) updateMigrationHistoryStorageVersion(ctx context.Context) error {- sqldb, err := driver.GetDbConnection(ctx, "bytebase")- if err != nil {- return err- }- query := `SELECT id, version FROM bytebase.migration_history`- rows, err := sqldb.Query(query)- if err != nil {- return err- }- type ver struct {- id int- version string- }- var vers []ver- for rows.Next() {- var v ver- if err := rows.Scan(&v.id, &v.version); err != nil {- return err- }- vers = append(vers, v)- }- if err := rows.Close(); err != nil {- return err- }-- updateQuery := `- ALTER TABLE- bytebase.migration_history- UPDATE- version = $1- WHERE id = $2 AND version = $3- `- for _, v := range vers {- if strings.HasPrefix(v.version, util.NonSemanticPrefix) {- continue- }- newVersion := fmt.Sprintf("%s%s", util.NonSemanticPrefix, v.version)- if _, err := sqldb.Exec(updateQuery, newVersion, v.id, v.version); err != nil {- return err- }- }- return nil-}-// Dump and restoreconst (databaseHeaderFmt = "" +diff --git a/plugin/db/clickhouse/migrate.go b/plugin/db/clickhouse/migrate.gonew file mode 100644index 0000000000..d8d66c956b--- /dev/null+++ b/plugin/db/clickhouse/migrate.go@@ -0,0 +1,339 @@+package clickhouse++import (+ "context"+ "database/sql"+ "fmt"+ "strings"+ "time"++ // embed will embeds the migration schema.+ _ "embed"++ "github.com/bytebase/bytebase/common/log"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/bytebase/bytebase/plugin/db/util"+ "go.uber.org/zap"+)++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 nil+ }++ if setup {+ log.Info("Bytebase migration schema not found, creating schema...",+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ if err := driver.Execute(ctx, migrationSchema); err != nil {+ log.Error("Failed to initialize migration schema.",+ zap.Error(err),+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ return util.FormatErrorWithQuery(err, migrationSchema)+ }+ log.Info("Successfully created migration schema.",+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ }++ 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+ `+ row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,+ namespace, largestBaselineSequence,+ )+ if err != nil {+ return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)+ }+ defer row.Close()++ var version sql.NullString+ row.Next()+ if err := row.Scan(&version); err != nil {+ return nil, err+ }++ 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)+ }+ row, err := tx.QueryContext(ctx, findLargestSequenceQuery,+ namespace,+ )+ if err != nil {+ return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)+ }+ defer row.Close()++ var sequence sql.NullInt32+ row.Next()+ if err := row.Scan(&sequence); err != nil {+ return -1, err+ }++ if !sequence.Valid {+ // Returns 0 if we haven't applied any migration for this namespace.+ return 0, nil+ }++ return int(sequence.Int32), 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) (int64, 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 int64+ maxIDQuery := "SELECT MAX(id)+1 FROM bytebase.migration_history"+ rows, err := tx.QueryContext(ctx, maxIDQuery)+ if err != nil {+ return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)+ }+ defer rows.Close()+ for rows.Next() {+ if err := rows.Scan(+ &insertedID,+ ); err != nil {+ return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)+ }+ }+ if err := rows.Err(); err != nil {+ return int64(0), 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,+ "PENDING",+ storedVersion,+ m.Description,+ statement,+ prevSchema,+ prevSchema,+ 0,+ m.IssueID,+ m.Payload,+ )+ if err != nil {+ return int64(0), 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 int64) error {+ const updateHistoryAsDoneQuery = `+ ALTER TABLE+ bytebase.migration_history+ UPDATE+ status = 'DONE',+ execution_duration_ns = $1,+ ` + "`schema` = $2" + `+ WHERE id = $3+ `+ _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, 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 int64) error {+ const updateHistoryAsFailedQuery = `+ ALTER TABLE+ bytebase.migration_history+ UPDATE+ status = 'FAILED',+ execution_duration_ns = $1+ WHERE id = $2+ `+ _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)+ return err+}++// ExecuteMigration will execute the migration.+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {+ return util.ExecuteMigration(ctx, driver, m, statement, db.BytebaseDatabase)+}++// FindMigrationHistoryList finds the migration history.+func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {+ baseQuery := `+ SELECT+ 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+ FROM bytebase.migration_history `+ paramNames, params := []string{}, []interface{}{}+ if v := find.ID; v != nil {+ paramNames, params = append(paramNames, "id"), append(params, *v)+ }+ if v := find.Database; v != nil {+ paramNames, params = append(paramNames, "namespace"), append(params, *v)+ }+ if v := find.Version; v != nil {+ // TODO(d): support semantic versioning.+ storedVersion, err := util.ToStoredVersion(false, *v, "")+ if err != nil {+ return nil, err+ }+ paramNames, params = append(paramNames, "version"), append(params, storedVersion)+ }+ if v := find.Source; v != nil {+ paramNames, params = append(paramNames, "source"), append(params, *v)+ }+ var query = baseQuery ++ db.FormatParamNameInNumberedPosition(paramNames) ++ `ORDER BY created_ts DESC`+ if v := find.Limit; v != nil {+ query += fmt.Sprintf(" LIMIT %d", *v)+ }+ // TODO(zp): modified param database of `util.FindMigrationHistoryList` when we support *clickhouse* database level.+ history, err := util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase, find, baseQuery)+ // TODO(d): remove this block once all existing customers all migrated to semantic versioning.+ if err != nil {+ if !strings.Contains(err.Error(), "invalid stored version") {+ return nil, err+ }+ if err := driver.updateMigrationHistoryStorageVersion(ctx); err != nil {+ return nil, err+ }+ return util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase, find, baseQuery)+ }+ return history, err+}+func (driver *Driver) updateMigrationHistoryStorageVersion(ctx context.Context) error {+ sqldb, err := driver.GetDbConnection(ctx, "bytebase")+ if err != nil {+ return err+ }+ query := `SELECT id, version FROM bytebase.migration_history`+ rows, err := sqldb.Query(query)+ if err != nil {+ return err+ }+ type ver struct {+ id int+ version string+ }+ var vers []ver+ for rows.Next() {+ var v ver+ if err := rows.Scan(&v.id, &v.version); err != nil {+ return err+ }+ vers = append(vers, v)+ }+ if err := rows.Close(); err != nil {+ return err+ }++ updateQuery := `+ ALTER TABLE+ bytebase.migration_history+ UPDATE+ version = $1+ WHERE id = $2 AND version = $3+ `+ for _, v := range vers {+ if strings.HasPrefix(v.version, util.NonSemanticPrefix) {+ continue+ }+ newVersion := fmt.Sprintf("%s%s", util.NonSemanticPrefix, v.version)+ if _, err := sqldb.Exec(updateQuery, newVersion, v.id, v.version); err != nil {+ return err+ }+ }+ return nil+}diff --git a/plugin/db/mysql/migrate.go b/plugin/db/mysql/migrate.gonew file mode 100644index 0000000000..0a979363d1--- /dev/null+++ b/plugin/db/mysql/migrate.go@@ -0,0 +1,321 @@+package mysql++import (+ "context"+ "database/sql"+ "fmt"+ "strings"++ // embed will embeds the migration schema.+ _ "embed"++ "github.com/bytebase/bytebase/common/log"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/bytebase/bytebase/plugin/db/util"+ "go.uber.org/zap"+)++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 nil+ }++ if setup {+ log.Info("Bytebase migration schema not found, creating schema...",+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ // 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.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ return util.FormatErrorWithQuery(err, migrationSchema)+ }+ log.Info("Successfully created migration schema.",+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ }++ 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 >= ?+ `+ row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,+ namespace, largestBaselineSequence,+ )+ if err != nil {+ return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)+ }+ defer row.Close()++ var version sql.NullString+ row.Next()+ if err := row.Scan(&version); err != nil {+ return nil, err+ }++ 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)+ }+ row, err := tx.QueryContext(ctx, findLargestSequenceQuery,+ namespace,+ )+ if err != nil {+ return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)+ }+ defer row.Close()++ var sequence sql.NullInt32+ row.Next()+ if err := row.Scan(&sequence); err != nil {+ return -1, err+ }++ if !sequence.Valid {+ // Returns 0 if we haven't applied any migration for this namespace.+ return 0, nil+ }++ return int(sequence.Int32), 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) (int64, 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(), ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, 0, ?, ?)+ `+ res, err := tx.ExecContext(ctx, insertHistoryQuery,+ m.Creator,+ m.Creator,+ m.ReleaseVersion,+ m.Namespace,+ sequence,+ m.Source,+ m.Type,+ storedVersion,+ m.Description,+ statement,+ prevSchema,+ prevSchema,+ m.IssueID,+ m.Payload,+ )+ if err != nil {+ return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)+ }++ insertedID, err := res.LastInsertId()+ if err != nil {+ return int64(0), 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 int64) error {+ const updateHistoryAsDoneQuery = `+ UPDATE+ bytebase.migration_history+ SET+ status = 'DONE',+ execution_duration_ns = ?,+ ` + "`schema` = ?" + `+ WHERE id = ?+ `+ _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, 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 int64) error {+ const updateHistoryAsFailedQuery = `+ UPDATE+ bytebase.migration_history+ SET+ status = 'FAILED',+ execution_duration_ns = ?+ WHERE id = ?+ `+ _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)+ return err+}++// ExecuteMigration will execute the migration.+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {+ return util.ExecuteMigration(ctx, driver, m, statement, db.BytebaseDatabase)+}++// FindMigrationHistoryList finds the migration history.+func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {+ baseQuery := `+ SELECT+ 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+ FROM bytebase.migration_history `+ paramNames, params := []string{}, []interface{}{}+ if v := find.ID; v != nil {+ paramNames, params = append(paramNames, "id"), append(params, *v)+ }+ if v := find.Database; v != nil {+ paramNames, params = append(paramNames, "namespace"), append(params, *v)+ }+ if v := find.Version; v != nil {+ // TODO(d): support semantic versioning.+ storedVersion, err := util.ToStoredVersion(false, *v, "")+ if err != nil {+ return nil, err+ }+ paramNames, params = append(paramNames, "version"), append(params, storedVersion)+ }+ if v := find.Source; v != nil {+ paramNames, params = append(paramNames, "source"), append(params, *v)+ }+ var query = baseQuery ++ db.FormatParamNameInQuestionMark(paramNames) ++ `ORDER BY created_ts DESC`+ if v := find.Limit; v != nil {+ query += fmt.Sprintf(" LIMIT %d", *v)+ }+ // TODO(zp): modified param database of `util.FindMigrationHistoryList` when we support *mysql* database level.+ history, err := util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase, find, baseQuery)+ // TODO(d): remove this block once all existing customers all migrated to semantic versioning.+ if err != nil {+ if !strings.Contains(err.Error(), "invalid stored version") {+ return nil, err+ }+ if err := driver.updateMigrationHistoryStorageVersion(ctx); err != nil {+ return nil, err+ }+ return util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase, find, baseQuery)+ }+ return history, err+}++func (driver *Driver) updateMigrationHistoryStorageVersion(ctx context.Context) error {+ sqldb, err := driver.GetDbConnection(ctx, db.BytebaseDatabase)+ if err != nil {+ return err+ }+ query := `SELECT id, version FROM bytebase.migration_history`+ rows, err := sqldb.Query(query)+ if err != nil {+ return err+ }+ type ver struct {+ id int+ version string+ }+ var vers []ver+ for rows.Next() {+ var v ver+ if err := rows.Scan(&v.id, &v.version); err != nil {+ return err+ }+ vers = append(vers, v)+ }+ if err := rows.Close(); err != nil {+ return err+ }++ updateQuery := `+ UPDATE+ bytebase.migration_history+ SET+ version = ?+ WHERE id = ? AND version = ?+ `+ for _, v := range vers {+ if strings.HasPrefix(v.version, util.NonSemanticPrefix) {+ continue+ }+ newVersion := fmt.Sprintf("%s%s", util.NonSemanticPrefix, v.version)+ if _, err := sqldb.Exec(updateQuery, newVersion, v.id, v.version); err != nil {+ return err+ }+ }+ return nil+}diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex 7fc270ea5c..7e9a604587 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -11,9 +11,6 @@ import ("strings""time"- // embed will embeds the migration schema.- _ "embed"-"github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/common/log"@@ -23,9 +20,6 @@ import ("go.uber.org/zap")-//go:embed mysql_migration_schema.sql-var migrationSchema string-var (systemDatabases = map[string]bool{"information_schema": true,@@ -39,8 +33,7 @@ var (viewTableType = "VIEW"excludeAutoIncrement = regexp.MustCompile(`AUTO_INCREMENT=\d+ `)- _ db.Driver = (*Driver)(nil)- _ util.MigrationExecutor = (*Driver)(nil)+ _ db.Driver = (*Driver)(nil))func init() {@@ -169,304 +162,6 @@ func (driver *Driver) Query(ctx context.Context, statement string, limit int) ([return util.Query(ctx, driver.db, statement, limit)}-// 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 nil- }-- if setup {- log.Info("Bytebase migration schema not found, creating schema...",- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- // 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.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- return util.FormatErrorWithQuery(err, migrationSchema)- }- log.Info("Successfully created migration schema.",- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- }-- 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 >= ?- `- row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,- namespace, largestBaselineSequence,- )- if err != nil {- return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)- }- defer row.Close()-- var version sql.NullString- row.Next()- if err := row.Scan(&version); err != nil {- return nil, err- }-- 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)- }- row, err := tx.QueryContext(ctx, findLargestSequenceQuery,- namespace,- )- if err != nil {- return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)- }- defer row.Close()-- var sequence sql.NullInt32- row.Next()- if err := row.Scan(&sequence); err != nil {- return -1, err- }-- if !sequence.Valid {- // Returns 0 if we haven't applied any migration for this namespace.- return 0, nil- }-- return int(sequence.Int32), 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) (int64, 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(), ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, 0, ?, ?)- `- res, err := tx.ExecContext(ctx, insertHistoryQuery,- m.Creator,- m.Creator,- m.ReleaseVersion,- m.Namespace,- sequence,- m.Source,- m.Type,- storedVersion,- m.Description,- statement,- prevSchema,- prevSchema,- m.IssueID,- m.Payload,- )- if err != nil {- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)- }-- insertedID, err := res.LastInsertId()- if err != nil {- return int64(0), 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 int64) error {- const updateHistoryAsDoneQuery = `- UPDATE- bytebase.migration_history- SET- status = 'DONE',- execution_duration_ns = ?,- ` + "`schema` = ?" + `- WHERE id = ?- `- _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, 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 int64) error {- const updateHistoryAsFailedQuery = `- UPDATE- bytebase.migration_history- SET- status = 'FAILED',- execution_duration_ns = ?- WHERE id = ?- `- _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)- return err-}--// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {- return util.ExecuteMigration(ctx, driver, m, statement, db.BytebaseDatabase)-}--// FindMigrationHistoryList finds the migration history.-func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {- baseQuery := `- SELECT- 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- FROM bytebase.migration_history `- paramNames, params := []string{}, []interface{}{}- if v := find.ID; v != nil {- paramNames, params = append(paramNames, "id"), append(params, *v)- }- if v := find.Database; v != nil {- paramNames, params = append(paramNames, "namespace"), append(params, *v)- }- if v := find.Version; v != nil {- // TODO(d): support semantic versioning.- storedVersion, err := util.ToStoredVersion(false, *v, "")- if err != nil {- return nil, err- }- paramNames, params = append(paramNames, "version"), append(params, storedVersion)- }- if v := find.Source; v != nil {- paramNames, params = append(paramNames, "source"), append(params, *v)- }- var query = baseQuery +- db.FormatParamNameInQuestionMark(paramNames) +- `ORDER BY created_ts DESC`- if v := find.Limit; v != nil {- query += fmt.Sprintf(" LIMIT %d", *v)- }- // TODO(zp): modified param database of `util.FindMigrationHistoryList` when we support *mysql* database level.- history, err := util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase, find, baseQuery)- // TODO(d): remove this block once all existing customers all migrated to semantic versioning.- if err != nil {- if !strings.Contains(err.Error(), "invalid stored version") {- return nil, err- }- if err := driver.updateMigrationHistoryStorageVersion(ctx); err != nil {- return nil, err- }- return util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase, find, baseQuery)- }- return history, err-}--func (driver *Driver) updateMigrationHistoryStorageVersion(ctx context.Context) error {- sqldb, err := driver.GetDbConnection(ctx, db.BytebaseDatabase)- if err != nil {- return err- }- query := `SELECT id, version FROM bytebase.migration_history`- rows, err := sqldb.Query(query)- if err != nil {- return err- }- type ver struct {- id int- version string- }- var vers []ver- for rows.Next() {- var v ver- if err := rows.Scan(&v.id, &v.version); err != nil {- return err- }- vers = append(vers, v)- }- if err := rows.Close(); err != nil {- return err- }-- updateQuery := `- UPDATE- bytebase.migration_history- SET- version = ?- WHERE id = ? AND version = ?- `- for _, v := range vers {- if strings.HasPrefix(v.version, util.NonSemanticPrefix) {- continue- }- newVersion := fmt.Sprintf("%s%s", util.NonSemanticPrefix, v.version)- if _, err := sqldb.Exec(updateQuery, newVersion, v.id, v.version); err != nil {- return err- }- }- return nil-}-// Dump and restoreconst (databaseHeaderFmt = "" +diff --git a/plugin/db/pg/migrate.go b/plugin/db/pg/migrate.gonew file mode 100644index 0000000000..ead505e744--- /dev/null+++ b/plugin/db/pg/migrate.go@@ -0,0 +1,394 @@+package pg++import (+ "context"+ "database/sql"+ "fmt"+ "strings"++ // embed will embeds the migration schema.+ _ "embed"++ "github.com/bytebase/bytebase/common/log"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/bytebase/bytebase/plugin/db/util"+ "go.uber.org/zap"+)++var (+ //go:embed pg_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) {+ // Don't use `bytebase` when user gives database instead of instance.+ if !driver.strictUseDb() {+ exist, err := driver.hasBytebaseDatabase(ctx)+ if err != nil {+ return false, err+ }+ if !exist {+ return true, nil+ }+ if err := driver.switchDatabase(db.BytebaseDatabase); err != nil {+ return false, err+ }+ }++ const query = `+ SELECT+ 1+ FROM information_schema.tables+ WHERE 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 nil+ }++ if setup {+ log.Info("Bytebase migration schema not found, creating schema...",+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )++ // Only try to create `bytebase` db when user provide an instance+ if !driver.strictUseDb() {+ exist, err := driver.hasBytebaseDatabase(ctx)+ if err != nil {+ log.Error("Failed to find bytebase database.",+ zap.Error(err),+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ return fmt.Errorf("failed to find bytebase database error: %v", err)+ }++ if !exist {+ // Create `bytebase` database+ if _, err := driver.db.ExecContext(ctx, createBytebaseDatabaseStmt); err != nil {+ log.Error("Failed to create bytebase database.",+ zap.Error(err),+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ return util.FormatErrorWithQuery(err, createBytebaseDatabaseStmt)+ }+ }++ if err := driver.switchDatabase(db.BytebaseDatabase); err != nil {+ log.Error("Failed to switch to bytebase database.",+ zap.Error(err),+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ return fmt.Errorf("failed to switch to bytebase database error: %v", err)+ }+ }++ // Create `migration_history` table+ if _, err := driver.db.ExecContext(ctx, migrationSchema); err != nil {+ log.Error("Failed to initialize migration schema.",+ zap.Error(err),+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ return util.FormatErrorWithQuery(err, migrationSchema)+ }+ log.Info("Successfully created migration schema.",+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ }++ 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 migration_history+ WHERE namespace = $1 AND sequence >= $2+ `+ row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,+ namespace, largestBaselineSequence,+ )+ if err != nil {+ return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)+ }+ defer row.Close()++ var version sql.NullString+ row.Next()+ if err := row.Scan(&version); err != nil {+ return nil, err+ }++ 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 migration_history+ WHERE namespace = $1`+ if baseline {+ findLargestSequenceQuery = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", findLargestSequenceQuery, db.Baseline, db.Branch)+ }+ row, err := tx.QueryContext(ctx, findLargestSequenceQuery,+ namespace,+ )+ if err != nil {+ return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)+ }+ defer row.Close()++ var sequence sql.NullInt32+ row.Next()+ if err := row.Scan(&sequence); err != nil {+ return -1, err+ }++ if !sequence.Valid {+ // Returns 0 if we haven't applied any migration for this namespace.+ return 0, nil+ }++ return int(sequence.Int32), 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) (int64, error) {+ const insertHistoryQuery = `+ INSERT INTO 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 ($1, EXTRACT(epoch from NOW()), $2, EXTRACT(epoch from NOW()), $3, $4, $5, $6, $7, 'PENDING', $8, $9, $10, $11, $12, 0, $13, $14)+ RETURNING id+ `+ var insertedID int64+ if err := tx.QueryRowContext(ctx, insertHistoryQuery,+ m.Creator,+ m.Creator,+ m.ReleaseVersion,+ m.Namespace,+ sequence,+ m.Source,+ m.Type,+ storedVersion,+ m.Description,+ statement,+ prevSchema,+ prevSchema,+ m.IssueID,+ m.Payload,+ ).Scan(&insertedID); err != nil {+ return 0, err+ }+ 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 int64) error {+ const updateHistoryAsDoneQuery = `+ UPDATE+ migration_history+ SET+ status = 'DONE',+ execution_duration_ns = $1,+ "schema" = $2+ WHERE id = $3+ `+ _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, 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 int64) error {+ const updateHistoryAsFailedQuery = `+ UPDATE+ migration_history+ SET+ status = 'FAILED',+ execution_duration_ns = $1+ WHERE id = $2+ `+ _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)+ return err+}++// ExecuteMigration will execute the migration.+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {+ if driver.strictUseDb() {+ return util.ExecuteMigration(ctx, driver, m, statement, driver.strictDatabase)+ }+ return util.ExecuteMigration(ctx, driver, m, statement, db.BytebaseDatabase)+}++// FindMigrationHistoryList finds the migration history.+func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {+ baseQuery := `+ SELECT+ 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+ FROM migration_history `+ paramNames, params := []string{}, []interface{}{}+ if v := find.ID; v != nil {+ paramNames, params = append(paramNames, "id"), append(params, *v)+ }+ if v := find.Database; v != nil {+ paramNames, params = append(paramNames, "namespace"), append(params, *v)+ }+ if v := find.Version; v != nil {+ // TODO(d): support semantic versioning.+ storedVersion, err := util.ToStoredVersion(false, *v, "")+ if err != nil {+ return nil, err+ }+ paramNames, params = append(paramNames, "version"), append(params, storedVersion)+ }+ if v := find.Source; v != nil {+ paramNames, params = append(paramNames, "source"), append(params, *v)+ }+ var query = baseQuery ++ db.FormatParamNameInNumberedPosition(paramNames) ++ `ORDER BY created_ts DESC`+ if v := find.Limit; v != nil {+ query += fmt.Sprintf(" LIMIT %d", *v)+ }++ database := db.BytebaseDatabase+ if driver.strictUseDb() {+ database = driver.strictDatabase+ }+ history, err := util.FindMigrationHistoryList(ctx, query, params, driver, database, find, baseQuery)+ // TODO(d): remove this block once all existing customers all migrated to semantic versioning.+ // Skip this backfill for bytebase's database "bb" with user "bb". We will use the one in pg_engine.go instead.+ isBytebaseDatabase := strings.Contains(driver.baseDSN, "user=bb") && strings.Contains(driver.baseDSN, "host=/tmp")+ if err != nil && !isBytebaseDatabase {+ if !strings.Contains(err.Error(), "invalid stored version") {+ return nil, err+ }+ if err := driver.updateMigrationHistoryStorageVersion(ctx); err != nil {+ return nil, err+ }+ return util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase, find, baseQuery)+ }+ return history, err+}++func (driver *Driver) updateMigrationHistoryStorageVersion(ctx context.Context) error {+ var sqldb *sql.DB+ var err error+ if !driver.strictUseDb() {+ sqldb, err = driver.GetDbConnection(ctx, db.BytebaseDatabase)+ }+ if err != nil {+ return err+ }++ query := `SELECT id, version FROM migration_history`+ rows, err := sqldb.Query(query)+ if err != nil {+ return err+ }+ type ver struct {+ id int+ version string+ }+ var vers []ver+ for rows.Next() {+ var v ver+ if err := rows.Scan(&v.id, &v.version); err != nil {+ return err+ }+ vers = append(vers, v)+ }+ if err := rows.Close(); err != nil {+ return err+ }++ updateQuery := `+ UPDATE+ migration_history+ SET+ version = $1+ WHERE id = $2 AND version = $3+ `+ for _, v := range vers {+ if strings.HasPrefix(v.version, util.NonSemanticPrefix) {+ continue+ }+ newVersion := fmt.Sprintf("%s%s", util.NonSemanticPrefix, v.version)+ if _, err := sqldb.Exec(updateQuery, newVersion, v.id, v.version); err != nil {+ return err+ }+ }+ return nil+}++func (driver *Driver) hasBytebaseDatabase(ctx context.Context) (bool, error) {+ databases, err := driver.getDatabases()+ if err != nil {+ return false, err+ }+ exist := false+ for _, database := range databases {+ if database.name == db.BytebaseDatabase {+ exist = true+ break+ }+ }+ return exist, nil+}diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.goindex e83553fb44..80350e9374 100644--- a/plugin/db/pg/pg.go+++ b/plugin/db/pg/pg.go@@ -14,21 +14,14 @@ import ("github.com/bytebase/bytebase/common/log"- // embed will embeds the migration schema.- _ "embed"-// Import pg driver.// init() in pgx/v4/stdlib will register it's pgx driver_ "github.com/jackc/pgx/v4/stdlib""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/db/util"- "go.uber.org/zap")-//go:embed pg_migration_schema.sql-var migrationSchema string-var (systemDatabases = map[string]bool{"template0": true,@@ -40,8 +33,7 @@ var (// driverName is the driver name that our driver dependence register, now is "pgx".driverName = "pgx"- _ db.Driver = (*Driver)(nil)- _ util.MigrationExecutor = (*Driver)(nil)+ _ db.Driver = (*Driver)(nil))func init() {@@ -334,377 +326,6 @@ func (driver *Driver) Query(ctx context.Context, statement string, limit int) ([return util.Query(ctx, driver.db, statement, limit)}-// NeedsSetupMigration returns whether it needs to setup migration.-func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {- // Don't use `bytebase` when user gives database instead of instance.- if !driver.strictUseDb() {- exist, err := driver.hasBytebaseDatabase(ctx)- if err != nil {- return false, err- }- if !exist {- return true, nil- }- if err := driver.switchDatabase(db.BytebaseDatabase); err != nil {- return false, err- }- }-- const query = `- SELECT- 1- FROM information_schema.tables- WHERE table_name = 'migration_history'- `-- return util.NeedsSetupMigrationSchema(ctx, driver.db, query)-}--func (driver *Driver) hasBytebaseDatabase(ctx context.Context) (bool, error) {- databases, err := driver.getDatabases()- if err != nil {- return false, err- }- exist := false- for _, database := range databases {- if database.name == db.BytebaseDatabase {- exist = true- break- }- }- return exist, nil-}--// SetupMigrationIfNeeded sets up migration if needed.-func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {- setup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- return nil- }-- if setup {- log.Info("Bytebase migration schema not found, creating schema...",- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )-- // Only try to create `bytebase` db when user provide an instance- if !driver.strictUseDb() {- exist, err := driver.hasBytebaseDatabase(ctx)- if err != nil {- log.Error("Failed to find bytebase database.",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- return fmt.Errorf("failed to find bytebase database error: %v", err)- }-- if !exist {- // Create `bytebase` database- if _, err := driver.db.ExecContext(ctx, createBytebaseDatabaseStmt); err != nil {- log.Error("Failed to create bytebase database.",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- return util.FormatErrorWithQuery(err, createBytebaseDatabaseStmt)- }- }-- if err := driver.switchDatabase(db.BytebaseDatabase); err != nil {- log.Error("Failed to switch to bytebase database.",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- return fmt.Errorf("failed to switch to bytebase database error: %v", err)- }- }-- // Create `migration_history` table- if _, err := driver.db.ExecContext(ctx, migrationSchema); err != nil {- log.Error("Failed to initialize migration schema.",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- return util.FormatErrorWithQuery(err, migrationSchema)- }- log.Info("Successfully created migration schema.",- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- }-- 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 migration_history- WHERE namespace = $1 AND sequence >= $2- `- row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,- namespace, largestBaselineSequence,- )- if err != nil {- return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)- }- defer row.Close()-- var version sql.NullString- row.Next()- if err := row.Scan(&version); err != nil {- return nil, err- }-- 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 migration_history- WHERE namespace = $1`- if baseline {- findLargestSequenceQuery = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", findLargestSequenceQuery, db.Baseline, db.Branch)- }- row, err := tx.QueryContext(ctx, findLargestSequenceQuery,- namespace,- )- if err != nil {- return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)- }- defer row.Close()-- var sequence sql.NullInt32- row.Next()- if err := row.Scan(&sequence); err != nil {- return -1, err- }-- if !sequence.Valid {- // Returns 0 if we haven't applied any migration for this namespace.- return 0, nil- }-- return int(sequence.Int32), 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) (int64, error) {- const insertHistoryQuery = `- INSERT INTO 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 ($1, EXTRACT(epoch from NOW()), $2, EXTRACT(epoch from NOW()), $3, $4, $5, $6, $7, 'PENDING', $8, $9, $10, $11, $12, 0, $13, $14)- RETURNING id- `- var insertedID int64- if err := tx.QueryRowContext(ctx, insertHistoryQuery,- m.Creator,- m.Creator,- m.ReleaseVersion,- m.Namespace,- sequence,- m.Source,- m.Type,- storedVersion,- m.Description,- statement,- prevSchema,- prevSchema,- m.IssueID,- m.Payload,- ).Scan(&insertedID); err != nil {- return 0, err- }- 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 int64) error {- const updateHistoryAsDoneQuery = `- UPDATE- migration_history- SET- status = 'DONE',- execution_duration_ns = $1,- "schema" = $2- WHERE id = $3- `- _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, 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 int64) error {- const updateHistoryAsFailedQuery = `- UPDATE- migration_history- SET- status = 'FAILED',- execution_duration_ns = $1- WHERE id = $2- `- _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)- return err-}--// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {- if driver.strictUseDb() {- return util.ExecuteMigration(ctx, driver, m, statement, driver.strictDatabase)- }- return util.ExecuteMigration(ctx, driver, m, statement, db.BytebaseDatabase)-}--// FindMigrationHistoryList finds the migration history.-func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {- baseQuery := `- SELECT- 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- FROM migration_history `- paramNames, params := []string{}, []interface{}{}- if v := find.ID; v != nil {- paramNames, params = append(paramNames, "id"), append(params, *v)- }- if v := find.Database; v != nil {- paramNames, params = append(paramNames, "namespace"), append(params, *v)- }- if v := find.Version; v != nil {- // TODO(d): support semantic versioning.- storedVersion, err := util.ToStoredVersion(false, *v, "")- if err != nil {- return nil, err- }- paramNames, params = append(paramNames, "version"), append(params, storedVersion)- }- if v := find.Source; v != nil {- paramNames, params = append(paramNames, "source"), append(params, *v)- }- var query = baseQuery +- db.FormatParamNameInNumberedPosition(paramNames) +- `ORDER BY created_ts DESC`- if v := find.Limit; v != nil {- query += fmt.Sprintf(" LIMIT %d", *v)- }-- database := db.BytebaseDatabase- if driver.strictUseDb() {- database = driver.strictDatabase- }- history, err := util.FindMigrationHistoryList(ctx, query, params, driver, database, find, baseQuery)- // TODO(d): remove this block once all existing customers all migrated to semantic versioning.- // Skip this backfill for bytebase's database "bb" with user "bb". We will use the one in pg_engine.go instead.- isBytebaseDatabase := strings.Contains(driver.baseDSN, "user=bb") && strings.Contains(driver.baseDSN, "host=/tmp")- if err != nil && !isBytebaseDatabase {- if !strings.Contains(err.Error(), "invalid stored version") {- return nil, err- }- if err := driver.updateMigrationHistoryStorageVersion(ctx); err != nil {- return nil, err- }- return util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase, find, baseQuery)- }- return history, err-}--func (driver *Driver) updateMigrationHistoryStorageVersion(ctx context.Context) error {- var sqldb *sql.DB- var err error- if !driver.strictUseDb() {- sqldb, err = driver.GetDbConnection(ctx, db.BytebaseDatabase)- }- if err != nil {- return err- }-- query := `SELECT id, version FROM migration_history`- rows, err := sqldb.Query(query)- if err != nil {- return err- }- type ver struct {- id int- version string- }- var vers []ver- for rows.Next() {- var v ver- if err := rows.Scan(&v.id, &v.version); err != nil {- return err- }- vers = append(vers, v)- }- if err := rows.Close(); err != nil {- return err- }-- updateQuery := `- UPDATE- migration_history- SET- version = $1- WHERE id = $2 AND version = $3- `- for _, v := range vers {- if strings.HasPrefix(v.version, util.NonSemanticPrefix) {- continue- }- newVersion := fmt.Sprintf("%s%s", util.NonSemanticPrefix, v.version)- if _, err := sqldb.Exec(updateQuery, newVersion, v.id, v.version); err != nil {- return err- }- }- return nil-}-// Dump and restore// Dump dumps the database.diff --git a/plugin/db/snowflake/migrate.go b/plugin/db/snowflake/migrate.gonew file mode 100644index 0000000000..88871ff8fb--- /dev/null+++ b/plugin/db/snowflake/migrate.go@@ -0,0 +1,364 @@+package snowflake++import (+ "context"+ "database/sql"+ "fmt"+ "strings"++ // embed will embeds the migration schema.+ _ "embed"++ "github.com/bytebase/bytebase/common/log"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/bytebase/bytebase/plugin/db/util"+ "go.uber.org/zap"+)++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 nil+ }++ if setup {+ log.Info("Bytebase migration schema not found, creating schema...",+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ // Should use role SYSADMIN.+ if err := driver.Execute(ctx, migrationSchema); err != nil {+ log.Error("Failed to initialize migration schema.",+ zap.Error(err),+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ return util.FormatErrorWithQuery(err, migrationSchema)+ }+ log.Info("Successfully created migration schema.",+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ }++ 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 >= ?+ `+ row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,+ namespace, largestBaselineSequence,+ )+ if err != nil {+ return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)+ }+ defer row.Close()++ var version sql.NullString+ row.Next()+ if err := row.Scan(&version); err != nil {+ return nil, err+ }++ 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)+ }+ row, err := tx.QueryContext(ctx, findLargestSequenceQuery,+ namespace,+ )+ if err != nil {+ return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)+ }+ defer row.Close()++ var sequence sql.NullInt32+ row.Next()+ if err := row.Scan(&sequence); err != nil {+ return -1, err+ }++ if !sequence.Valid {+ // Returns 0 if we haven't applied any migration for this namespace.+ return 0, nil+ }++ return int(sequence.Int32), 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) (int64, 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()), ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, 0, ?, ?)+ `+ var insertedID int64+ maxIDQuery := "SELECT MAX(id)+1 FROM bytebase.public.migration_history"+ rows, err := tx.QueryContext(ctx, maxIDQuery)+ if err != nil {+ return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)+ }+ defer rows.Close()+ var id sql.NullInt64+ for rows.Next() {+ if err := rows.Scan(+ &id,+ ); err != nil {+ return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)+ }+ }+ if err := rows.Err(); err != nil {+ return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)+ }+ if id.Valid {+ insertedID = id.Int64+ } else {+ insertedID = 1+ }++ _, err = tx.ExecContext(ctx, insertHistoryQuery,+ m.Creator,+ m.Creator,+ m.ReleaseVersion,+ m.Namespace,+ sequence,+ m.Source,+ m.Type,+ storedVersion,+ m.Description,+ statement,+ prevSchema,+ prevSchema,+ m.IssueID,+ m.Payload,+ )+ if err != nil {+ return int64(0), 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 int64) error {+ const updateHistoryAsDoneQuery = `+ UPDATE+ bytebase.public.migration_history+ SET+ status = 'DONE',+ execution_duration_ns = ?,+ schema = ?+ WHERE id = ?+ `+ _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, 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 int64) error {+ const updateHistoryAsFailedQuery = `+ UPDATE+ bytebase.public.migration_history+ SET+ status = 'FAILED',+ execution_duration_ns = ?+ WHERE id = ?+ `+ _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)+ return err+}++// ExecuteMigration will execute the migration.+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {+ if err := driver.useRole(ctx, sysAdminRole); err != nil {+ return int64(0), "", err+ }+ return util.ExecuteMigration(ctx, driver, m, statement, bytebaseDatabase)+}++// FindMigrationHistoryList finds the migration history.+func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {+ baseQuery := `+ SELECT+ 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+ FROM bytebase.public.migration_history `+ paramNames, params := []string{}, []interface{}{}+ if v := find.ID; v != nil {+ paramNames, params = append(paramNames, "id"), append(params, *v)+ }+ if v := find.Database; v != nil {+ paramNames, params = append(paramNames, "namespace"), append(params, *v)+ }+ if v := find.Version; v != nil {+ // TODO(d): support semantic versioning.+ storedVersion, err := util.ToStoredVersion(false, *v, "")+ if err != nil {+ return nil, err+ }+ paramNames, params = append(paramNames, "version"), append(params, storedVersion)+ }+ if v := find.Source; v != nil {+ paramNames, params = append(paramNames, "source"), append(params, *v)+ }+ var query = baseQuery ++ db.FormatParamNameInQuestionMark(paramNames) ++ `ORDER BY created_ts DESC`+ if v := find.Limit; v != nil {+ query += fmt.Sprintf(" LIMIT %d", *v)+ }+ // TODO(zp): modified param `bytebaseDatabase` of `util.FindMigrationHistoryList` when we support *snowflake* database level.+ history, err := util.FindMigrationHistoryList(ctx, query, params, driver, bytebaseDatabase, find, baseQuery)+ // TODO(d): remove this block once all existing customers all migrated to semantic versioning.+ if err != nil {+ if !strings.Contains(err.Error(), "invalid stored version") {+ return nil, err+ }+ if err := driver.updateMigrationHistoryStorageVersion(ctx); err != nil {+ return nil, err+ }+ return util.FindMigrationHistoryList(ctx, query, params, driver, bytebaseDatabase, find, baseQuery)+ }+ return history, err+}++func (driver *Driver) updateMigrationHistoryStorageVersion(ctx context.Context) error {+ sqldb, err := driver.GetDbConnection(ctx, "bytebase")+ if err != nil {+ return err+ }+ query := `SELECT id, version FROM bytebase.public.migration_history`+ rows, err := sqldb.Query(query)+ if err != nil {+ return err+ }+ type ver struct {+ id int+ version string+ }+ var vers []ver+ for rows.Next() {+ var v ver+ if err := rows.Scan(&v.id, &v.version); err != nil {+ return err+ }+ vers = append(vers, v)+ }+ if err := rows.Close(); err != nil {+ return err+ }++ updateQuery := `+ UPDATE+ bytebase.public.migration_history+ SET+ version = ?+ WHERE id = ? AND version = ?+ `+ for _, v := range vers {+ if strings.HasPrefix(v.version, util.NonSemanticPrefix) {+ continue+ }+ newVersion := fmt.Sprintf("%s%s", util.NonSemanticPrefix, v.version)+ if _, err := sqldb.Exec(updateQuery, newVersion, v.id, v.version); err != nil {+ return err+ }+ }+ return nil+}++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/plugin/db/snowflake/snowflake.go b/plugin/db/snowflake/snowflake.goindex 8f1979fb7c..9d1ab0beda 100644--- a/plugin/db/snowflake/snowflake.go+++ b/plugin/db/snowflake/snowflake.go@@ -8,9 +8,6 @@ import ("io""strings"- // embed will embeds the migration schema.- _ "embed"-"github.com/bytebase/bytebase/common/log""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/db/util"@@ -19,9 +16,6 @@ import ("go.uber.org/zap")-//go:embed snowflake_migration_schema.sql-var migrationSchema string-var (systemSchemas = map[string]bool{"information_schema": true,@@ -30,8 +24,7 @@ var (sysAdminRole = "SYSADMIN"accountAdminRole = "ACCOUNTADMIN"- _ db.Driver = (*Driver)(nil)- _ util.MigrationExecutor = (*Driver)(nil)+ _ db.Driver = (*Driver)(nil))func init() {@@ -271,347 +264,6 @@ func (driver *Driver) Query(ctx context.Context, statement string, limit int) ([return util.Query(ctx, driver.db, statement, limit)}-// 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)-}--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-}--// SetupMigrationIfNeeded sets up migration if needed.-func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {- setup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- return nil- }-- if setup {- log.Info("Bytebase migration schema not found, creating schema...",- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- // Should use role SYSADMIN.- if err := driver.Execute(ctx, migrationSchema); err != nil {- log.Error("Failed to initialize migration schema.",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- return util.FormatErrorWithQuery(err, migrationSchema)- }- log.Info("Successfully created migration schema.",- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- }-- 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 >= ?- `- row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,- namespace, largestBaselineSequence,- )- if err != nil {- return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)- }- defer row.Close()-- var version sql.NullString- row.Next()- if err := row.Scan(&version); err != nil {- return nil, err- }-- 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)- }- row, err := tx.QueryContext(ctx, findLargestSequenceQuery,- namespace,- )- if err != nil {- return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)- }- defer row.Close()-- var sequence sql.NullInt32- row.Next()- if err := row.Scan(&sequence); err != nil {- return -1, err- }-- if !sequence.Valid {- // Returns 0 if we haven't applied any migration for this namespace.- return 0, nil- }-- return int(sequence.Int32), 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) (int64, 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()), ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, 0, ?, ?)- `- var insertedID int64- maxIDQuery := "SELECT MAX(id)+1 FROM bytebase.public.migration_history"- rows, err := tx.QueryContext(ctx, maxIDQuery)- if err != nil {- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)- }- defer rows.Close()- var id sql.NullInt64- for rows.Next() {- if err := rows.Scan(- &id,- ); err != nil {- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)- }- }- if err := rows.Err(); err != nil {- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)- }- if id.Valid {- insertedID = id.Int64- } else {- insertedID = 1- }-- _, err = tx.ExecContext(ctx, insertHistoryQuery,- m.Creator,- m.Creator,- m.ReleaseVersion,- m.Namespace,- sequence,- m.Source,- m.Type,- storedVersion,- m.Description,- statement,- prevSchema,- prevSchema,- m.IssueID,- m.Payload,- )- if err != nil {- return int64(0), 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 int64) error {- const updateHistoryAsDoneQuery = `- UPDATE- bytebase.public.migration_history- SET- status = 'DONE',- execution_duration_ns = ?,- schema = ?- WHERE id = ?- `- _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, 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 int64) error {- const updateHistoryAsFailedQuery = `- UPDATE- bytebase.public.migration_history- SET- status = 'FAILED',- execution_duration_ns = ?- WHERE id = ?- `- _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)- return err-}--// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {- if err := driver.useRole(ctx, sysAdminRole); err != nil {- return int64(0), "", err- }- return util.ExecuteMigration(ctx, driver, m, statement, bytebaseDatabase)-}--// FindMigrationHistoryList finds the migration history.-func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {- baseQuery := `- SELECT- 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- FROM bytebase.public.migration_history `- paramNames, params := []string{}, []interface{}{}- if v := find.ID; v != nil {- paramNames, params = append(paramNames, "id"), append(params, *v)- }- if v := find.Database; v != nil {- paramNames, params = append(paramNames, "namespace"), append(params, *v)- }- if v := find.Version; v != nil {- // TODO(d): support semantic versioning.- storedVersion, err := util.ToStoredVersion(false, *v, "")- if err != nil {- return nil, err- }- paramNames, params = append(paramNames, "version"), append(params, storedVersion)- }- if v := find.Source; v != nil {- paramNames, params = append(paramNames, "source"), append(params, *v)- }- var query = baseQuery +- db.FormatParamNameInQuestionMark(paramNames) +- `ORDER BY created_ts DESC`- if v := find.Limit; v != nil {- query += fmt.Sprintf(" LIMIT %d", *v)- }- // TODO(zp): modified param `bytebaseDatabase` of `util.FindMigrationHistoryList` when we support *snowflake* database level.- history, err := util.FindMigrationHistoryList(ctx, query, params, driver, bytebaseDatabase, find, baseQuery)- // TODO(d): remove this block once all existing customers all migrated to semantic versioning.- if err != nil {- if !strings.Contains(err.Error(), "invalid stored version") {- return nil, err- }- if err := driver.updateMigrationHistoryStorageVersion(ctx); err != nil {- return nil, err- }- return util.FindMigrationHistoryList(ctx, query, params, driver, bytebaseDatabase, find, baseQuery)- }- return history, err-}--func (driver *Driver) updateMigrationHistoryStorageVersion(ctx context.Context) error {- sqldb, err := driver.GetDbConnection(ctx, "bytebase")- if err != nil {- return err- }- query := `SELECT id, version FROM bytebase.public.migration_history`- rows, err := sqldb.Query(query)- if err != nil {- return err- }- type ver struct {- id int- version string- }- var vers []ver- for rows.Next() {- var v ver- if err := rows.Scan(&v.id, &v.version); err != nil {- return err- }- vers = append(vers, v)- }- if err := rows.Close(); err != nil {- return err- }-- updateQuery := `- UPDATE- bytebase.public.migration_history- SET- version = ?- WHERE id = ? AND version = ?- `- for _, v := range vers {- if strings.HasPrefix(v.version, util.NonSemanticPrefix) {- continue- }- newVersion := fmt.Sprintf("%s%s", util.NonSemanticPrefix, v.version)- if _, err := sqldb.Exec(updateQuery, newVersion, v.id, v.version); err != nil {- return err- }- }- return nil-}-// Dump and restoreconst (databaseHeaderFmt = "" +diff --git a/plugin/db/sqlite/migrate.go b/plugin/db/sqlite/migrate.gonew file mode 100644index 0000000000..74efc2608d--- /dev/null+++ b/plugin/db/sqlite/migrate.go@@ -0,0 +1,281 @@+package sqlite++import (+ "context"+ "database/sql"+ "fmt"++ // embed will embeds the migration schema.+ _ "embed"++ "github.com/bytebase/bytebase/common/log"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/bytebase/bytebase/plugin/db/util"+ "go.uber.org/zap"+)++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 nil+ }++ if setup {+ log.Info("Bytebase migration schema not found, creating schema...",+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )++ if _, err := driver.GetDbConnection(ctx, bytebaseDatabase); err != nil {+ log.Error("Failed to switch to bytebase database.",+ zap.Error(err),+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ return fmt.Errorf("failed to switch to bytebase database error: %v", err)+ }++ if _, err := driver.db.ExecContext(ctx, migrationSchema); err != nil {+ log.Error("Failed to initialize migration schema.",+ zap.Error(err),+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ return util.FormatErrorWithQuery(err, migrationSchema)+ }+ log.Info("Successfully created migration schema.",+ zap.String("environment", driver.connectionCtx.EnvironmentName),+ zap.String("database", driver.connectionCtx.InstanceName),+ )+ }++ 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 >= ?+ `+ row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,+ namespace, largestBaselineSequence,+ )+ if err != nil {+ return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)+ }+ defer row.Close()++ var version sql.NullString+ row.Next()+ if err := row.Scan(&version); err != nil {+ return nil, err+ }++ 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)+ }+ row, err := tx.QueryContext(ctx, findLargestSequenceQuery,+ namespace,+ )+ if err != nil {+ return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)+ }+ defer row.Close()++ var sequence sql.NullInt32+ row.Next()+ if err := row.Scan(&sequence); err != nil {+ return -1, err+ }++ if !sequence.Valid {+ // Returns 0 if we haven't applied any migration for this namespace.+ return 0, nil+ }++ return int(sequence.Int32), 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) (int64, 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'), ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, 0, ?, ?)+ `+ res, err := tx.ExecContext(ctx, insertHistoryQuery,+ m.Creator,+ m.Creator,+ m.ReleaseVersion,+ m.Namespace,+ sequence,+ m.Source,+ m.Type,+ storedVersion,+ m.Description,+ statement,+ prevSchema,+ prevSchema,+ m.IssueID,+ m.Payload,+ )+ if err != nil {+ return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)+ }++ insertedID, err := res.LastInsertId()+ if err != nil {+ return int64(0), 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 int64) error {+ const updateHistoryAsDoneQuery = `+ UPDATE+ bytebase_migration_history+ SET+ status = 'DONE',+ execution_duration_ns = ?,+ schema = ?+ WHERE id = ?+ `+ _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, 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 int64) error {+ const updateHistoryAsFailedQuery = `+ UPDATE+ bytebase_migration_history+ SET+ status = 'FAILED',+ execution_duration_ns = ?+ WHERE id = ?+ `+ _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)+ return err+}++// ExecuteMigration will execute the migration.+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {+ return util.ExecuteMigration(ctx, driver, m, statement, bytebaseDatabase)+}++// FindMigrationHistoryList finds the migration history.+func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {+ baseQuery := `+ SELECT+ 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+ FROM bytebase_migration_history `+ paramNames, params := []string{}, []interface{}{}+ if v := find.ID; v != nil {+ paramNames, params = append(paramNames, "id"), append(params, *v)+ }+ if v := find.Database; v != nil {+ paramNames, params = append(paramNames, "namespace"), append(params, *v)+ }+ if v := find.Version; v != nil {+ // TODO(d): support semantic versioning.+ storedVersion, err := util.ToStoredVersion(false, *v, "")+ if err != nil {+ return nil, err+ }+ paramNames, params = append(paramNames, "version"), append(params, storedVersion)+ }+ if v := find.Source; v != nil {+ paramNames, params = append(paramNames, "source"), append(params, *v)+ }+ var query = baseQuery ++ db.FormatParamNameInQuestionMark(paramNames) ++ `ORDER BY created_ts DESC`+ if v := find.Limit; v != nil {+ query += fmt.Sprintf(" LIMIT %d", *v)+ }+ return util.FindMigrationHistoryList(ctx, query, params, driver, bytebaseDatabase, find, baseQuery)+}diff --git a/plugin/db/sqlite/sqlite.go b/plugin/db/sqlite/sqlite.goindex 39cb79c304..a63f1c7005 100644--- a/plugin/db/sqlite/sqlite.go+++ b/plugin/db/sqlite/sqlite.go@@ -10,21 +10,13 @@ import ("path""strings"- // embed will embeds the migration schema.- _ "embed"-// Import sqlite3 driver._ "github.com/mattn/go-sqlite3"- "github.com/bytebase/bytebase/common/log""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/db/util"- "go.uber.org/zap")-//go:embed sqlite_migration_schema.sql-var migrationSchema string-var (bytebaseDatabase = "bytebase"excludedDatabaseList = map[string]bool{@@ -32,8 +24,7 @@ var (bytebaseDatabase: true,}- _ db.Driver = (*Driver)(nil)- _ util.MigrationExecutor = (*Driver)(nil)+ _ db.Driver = (*Driver)(nil))func init() {@@ -191,265 +182,6 @@ func (driver *Driver) Query(ctx context.Context, statement string, limit int) ([return util.Query(ctx, driver.db, statement, limit)}-// 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 nil- }-- if setup {- log.Info("Bytebase migration schema not found, creating schema...",- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )-- if _, err := driver.GetDbConnection(ctx, bytebaseDatabase); err != nil {- log.Error("Failed to switch to bytebase database.",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- return fmt.Errorf("failed to switch to bytebase database error: %v", err)- }-- if _, err := driver.db.ExecContext(ctx, migrationSchema); err != nil {- log.Error("Failed to initialize migration schema.",- zap.Error(err),- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- return util.FormatErrorWithQuery(err, migrationSchema)- }- log.Info("Successfully created migration schema.",- zap.String("environment", driver.connectionCtx.EnvironmentName),- zap.String("database", driver.connectionCtx.InstanceName),- )- }-- 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 >= ?- `- row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,- namespace, largestBaselineSequence,- )- if err != nil {- return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)- }- defer row.Close()-- var version sql.NullString- row.Next()- if err := row.Scan(&version); err != nil {- return nil, err- }-- 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)- }- row, err := tx.QueryContext(ctx, findLargestSequenceQuery,- namespace,- )- if err != nil {- return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)- }- defer row.Close()-- var sequence sql.NullInt32- row.Next()- if err := row.Scan(&sequence); err != nil {- return -1, err- }-- if !sequence.Valid {- // Returns 0 if we haven't applied any migration for this namespace.- return 0, nil- }-- return int(sequence.Int32), 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) (int64, 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'), ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, 0, ?, ?)- `- res, err := tx.ExecContext(ctx, insertHistoryQuery,- m.Creator,- m.Creator,- m.ReleaseVersion,- m.Namespace,- sequence,- m.Source,- m.Type,- storedVersion,- m.Description,- statement,- prevSchema,- prevSchema,- m.IssueID,- m.Payload,- )- if err != nil {- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)- }-- insertedID, err := res.LastInsertId()- if err != nil {- return int64(0), 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 int64) error {- const updateHistoryAsDoneQuery = `- UPDATE- bytebase_migration_history- SET- status = 'DONE',- execution_duration_ns = ?,- schema = ?- WHERE id = ?- `- _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, 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 int64) error {- const updateHistoryAsFailedQuery = `- UPDATE- bytebase_migration_history- SET- status = 'FAILED',- execution_duration_ns = ?- WHERE id = ?- `- _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)- return err-}--// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {- return util.ExecuteMigration(ctx, driver, m, statement, bytebaseDatabase)-}--// FindMigrationHistoryList finds the migration history.-func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {- baseQuery := `- SELECT- 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- FROM bytebase_migration_history `- paramNames, params := []string{}, []interface{}{}- if v := find.ID; v != nil {- paramNames, params = append(paramNames, "id"), append(params, *v)- }- if v := find.Database; v != nil {- paramNames, params = append(paramNames, "namespace"), append(params, *v)- }- if v := find.Version; v != nil {- // TODO(d): support semantic versioning.- storedVersion, err := util.ToStoredVersion(false, *v, "")- if err != nil {- return nil, err- }- paramNames, params = append(paramNames, "version"), append(params, storedVersion)- }- if v := find.Source; v != nil {- paramNames, params = append(paramNames, "source"), append(params, *v)- }- var query = baseQuery +- db.FormatParamNameInQuestionMark(paramNames) +- `ORDER BY created_ts DESC`- if v := find.Limit; v != nil {- query += fmt.Sprintf(" LIMIT %d", *v)- }- return util.FindMigrationHistoryList(ctx, query, params, driver, bytebaseDatabase, find, baseQuery)-}-// Dump dumps the database.func (driver *Driver) Dump(ctx context.Context, database string, out io.Writer, schemaOnly bool) (string, error) {if database == "" {