niki/repository/mysql/db.go

50 lines
1.1 KiB
Go
Raw 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"`
}
2024-01-01 07:22:14 +00:00
type DB struct {
2023-12-16 07:20:01 +00:00
config Config
db *sql.DB
}
2024-01-01 07:22:14 +00:00
func (m *DB) Conn() *sql.DB {
2023-12-16 07:20:01 +00:00
return m.db
}
2024-01-01 07:22:14 +00:00
// TODO: this temperary to ignore linter error (magic number).
const (
dbMaxConnLifetime = time.Minute * 3
dbMaxOpenConns = 10
dbMaxIdleConns = 10
)
func New(config Config) *DB {
2023-12-16 07:20:01 +00:00
// 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 {
2024-01-01 07:22:14 +00:00
panic(fmt.Errorf("can't open mysql db: %w", err))
2023-12-16 07:20:01 +00:00
}
// See "Important settings" section.
2024-01-01 07:22:14 +00:00
db.SetConnMaxLifetime(dbMaxConnLifetime)
db.SetMaxOpenConns(dbMaxOpenConns)
db.SetMaxIdleConns(dbMaxIdleConns)
2023-12-16 07:20:01 +00:00
2024-01-01 07:22:14 +00:00
return &DB{config: config, db: db}
2023-12-16 07:20:01 +00:00
}