47 lines
986 B
Go
47 lines
986 B
Go
// Command migrate applies db/schema.sql to DATABASE_URL.
|
|
// Usage: go run ./cmd/migrate [-schema db/schema.sql]
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"flag"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func main() {
|
|
schemaPath := flag.String("schema", "db/schema.sql", "path to schema file")
|
|
flag.Parse()
|
|
|
|
dsn := os.Getenv("DATABASE_URL")
|
|
if dsn == "" {
|
|
fmt.Fprintln(os.Stderr, "error: DATABASE_URL not set")
|
|
os.Exit(1)
|
|
}
|
|
|
|
sqlBytes, err := os.ReadFile(*schemaPath)
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, "error reading schema:", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
|
|
pool, err := pgxpool.New(ctx, dsn)
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, "error connecting:", err)
|
|
os.Exit(1)
|
|
}
|
|
defer pool.Close()
|
|
|
|
if _, err := pool.Exec(ctx, string(sqlBytes)); err != nil {
|
|
fmt.Fprintln(os.Stderr, "error applying schema:", err)
|
|
os.Exit(1)
|
|
}
|
|
fmt.Println("schema applied to", dsn)
|
|
}
|