95 lines
2.5 KiB
Go
95 lines
2.5 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"embed"
|
|
"fmt"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"sort"
|
|
"time"
|
|
)
|
|
|
|
//go:embed migrations/*.sql
|
|
var migrations embed.FS
|
|
|
|
func Open(ctx context.Context, url string) (*pgxpool.Pool, error) {
|
|
cfg, err := pgxpool.ParseConfig(url)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid database configuration")
|
|
}
|
|
cfg.MaxConns = 10
|
|
cfg.MinConns = 0
|
|
cfg.MaxConnLifetime = 30 * time.Minute
|
|
cfg.MaxConnIdleTime = 5 * time.Minute
|
|
cfg.ConnConfig.ConnectTimeout = 2 * time.Second
|
|
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "2000"
|
|
cfg.ConnConfig.RuntimeParams["lock_timeout"] = "1000"
|
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("cannot create database pool")
|
|
}
|
|
if err = pool.Ping(ctx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("database unavailable")
|
|
}
|
|
return pool, nil
|
|
}
|
|
|
|
// All migrations and the version ledger commit together. An advisory lock also
|
|
// serializes bootstrap across API instances; edited applied migrations fail.
|
|
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
|
tx, err := pool.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(2026002)"); err != nil {
|
|
return err
|
|
}
|
|
if _, err = tx.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())`); err != nil {
|
|
return err
|
|
}
|
|
entries, err := migrations.ReadDir("migrations")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
|
|
for _, entry := range entries {
|
|
body, err := migrations.ReadFile("migrations/" + entry.Name())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
checksum := fmt.Sprintf("%x", sha256.Sum256(body))
|
|
var stored string
|
|
rows, err := tx.Query(ctx, "SELECT checksum FROM schema_migrations WHERE version=$1", entry.Name())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
found := rows.Next()
|
|
if found {
|
|
err = rows.Scan(&stored)
|
|
}
|
|
if err == nil {
|
|
err = rows.Err()
|
|
}
|
|
rows.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if found {
|
|
if stored != checksum {
|
|
return fmt.Errorf("applied migration changed: %s", entry.Name())
|
|
}
|
|
continue
|
|
}
|
|
if _, err = tx.Exec(ctx, string(body)); err != nil {
|
|
return err
|
|
}
|
|
if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version,checksum) VALUES($1,$2)", entry.Name(), checksum); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return tx.Commit(ctx)
|
|
}
|