Put project modules under pkg directory

This commit is contained in:
Andrey Chervyakov 2021-04-12 17:17:09 +06:00
parent f4684be37d
commit e1516e450b
13 changed files with 7 additions and 7 deletions

View file

@ -0,0 +1,65 @@
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
}

View file

@ -0,0 +1,33 @@
package database
import (
"context"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/jackc/tern/migrate"
"time"
)
func runMigrations(pool *pgxpool.Pool) (err error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
conn, err := pool.Acquire(ctx)
if err != nil {
return
}
migrator, err := migrate.NewMigrator(ctx, conn.Conn(), "schema_version")
if err != nil {
return
}
if err = migrator.LoadMigrations("./migrations"); err != nil {
return
}
if err = migrator.Migrate(ctx); err != nil {
return
}
return
}

View file

@ -0,0 +1,15 @@
package database
import (
"github.com/jackc/pgx/v4/pgxpool"
"github.com/rs/zerolog/log"
)
func LogPoolState(pool *pgxpool.Pool, message string) {
stat := pool.Stat()
log.Info().
Int32("acquired_conns", stat.AcquiredConns()).
Int32("idle_conns", stat.IdleConns()).
Int32("total_conns", stat.TotalConns()).
Msg(message)
}