postgresql/postgresql.go

73 lines
1.6 KiB
Go

package postgresql
import (
"database/sql"
"fmt"
"time"
_ "github.com/jackc/pgx/v4/stdlib"
"github.com/volatiletech/sqlboiler/v4/boil"
"go.elastic.co/apm/module/apmsql/v2"
_ "go.elastic.co/apm/module/apmsql/v2/pgxv4"
)
type Config struct {
Host string
Port int
User string
Password string
DBName string
SSLMode string
IsDebug bool
MaxOpenConnections int
MaxIdleConnections int
ConnectionLifetime time.Duration
UseElasticAPM bool
}
// Connect ...
func Connect(cfg Config, server string) (db *sql.DB, err error) {
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)
// connect
if cfg.UseElasticAPM {
db, err = apmsql.Open("pgx", uri)
} else {
db, err = sql.Open("pgx", uri)
}
if err != nil {
panic(err)
}
// ping
if err = db.Ping(); err != nil {
fmt.Printf("[postgresql] pgx ping error: %s", err.Error())
return nil, err
}
// 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)
// run migration
runMigration(db, server)
// debug mode
boil.DebugMode = cfg.IsDebug
fmt.Printf("⚡️[postgres]: connected to %s:%d, with APM: %t \n", cfg.Host, cfg.Port, cfg.UseElasticAPM)
return db, nil
}