Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: cleanup db connection (#5433)
Danny Xuf59d91339914
diff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.goindex f52802d349..a647c0e4f2 100644--- a/backend/plugin/advisor/utils_for_tests.go+++ b/backend/plugin/advisor/utils_for_tests.go@@ -237,9 +237,9 @@ func (*MockDriver) GetType() database.Type {return database.Type("MOCK")}-// GetDBConnection implements the Driver interface.-func (*MockDriver) GetDBConnection(_ context.Context, _ string) (*sql.DB, error) {- return nil, nil+// GetDB gets the database.+func (*MockDriver) GetDB() *sql.DB {+ return nil}// Execute implements the Driver interface.diff --git a/backend/plugin/db/clickhouse/clickhouse.go b/backend/plugin/db/clickhouse/clickhouse.goindex c0cbe3e536..e260f146df 100644--- a/backend/plugin/db/clickhouse/clickhouse.go+++ b/backend/plugin/db/clickhouse/clickhouse.go@@ -101,9 +101,9 @@ func (*Driver) GetType() db.Type {return db.ClickHouse}-// GetDBConnection gets a database connection.-func (driver *Driver) GetDBConnection(context.Context, string) (*sql.DB, error) {- return driver.db, nil+// GetDB gets the database.+func (driver *Driver) GetDB() *sql.DB {+ return driver.db}// getVersion gets the version.diff --git a/backend/plugin/db/clickhouse/migrate.go b/backend/plugin/db/clickhouse/migrate.goindex 91f7594d49..4cd4323362 100644--- a/backend/plugin/db/clickhouse/migrate.go+++ b/backend/plugin/db/clickhouse/migrate.go@@ -59,5 +59,5 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migif v := find.Offset; v != nil {query += fmt.Sprintf(" OFFSET %d", *v)}- return util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase)+ return util.FindMigrationHistoryList(ctx, query, params, driver.db)}diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.goindex f4e8810883..3a839b8275 100644--- a/backend/plugin/db/driver.go+++ b/backend/plugin/db/driver.go@@ -463,7 +463,7 @@ type Driver interface {Close(ctx context.Context) errorPing(ctx context.Context) errorGetType() Type- GetDBConnection(ctx context.Context, database string) (*sql.DB, error)+ GetDB() *sql.DB// Execute will execute the statement. For CREATE DATABASE statement, some types of databases such as Postgres// will not use transactions to execute the statement but will still use transactions to execute the rest of statements.Execute(ctx context.Context, statement string, createDatabase bool) (int64, error)diff --git a/backend/plugin/db/mongodb/mongodb.go b/backend/plugin/db/mongodb/mongodb.goindex 4ed13d3023..05651caeae 100644--- a/backend/plugin/db/mongodb/mongodb.go+++ b/backend/plugin/db/mongodb/mongodb.go@@ -75,11 +75,9 @@ func (*Driver) GetType() db.Type {return db.MongoDB}-// GetDBConnection returns a database connection.-// It always return nil because it has not implemented the SQL interface, and we always return error, it's caller's responsibility to-// avoid calling this function for MongoDB.-func (*Driver) GetDBConnection(_ context.Context, _ string) (*sql.DB, error) {- return nil, errors.New("mongodb doesn't support GetDBConnection")+// GetDB gets the database.+func (*Driver) GetDB() *sql.DB {+ panic("mongodb doesn't support GetD")}// Execute executes a statement, always returns 0 as the number of rows affected because we execute the statement by mongosh, it's hard to catch the row effected number.diff --git a/backend/plugin/db/mssql/mssql.go b/backend/plugin/db/mssql/mssql.goindex 70a2583f4b..30d1a32585 100644--- a/backend/plugin/db/mssql/mssql.go+++ b/backend/plugin/db/mssql/mssql.go@@ -73,12 +73,9 @@ func (*Driver) GetType() db.Type {return db.MSSQL}-// GetDBConnection gets a database connection.-func (driver *Driver) GetDBConnection(ctx context.Context, database string) (*sql.DB, error) {- if _, err := driver.db.ExecContext(ctx, fmt.Sprintf(`USE "%s"`, database)); err != nil {- return nil, err- }- return driver.db, nil+// GetDB gets the database.+func (driver *Driver) GetDB() *sql.DB {+ return driver.db}// Execute executes a SQL statement and returns the affected rows.diff --git a/backend/plugin/db/mysql/migrate.go b/backend/plugin/db/mysql/migrate.goindex bf5992f629..8c4f5c2074 100644--- a/backend/plugin/db/mysql/migrate.go+++ b/backend/plugin/db/mysql/migrate.go@@ -59,5 +59,5 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migif v := find.Offset; v != nil {query += fmt.Sprintf(" OFFSET %d", *v)}- return util.FindMigrationHistoryList(ctx, query, params, driver, db.BytebaseDatabase)+ return util.FindMigrationHistoryList(ctx, query, params, driver.db)}diff --git a/backend/plugin/db/mysql/mysql.go b/backend/plugin/db/mysql/mysql.goindex f05227a07a..178aeef40b 100644--- a/backend/plugin/db/mysql/mysql.go+++ b/backend/plugin/db/mysql/mysql.go@@ -131,9 +131,9 @@ func (driver *Driver) GetType() db.Type {return driver.dbType}-// GetDBConnection gets a database connection.-func (driver *Driver) GetDBConnection(context.Context, string) (*sql.DB, error) {- return driver.db, nil+// GetDB gets the database.+func (driver *Driver) GetDB() *sql.DB {+ return driver.db}// getDatabases gets all databases of an instance.diff --git a/backend/plugin/db/mysql/restore.go b/backend/plugin/db/mysql/restore.goindex 58f995c25c..29d7807ad5 100644--- a/backend/plugin/db/mysql/restore.go+++ b/backend/plugin/db/mysql/restore.go@@ -267,10 +267,7 @@ func (driver *Driver) RestoreBackupToPITRDatabase(ctx context.Context, backup io// If there's already a PITR database, it means there's a failed trial before this task execution.// We need to clean up the dirty state and start clean for idempotent task execution.stmt := fmt.Sprintf("DROP DATABASE IF EXISTS `%s`; CREATE DATABASE `%s`;", pitrDatabaseName, pitrDatabaseName)- db, err := driver.GetDBConnection(ctx, "")- if err != nil {- return errors.Wrapf(err, "failed to get connection to restore backup")- }+ db := driver.GetDB()if _, err := db.ExecContext(ctx, stmt); err != nil {return errors.Wrapf(err, "failed to create the PITR database %s", pitrDatabaseName)}@@ -822,11 +819,7 @@ func (driver *Driver) writeBinlogMetadataFile(ctx context.Context, binlogFileNam// GetSortedBinlogFilesOnServer returns the information of binlog files in ascending order by their numeric extension.func (driver *Driver) GetSortedBinlogFilesOnServer(ctx context.Context) ([]BinlogFile, error) {- db, err := driver.GetDBConnection(ctx, "")- if err != nil {- return nil, err- }-+ db := driver.GetDB()query := "SHOW BINARY LOGS"rows, err := db.QueryContext(ctx, query)if err != nil {@@ -1100,11 +1093,7 @@ func (driver *Driver) CheckServerVersionForPITR(ctx context.Context) error {// CheckEngineInnoDB checks that the tables in the database is all using InnoDB as the storage engine.func (driver *Driver) CheckEngineInnoDB(ctx context.Context, database string) error {- db, err := driver.GetDBConnection(ctx, "")- if err != nil {- return err- }-+ db := driver.GetDB()// ref: https://dev.mysql.com/doc/refman/8.0/en/information-schema-tables-table.htmlquery := fmt.Sprintf("SELECT table_name, engine FROM information_schema.tables WHERE table_schema='%s';", database)rows, err := db.QueryContext(ctx, query)@@ -1132,11 +1121,7 @@ func (driver *Driver) CheckEngineInnoDB(ctx context.Context, database string) er}func (driver *Driver) getServerVariable(ctx context.Context, varName string) (string, error) {- db, err := driver.GetDBConnection(ctx, "")- if err != nil {- return "", err- }-+ db := driver.GetDB()query := fmt.Sprintf("SHOW VARIABLES LIKE '%s'", varName)var varNameFound, value stringif err := db.QueryRowContext(ctx, query).Scan(&varNameFound, &value); err != nil {diff --git a/backend/plugin/db/oracle/oracle.go b/backend/plugin/db/oracle/oracle.goindex 5c9f27e311..30beef0896 100644--- a/backend/plugin/db/oracle/oracle.go+++ b/backend/plugin/db/oracle/oracle.go@@ -69,9 +69,9 @@ func (*Driver) GetType() db.Type {return db.Oracle}-// GetDBConnection gets a database connection.-func (driver *Driver) GetDBConnection(_ context.Context, _ string) (*sql.DB, error) {- return driver.db, nil+// GetDB gets the database.+func (driver *Driver) GetDB() *sql.DB {+ return driver.db}// Execute executes a SQL statement and returns the affected rows.diff --git a/backend/plugin/db/pg/migrate.go b/backend/plugin/db/pg/migrate.goindex a5dd62d0bc..618ab893ae 100644--- a/backend/plugin/db/pg/migrate.go+++ b/backend/plugin/db/pg/migrate.go@@ -311,7 +311,7 @@ func (driver *Driver) executeMigration(ctx context.Context, m *db.MigrationInfo,}if doMigrate {// Switch to the target database only if we're NOT creating this target database.- // We should not call GetDBConnection() if the instance is MongoDB because it doesn't support.+ // We should not call getDBConnection() if the instance is MongoDB because it doesn't support.if !m.CreateDatabase {if _, err := driver.GetDBConnection(ctx, m.Database); err != nil {return "", "", err@@ -501,7 +501,11 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migif driver.strictUseDb() {database = driver.strictDatabase}- return util.FindMigrationHistoryList(ctx, query, params, driver, database)+ db, err := driver.GetDBConnection(ctx, database)+ if err != nil {+ return nil, err+ }+ return util.FindMigrationHistoryList(ctx, query, params, db)}func (driver *Driver) hasBytebaseDatabase(ctx context.Context) (bool, error) {diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.goindex ec35998546..323174f3e8 100644--- a/backend/plugin/db/pg/pg.go+++ b/backend/plugin/db/pg/pg.go@@ -220,6 +220,11 @@ func (*Driver) GetType() db.Type {return db.Postgres}+// GetDB gets the database.+func (driver *Driver) GetDB() *sql.DB {+ return driver.db+}+// GetDBConnection gets a database connection.func (driver *Driver) GetDBConnection(_ context.Context, database string) (*sql.DB, error) {if driver.db != nil {@@ -324,7 +329,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, createDatabreturn err}} else if strings.HasPrefix(stmt, "\\connect ") {- // For the case of `\connect "dbname";`, we need to use GetDBConnection() instead of executing the statement.+ // For the case of `\connect "dbname";`, we need to use getDBConnection() instead of executing the statement.parts := strings.Split(stmt, `"`)if len(parts) != 3 {return errors.Errorf("invalid statement %q", stmt)diff --git a/backend/plugin/db/redis/redis.go b/backend/plugin/db/redis/redis.goindex 753949ffa6..318b58bc66 100644--- a/backend/plugin/db/redis/redis.go+++ b/backend/plugin/db/redis/redis.go@@ -102,9 +102,9 @@ func (*Driver) GetType() db.Type {return db.Redis}-// GetDBConnection is not supported for redis.-func (*Driver) GetDBConnection(context.Context, string) (*sql.DB, error) {- return nil, errors.New("redis: not supported")+// GetDB gets the database.+func (*Driver) GetDB() *sql.DB {+ panic("redis: not supported")}// Execute will execute the statement. For CREATE DATABASE statement, some types of databases such as Postgresdiff --git a/backend/plugin/db/redshift/redshift.go b/backend/plugin/db/redshift/redshift.goindex c65891ec9d..7ec0571b38 100644--- a/backend/plugin/db/redshift/redshift.go+++ b/backend/plugin/db/redshift/redshift.go@@ -199,8 +199,13 @@ func (*Driver) GetType() db.Type {return db.Redshift}-// GetDBConnection returns the database connection.-func (driver *Driver) GetDBConnection(_ context.Context, database string) (*sql.DB, error) {+// GetDB gets the database.+func (driver *Driver) GetDB() *sql.DB {+ return driver.db+}++// getDBConnection returns the database connection.+func (driver *Driver) getDBConnection(_ context.Context, database string) (*sql.DB, error) {if err := driver.switchDatabase(database); err != nil {return nil, err}@@ -275,12 +280,12 @@ func (driver *Driver) Execute(ctx context.Context, statement string, createDatabreturn err}} else if strings.HasPrefix(stmt, "\\connect ") {- // For the case of `\connect "dbname";`, we need to use GetDBConnection() instead of executing the statement.+ // For the case of `\connect "dbname";`, we need to use getDBConnection() instead of executing the statement.parts := strings.Split(stmt, `"`)if len(parts) != 3 {return errors.Errorf("invalid statement %q", stmt)}- if _, err = driver.GetDBConnection(ctx, parts[1]); err != nil {+ if _, err = driver.getDBConnection(ctx, parts[1]); err != nil {return err}// Update current ownerdiff --git a/backend/plugin/db/redshift/sync.go b/backend/plugin/db/redshift/sync.goindex 9792ca917e..18c016907d 100644--- a/backend/plugin/db/redshift/sync.go+++ b/backend/plugin/db/redshift/sync.go@@ -152,7 +152,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*sreturn nil, common.Errorf(common.NotFound, "database %q not found", databaseName)}- sqldb, err := driver.GetDBConnection(ctx, databaseName)+ sqldb, err := driver.getDBConnection(ctx, databaseName)if err != nil {return nil, errors.Wrapf(err, "failed to get database connection for %q", databaseName)}diff --git a/backend/plugin/db/snowflake/snowflake.go b/backend/plugin/db/snowflake/snowflake.goindex ac3f854188..50c0ed6b55 100644--- a/backend/plugin/db/snowflake/snowflake.go+++ b/backend/plugin/db/snowflake/snowflake.go@@ -106,9 +106,9 @@ func (*Driver) GetType() db.Type {return db.Snowflake}-// GetDBConnection gets a database connection.-func (driver *Driver) GetDBConnection(context.Context, string) (*sql.DB, error) {- return driver.db, nil+// GetDB gets the database.+func (driver *Driver) GetDB() *sql.DB {+ return driver.db}// getVersion gets the version.diff --git a/backend/plugin/db/spanner/spanner.go b/backend/plugin/db/spanner/spanner.goindex fd9fbdfa00..e6fa2a714a 100644--- a/backend/plugin/db/spanner/spanner.go+++ b/backend/plugin/db/spanner/spanner.go@@ -122,8 +122,8 @@ func (*Driver) GetType() db.Type {return db.Spanner}-// GetDBConnection gets a database connection.-func (*Driver) GetDBConnection(_ context.Context, _ string) (*sql.DB, error) {+// GetDB gets the database.+func (*Driver) GetDB() *sql.DB {panic("not implemented")}diff --git a/backend/plugin/db/sqlite/dump.go b/backend/plugin/db/sqlite/dump.goindex 68acd1fb31..591621e68a 100644--- a/backend/plugin/db/sqlite/dump.go+++ b/backend/plugin/db/sqlite/dump.go@@ -48,7 +48,7 @@ type sqliteSchema struct {}func (driver *Driver) dumpOneDatabase(ctx context.Context, database string, out io.Writer, schemaOnly bool) error {- if _, err := driver.GetDBConnection(ctx, database); err != nil {+ if _, err := driver.getDBConnection(ctx, database); err != nil {return err}diff --git a/backend/plugin/db/sqlite/sqlite.go b/backend/plugin/db/sqlite/sqlite.goindex 7562649705..bfde289ba4 100644--- a/backend/plugin/db/sqlite/sqlite.go+++ b/backend/plugin/db/sqlite/sqlite.go@@ -46,7 +46,7 @@ func (driver *Driver) Open(ctx context.Context, _ db.Type, config db.ConnectionCdriver.dir = config.Host// If config.Database is empty, we will get a connection to in-memory database.- if _, err := driver.GetDBConnection(ctx, config.Database); err != nil {+ if _, err := driver.getDBConnection(ctx, config.Database); err != nil {return nil, err}driver.connectionCtx = connCtx@@ -71,9 +71,14 @@ func (*Driver) GetType() db.Type {return db.SQLite}-// GetDBConnection gets a database connection.+// GetDB gets the database.+func (driver *Driver) GetDB() *sql.DB {+ return driver.db+}++// getDBConnection gets a database connection.// If database is empty, we will get a connect to in-memory database.-func (driver *Driver) GetDBConnection(_ context.Context, database string) (*sql.DB, error) {+func (driver *Driver) getDBConnection(_ context.Context, database string) (*sql.DB, error) {if driver.db != nil {if err := driver.db.Close(); err != nil {return nil, err@@ -127,7 +132,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ bool) (inif len(parts) != 3 {return errors.Errorf("invalid statement %q", stmt)}- db, err := driver.GetDBConnection(ctx, parts[1])+ db, err := driver.getDBConnection(ctx, parts[1])if err != nil {return err}diff --git a/backend/plugin/db/sqlite/sync.go b/backend/plugin/db/sqlite/sync.goindex 87a44bdd52..45a358df7d 100644--- a/backend/plugin/db/sqlite/sync.go+++ b/backend/plugin/db/sqlite/sync.go@@ -74,7 +74,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*sreturn nil, common.Errorf(common.NotFound, "database %q not found", databaseName)}- sqldb, err := driver.GetDBConnection(ctx, databaseName)+ sqldb, err := driver.getDBConnection(ctx, databaseName)if err != nil {return nil, errors.Wrapf(err, "failed to get database connection for %q", databaseName)}diff --git a/backend/plugin/db/util/driverutil.go b/backend/plugin/db/util/driverutil.goindex fc3bddcaee..54b7e23559 100644--- a/backend/plugin/db/util/driverutil.go+++ b/backend/plugin/db/util/driverutil.go@@ -358,13 +358,9 @@ func getMSSQLStatementWithResultLimit(stmt string, limit int) string {}// FindMigrationHistoryList will find the list of migration history.-func FindMigrationHistoryList(ctx context.Context, findMigrationHistoryListQuery string, queryParams []any, driver db.Driver, database string) ([]*db.MigrationHistory, error) {+func FindMigrationHistoryList(ctx context.Context, findMigrationHistoryListQuery string, queryParams []any, sqldb *sql.DB) ([]*db.MigrationHistory, error) {// To support `pg` option, the util layer will not know which database where `migration_history` table is,// so we need to connect to the database provided by params.- sqldb, err := driver.GetDBConnection(ctx, database)- if err != nil {- return nil, err- }tx, err := sqldb.BeginTx(ctx, nil)if err != nil {return nil, errdiff --git a/backend/runner/rollbackrun/runner.go b/backend/runner/rollbackrun/runner.goindex 95a21e9c5f..51b6d4c37f 100644--- a/backend/runner/rollbackrun/runner.go+++ b/backend/runner/rollbackrun/runner.go@@ -151,11 +151,7 @@ func (r *Runner) generateOracleRollbackSQLImpl(ctx context.Context, payload *api}defer driver.Close(ctx)- db, err := driver.GetDBConnection(ctx, "")- if err != nil {- return nil, errors.Wrapf(err, "failed to get database connection")- }-+ db := driver.GetDB()// Get the undo SQL from the undo log.var statements bytes.Bufferrows, err := db.QueryContext(ctx, "SELECT undo_sql FROM flashback_transaction_query WHERE xid=HEXTORAW(:1)", payload.TransactionID)diff --git a/backend/runner/taskcheck/statement_advisor_composite_executor.go b/backend/runner/taskcheck/statement_advisor_composite_executor.goindex 33dac887ea..348b21effb 100644--- a/backend/runner/taskcheck/statement_advisor_composite_executor.go+++ b/backend/runner/taskcheck/statement_advisor_composite_executor.go@@ -109,10 +109,7 @@ func (e *StatementAdvisorCompositeExecutor) Run(ctx context.Context, taskCheckRureturn nil, err}defer driver.Close(ctx)- connection, err := driver.GetDBConnection(ctx, database.DatabaseName)- if err != nil {- return nil, err- }+ connection := driver.GetDB()adviceList, err := advisor.SQLReviewCheck(payload.Statement, policy.RuleList, advisor.SQLReviewCheckContext{Charset: dbSchema.Metadata.CharacterSet,diff --git a/backend/runner/taskcheck/statement_affected_rows_report_executor.go b/backend/runner/taskcheck/statement_affected_rows_report_executor.goindex 19a33139ea..9e5f5c535d 100644--- a/backend/runner/taskcheck/statement_affected_rows_report_executor.go+++ b/backend/runner/taskcheck/statement_affected_rows_report_executor.go@@ -78,11 +78,7 @@ func (s *StatementAffectedRowsReportExecutor) Run(ctx context.Context, _ *store.}defer driver.Close(ctx)- sqlDB, err := driver.GetDBConnection(ctx, database.DatabaseName)- if err != nil {- return nil, err- }-+ sqlDB := driver.GetDB()switch instance.Engine {case db.Postgres:return reportStatementAffectedRowsForPostgres(ctx, sqlDB, payload.Statement)diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.goindex 1c7a766ef6..c3d1a903fc 100644--- a/backend/runner/taskrun/executor.go+++ b/backend/runner/taskrun/executor.go@@ -284,10 +284,7 @@ func setThreadIDAndStartBinlogCoordinate(ctx context.Context, driver db.Driver,}payload.ThreadID = connID- db, err := driver.GetDBConnection(ctx, "")- if err != nil {- return nil, errors.Wrap(err, "failed to get the DB connection")- }+ db := driver.GetDB()binlogInfo, err := mysql.GetBinlogInfo(ctx, db)if err != nil {return nil, errors.Wrap(err, "failed to get the binlog info before executing the migration transaction")@@ -323,10 +320,7 @@ func setMigrationIDAndEndBinlogCoordinate(ctx context.Context, driver db.Driver,}payload.MigrationID = migrationID- db, err := driver.GetDBConnection(ctx, "")- if err != nil {- return nil, errors.Wrap(err, "failed to get the DB connection")- }+ db := driver.GetDB()binlogInfo, err := mysql.GetBinlogInfo(ctx, db)if err != nil {return nil, errors.Wrap(err, "failed to get the binlog info before executing the migration transaction")diff --git a/backend/runner/taskrun/pitr_cutover_executor.go b/backend/runner/taskrun/pitr_cutover_executor.goindex 1c9a17f034..0e18baa1cf 100644--- a/backend/runner/taskrun/pitr_cutover_executor.go+++ b/backend/runner/taskrun/pitr_cutover_executor.go@@ -124,13 +124,7 @@ func (exec *PITRCutoverExecutor) pitrCutover(ctx context.Context, dbFactory *dbfreturn true, nil, err}- driver, err := dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)- if err != nil {- return true, nil, err- }- defer driver.Close(ctx)-- if err := exec.doCutover(ctx, driver, instance, issue, database.DatabaseName); err != nil {+ if err := exec.doCutover(ctx, instance, issue, database.DatabaseName); err != nil {return true, nil, err}@@ -155,7 +149,12 @@ func (exec *PITRCutoverExecutor) pitrCutover(ctx context.Context, dbFactory *dbfIssueID: strconv.Itoa(issue.UID),}- if _, _, err := utils.ExecuteMigration(ctx, exec.store, driver, m, "/* pitr cutover */", nil /* executeBeforeCommitTx */); err != nil {+ driver, err := dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)+ if err != nil {+ return true, nil, err+ }+ defer driver.Close(ctx)+ if _, _, err := utils.ExecuteMigration(ctx, exec.store, driver, m, "" /* pitr cutover */, nil /* executeBeforeCommitTx */); err != nil {log.Error("Failed to add migration history record", zap.Error(err))return true, nil, errors.Wrap(err, "failed to add migration history record")}@@ -180,7 +179,7 @@ func (exec *PITRCutoverExecutor) pitrCutover(ctx context.Context, dbFactory *dbf}, nil}-func (exec *PITRCutoverExecutor) doCutover(ctx context.Context, driver db.Driver, instance *store.InstanceMessage, issue *store.IssueMessage, databaseName string) error {+func (exec *PITRCutoverExecutor) doCutover(ctx context.Context, instance *store.InstanceMessage, issue *store.IssueMessage, databaseName string) error {switch instance.Engine {case db.Postgres:// Retry so that if there are clients reconnecting to the related databases, we can potentially kill the connections and do the cutover successfully.@@ -192,7 +191,7 @@ func (exec *PITRCutoverExecutor) doCutover(ctx context.Context, driver db.Driverselect {case <-ticker.C:retry++- if err := exec.pitrCutoverPostgres(ctx, driver, issue, databaseName); err != nil {+ if err := exec.pitrCutoverPostgres(ctx, instance, issue, databaseName); err != nil {if retry == maxRetry {return errors.Wrapf(err, "failed to do cutover for PostgreSQL after retried for %d times", maxRetry)}@@ -205,7 +204,7 @@ func (exec *PITRCutoverExecutor) doCutover(ctx context.Context, driver db.Driver}}case db.MySQL, db.MariaDB:- if err := exec.pitrCutoverMySQL(ctx, driver, issue, databaseName); err != nil {+ if err := exec.pitrCutoverMySQL(ctx, instance, issue, databaseName); err != nil {return errors.Wrap(err, "failed to do cutover for MySQL")}return nil@@ -214,11 +213,13 @@ func (exec *PITRCutoverExecutor) doCutover(ctx context.Context, driver db.Driver}}-func (*PITRCutoverExecutor) pitrCutoverMySQL(ctx context.Context, driver db.Driver, issue *store.IssueMessage, databaseName string) error {- driverDB, err := driver.GetDBConnection(ctx, "")+func (exec *PITRCutoverExecutor) pitrCutoverMySQL(ctx context.Context, instance *store.InstanceMessage, issue *store.IssueMessage, databaseName string) error {+ driver, err := exec.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)if err != nil {return err}+ defer driver.Close(ctx)+ driverDB := driver.GetDB()conn, err := driverDB.Conn(ctx)if err != nil {return err@@ -234,13 +235,15 @@ func (*PITRCutoverExecutor) pitrCutoverMySQL(ctx context.Context, driver db.Drivreturn nil}-func (*PITRCutoverExecutor) pitrCutoverPostgres(ctx context.Context, driver db.Driver, issue *store.IssueMessage, databaseName string) error {+func (exec *PITRCutoverExecutor) pitrCutoverPostgres(ctx context.Context, instance *store.InstanceMessage, issue *store.IssueMessage, databaseName string) error {pitrDatabaseName := util.GetPITRDatabaseName(databaseName, issue.CreatedTime.Unix())pitrOldDatabaseName := util.GetPITROldDatabaseName(databaseName, issue.CreatedTime.Unix())- db, err := driver.GetDBConnection(ctx, db.BytebaseDatabase)++ defaultDBDriver, err := exec.dbFactory.GetAdminDatabaseDriver(ctx, instance, db.BytebaseDatabase)if err != nil {- return errors.Wrap(err, "failed to get connection for PostgreSQL")+ return err}+ db := defaultDBDriver.GetDB()// The original database may not exist.// This is possible if there's a former task execution which successfully renamed original -> _del database and failed.diff --git a/backend/runner/taskrun/pitr_restore_executor.go b/backend/runner/taskrun/pitr_restore_executor.goindex aaa4c6d1fe..27036c6ad5 100644--- a/backend/runner/taskrun/pitr_restore_executor.go+++ b/backend/runner/taskrun/pitr_restore_executor.go@@ -386,10 +386,12 @@ func (*PITRRestoreExecutor) doRestoreInPlacePostgres(ctx context.Context, storesreturn nil, errors.Wrapf(err, "failed to get the OWNER of database %q", database.DatabaseName)}- db, err := driver.GetDBConnection(ctx, db.BytebaseDatabase)+ defaultDBDriver, err := dbFactory.GetAdminDatabaseDriver(ctx, instance, "")if err != nil {- return nil, errors.Wrap(err, "failed to get connection for PostgreSQL")+ return nil, err}+ defer defaultDBDriver.Close(ctx)+ db := defaultDBDriver.GetDB()pitrDatabaseName := util.GetPITRDatabaseName(database.DatabaseName, issue.CreatedTime.Unix())// If there's already a PITR database, it means there's a failed trial before this task execution.// We need to clean up the dirty state and start clean for idempotent task execution.@@ -399,12 +401,13 @@ func (*PITRRestoreExecutor) doRestoreInPlacePostgres(ctx context.Context, storesif _, err := db.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE %s WITH OWNER %s;", pitrDatabaseName, originalOwner)); err != nil {return nil, errors.Wrapf(err, "failed to create the PITR database %q", pitrDatabaseName)}- // Switch to the PITR database.- // TODO(dragonly): This is a trick, needs refactor.- if _, err := driver.GetDBConnection(ctx, pitrDatabaseName); err != nil {- return nil, errors.Wrapf(err, "failed to switch connection to database %q", pitrDatabaseName)++ pitrDBDriver, err := dbFactory.GetAdminDatabaseDriver(ctx, instance, "")+ if err != nil {+ return nil, err}- if err := driver.Restore(ctx, backupFile); err != nil {+ defer pitrDBDriver.Close(ctx)+ if err := pitrDBDriver.Restore(ctx, backupFile); err != nil {return nil, errors.Wrapf(err, "failed to restore backup to the PITR database %q", pitrDatabaseName)}return &api.TaskRunResultPayload{diff --git a/backend/server/issue.go b/backend/server/issue.goindex f3fbf80fdc..dd44e12221 100644--- a/backend/server/issue.go+++ b/backend/server/issue.go@@ -1134,11 +1134,7 @@ func (s *Server) createDatabaseCreateTaskList(ctx context.Context, c api.CreateDdefer driver.Close(ctx)var lowerCaseTableNames intvar unused any- db, err := driver.GetDBConnection(ctx, "" /* databaseName */)- if err != nil {- log.Warn("failed to get db connection for instance %q", zap.Error(err), zap.String("instance", instance.Title))- break- }+ db := driver.GetDB()if err := db.QueryRowContext(ctx, "SHOW VARIABLES LIKE 'lower_case_table_names'").Scan(&unused, &lowerCaseTableNames); err != nil {log.Warn("failed to get lower_case_table_names for instance %q", zap.Error(err), zap.String("instance", instance.Title))breakdiff --git a/backend/server/openapi_sql.go b/backend/server/openapi_sql.goindex 01c89c9e3a..6119b33213 100644--- a/backend/server/openapi_sql.go+++ b/backend/server/openapi_sql.go@@ -134,10 +134,7 @@ func (s *Server) sqlCheckController(c echo.Context) error {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get database driver").SetInternal(err)}defer driver.Close(ctx)- connection, err = driver.GetDBConnection(ctx, database.DatabaseName)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get database connection").SetInternal(err)- }+ connection = driver.GetDB()} else {databaseType = request.DatabaseTypeif databaseType == "" {diff --git a/backend/server/sql.go b/backend/server/sql.goindex 430dbf1e22..4f068f86d4 100644--- a/backend/server/sql.go+++ b/backend/server/sql.go@@ -342,11 +342,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get database driver").SetInternal(err)}defer driver.Close(ctx)- connection, err := driver.GetDBConnection(ctx, exec.DatabaseName)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get database connection").SetInternal(err)- }-+ connection := driver.GetDB()adviceLevel, adviceList, err = s.sqlCheck(ctx,dbType,@@ -436,7 +432,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {}, nil}- sqlDB, err := driver.GetDBConnection(ctx, exec.DatabaseName)+ sqlDB := driver.GetDB()if err != nil {return nil, err}@@ -636,10 +632,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {}, nil}- sqlDB, err := driver.GetDBConnection(ctx, exec.DatabaseName)- if err != nil {- return nil, err- }+ sqlDB := driver.GetDB()conn, err := sqlDB.Conn(ctx)if err != nil {return nil, errdiff --git a/backend/server/webhook.go b/backend/server/webhook.goindex ecee9e066e..30c6916ce8 100644--- a/backend/server/webhook.go+++ b/backend/server/webhook.go@@ -552,11 +552,7 @@ func (s *Server) sqlAdviceForFile(if err != nil {return nil, err}- connection, err := driver.GetDBConnection(ctx, database.DatabaseName)- if err != nil {- return nil, err- }-+ connection := driver.GetDB()dbSchema, err := s.store.GetDBSchema(ctx, database.UID)if err != nil {return nil, errdiff --git a/backend/store/pg_engine.go b/backend/store/pg_engine.goindex 4e4e5bdce8..08b938653c 100644--- a/backend/store/pg_engine.go+++ b/backend/store/pg_engine.go@@ -98,7 +98,7 @@ func NewDB(connCfg dbdriver.ConnectionConfig, binDir, demoName string, readonly// Open opens the database connection.func (db *DB) Open(ctx context.Context) (schemaVersion *semver.Version, err error) {- d, err := dbdriver.Open(+ driver, err := dbdriver.Open(ctx,dbdriver.Postgres,dbdriver.DriverConfig{DbBinDir: db.binDir},@@ -116,7 +116,7 @@ func (db *DB) Open(ctx context.Context) (schemaVersion *semver.Version, err erro// The database storing metadata is the same as user name.databaseName = db.connCfg.Username}- pgDriver := d.(*pg.Driver)+ pgDriver := driver.(*pg.Driver)if db.readonly {log.Info("Database is opened in readonly mode. Skip migration and demo data setup.")@@ -128,7 +128,7 @@ func (db *DB) Open(ctx context.Context) (schemaVersion *semver.Version, err erroreturn nil, errors.Wrap(err, "failed to get current schema version")}- db.db, err = d.GetDBConnection(ctx, databaseName)+ db.db, err = pgDriver.GetDBConnection(ctx, databaseName)if err != nil {return nil, errors.Wrapf(err, "failed to connect to metaDB %q", databaseName)}@@ -157,7 +157,7 @@ func (db *DB) Open(ctx context.Context) (schemaVersion *semver.Version, err erro}log.Info(fmt.Sprintf("Current schema version after migration: %s", verAfter))- db.db, err = d.GetDBConnection(ctx, databaseName)+ db.db, err = pgDriver.GetDBConnection(ctx, databaseName)if err != nil {return nil, errors.Wrapf(err, "failed to connect to metaDB %q", databaseName)}