Add existing codebase

This commit is contained in:
Andrey Chervyakov 2021-04-12 17:01:00 +06:00
commit e12550a643
25 changed files with 1409 additions and 0 deletions

View file

@ -0,0 +1,47 @@
package database
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/knadh/koanf"
)
func Pool(config *koanf.Koanf) *pgxpool.Pool {
connStr, err := getConnectionString(config)
if err != nil {
panic(err)
}
pool, err := pgxpool.Connect(context.Background(), connStr)
if err != nil {
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,27 @@
package database
import (
"context"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/jackc/tern/migrate"
)
func Migrate(pool *pgxpool.Pool) {
conn, err := pool.Acquire(context.Background())
if err != nil {
panic(err)
}
migrator, err := migrate.NewMigrator(context.Background(), conn.Conn(), "schema_version")
if err != nil {
panic(err)
}
if err = migrator.LoadMigrations("./migrations"); err != nil {
panic(err)
}
if err = migrator.Migrate(context.Background()); err != nil {
panic(err)
}
}