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

56 lines
1.3 KiB
Go
Raw Permalink Normal View History

2022-08-27 13:21:05 +00:00
package db
import (
2023-02-10 13:23:30 +00:00
"context"
"github.com/fthvgb1/wp-go/internal/pkg/config"
2023-02-10 13:23:30 +00:00
"github.com/fthvgb1/wp-go/model"
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"
2022-08-27 13:21:05 +00:00
)
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
}
2023-02-10 13:23:30 +00:00
func QueryDb(db *sqlx.DB) *model.SqlxQuery {
query := model.NewSqlxQuery(db, model.NewUniversalDb(
nil,
nil))
2023-02-10 13:23:30 +00:00
model.SetSelect(query, func(ctx context.Context, a any, s string, args ...any) error {
if config.GetConfig().ShowQuerySql {
go log.Println(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 config.GetConfig().ShowQuerySql {
go log.Println(model.FormatSql(s, args...))
}
return query.Gets(ctx, a, s, args...)
})
2023-02-10 13:23:30 +00:00
return query
}