wp-go/app/pkg/db/db.go

78 lines
1.8 KiB
Go
Raw Normal View History

2022-08-27 13:21:05 +00:00
package db
import (
2023-02-10 13:23:30 +00:00
"context"
2023-05-04 12:36:17 +00:00
"github.com/fthvgb1/wp-go/app/pkg/config"
"github.com/fthvgb1/wp-go/cache/reload"
2023-02-10 13:23:30 +00:00
"github.com/fthvgb1/wp-go/model"
2023-04-05 12:54:38 +00:00
"github.com/fthvgb1/wp-go/safety"
2022-08-27 13:21:05 +00:00
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
2023-02-10 13:23:30 +00:00
"log"
"runtime"
2022-08-27 13:21:05 +00:00
)
2023-04-05 12:54:38 +00:00
var safeDb = safety.NewVar[*sqlx.DB](nil)
var showQuerySql func() bool
2022-08-27 13:21:05 +00:00
2024-03-27 05:09:46 +00:00
func GetSqlxDB() *sqlx.DB {
return safeDb.Load()
}
2023-04-05 12:54:38 +00:00
func InitDb() (*safety.Var[*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()
2023-04-05 12:54:38 +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
}
2023-04-11 05:11:21 +00:00
preDb := safeDb.Load()
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-04-05 12:54:38 +00:00
safeDb.Store(db)
2023-04-11 05:42:14 +00:00
if preDb != nil {
_ = preDb.Close()
}
if showQuerySql == nil {
showQuerySql = reload.BuildFnVal("showQuerySql", false, func() bool {
return config.GetConfig().ShowQuerySql
})
}
2023-04-05 12:54:38 +00:00
return safeDb, err
2022-08-27 13:21:05 +00:00
}
2023-02-10 13:23:30 +00:00
2023-04-05 12:54:38 +00:00
func QueryDb(db *safety.Var[*sqlx.DB]) *model.SqlxQuery {
query := model.NewSqlxQuery(db, model.NewUniversalDb(
nil,
nil))
model.SetSelect(query, func(ctx context.Context, a any, s string, args ...any) error {
if showQuerySql() {
_, f, l, _ := runtime.Caller(5)
go func() {
log.Printf("%v:%v %v\n", f, l, model.FormatSql(s, args...))
}()
}
return query.Selects(ctx, a, s, args...)
})
model.SetGet(query, func(ctx context.Context, a any, s string, args ...any) error {
if showQuerySql() {
_, f, l, _ := runtime.Caller(5)
go func() {
log.Printf("%v:%v %v\n", f, l, model.FormatSql(s, args...))
}()
}
return query.Gets(ctx, a, s, args...)
})
2023-02-10 13:23:30 +00:00
return query
}