Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support `-pg` option (#1164)
h3n4l82e567ca06dc
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.goindex 7a4e6dc279..9490c59971 100644--- a/bin/server/cmd/root.go+++ b/bin/server/cmd/root.go@@ -132,7 +132,7 @@ func init() {// TODO(tianzhou): this needs more bake time. There are couple blocking issues:// 1. Currently, we will create a separate bytebase database to store the migration_history table, we need to put it inside the specified database here.// 2. We need to move the logic of creating bytebase metadata db logic outside. Because with --pg option, the db has already been created.- // rootCmd.PersistentFlags().StringVar(&pgURL, "pg", "", "optional external PostgreSQL instance connection url; for example postgresql://user:secret@masterhost:5432/dbname?sslrootcert=cert")+ rootCmd.PersistentFlags().StringVar(&pgURL, "pg", "", "optional external PostgreSQL instance connection url(must provide dbname); for example postgresql://user:secret@masterhost:5432/dbname?sslrootcert=cert")}// -----------------------------------Command Line Config END--------------------------------------@@ -367,7 +367,9 @@ func (m *Main) newExternalDB() (*store.DB, error) {return nil, fmt.Errorf("invalid connection protocol: %s", u.Scheme)}- connCfg := dbdriver.ConnectionConfig{}+ connCfg := dbdriver.ConnectionConfig{+ StrictUseDb: true,+ }if u.User != nil {connCfg.Username = u.User.Username()@@ -387,9 +389,11 @@ func (m *Main) newExternalDB() (*store.DB, error) {// By default, follow the PG convention to use user name as the database nameconnCfg.Database = connCfg.Username- if u.Path != "" {- connCfg.Database = u.Path[1:]++ if u.Path == "" {+ return nil, fmt.Errorf("missing database in the --pg connection string")}+ connCfg.Database = u.Path[1:]q := u.Query()connCfg.TLSConfig = dbdriver.TLSConfig{@@ -410,10 +414,11 @@ func (m *Main) newEmbeddedDB() (*store.DB, error) {// Even when Postgres opens Unix domain socket only for connection, it still requires a port as ID to differentiate different Postgres instances.connCfg := dbdriver.ConnectionConfig{- Username: m.profile.pgUser,- Password: "",- Host: common.GetPostgresSocketDir(),- Port: fmt.Sprintf("%d", m.profile.datastorePort),+ Username: m.profile.pgUser,+ Password: "",+ Host: common.GetPostgresSocketDir(),+ Port: fmt.Sprintf("%d", m.profile.datastorePort),+ StrictUseDb: false,}db := store.NewDB(m.l, connCfg, m.profile.demoDataDir, readonly, version, m.profile.mode)return db, nildiff --git a/plugin/db/clickhouse/clickhouse.go b/plugin/db/clickhouse/clickhouse.goindex 138410c3ed..36870756fd 100644--- a/plugin/db/clickhouse/clickhouse.go+++ b/plugin/db/clickhouse/clickhouse.go@@ -572,7 +572,7 @@ func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDu// 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.l, driver, m, statement)+ return util.ExecuteMigration(ctx, driver.l, driver, m, statement, db.BytebaseDatabase)}// FindMigrationHistoryList finds the migration history.@@ -623,7 +623,8 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migif v := find.Limit; v != nil {query += fmt.Sprintf(" LIMIT %d", *v)}- history, err := util.FindMigrationHistoryList(ctx, query, params, driver, find, baseQuery)+ // 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") {@@ -632,7 +633,7 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migif err := driver.updateMigrationHistoryStorageVersion(ctx); err != nil {return nil, err}- return util.FindMigrationHistoryList(ctx, query, params, driver, find, baseQuery)+ return util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase, find, baseQuery)}return history, err}diff --git a/plugin/db/driver.go b/plugin/db/driver.goindex 739fc5e4a9..e0660844da 100644--- a/plugin/db/driver.go+++ b/plugin/db/driver.go@@ -30,6 +30,8 @@ const (SQLite Type = "SQLITE"// TiDB is the database type for TiDB.TiDB Type = "TIDB"++ BytebaseDatabase = "bytebase")// User is the database user.@@ -51,7 +53,7 @@ type View struct {// Index is the database index.type Index struct {Name string- // This could refer to a column or an expression+ // This could refer to a column or an expression.Expression stringPosition int// Type isn't supported for SQLite.@@ -373,6 +375,8 @@ type ConnectionConfig struct {TLSConfig TLSConfig// ReadOnly is only supported for Postgres at the moment.ReadOnly bool+ // StrictUseDb will only set as true if the user gives only a database instead of a whole instance to access.+ StrictUseDb bool}// ConnectionContext is the context for connection.diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex 1d7f5577a6..15b380b385 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -728,7 +728,7 @@ func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDu// 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.l, driver, m, statement)+ return util.ExecuteMigration(ctx, driver.l, driver, m, statement, db.BytebaseDatabase)}// FindMigrationHistoryList finds the migration history.@@ -779,7 +779,8 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migif v := find.Limit; v != nil {query += fmt.Sprintf(" LIMIT %d", *v)}- history, err := util.FindMigrationHistoryList(ctx, query, params, driver, find, baseQuery)+ // 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") {@@ -788,13 +789,13 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migif err := driver.updateMigrationHistoryStorageVersion(ctx); err != nil {return nil, err}- return util.FindMigrationHistoryList(ctx, query, params, driver, find, baseQuery)+ 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")+ sqldb, err := driver.GetDbConnection(ctx, db.BytebaseDatabase)if err != nil {return err}diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.goindex 6c0ab3ec62..e59fd8e369 100644--- a/plugin/db/pg/pg.go+++ b/plugin/db/pg/pg.go@@ -38,7 +38,6 @@ var ("-- PostgreSQL database structure for %s\n" +"--\n"useDatabaseFmt = "\\connect %s;\n\n"- bytebaseDatabase = "bytebase"createBytebaseDatabaseStmt = "CREATE DATABASE bytebase;"// driverName is the driver name that our driver dependence register, now is "pgx".@@ -59,6 +58,9 @@ type Driver struct {db *sql.DBbaseDSN string++ // strictDatabase should be used only if the user gives only a database instead of a whole instance to access.+ strictDatabase string}func newDriver(config db.DriverConfig) db.Driver {@@ -92,6 +94,9 @@ func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.Connec}driver.baseDSN = dsndriver.connectionCtx = connCtx+ if config.StrictUseDb {+ driver.strictDatabase = config.Database+ }db, err := sql.Open(driverName, dsn)if err != nil {@@ -176,7 +181,7 @@ func (driver *Driver) GetDbConnection(ctx context.Context, database string) (*sqreturn driver.db, nil}-// GetVersion gets the version.+// GetVersion gets the version of Postgres server.func (driver *Driver) GetVersion(ctx context.Context) (string, error) {query := "SHOW server_version"versionRow, err := driver.db.QueryContext(ctx, query)@@ -418,15 +423,18 @@ func (driver *Driver) Query(ctx context.Context, statement string, limit int) ([// 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- }- if err := driver.switchDatabase(bytebaseDatabase); err != nil {- return false, err+ // 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 = `@@ -435,6 +443,7 @@ func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {FROM information_schema.tablesWHERE table_name = 'migration_history'`+return util.NeedsSetupMigrationSchema(ctx, driver.db, query)}@@ -445,7 +454,7 @@ func (driver *Driver) hasBytebaseDatabase(ctx context.Context) (bool, error) {}exist := falsefor _, database := range databases {- if database.name == bytebaseDatabase {+ if database.name == db.BytebaseDatabase {exist = truebreak}@@ -466,36 +475,41 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {zap.String("database", driver.connectionCtx.InstanceName),)- exist, err := driver.hasBytebaseDatabase(ctx)- if err != nil {- driver.l.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 {- if _, err := driver.db.ExecContext(ctx, createBytebaseDatabaseStmt); err != nil {- driver.l.Error("Failed to create bytebase database.",+ // Only try to create `bytebase` db when user provide an instance+ if !driver.strictUseDb() {+ exist, err := driver.hasBytebaseDatabase(ctx)+ if err != nil {+ driver.l.Error("Failed to find bytebase database.",zap.Error(err),zap.String("environment", driver.connectionCtx.EnvironmentName),zap.String("database", driver.connectionCtx.InstanceName),)- return util.FormatErrorWithQuery(err, createBytebaseDatabaseStmt)+ return fmt.Errorf("failed to find bytebase database error: %v", err)}- }- if err := driver.switchDatabase(bytebaseDatabase); err != nil {- driver.l.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 !exist {+ // Create `bytebase` database+ if _, err := driver.db.ExecContext(ctx, createBytebaseDatabaseStmt); err != nil {+ driver.l.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 {+ driver.l.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` tableif _, err := driver.db.ExecContext(ctx, migrationSchema); err != nil {driver.l.Error("Failed to initialize migration schema.",zap.Error(err),@@ -653,7 +667,10 @@ func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDu// 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.l, driver, m, statement)+ if driver.strictUseDb() {+ return util.ExecuteMigration(ctx, driver.l, driver, m, statement, driver.strictDatabase)+ }+ return util.ExecuteMigration(ctx, driver.l, driver, m, statement, db.BytebaseDatabase)}// FindMigrationHistoryList finds the migration history.@@ -704,7 +721,12 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migif v := find.Limit; v != nil {query += fmt.Sprintf(" LIMIT %d", *v)}- history, err := util.FindMigrationHistoryList(ctx, query, params, driver, find, baseQuery)++ 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")@@ -715,16 +737,21 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migif err := driver.updateMigrationHistoryStorageVersion(ctx); err != nil {return nil, err}- return util.FindMigrationHistoryList(ctx, query, params, driver, find, baseQuery)+ 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")+ 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 {@@ -1005,6 +1032,10 @@ func (driver *Driver) getDatabases() ([]*pgDatabaseSchema, error) {return dbs, nil}+func (driver *Driver) strictUseDb() bool {+ return len(driver.strictDatabase) != 0+}+// pgDatabaseSchema describes a pg database schema.type pgDatabaseSchema struct {name stringdiff --git a/plugin/db/pg/pg_migration_schema.sql b/plugin/db/pg/pg_migration_schema.sqlindex 566a6f3d51..69c579ce00 100644--- a/plugin/db/pg/pg_migration_schema.sql+++ b/plugin/db/pg/pg_migration_schema.sql@@ -12,7 +12,7 @@ CREATE TABLE migration_history (updated_by TEXT NOT NULL,updated_ts BIGINT NOT NULL,-- Record the client version creating this migration history. For Bytebase, we use its binary release version. Different Bytebase release might- -- record different history info and thie field helps to handle such situation properly. Moreover, it helps debugging.+ -- record different history info and this field helps to handle such situation properly. Moreover, it helps debugging.release_version TEXT NOT NULL,-- Allows granular tracking of migration history (e.g If an application manages schemas for a multi-tenant service and each tenant has its own schema, that application can use namespace to record the tenant name to track the per-tenant schema migration)-- Since bytebase also manages different application databases from an instance, it leverages this field to track each database migration history.diff --git a/plugin/db/snowflake/snowflake.go b/plugin/db/snowflake/snowflake.goindex 79bf6d125f..ff243d6b54 100644--- a/plugin/db/snowflake/snowflake.go+++ b/plugin/db/snowflake/snowflake.go@@ -748,7 +748,7 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,if err := driver.useRole(ctx, sysAdminRole); err != nil {return int64(0), "", err}- return util.ExecuteMigration(ctx, driver.l, driver, m, statement)+ return util.ExecuteMigration(ctx, driver.l, driver, m, statement, bytebaseDatabase)}// FindMigrationHistoryList finds the migration history.@@ -799,7 +799,8 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migif v := find.Limit; v != nil {query += fmt.Sprintf(" LIMIT %d", *v)}- history, err := util.FindMigrationHistoryList(ctx, query, params, driver, find, baseQuery)+ // 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") {@@ -808,7 +809,7 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migif err := driver.updateMigrationHistoryStorageVersion(ctx); err != nil {return nil, err}- return util.FindMigrationHistoryList(ctx, query, params, driver, find, baseQuery)+ return util.FindMigrationHistoryList(ctx, query, params, driver, bytebaseDatabase, find, baseQuery)}return history, err}diff --git a/plugin/db/sqlite/sqlite.go b/plugin/db/sqlite/sqlite.goindex f4e7cdeca9..8e1e48b315 100644--- a/plugin/db/sqlite/sqlite.go+++ b/plugin/db/sqlite/sqlite.go@@ -577,7 +577,7 @@ func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDu// 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.l, driver, m, statement)+ return util.ExecuteMigration(ctx, driver.l, driver, m, statement, bytebaseDatabase)}// FindMigrationHistoryList finds the migration history.@@ -628,7 +628,7 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migif v := find.Limit; v != nil {query += fmt.Sprintf(" LIMIT %d", *v)}- return util.FindMigrationHistoryList(ctx, query, params, driver, find, baseQuery)+ return util.FindMigrationHistoryList(ctx, query, params, driver, bytebaseDatabase, find, baseQuery)}// Dump dumps the database.diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.goindex 1c9a416f2f..4e85dc6320 100644--- a/plugin/db/util/driverutil.go+++ b/plugin/db/util/driverutil.go@@ -16,10 +16,6 @@ import ("go.uber.org/zap")-const (- bytebaseDatabase = "bytebase"-)-// FormatErrorWithQuery will format the error with failed query.func FormatErrorWithQuery(err error, query string) error {return common.Errorf(common.DbExecutionError, fmt.Errorf("failed to execute error: %w\n\nquery:\n%q", err, query))@@ -129,7 +125,7 @@ type MigrationExecutor interface {// ExecuteMigration will execute the database migration.// Returns the created migraiton history id and the updated schema on success.-func ExecuteMigration(ctx context.Context, l *zap.Logger, executor MigrationExecutor, m *db.MigrationInfo, statement string) (migrationHistoryID int64, updatedSchema string, resErr error) {+func ExecuteMigration(ctx context.Context, l *zap.Logger, executor MigrationExecutor, m *db.MigrationInfo, statement string, databaseName string) (migrationHistoryID int64, updatedSchema string, resErr error) {var prevSchemaBuf bytes.Buffer// Don't record schema if the database hasn't exist yet.if !m.CreateDatabase {@@ -142,7 +138,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, executor MigrationExec// Phase 1 - Precheck before executing migration// Phase 2 - Record migration history as PENDING- insertedID, err := beginMigration(ctx, executor, m, prevSchemaBuf.String(), statement)+ insertedID, err := beginMigration(ctx, executor, m, prevSchemaBuf.String(), statement, databaseName)if err != nil {return -1, "", err}@@ -150,7 +146,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, executor MigrationExecstartedNs := time.Now().UnixNano()defer func() {- if err := endMigration(ctx, l, executor, startedNs, insertedID, updatedSchema, resErr == nil /*isDone*/); err != nil {+ if err := endMigration(ctx, l, executor, startedNs, insertedID, updatedSchema, databaseName, resErr == nil /*isDone*/); err != nil {l.Error("Failed to update migration history record",zap.Error(err),zap.Int64("migration_id", migrationHistoryID),@@ -184,7 +180,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, executor MigrationExec}// beginMigration checks before executing migration and inserts a migration history record with pending status.-func beginMigration(ctx context.Context, executor MigrationExecutor, m *db.MigrationInfo, prevSchema string, statement string) (insertedID int64, err error) {+func beginMigration(ctx context.Context, executor MigrationExecutor, m *db.MigrationInfo, prevSchema string, statement string, databaseName string) (insertedID int64, err error) {// Convert verion to stored version.storedVersion, err := ToStoredVersion(m.UseSemanticVersion, m.Version, m.SemanticVersionSuffix)if err != nil {@@ -211,7 +207,7 @@ func beginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migra}}- sqldb, err := executor.GetDbConnection(ctx, bytebaseDatabase)+ sqldb, err := executor.GetDbConnection(ctx, databaseName)if err != nil {return -1, err}@@ -251,10 +247,10 @@ func beginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migra}// endMigration updates the migration history record to DONE or FAILED depending on migration is done or not.-func endMigration(ctx context.Context, l *zap.Logger, executor MigrationExecutor, startedNs int64, migrationHistoryID int64, updatedSchema string, isDone bool) (err error) {+func endMigration(ctx context.Context, l *zap.Logger, executor MigrationExecutor, startedNs int64, migrationHistoryID int64, updatedSchema string, databaseName string, isDone bool) (err error) {migrationDurationNs := time.Now().UnixNano() - startedNs- sqldb, err := executor.GetDbConnection(ctx, bytebaseDatabase)+ sqldb, err := executor.GetDbConnection(ctx, databaseName)if err != nil {return err}@@ -378,8 +374,10 @@ func Query(ctx context.Context, l *zap.Logger, sqldb *sql.DB, statement string,}// FindMigrationHistoryList will find the list of migration history.-func FindMigrationHistoryList(ctx context.Context, findMigrationHistoryListQuery string, queryParams []interface{}, driver db.Driver, find *db.MigrationHistoryFind, baseQuery string) ([]*db.MigrationHistory, error) {- sqldb, err := driver.GetDbConnection(ctx, bytebaseDatabase)+func FindMigrationHistoryList(ctx context.Context, findMigrationHistoryListQuery string, queryParams []interface{}, driver db.Driver, database string, find *db.MigrationHistoryFind, baseQuery string) ([]*db.MigrationHistory, error) {+ // To support `pg` option, util layer will not know which database `migration_history` is located in,+ // so wo need connect database provided by params.+ sqldb, err := driver.GetDbConnection(ctx, database)if err != nil {return nil, err}diff --git a/store/pg_engine.go b/store/pg_engine.goindex 7da6ab59ec..070cc0e46f 100644--- a/store/pg_engine.go+++ b/store/pg_engine.go@@ -105,7 +105,13 @@ func (db *DB) Open(ctx context.Context) (err error) {if err != nil {return err}- databaseName := db.connCfg.Username++ var databaseName string+ if db.connCfg.StrictUseDb {+ databaseName = db.connCfg.Database+ } else {+ databaseName = db.connCfg.Username+ }if db.readonly {db.l.Info("Database is opened in readonly mode. Skip migration and demo data setup.")@@ -123,28 +129,31 @@ func (db *DB) Open(ctx context.Context) (err error) {if err := d.SetupMigrationIfNeeded(ctx); err != nil {return err}+// TODO(d): remove this block once all existing customers all migrated to semantic versioning.- if _, err := getLatestVersion(ctx, d, databaseName); err != nil {- // Convert existing record to semantic versioning format.- if !strings.Contains(err.Error(), "invalid stored version") {- return err- }- db.l.Info("Migrating migration history version storage format to semantic version.")- db, err := d.GetDbConnection(ctx, "bytebase")- if err != nil {- return err- }- // This migrates the CREATE DATABASE record to semantic version format.- // https://github.com/bytebase/bytebase/blob/release/v1.0.2/store/pg_engine.go#L251- // This 1.0.0 should correspond to 1.0/0000__initial_schema.sql.- if _, err := db.ExecContext(ctx, "UPDATE migration_history SET version = '0001.0000.0000-20210113000000' WHERE id = 1 AND version = '10000';"); err != nil {- return err- }- // This migrates the initial schema migration to semantic version format.- // https://github.com/bytebase/bytebase/blob/release/v1.0.2/store/pg_engine.go#L295- // This 1.0.1 should correspond to 1.0/0001__initial_data.sql.- if _, err := db.ExecContext(ctx, "UPDATE migration_history SET version = '0001.0000.0001-20210113000001' WHERE id = 2 AND version = '10001';"); err != nil {- return err+ if !db.connCfg.StrictUseDb {+ if _, err := getLatestVersion(ctx, d, databaseName); err != nil {+ // Convert existing record to semantic versioning format.+ if !strings.Contains(err.Error(), "invalid stored version") {+ return err+ }+ db.l.Info("Migrating migration history version storage format to semantic version.")+ db, err := d.GetDbConnection(ctx, "bytebase")+ if err != nil {+ return err+ }+ // This migrates the CREATE DATABASE record to semantic version format.+ // https://github.com/bytebase/bytebase/blob/release/v1.0.2/store/pg_engine.go#L251+ // This 1.0.0 should correspond to 1.0/0000__initial_schema.sql.+ if _, err := db.ExecContext(ctx, "UPDATE migration_history SET version = '0001.0000.0000-20210113000000' WHERE id = 1 AND version = '10000';"); err != nil {+ return err+ }+ // This migrates the initial schema migration to semantic version format.+ // https://github.com/bytebase/bytebase/blob/release/v1.0.2/store/pg_engine.go#L295+ // This 1.0.1 should correspond to 1.0/0001__initial_data.sql.+ if _, err := db.ExecContext(ctx, "UPDATE migration_history SET version = '0001.0000.0001-20210113000001' WHERE id = 2 AND version = '10001';"); err != nil {+ return err+ }}}@@ -153,7 +162,7 @@ func (db *DB) Open(ctx context.Context) (err error) {return fmt.Errorf("failed to get current schema version: %w", err)}- if err := migrate(ctx, d, verBefore, db.mode, db.serverVersion, databaseName, db.l); err != nil {+ if err := migrate(ctx, d, verBefore, db.mode, db.connCfg.StrictUseDb, db.serverVersion, databaseName, db.l); err != nil {return fmt.Errorf("failed to migrate: %w", err)}@@ -264,7 +273,7 @@ const (// file run in a transaction to prevent partial migrations.//// The procedure follows https://github.com/bytebase/bytebase/blob/main/docs/schema-update-guide.md.-func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, mode common.ReleaseMode, serverVersion, databaseName string, l *zap.Logger) error {+func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, mode common.ReleaseMode, strictDb bool, serverVersion, databaseName string, l *zap.Logger) error {l.Info("Apply database migration if needed...")if curVer == nil {l.Info("The database schema has not been setup.")@@ -308,8 +317,16 @@ func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, modif err != nil {return fmt.Errorf("failed to read latest data %q, error %w", latestSchemaPath, err)}- // We will create the database together with initial schema and data migration.- stmt := fmt.Sprintf("CREATE DATABASE %s;\n\\connect \"%s\";\n%s\n%s", databaseName, databaseName, buf, dataBuf)++ var stmt string+ if strictDb {+ // User gives only database instead of instance, we cannot create database again.+ stmt = fmt.Sprintf("%s\n%s", buf, dataBuf)+ } else {+ // We will create the database together with initial schema and data migration.+ stmt = fmt.Sprintf("CREATE DATABASE %s;\n\\connect \"%s\";\n%s\n%s", databaseName, databaseName, buf, dataBuf)+ }+if _, _, err := d.ExecuteMigration(ctx,&dbdriver.MigrationInfo{@@ -323,7 +340,7 @@ func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, modSource: dbdriver.LIBRARY,Type: dbdriver.Migrate,Description: fmt.Sprintf("Initial migration version %s server version %s with file %s.", cutoffSchemaVersion, serverVersion, latestSchemaPath),- CreateDatabase: true,+ CreateDatabase: !strictDb,},stmt,); err != nil {diff --git a/store/pg_engine_test.go b/store/pg_engine_test.goindex d57b328b01..f8e4985521 100644--- a/store/pg_engine_test.go+++ b/store/pg_engine_test.go@@ -175,7 +175,7 @@ func TestMigrationCompatibility(t *testing.T) {// Create a database with release latest schema.databaseName := "hidb"// Passing curVers = nil will create the database.- err = migrate(ctx, d, nil, common.ReleaseModeProd, serverVersion, databaseName, l)+ err = migrate(ctx, d, nil, common.ReleaseModeProd, false /*strictDb*/, serverVersion, databaseName, l)require.NoError(t, err)// Check migration history.histories, err := d.FindMigrationHistoryList(ctx, &dbdriver.MigrationHistoryFind{@@ -186,7 +186,7 @@ func TestMigrationCompatibility(t *testing.T) {require.Equal(t, histories[0].Version, releaseVersion.String())// Check no migration after passing current version as the release cutoff version.- err = migrate(ctx, d, &releaseVersion, common.ReleaseModeProd, serverVersion, databaseName, l)+ err = migrate(ctx, d, &releaseVersion, common.ReleaseModeProd, false /*strictDb*/, serverVersion, databaseName, l)require.NoError(t, err)// Check migration history.histories, err = d.FindMigrationHistoryList(ctx, &dbdriver.MigrationHistoryFind{@@ -196,7 +196,7 @@ func TestMigrationCompatibility(t *testing.T) {require.Len(t, histories, 1)// Apply migration to dev latest if there are patches.- err = migrate(ctx, d, &releaseVersion, common.ReleaseModeDev, serverVersion, databaseName, l)+ err = migrate(ctx, d, &releaseVersion, common.ReleaseModeDev, false /*strictDb*/, serverVersion, databaseName, l)require.NoError(t, err)// Check migration history.