Put project modules under pkg directory
This commit is contained in:
parent
f4684be37d
commit
e1516e450b
13 changed files with 7 additions and 7 deletions
65
pkg/cgnolink/database/database.go
Normal file
65
pkg/cgnolink/database/database.go
Normal 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
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue