Skip to content

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

chore: cleanup pg switchDB (#5426)

Danny Xu1b0dd6e18e43
diff --git a/backend/plugin/db/pg/migrate.go b/backend/plugin/db/pg/migrate.go
index f49dd98d80..9f11447232 100644
--- a/backend/plugin/db/pg/migrate.go
+++ b/backend/plugin/db/pg/migrate.go
@@ -34,7 +34,7 @@ func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {
if !exist {
return true, nil
}
- if err := driver.switchDatabase(db.BytebaseDatabase); err != nil {
+ if _, err := driver.GetDBConnection(ctx, db.BytebaseDatabase); err != nil {
return false, err
}
}
@@ -86,7 +86,7 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {
}
}
- if err := driver.switchDatabase(db.BytebaseDatabase); err != nil {
+ if _, err := driver.GetDBConnection(ctx, db.BytebaseDatabase); err != nil {
log.Error("Failed to switch to database \"bytebase\".",
zap.Error(err),
zap.String("environment", driver.connectionCtx.EnvironmentID),
diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.go
index 31ca4bd4c4..ec35998546 100644
--- a/backend/plugin/db/pg/pg.go
+++ b/backend/plugin/db/pg/pg.go
@@ -222,10 +222,29 @@ func (*Driver) GetType() db.Type {
// GetDBConnection gets a database connection.
func (driver *Driver) GetDBConnection(_ context.Context, database string) (*sql.DB, error) {
- if err := driver.switchDatabase(database); err != nil {
+ if driver.db != nil {
+ unregisterConnectionConfig(driver.connectionString)
+ if err := driver.db.Close(); err != nil {
+ return nil, err
+ }
+ }
+
+ dsn := driver.baseDSN + " dbname=" + database
+
+ connectionString, err := registerConnectionConfig(dsn, driver.config.TLSConfig)
+ if err != nil {
return nil, err
}
- return driver.db, nil
+ driver.connectionString = connectionString
+
+ db, err := sql.Open(driverName, driver.connectionString)
+ if err != nil {
+ return nil, err
+ }
+ driver.db = db
+ driver.databaseName = database
+
+ return db, nil
}
// getDatabases gets all databases of an instance.
@@ -495,28 +514,3 @@ func (*Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string,
}
return util.Query(ctx, db.Postgres, conn, statement, queryContext)
}
-
-func (driver *Driver) switchDatabase(dbName string) error {
- if driver.db != nil {
- unregisterConnectionConfig(driver.connectionString)
- if err := driver.db.Close(); err != nil {
- return err
- }
- }
-
- dsn := driver.baseDSN + " dbname=" + dbName
-
- connectionString, err := registerConnectionConfig(dsn, driver.config.TLSConfig)
- if err != nil {
- return err
- }
- driver.connectionString = connectionString
-
- db, err := sql.Open(driverName, driver.connectionString)
- if err != nil {
- return err
- }
- driver.db = db
- driver.databaseName = dbName
- return nil
-}