wp-go/internal/pkg/db/db.go

33 lines
712 B
Go
Raw Normal View History

2022-08-27 13:21:05 +00:00
package db
import (
"github.com/fthvgb1/wp-go/internal/pkg/config"
2022-08-27 13:21:05 +00:00
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
2023-02-06 09:58:24 +00:00
var db *sqlx.DB
2022-08-27 13:21:05 +00:00
2023-02-06 09:58:24 +00:00
func InitDb() (*sqlx.DB, error) {
2023-02-05 13:06:04 +00:00
c := config.GetConfig()
2022-11-15 08:36:21 +00:00
dsn := c.Mysql.Dsn.GetDsn()
2022-08-27 13:21:05 +00:00
var err error
2023-02-06 09:58:24 +00:00
db, err = sqlx.Open("mysql", dsn)
2022-08-27 13:21:05 +00:00
if err != nil {
2023-02-06 09:58:24 +00:00
return nil, err
2022-08-27 13:21:05 +00:00
}
2022-11-15 08:36:21 +00:00
if c.Mysql.Pool.ConnMaxIdleTime != 0 {
2023-02-06 09:58:24 +00:00
db.SetConnMaxIdleTime(c.Mysql.Pool.ConnMaxLifetime)
2022-08-27 13:21:05 +00:00
}
2022-11-15 08:36:21 +00:00
if c.Mysql.Pool.MaxIdleConn != 0 {
2023-02-06 09:58:24 +00:00
db.SetMaxIdleConns(c.Mysql.Pool.MaxIdleConn)
2022-08-27 13:21:05 +00:00
}
2022-11-15 08:36:21 +00:00
if c.Mysql.Pool.MaxOpenConn != 0 {
2023-02-06 09:58:24 +00:00
db.SetMaxOpenConns(c.Mysql.Pool.MaxOpenConn)
2022-08-27 13:21:05 +00:00
}
2022-11-15 08:36:21 +00:00
if c.Mysql.Pool.ConnMaxLifetime != 0 {
2023-02-06 09:58:24 +00:00
db.SetConnMaxLifetime(c.Mysql.Pool.ConnMaxLifetime)
2022-08-27 13:21:05 +00:00
}
2023-02-06 09:58:24 +00:00
return db, err
2022-08-27 13:21:05 +00:00
}