some fixes related to the logic of how we initially create the db and run migs
This commit is contained in:
+4
-4
@@ -2,9 +2,9 @@ assets: "./assets/"
|
||||
port: 8081
|
||||
postgres:
|
||||
user: expdbuser
|
||||
pass: thepass
|
||||
db: thedb
|
||||
host: /home/esilva/Desktop/projetos/expenses/src/pgImage/pgSocket/
|
||||
port: 5432
|
||||
pass: expDBPass
|
||||
db: expenses
|
||||
host: "127.0.0.1"
|
||||
port: 5431
|
||||
migrationsPath: "file://expenses/repo/pgdb/migrations/"
|
||||
migCustomScripts: "./expenses/repo/pgdb/migrations/custom/"
|
||||
|
||||
+87
-5
@@ -3,12 +3,15 @@ package expenses
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"github.com/ESilva15/expenses/config"
|
||||
"github.com/ESilva15/expenses/expenses/repo"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
@@ -57,25 +60,73 @@ func getPgConnString(cfg *config.Configuration) string {
|
||||
cfg.PgCfg.User, cfg.PgCfg.Pass, cfg.PgCfg.DB, cfg.PgCfg.Host, cfg.PgCfg.Port)
|
||||
}
|
||||
|
||||
func createTargetDatabase(cfg *config.Configuration) error {
|
||||
// Connect to the default 'postgres' database instead of cfg.PgCfg.DB
|
||||
adminConnStr := fmt.Sprintf("postgres://%s:%s@/%s?host=%s&port=%s&sslmode=disable",
|
||||
cfg.PgCfg.User, cfg.PgCfg.Pass, "postgres", cfg.PgCfg.Host, cfg.PgCfg.Port)
|
||||
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, adminConnStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to connect to default postgres db: %w", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
// Execute CREATE DATABASE (Note: database identifiers cannot be parameterized with $1)
|
||||
query := fmt.Sprintf("CREATE DATABASE %s", cfg.PgCfg.DB)
|
||||
_, err = pool.Exec(ctx, query)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create database: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("Database %q created successfully!", cfg.PgCfg.DB)
|
||||
return nil
|
||||
}
|
||||
|
||||
func runMigrations(luaVM *lua.LState) error {
|
||||
cfg := config.GetInstance()
|
||||
pgStr := getPgConnString(cfg)
|
||||
|
||||
migrator, err := repo.NewPgMigrator(pgStr)
|
||||
if err != nil {
|
||||
return err
|
||||
// Check if error is due to database not existing
|
||||
if isDatabaseNotFoundError(err) {
|
||||
log.Printf("Database %q does not exist. Creating it...", cfg.PgCfg.DB)
|
||||
if createErr := createTargetDatabase(cfg); createErr != nil {
|
||||
return fmt.Errorf("failed to create missing database: %w", createErr)
|
||||
}
|
||||
|
||||
// Retry creating the migrator after the database is created
|
||||
migrator, err = repo.NewPgMigrator(pgStr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
err = migrator.RunMigrations(luaVM)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to apply migrations: %v", err)
|
||||
migrator.Close()
|
||||
return fmt.Errorf("failed to apply migrations: %w", err)
|
||||
}
|
||||
|
||||
migrator.Close()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Helper to check for PostgreSQL code "3D000" or text fallback
|
||||
func isDatabaseNotFoundError(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "3D000" {
|
||||
return true
|
||||
}
|
||||
|
||||
// Fallback string check if wrapped differently by the repo layer
|
||||
return strings.Contains(err.Error(), "does not exist")
|
||||
}
|
||||
|
||||
// GoToMigration provides a way to force moving to the specified migration.
|
||||
func (a *ExpApp) GoToMigration(id uint) error {
|
||||
cfg := config.GetInstance()
|
||||
@@ -107,6 +158,37 @@ func createPGXPoolConn(ctx context.Context) (*pgxpool.Pool, error) {
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func PrepareDB(ctx context.Context, luaVM *lua.LState) error {
|
||||
// Attempt to prepare the database
|
||||
err := runMigrations(luaVM)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to run migrations: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func CheckDatabase(ctx context.Context, luaVM *lua.LState) error {
|
||||
cfg := config.GetInstance()
|
||||
pgStr := getPgConnString(cfg)
|
||||
|
||||
conn, err := pgxpool.New(ctx, pgStr)
|
||||
if err != nil {
|
||||
// Unable to create the database
|
||||
return err
|
||||
}
|
||||
|
||||
var result int
|
||||
err = conn.QueryRow(ctx, "SELECT status,version FROM dbstat").Scan(&result)
|
||||
if err != nil {
|
||||
if err := PrepareDB(ctx, luaVM); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartApp will configure and open the required connections to run this app.
|
||||
func StartApp() error {
|
||||
config.SetConfig("./config.yaml")
|
||||
@@ -118,13 +200,13 @@ func StartApp() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Run the migrations
|
||||
// Run migrations (will automatically create the database if it doesn't exist)
|
||||
err = runMigrations(luaVM)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to run migrations: %v", err)
|
||||
}
|
||||
|
||||
// Create our final app thing
|
||||
// Create our final app pool connection
|
||||
conn, err := createPGXPoolConn(ctx)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to open DB: %v", err)
|
||||
|
||||
Reference in New Issue
Block a user