Files
mtusi2026lab6/internal/database/database.go
T

106 lines
2.8 KiB
Go

package database
import (
"context"
"crypto/sha256"
"embed"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"mtusi/messenger/internal/telemetry"
"os"
"sort"
"strconv"
"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
if v := os.Getenv("DB_POOL_MAX"); v != "" {
n, e := strconv.Atoi(v)
if e != nil || n < 1 || n > 64 {
return nil, fmt.Errorf("DB_POOL_MAX must be 1..64")
}
cfg.MaxConns = int32(n)
}
cfg.ConnConfig.Tracer = telemetry.DBTracer{}
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)
}