How do I run migrations using pgx?

To run migrations using pgx in Go, you'll typically follow a series of steps that involve setting up your PostgreSQL database connection, creating migration files, and applying those migrations programmatically. Below is an example of how to structure your migration script using the pgx library.

// Import necessary packages package main import ( "context" "github.com/jackc/pgx/v4" "log" "os" ) func main() { // Connect to the PostgreSQL database conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) if err != nil { log.Fatal(err) } defer conn.Close(context.Background()) // Define your migrations migrations := []string{ `CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name TEXT, email TEXT UNIQUE );`, // Add more migrations as needed } // Execute the migrations for _, migration := range migrations { _, err := conn.Exec(context.Background(), migration) if err != nil { log.Fatalf("Failed to execute migration: %v", err) } } log.Println("Migrations applied successfully!") }

pgx Go migrations PostgreSQL database migrations go postgres pgx migration example