Skip to content

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

pg: move shared functions to util package.

spinningbot750decdbb83b
diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.go
index e55bf8b8bc..2bb5ec167f 100644
--- a/plugin/db/mysql/mysql.go
+++ b/plugin/db/mysql/mysql.go
@@ -9,7 +9,6 @@ import (
"io"
"strings"
- "github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/db/util"
"github.com/go-sql-driver/mysql"
@@ -518,13 +517,10 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,
`
args := util.MigrationExecutionArgs{
- CheckDuplicateVersion: checkDuplicateVersion,
- CheckOutofOrderVersion: checkOutofOrderVersion,
- FindBaseline: findBaseline,
- FindNextSequence: findNextSequence,
- DumpTxn: dumpTxn,
- InsertHistoryQuery: insertHistoryQuery,
- UpdateHistoryQuery: updateHistoryQuery,
+ DumpTxn: dumpTxn,
+ InsertHistoryQuery: insertHistoryQuery,
+ UpdateHistoryQuery: updateHistoryQuery,
+ TablePrefix: "bytebase.",
}
return util.ExecuteMigration(ctx, driver.db, m, statement, args)
}
@@ -618,121 +614,6 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Mig
return list, nil
}
-func findBaseline(ctx context.Context, tx *sql.Tx, namespace string) (bool, error) {
- query := `
- SELECT 1 FROM bytebase.migration_history WHERE namespace = ? AND ` + "`type` = 'BASELINE'" + `
- `
- args := []interface{}{namespace}
- row, err := tx.QueryContext(ctx, query,
- args...,
- )
-
- if err != nil {
- return false, util.FormatErrorWithQuery(err, query)
- }
- defer row.Close()
-
- if !row.Next() {
- return false, nil
- }
-
- return true, nil
-}
-
-func checkDuplicateVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (bool, error) {
- query := `
- SELECT 1 FROM bytebase.migration_history WHERE namespace = ? AND ` + "`engine` = ? AND version = ?" + `
- `
- args := []interface{}{namespace, engine.String(), version}
- row, err := tx.QueryContext(ctx, query,
- args...,
- )
-
- if err != nil {
- return false, util.FormatErrorWithQuery(err, query)
- }
- defer row.Close()
-
- if row.Next() {
- return true, nil
- }
- return false, nil
-}
-
-func checkOutofOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (*string, error) {
- query := `
- SELECT MIN(version) FROM bytebase.migration_history WHERE namespace = ? AND ` + "`engine` = ? AND STRCMP(?, version) = -1" + `
- `
- args := []interface{}{namespace, engine.String(), version}
- row, err := tx.QueryContext(ctx, query,
- args...,
- )
-
- if err != nil {
- return nil, util.FormatErrorWithQuery(err, query)
- }
- defer row.Close()
-
- var minVersion sql.NullString
- row.Next()
- if err := row.Scan(&minVersion); err != nil {
- return nil, err
- }
-
- if minVersion.Valid {
- return &minVersion.String, nil
- }
-
- return nil, nil
-}
-
-func findNextSequence(ctx context.Context, tx *sql.Tx, namespace string, requireBaseline bool) (int, error) {
- query := `
- SELECT MAX(sequence) + 1 FROM bytebase.migration_history WHERE namespace = ?
- `
- args := []interface{}{namespace}
- row, err := tx.QueryContext(ctx, query,
- args...,
- )
-
- if err != nil {
- return -1, util.FormatErrorWithQuery(err, query)
- }
- defer row.Close()
-
- var sequence sql.NullInt32
- row.Next()
- if err := row.Scan(&sequence); err != nil {
- return -1, err
- }
-
- if !sequence.Valid {
- // Returns 1 if we haven't applied any migration for this namespace and doesn't require baselining
- if !requireBaseline {
- return 1, nil
- }
-
- // This should not happen normally since we already check the baselining exist beforehand. Just in case.
- return -1, common.Errorf(common.MigrationBaselineMissing, fmt.Errorf("unable to generate next migration_sequence, no migration hisotry found for %q, do you forget to baselining?", namespace))
- }
-
- return int(sequence.Int32), nil
-}
-
-func formatError(err error) error {
- if err == nil {
- return nil
- }
-
- if strings.Contains(err.Error(), "bytebase_idx_unique_migration_history_namespace_version") {
- return fmt.Errorf("version has already been applied")
- } else if strings.Contains(err.Error(), "bytebase_idx_unique_migration_history_namespace_sequence") {
- return fmt.Errorf("concurrent migration")
- }
-
- return err
-}
-
// Dump and restore
const (
databaseHeaderFmt = "" +
diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.go
index 8efee4ebc0..3260ac1ee0 100644
--- a/plugin/db/pg/pg.go
+++ b/plugin/db/pg/pg.go
@@ -408,7 +408,43 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {
}
func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, error) {
- return "", fmt.Errorf("not implemented")
+ insertHistoryQuery := `
+ INSERT INTO migration_history (
+ created_by,
+ created_ts,
+ updated_by,
+ updated_ts,
+ namespace,
+ sequence,
+ ` + "`engine`," + `
+ ` + "`type`," + `
+ ` + "`status`," + `
+ version,
+ description,
+ statement,
+ ` + "`schema`," + `
+ execution_duration,
+ issue_id,
+ payload
+ )
+ VALUES (?, EXTRACT(epoch from NOW()), ?, EXTRACT(epoch from NOW()), ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, 0, ?, ?)
+`
+ updateHistoryQuery := `
+ UPDATE migration_history SET
+ ` + "`status` = 'DONE'," + `
+ ` + "execution_duration = ?," + `
+ ` + "`schema` = ?" + `
+ WHERE id = ?
+ `
+
+ args := util.MigrationExecutionArgs{
+ // TODO(spinningbot): implement dumpTxn.
+ // DumpTxn: dumpTxn,
+ InsertHistoryQuery: insertHistoryQuery,
+ UpdateHistoryQuery: updateHistoryQuery,
+ TablePrefix: "",
+ }
+ return util.ExecuteMigration(ctx, driver.db, m, statement, args)
}
func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {
diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.go
index 8b96a8def3..9aa4ce313e 100644
--- a/plugin/db/util/driverutil.go
+++ b/plugin/db/util/driverutil.go
@@ -35,13 +35,10 @@ func NeedsSetupMigrationSchema(ctx context.Context, sqldb *sql.DB, query string)
// MigrationExecutionArgs includes the arguments for ExecuteMigration().
type MigrationExecutionArgs struct {
- CheckDuplicateVersion func(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (bool, error)
- CheckOutofOrderVersion func(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (*string, error)
- FindBaseline func(ctx context.Context, tx *sql.Tx, namespace string) (bool, error)
- FindNextSequence func(ctx context.Context, tx *sql.Tx, namespace string, requireBaseline bool) (int, error)
- DumpTxn func(ctx context.Context, txn *sql.Tx, database string, out io.Writer, schemaOnly bool) error
- InsertHistoryQuery string
- UpdateHistoryQuery string
+ DumpTxn func(ctx context.Context, txn *sql.Tx, database string, out io.Writer, schemaOnly bool) error
+ InsertHistoryQuery string
+ UpdateHistoryQuery string
+ TablePrefix string
}
// ExecuteMigration will execute the database migration.
@@ -54,7 +51,7 @@ func ExecuteMigration(ctx context.Context, sqldb *sql.DB, m *db.MigrationInfo, s
// Phase 1 - Precheck before executing migration
// Check if the same migration version has alraedy been applied
- duplicate, err := args.CheckDuplicateVersion(ctx, tx, m.Namespace, m.Engine, m.Version)
+ duplicate, err := checkDuplicateVersion(ctx, tx, m.Namespace, m.Engine, m.Version, args.TablePrefix)
if err != nil {
return "", err
}
@@ -63,7 +60,7 @@ func ExecuteMigration(ctx context.Context, sqldb *sql.DB, m *db.MigrationInfo, s
}
// Check if there is any higher version already been applied
- version, err := args.CheckOutofOrderVersion(ctx, tx, m.Namespace, m.Engine, m.Version)
+ version, err := checkOutofOrderVersion(ctx, tx, m.Namespace, m.Engine, m.Version, args.TablePrefix)
if err != nil {
return "", err
}
@@ -74,7 +71,7 @@ func ExecuteMigration(ctx context.Context, sqldb *sql.DB, m *db.MigrationInfo, s
// If the migration engine is VCS and type is not baseline and is not branch, then we can only proceed if there is existing baseline
// This check is also wrapped in transaction to avoid edge case where two baselinings are running concurrently.
if m.Engine == db.VCS && m.Type != db.Baseline && m.Type != db.Branch {
- hasBaseline, err := args.FindBaseline(ctx, tx, m.Namespace)
+ hasBaseline, err := findBaseline(ctx, tx, m.Namespace, args.TablePrefix)
if err != nil {
return "", err
}
@@ -86,7 +83,7 @@ func ExecuteMigration(ctx context.Context, sqldb *sql.DB, m *db.MigrationInfo, s
// VCS based SQL migration requires existing baselining
requireBaseline := m.Engine == db.VCS && m.Type == db.Migrate
- sequence, err := args.FindNextSequence(ctx, tx, m.Namespace, requireBaseline)
+ sequence, err := findNextSequence(ctx, tx, m.Namespace, requireBaseline, args.TablePrefix)
if err != nil {
return "", err
}
@@ -173,6 +170,115 @@ func ExecuteMigration(ctx context.Context, sqldb *sql.DB, m *db.MigrationInfo, s
return afterSchemaBuf.String(), nil
}
+func findBaseline(ctx context.Context, tx *sql.Tx, namespace, tablePrefix string) (bool, error) {
+ query := `
+ SELECT 1 FROM ` +
+ tablePrefix + `migration_history ` +
+ `WHERE namespace = ? AND ` + "`type` = 'BASELINE'" + `
+ `
+ args := []interface{}{namespace}
+ row, err := tx.QueryContext(ctx, query,
+ args...,
+ )
+
+ if err != nil {
+ return false, FormatErrorWithQuery(err, query)
+ }
+ defer row.Close()
+
+ if !row.Next() {
+ return false, nil
+ }
+
+ return true, nil
+}
+
+func checkDuplicateVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version, tablePrefix string) (bool, error) {
+ query := `
+ SELECT 1 FROM ` +
+ tablePrefix + `migration_history ` +
+ `WHERE namespace = ? AND ` + "`engine` = ? AND version = ?" + `
+ `
+ args := []interface{}{namespace, engine.String(), version}
+ row, err := tx.QueryContext(ctx, query,
+ args...,
+ )
+
+ if err != nil {
+ return false, FormatErrorWithQuery(err, query)
+ }
+ defer row.Close()
+
+ if row.Next() {
+ return true, nil
+ }
+ return false, nil
+}
+
+func checkOutofOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version, tablePrefix string) (*string, error) {
+ query := `
+ SELECT MIN(version) FROM ` +
+ tablePrefix + `migration_history ` +
+ `WHERE namespace = ? AND ` + "`engine` = ? AND STRCMP(?, version) = -1" + `
+ `
+ args := []interface{}{namespace, engine.String(), version}
+ row, err := tx.QueryContext(ctx, query,
+ args...,
+ )
+
+ if err != nil {
+ return nil, FormatErrorWithQuery(err, query)
+ }
+ defer row.Close()
+
+ var minVersion sql.NullString
+ row.Next()
+ if err := row.Scan(&minVersion); err != nil {
+ return nil, err
+ }
+
+ if minVersion.Valid {
+ return &minVersion.String, nil
+ }
+
+ return nil, nil
+}
+
+func findNextSequence(ctx context.Context, tx *sql.Tx, namespace string, requireBaseline bool, tablePrefix string) (int, error) {
+ query := `
+ SELECT MAX(sequence) + 1 FROM ` +
+ tablePrefix + `migration_history ` +
+ `WHERE namespace = ?
+ `
+ args := []interface{}{namespace}
+ row, err := tx.QueryContext(ctx, query,
+ args...,
+ )
+
+ if err != nil {
+ return -1, FormatErrorWithQuery(err, query)
+ }
+ defer row.Close()
+
+ var sequence sql.NullInt32
+ row.Next()
+ if err := row.Scan(&sequence); err != nil {
+ return -1, err
+ }
+
+ if !sequence.Valid {
+ // Returns 1 if we haven't applied any migration for this namespace and doesn't require baselining
+ if !requireBaseline {
+ return 1, nil
+ }
+
+ // This should not happen normally since we already check the baselining exist beforehand. Just in case.
+ return -1, common.Errorf(common.MigrationBaselineMissing, fmt.Errorf("unable to generate next migration_sequence, no migration hisotry found for %q, do you forget to baselining?", namespace))
+ }
+
+ return int(sequence.Int32), nil
+}
+
func formatError(err error) error {
if err == nil {
return nil