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

79 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-08-27 13:21:05 +00:00
package db
import (
"context"
2022-11-17 03:22:29 +00:00
"fmt"
"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"
2022-11-07 08:37:06 +00:00
"log"
"os"
2022-11-17 03:22:29 +00:00
"strconv"
2022-11-07 08:37:06 +00:00
"strings"
2022-08-27 13:21:05 +00:00
)
var Db *sqlx.DB
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 {
2022-11-07 08:37:06 +00:00
if os.Getenv("SHOW_SQL") == "true" {
2022-11-17 03:22:29 +00:00
go log.Println(formatSql(sql, params))
2022-11-07 08:37:06 +00:00
}
return r.sqlx.Select(dest, sql, params...)
}
func (r SqlxDb) Get(ctx context.Context, dest any, sql string, params ...any) error {
2022-11-07 08:37:06 +00:00
if os.Getenv("SHOW_SQL") == "true" {
2022-11-17 03:22:29 +00:00
go log.Println(formatSql(sql, params))
2022-11-07 08:37:06 +00:00
}
return r.sqlx.Get(dest, sql, params...)
}
2022-11-17 03:22:29 +00:00
func formatSql(sql string, params []any) string {
for _, param := range params {
switch param.(type) {
case string:
sql = strings.Replace(sql, "?", fmt.Sprintf("'%s'", param.(string)), 1)
case int64:
sql = strings.Replace(sql, "?", strconv.FormatInt(param.(int64), 10), 1)
case int:
sql = strings.Replace(sql, "?", strconv.Itoa(param.(int)), 1)
case uint64:
sql = strings.Replace(sql, "?", strconv.FormatUint(param.(uint64), 10), 1)
case float64:
sql = strings.Replace(sql, "?", fmt.Sprintf("%f", param.(float64)), 1)
}
}
return sql
}
2022-08-27 13:21:05 +00:00
func InitDb() error {
2022-11-15 08:36:21 +00:00
c := config.Conf.Load()
dsn := c.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-15 08:36:21 +00:00
if c.Mysql.Pool.ConnMaxIdleTime != 0 {
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 {
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 {
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 {
Db.SetConnMaxLifetime(c.Mysql.Pool.ConnMaxLifetime)
2022-08-27 13:21:05 +00:00
}
return err
}