package database import ( "context" "embed" "fmt" "time" "github.com/jackc/pgx/v5/pgxpool" ) //go:embed migrations/001_initial.sql var migrations embed.FS func Open(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) { cfg, err := pgxpool.ParseConfig(databaseURL) if err != nil { return nil, fmt.Errorf("parse database URL: %w", err) } cfg.MaxConns = 20 cfg.MinConns = 1 cfg.MaxConnLifetime = 30 * time.Minute cfg.MaxConnIdleTime = 5 * time.Minute pool, err := pgxpool.NewWithConfig(ctx, cfg) if err != nil { return nil, fmt.Errorf("open database: %w", err) } if err := pool.Ping(ctx); err != nil { pool.Close() return nil, fmt.Errorf("ping database: %w", err) } return pool, nil } func Migrate(ctx context.Context, pool *pgxpool.Pool) error { data, err := migrations.ReadFile("migrations/001_initial.sql") if err != nil { return fmt.Errorf("read migration: %w", err) } lockCtx, cancel := context.WithTimeout(ctx, 5*time.Minute) defer cancel() conn, err := pool.Acquire(lockCtx) if err != nil { return fmt.Errorf("acquire migration connection: %w", err) } defer conn.Release() if _, err := conn.Exec(lockCtx, `SELECT pg_advisory_lock(42424242)`); err != nil { return fmt.Errorf("acquire migration lock: %w", err) } defer func() { _, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock(42424242)`) }() if _, err := conn.Exec(lockCtx, string(data)); err != nil { return fmt.Errorf("run migration: %w", err) } return nil }