2022-11-30 10:51:24 +01:00
|
|
|
package postgres
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2023-03-01 12:19:57 +01:00
|
|
|
"os"
|
2022-11-30 10:51:24 +01:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
2023-03-01 12:19:57 +01:00
|
|
|
"github.com/jackc/tern/v2/migrate"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
schemaTable = "schema_version"
|
2022-11-30 10:51:24 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type PostgresPoolOpts struct {
|
2023-03-01 12:19:57 +01:00
|
|
|
DSN string
|
|
|
|
MigrationsFolderPath string
|
2022-11-30 10:51:24 +01:00
|
|
|
}
|
|
|
|
|
2023-02-17 09:43:20 +01:00
|
|
|
// NewPostgresPool creates a reusbale connection pool across the cic-custodial component.
|
2022-11-30 10:51:24 +01:00
|
|
|
func NewPostgresPool(o PostgresPoolOpts) (*pgxpool.Pool, error) {
|
|
|
|
parsedConfig, err := pgxpool.ParseConfig(o.DSN)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
dbPool, err := pgxpool.NewWithConfig(context.Background(), parsedConfig)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
2023-03-01 12:19:57 +01:00
|
|
|
conn, err := dbPool.Acquire(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer conn.Release()
|
|
|
|
|
|
|
|
migrator, err := migrate.NewMigrator(ctx, conn.Conn(), schemaTable)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := migrator.LoadMigrations(os.DirFS(o.MigrationsFolderPath)); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := migrator.Migrate(ctx); err != nil {
|
2022-11-30 10:51:24 +01:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return dbPool, nil
|
|
|
|
}
|