forked from ebhomengo/niki
1
0
Fork 0
niki/repository/mysql/db.go

43 lines
1000 B
Go
Raw Permalink Normal View History

2023-12-16 07:20:01 +00:00
package mysql
import (
"database/sql"
"fmt"
"time"
)
type Config struct {
Username string `koanf:"username"`
Password string `koanf:"password"`
Port int `koanf:"port"`
Host string `koanf:"host"`
DBName string `koanf:"db_name"`
}
type MySQLDB struct {
config Config
db *sql.DB
}
func (m *MySQLDB) Conn() *sql.DB {
return m.db
}
func New(config Config) *MySQLDB {
// parseTime=true changes the output type of DATE and DATETIME values to time.Time
// instead of []byte / string
// The date or datetime like 0000-00-00 00:00:00 is converted into zero value of time.Time
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@(%s:%d)/%s?parseTime=true",
config.Username, config.Password, config.Host, config.Port, config.DBName))
if err != nil {
panic(fmt.Errorf("can't open mysql db: %v", err))
}
// See "Important settings" section.
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
return &MySQLDB{config: config, db: db}
}