42 lines
1.0 KiB
Go
42 lines
1.0 KiB
Go
// Package store persists the master's state in Postgres.
|
|
package store
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// Store is the Postgres-backed storage for the master.
|
|
type Store struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
// Open connects to Postgres and applies pending migrations.
|
|
func Open(ctx context.Context, url string) (*Store, error) {
|
|
cfg, err := pgxpool.ParseConfig(url)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse DATABASE_URL: %w", err)
|
|
}
|
|
return openWithConfig(ctx, cfg)
|
|
}
|
|
|
|
func openWithConfig(ctx context.Context, cfg *pgxpool.Config) (*Store, error) {
|
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("connect postgres: %w", err)
|
|
}
|
|
if err := migrate(ctx, pool); err != nil {
|
|
pool.Close()
|
|
return nil, err
|
|
}
|
|
return &Store{pool: pool}, nil
|
|
}
|
|
|
|
// Close releases the connection pool.
|
|
func (s *Store) Close() { s.pool.Close() }
|
|
|
|
// Ping checks that Postgres answers. Used by /healthz.
|
|
func (s *Store) Ping(ctx context.Context) error { return s.pool.Ping(ctx) }
|