MarketingSystemDataExportTool/server/internal/db/mysql.go

30 lines
918 B
Go

package db
import (
"database/sql"
"strings"
_ "github.com/go-sql-driver/mysql"
)
func ConnectMySQL(dsn string) (*sql.DB, error) {
db, err := sql.Open("mysql", dsn)
if err != nil {
return nil, err
}
if err := db.Ping(); err != nil {
// Error 8001: Not allowed to execute statement that may change data on polar slave
// This error can occur on read-only replicas but the connection may still be usable
// Try a simple SELECT to verify the connection is actually working
if strings.Contains(err.Error(), "8001") || strings.Contains(err.Error(), "polar slave") {
var dummy int
if testErr := db.QueryRow("SELECT 1").Scan(&dummy); testErr == nil {
// Connection is actually working, ignore the ping error
return db, nil
}
}
return nil, err
}
return db, nil
}