58 lines
1.9 KiB
Go
58 lines
1.9 KiB
Go
package bootstrap
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"time"
|
|
|
|
"lincodex/backend/config"
|
|
"lincodex/backend/db"
|
|
"lincodex/backend/internal/adapter/secondary/postgres"
|
|
)
|
|
|
|
// startupMigrationTimeout bounds lock waiting and migration work before the
|
|
// servers start. It matches the migration lock retry window.
|
|
const startupMigrationTimeout = 5 * time.Minute
|
|
|
|
// migrateDatabase applies embedded migrations before any listener opens, so the
|
|
// service never serves requests against an older schema. Without DATABASE_URL
|
|
// the service keeps its existing behavior: it starts and reports not ready.
|
|
func migrateDatabase(ctx context.Context, settings config.Config, logger *slog.Logger) error {
|
|
if !settings.DatabaseMigrateOnStart {
|
|
logger.Info("startup database migrations are disabled")
|
|
return nil
|
|
}
|
|
if settings.DatabaseURL == "" {
|
|
logger.Warn("startup database migrations skipped because DATABASE_URL is not set")
|
|
return nil
|
|
}
|
|
migrations, err := db.Migrations()
|
|
if err != nil {
|
|
return fmt.Errorf("bootstrap.migrateDatabase - load migrations: %w", err)
|
|
}
|
|
migrator, err := postgres.NewMigrator(settings.DatabaseURL, migrations)
|
|
if err != nil {
|
|
return fmt.Errorf("bootstrap.migrateDatabase - create migrator: %w", err)
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, startupMigrationTimeout)
|
|
defer cancel()
|
|
applied, err := migrator.Up(ctx)
|
|
if closeErr := migrator.Close(); closeErr != nil {
|
|
err = errors.Join(err, fmt.Errorf("bootstrap.migrateDatabase - close migrator: %w", closeErr))
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("bootstrap.migrateDatabase - apply migrations: %w", err)
|
|
}
|
|
for _, migration := range applied {
|
|
logger.Info("database migration applied",
|
|
slog.Int64("version", migration.Version),
|
|
slog.String("name", migration.Name),
|
|
slog.Duration("duration", migration.Duration),
|
|
)
|
|
}
|
|
logger.Info("database schema is up to date", slog.Int("applied_migrations", len(applied)))
|
|
return nil
|
|
}
|