How do I run migrations using database/sql with Postgres?

Running migrations using Go's database/sql package with Postgres involves executing SQL statements to create or modify database structures. Here's how you can effectively manage migrations.

Keywords: Go migrations, database/sql, Postgres, Go database migrations, SQL migrations
Description: This guide provides an overview of running migrations in Go using the database/sql package with a PostgreSQL database. Learn how to execute SQL migration scripts efficiently.
package main import ( "database/sql" "log" _ "github.com/lib/pq" // Postgres driver ) func main() { // Connect to the Postgres database connStr := "user=username dbname=mydb password=mysecretpassword sslmode=disable" db, err := sql.Open("postgres", connStr) if err != nil { log.Fatal(err) } defer db.Close() // Create a migration function err = runMigrations(db) if err != nil { log.Fatal(err) } log.Println("Migrations completed successfully!") } func runMigrations(db *sql.DB) error { // Example of a simple migration script sqlStatement := ` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name VARCHAR(50), email VARCHAR(50) UNIQUE NOT NULL );` _, err := db.Exec(sqlStatement) return err }

Keywords: Go migrations database/sql Postgres Go database migrations SQL migrations