package migrate import ( "context" "fmt" "os" "path/filepath" "sort" "strings" "github.com/jackc/pgx/v5/pgxpool" ) func Apply(ctx context.Context, pool *pgxpool.Pool, dir string) error { entries, err := os.ReadDir(dir) if err != nil { return fmt.Errorf("read migrations: %w", err) } var names []string for _, entry := range entries { if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") { continue } names = append(names, entry.Name()) } sort.Strings(names) if len(names) == 0 { return fmt.Errorf("no sql migrations in %s", dir) } _, err = pool.Exec(ctx, ` CREATE TABLE IF NOT EXISTS schema_migrations ( version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now() )`) if err != nil { return err } for _, name := range names { var exists bool if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = $1)`, name).Scan(&exists); err != nil { return err } if exists { continue } body, err := os.ReadFile(filepath.Join(dir, name)) if err != nil { return err } tx, err := pool.Begin(ctx) if err != nil { return err } for _, stmt := range statements(string(body)) { if _, err := tx.Exec(ctx, stmt); err != nil { _ = tx.Rollback(ctx) return fmt.Errorf("%s: %w", name, err) } } if _, err := tx.Exec(ctx, `INSERT INTO schema_migrations (version) VALUES ($1)`, name); err != nil { _ = tx.Rollback(ctx) return err } if err := tx.Commit(ctx); err != nil { return err } } return nil } func statements(body string) []string { parts := strings.Split(body, ";") out := make([]string, 0, len(parts)) for _, part := range parts { stmt := strings.TrimSpace(part) if stmt != "" { out = append(out, stmt) } } return out }