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"
|
|
|
|
"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
|
|
|
// Connect ...
|
2022-08-26 08:17:25 +00:00
|
|
|
func Connect(cfg Config, server string) (*sql.DB, error) {
|
2022-08-24 08:45:16 +00:00
|
|
|
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
|
2022-08-24 08:46:56 +00:00
|
|
|
db, 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
|
2022-08-24 08:46:56 +00:00
|
|
|
if err = db.Ping(); err != nil {
|
2022-12-19 04:22:38 +00:00
|
|
|
fmt.Printf("[postgresql] pgx ping error: %s", err.Error())
|
2022-08-26 08:17:25 +00:00
|
|
|
return nil, err
|
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-26 08:17:25 +00:00
|
|
|
return db, nil
|
2022-08-24 08:45:16 +00:00
|
|
|
}
|