2022-05-02 08:19:37 -07:00
|
|
|
// migrate runs (forward) migrations
|
2023-03-15 02:04:48 -07:00
|
|
|
package migrate
|
2022-05-02 08:19:37 -07:00
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"embed"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/joho/godotenv"
|
|
|
|
migrate "github.com/rubenv/sql-migrate"
|
2023-03-15 02:04:48 -07:00
|
|
|
"github.com/urfave/cli/v2"
|
2022-05-02 08:19:37 -07:00
|
|
|
|
|
|
|
// SQL driver
|
2023-04-03 19:11:03 -07:00
|
|
|
_ "github.com/jackc/pgx/v5/stdlib"
|
2022-05-02 08:19:37 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
//go:embed *.sql
|
|
|
|
var migrations embed.FS
|
|
|
|
|
2023-03-15 02:04:48 -07:00
|
|
|
var Command = &cli.Command{
|
|
|
|
Name: "migrate",
|
|
|
|
Usage: "Migrate the database",
|
|
|
|
Action: run,
|
|
|
|
}
|
|
|
|
|
|
|
|
func run(c *cli.Context) error {
|
2022-05-02 08:19:37 -07:00
|
|
|
err := godotenv.Load()
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("error loading .env file:", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("error opening database:", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Println("opened database")
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
err := db.Close()
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("error closing database:", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
if err := db.Ping(); err != nil {
|
|
|
|
fmt.Println("error pinging database:", err)
|
2023-03-15 02:04:48 -07:00
|
|
|
return nil
|
2022-05-02 08:19:37 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
src := &migrate.EmbedFileSystemMigrationSource{
|
|
|
|
FileSystem: migrations,
|
|
|
|
Root: ".",
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Println("executing migrations")
|
|
|
|
n, err := migrate.Exec(db, "postgres", src, migrate.Up)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("error executing migrations:", err)
|
2023-03-15 02:04:48 -07:00
|
|
|
return nil
|
2022-05-02 08:19:37 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
if n == 0 {
|
|
|
|
fmt.Println("database is already up to date")
|
|
|
|
} else {
|
|
|
|
fmt.Printf("executed %v migrations!\n", n)
|
|
|
|
}
|
2023-03-15 02:04:48 -07:00
|
|
|
return nil
|
2022-05-02 08:19:37 -07:00
|
|
|
}
|