This commit is contained in:
Pavel Flegr 2026-04-08 17:53:30 +02:00
commit ef105e1cac
22 changed files with 3001 additions and 0 deletions

72
internal/db/migrate.go Normal file
View file

@ -0,0 +1,72 @@
package db
import (
"context"
"fmt"
"os"
"path/filepath"
"sort"
"github.com/jackc/pgx/v5/pgxpool"
)
func RunMigrations(ctx context.Context, pool *pgxpool.Pool, dir string) error {
if _, err := pool.Exec(ctx, `
create table if not exists schema_migrations (
filename text primary key,
applied_at timestamptz not null default now()
)
`); err != nil {
return fmt.Errorf("create schema_migrations: %w", err)
}
entries, err := os.ReadDir(dir)
if err != nil {
return fmt.Errorf("read migrations dir: %w", err)
}
var files []string
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".sql" {
continue
}
files = append(files, entry.Name())
}
sort.Strings(files)
for _, name := range files {
var exists bool
if err := pool.QueryRow(ctx, `select exists(select 1 from schema_migrations where filename = $1)`, name).Scan(&exists); err != nil {
return fmt.Errorf("check migration %s: %w", name, err)
}
if exists {
continue
}
body, err := os.ReadFile(filepath.Join(dir, name))
if err != nil {
return fmt.Errorf("read migration %s: %w", name, err)
}
tx, err := pool.Begin(ctx)
if err != nil {
return fmt.Errorf("begin migration %s: %w", name, err)
}
if _, err := tx.Exec(ctx, string(body)); err != nil {
_ = tx.Rollback(ctx)
return fmt.Errorf("execute migration %s: %w", name, err)
}
if _, err := tx.Exec(ctx, `insert into schema_migrations (filename) values ($1)`, name); err != nil {
_ = tx.Rollback(ctx)
return fmt.Errorf("record migration %s: %w", name, err)
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit migration %s: %w", name, err)
}
}
return nil
}