postgresql/postgresql.go

74 lines
1.6 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"
"time"
2023-02-03 13:58:03 +00:00
"github.com/jackc/pgx/v4/stdlib"
2022-08-24 08:45:16 +00:00
"github.com/volatiletech/sqlboiler/v4/boil"
"go.elastic.co/apm/module/apmsql/v2"
2023-02-03 13:21:16 +00:00
_ "go.elastic.co/apm/module/apmsql/v2/pgxv4"
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
UseElasticAPM bool
2022-08-24 08:45:16 +00:00
}
2021-08-09 03:24:54 +00:00
2022-08-24 08:45:16 +00:00
// Connect ...
func Connect(cfg Config, server string) (db *sql.DB, err 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
if cfg.UseElasticAPM {
2023-02-03 13:58:03 +00:00
apmsql.Register("pgx", &stdlib.Driver{})
2023-02-03 13:22:18 +00:00
db, err = apmsql.Open("pgx", uri)
} else {
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
fmt.Printf("⚡️[postgres]: connected to %s:%d, with APM: %t \n", cfg.Host, cfg.Port, cfg.UseElasticAPM)
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
}