2026-05-21 15:20:12 +08:00
|
|
|
package database
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"database/sql"
|
|
|
|
|
"fmt"
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
"github.com/go-sql-driver/mysql"
|
2026-06-04 19:39:08 +08:00
|
|
|
_ "github.com/go-sql-driver/mysql"
|
2026-05-21 15:20:12 +08:00
|
|
|
"github.com/luxsin/app-api/internal/config"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func Open(cfg config.DatabaseConfig) (*sql.DB, error) {
|
|
|
|
|
mc := mysql.Config{
|
|
|
|
|
User: cfg.User,
|
|
|
|
|
Passwd: cfg.Password,
|
|
|
|
|
Net: "tcp",
|
|
|
|
|
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
|
|
|
|
|
DBName: cfg.Name,
|
|
|
|
|
Params: map[string]string{
|
2026-06-04 19:39:08 +08:00
|
|
|
"charset": "utf8mb4",
|
|
|
|
|
"parseTime": "True",
|
|
|
|
|
"loc": "Local",
|
|
|
|
|
"allowNativePasswords": "true",
|
2026-05-21 15:20:12 +08:00
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
db, err := sql.Open("mysql", mc.FormatDSN())
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("open mysql: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
db.SetMaxOpenConns(25)
|
|
|
|
|
db.SetMaxIdleConns(5)
|
|
|
|
|
db.SetConnMaxLifetime(5 * time.Minute)
|
|
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
|
|
if err := db.PingContext(ctx); err != nil {
|
|
|
|
|
_ = db.Close()
|
|
|
|
|
return nil, fmt.Errorf("ping mysql: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return db, nil
|
|
|
|
|
}
|