69 lines
1.4 KiB
Go
69 lines
1.4 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
c "scripts/internal/config"
|
|
l "scripts/pkg/logger"
|
|
"time"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
_ "github.com/lib/pq"
|
|
)
|
|
|
|
var DB *Postgres
|
|
|
|
type Option func(*Postgres)
|
|
|
|
type Postgres struct {
|
|
ctx context.Context
|
|
conn *sqlx.DB
|
|
}
|
|
|
|
func (p *Postgres) Conn() *sqlx.DB {
|
|
return p.conn
|
|
}
|
|
|
|
func (p *Postgres) Context() context.Context {
|
|
return p.ctx
|
|
}
|
|
|
|
func WithContext(ctx context.Context) Option {
|
|
return func(p *Postgres) {
|
|
p.ctx = ctx
|
|
}
|
|
}
|
|
|
|
func InitDB(opts ...Option) {
|
|
p := &Postgres{
|
|
ctx: context.Background(),
|
|
}
|
|
|
|
for _, opt := range opts {
|
|
opt(p)
|
|
}
|
|
|
|
db, err := sqlx.ConnectContext(p.ctx, c.Conf.SqlSettings.DriverName, c.Conf.SqlSettings.DataSource)
|
|
if err != nil {
|
|
l.Log.Fatal().Err(err).Msg("failed to connect DB")
|
|
}
|
|
|
|
db.SetMaxIdleConns(c.Conf.SqlSettings.MaxIdleConns)
|
|
db.SetMaxOpenConns(c.Conf.SqlSettings.MaxOpenConns)
|
|
db.SetConnMaxLifetime(time.Duration(c.Conf.SqlSettings.ConnMaxLifetimeMilliseconds) * time.Millisecond)
|
|
db.SetConnMaxIdleTime(time.Duration(c.Conf.SqlSettings.ConnMaxIdleTimeMilliseconds) * time.Millisecond)
|
|
|
|
if err := db.Ping(); err != nil {
|
|
l.Log.Fatal().Err(err).Msg("failed to ping DB")
|
|
}
|
|
|
|
p.conn = db
|
|
DB = p
|
|
l.Log.Info().Msg("connect to postgres successfully ")
|
|
}
|
|
|
|
func (p *Postgres) Close() {
|
|
if err := p.Conn().Close(); err != nil {
|
|
l.Log.Error().Err(err).Msg("failed to close connect DB")
|
|
}
|
|
}
|