65 lines
1.4 KiB
Go
65 lines
1.4 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"github.com/jackc/pgx/v4/pgxpool"
|
|
"github.com/knadh/koanf"
|
|
"github.com/rs/zerolog/log"
|
|
"time"
|
|
)
|
|
|
|
func InitPool(config *koanf.Koanf) *pgxpool.Pool {
|
|
pool := NewPool(config)
|
|
|
|
if err := runMigrations(pool); err != nil {
|
|
log.Fatal().Err(err).Msg("Couldn't apply migrations")
|
|
panic(err)
|
|
}
|
|
|
|
return pool
|
|
}
|
|
|
|
func NewPool(config *koanf.Koanf) *pgxpool.Pool {
|
|
connStr, err := getConnectionString(config)
|
|
if err != nil {
|
|
log.Fatal().Err(err).Msg("Couldn't construct DB connection string")
|
|
panic(err)
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
|
|
pool, err := pgxpool.Connect(ctx, connStr)
|
|
if err != nil {
|
|
log.Fatal().Err(err).Msg("Couldn't connect to DB")
|
|
panic(err)
|
|
}
|
|
|
|
return pool
|
|
}
|
|
|
|
func getConnectionString(config *koanf.Koanf) (string, error) {
|
|
username := config.String("db.username")
|
|
if username == "" {
|
|
return "", errors.New("database username is missing")
|
|
}
|
|
|
|
password := config.String("db.password")
|
|
if password == "" {
|
|
return "", errors.New("database password is missing")
|
|
}
|
|
|
|
name := config.String("db.name")
|
|
if name == "" {
|
|
return "", errors.New("database name is missing")
|
|
}
|
|
|
|
host := config.String("db.host")
|
|
if name == "" {
|
|
return "", errors.New("database host is missing")
|
|
}
|
|
|
|
return fmt.Sprintf("postgresql://%s:%s@%s/%s", username, password, host, name), nil
|
|
}
|