72 lines
1.7 KiB
Go
72 lines
1.7 KiB
Go
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
|
|
}
|