postgresql/postgresql.go

79 lines
1.5 KiB
Go
Raw Normal View History

2021-08-09 03:24:54 +00:00
package postgresql
import (
2022-08-24 08:45:16 +00:00
"database/sql"
2021-08-09 03:24:54 +00:00
"fmt"
2022-08-24 08:45:16 +00:00
"github.com/Selly-Modules/logger"
2021-08-09 03:24:54 +00:00
"time"
2022-08-24 08:45:16 +00:00
_ "github.com/jackc/pgx/v4/stdlib"
"github.com/volatiletech/sqlboiler/v4/boil"
2021-08-09 03:24:54 +00:00
)
2022-08-24 08:45:16 +00:00
type Config struct {
Host string
Port int
User string
Password string
DBName string
SSLMode string
IsDebug bool
MaxOpenConnections int
MaxIdleConnections int
ConnectionLifetime time.Duration
}
2021-08-09 03:24:54 +00:00
2022-08-24 08:45:16 +00:00
var db *sql.DB
2021-08-09 03:24:54 +00:00
2022-08-24 08:45:16 +00:00
// Connect ...
func Connect(cfg Config, server string) {
uri := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName, cfg.SSLMode)
2021-08-09 03:30:00 +00:00
2022-08-24 08:45:16 +00:00
// connect
c, err := sql.Open("pgx", uri)
2021-08-09 03:24:54 +00:00
if err != nil {
2022-08-24 08:45:16 +00:00
panic(err)
}
// ping
if err = c.Ping(); err != nil {
logger.Error("pgx ping", logger.LogData{
Source: "Connect",
Message: err.Error(),
Data: cfg,
})
panic(err)
2021-08-09 03:24:54 +00:00
}
2022-08-24 08:45:16 +00:00
// assign
db = c
2021-08-09 03:24:54 +00:00
2022-08-24 08:45:16 +00:00
// config
if cfg.MaxOpenConnections == 0 {
cfg.MaxOpenConnections = 25
}
if cfg.MaxIdleConnections == 0 {
cfg.MaxIdleConnections = 25
}
if cfg.ConnectionLifetime == 0 {
cfg.ConnectionLifetime = 5 * time.Minute
}
db.SetMaxOpenConns(cfg.MaxOpenConnections)
db.SetMaxIdleConns(cfg.MaxIdleConnections)
db.SetConnMaxLifetime(cfg.ConnectionLifetime)
2021-08-09 03:24:54 +00:00
2022-08-24 08:45:16 +00:00
// run migration
runMigration(db, server)
2021-08-09 03:24:54 +00:00
2022-08-24 08:45:16 +00:00
// debug mode
boil.DebugMode = cfg.IsDebug
2021-08-09 03:24:54 +00:00
2022-08-24 08:45:16 +00:00
fmt.Printf("⚡️[postgres]: connected to %s:%d \n", cfg.Host, cfg.Port)
2021-08-09 03:24:54 +00:00
}
2022-08-24 08:45:16 +00:00
// GetDB ...
func GetDB() *sql.DB {
return db
}