forked from mtusi2026/mtusi2026lab4
85 lines
1.8 KiB
Go
85 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"embed"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
//go:embed migrations/*.sql
|
|
var migrationFS embed.FS
|
|
|
|
func migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
|
defer cancel()
|
|
|
|
conn, err := pool.Acquire(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer conn.Release()
|
|
if _, err := conn.Exec(ctx, `select pg_advisory_lock(727001)`); err != nil {
|
|
return err
|
|
}
|
|
defer conn.Exec(context.Background(), `select pg_advisory_unlock(727001)`)
|
|
|
|
_, err = conn.Exec(ctx, `
|
|
create table if not exists schema_migrations (
|
|
version text primary key,
|
|
applied_at timestamptz not null
|
|
)`)
|
|
if err != nil {
|
|
return fmt.Errorf("schema_migrations: %w", err)
|
|
}
|
|
|
|
entries, err := migrationFS.ReadDir("migrations")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var names []string
|
|
for _, e := range entries {
|
|
if !e.IsDir() && strings.HasSuffix(e.Name(), ".sql") {
|
|
names = append(names, e.Name())
|
|
}
|
|
}
|
|
sort.Strings(names)
|
|
|
|
for _, name := range names {
|
|
var exists bool
|
|
err := conn.QueryRow(ctx, `select exists(select 1 from schema_migrations where version=$1)`, name).Scan(&exists)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if exists {
|
|
continue
|
|
}
|
|
|
|
body, err := migrationFS.ReadFile("migrations/" + name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
tx, err := conn.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := tx.Exec(ctx, string(body)); err != nil {
|
|
_ = tx.Rollback(ctx)
|
|
return fmt.Errorf("migration %s: %w", name, err)
|
|
}
|
|
if _, err := tx.Exec(ctx, `insert into schema_migrations(version, applied_at) values($1, now())`, name); err != nil {
|
|
_ = tx.Rollback(ctx)
|
|
return err
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|