2022-08-27 13:21:05 +00:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
2022-11-07 08:04:13 +00:00
|
|
|
"context"
|
2022-08-27 13:21:05 +00:00
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
|
|
"github.com/jmoiron/sqlx"
|
2022-11-04 02:38:59 +00:00
|
|
|
"github/fthvgb1/wp-go/config"
|
2022-08-27 13:21:05 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var Db *sqlx.DB
|
|
|
|
|
2022-11-07 08:04:13 +00:00
|
|
|
type SqlxDb struct {
|
|
|
|
sqlx *sqlx.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSqlxDb(sqlx *sqlx.DB) *SqlxDb {
|
|
|
|
return &SqlxDb{sqlx: sqlx}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r SqlxDb) Select(ctx context.Context, dest any, sql string, params ...any) error {
|
|
|
|
return r.sqlx.Select(dest, sql, params...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r SqlxDb) Get(ctx context.Context, dest any, sql string, params ...any) error {
|
|
|
|
return r.sqlx.Get(dest, sql, params...)
|
|
|
|
}
|
|
|
|
|
2022-08-27 13:21:05 +00:00
|
|
|
func InitDb() error {
|
2022-11-04 02:38:59 +00:00
|
|
|
dsn := config.Conf.Mysql.Dsn.GetDsn()
|
2022-08-27 13:21:05 +00:00
|
|
|
var err error
|
|
|
|
Db, err = sqlx.Open("mysql", dsn)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-11-04 02:38:59 +00:00
|
|
|
if config.Conf.Mysql.Pool.ConnMaxIdleTime != 0 {
|
|
|
|
Db.SetConnMaxIdleTime(config.Conf.Mysql.Pool.ConnMaxLifetime)
|
2022-08-27 13:21:05 +00:00
|
|
|
}
|
2022-11-04 02:38:59 +00:00
|
|
|
if config.Conf.Mysql.Pool.MaxIdleConn != 0 {
|
|
|
|
Db.SetMaxIdleConns(config.Conf.Mysql.Pool.MaxIdleConn)
|
2022-08-27 13:21:05 +00:00
|
|
|
}
|
2022-11-04 02:38:59 +00:00
|
|
|
if config.Conf.Mysql.Pool.MaxOpenConn != 0 {
|
|
|
|
Db.SetMaxOpenConns(config.Conf.Mysql.Pool.MaxOpenConn)
|
2022-08-27 13:21:05 +00:00
|
|
|
}
|
2022-11-04 02:38:59 +00:00
|
|
|
if config.Conf.Mysql.Pool.ConnMaxLifetime != 0 {
|
|
|
|
Db.SetConnMaxLifetime(config.Conf.Mysql.Pool.ConnMaxLifetime)
|
2022-08-27 13:21:05 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|