From 454dcf573a14fa4cf29ee3cfcb1fcd1fc097b343 Mon Sep 17 00:00:00 2001 From: Alexis Viscogliosi Date: Thu, 31 Oct 2024 13:33:24 +0100 Subject: [PATCH] refactor: improve error message and code organization in amigo package --- cmd/root.go | 5 +++-- pkg/amigo/setup_slog.go | 6 +++++- pkg/schema/migrator.go | 8 ++++++-- pkg/schema/sql_migration_impl.go | 4 ++-- 4 files changed, 16 insertions(+), 7 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index ff90825..927f1a6 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -2,13 +2,14 @@ package cmd import ( "fmt" + "os" + "path/filepath" + "github.com/alexisvisco/amigo/pkg/amigo" "github.com/alexisvisco/amigo/pkg/amigoctx" "github.com/alexisvisco/amigo/pkg/utils/events" "github.com/alexisvisco/amigo/pkg/utils/logger" "github.com/spf13/viper" - "os" - "path/filepath" "github.com/spf13/cobra" ) diff --git a/pkg/amigo/setup_slog.go b/pkg/amigo/setup_slog.go index 0cabd70..2484fad 100644 --- a/pkg/amigo/setup_slog.go +++ b/pkg/amigo/setup_slog.go @@ -1,13 +1,17 @@ package amigo import ( - "github.com/alexisvisco/amigo/pkg/utils/logger" "io" "log/slog" + + "github.com/alexisvisco/amigo/pkg/utils/logger" ) func (a Amigo) SetupSlog(writer io.Writer) { logger.ShowSQLEvents = a.ctx.ShowSQL + if writer == nil { + return + } if a.ctx.JSON { slog.SetDefault(slog.New(slog.NewJSONHandler(writer, nil))) diff --git a/pkg/schema/migrator.go b/pkg/schema/migrator.go index babe022..82821e7 100644 --- a/pkg/schema/migrator.go +++ b/pkg/schema/migrator.go @@ -3,6 +3,7 @@ package schema import ( "context" "fmt" + "reflect" "regexp" "slices" "time" @@ -113,8 +114,11 @@ func (m *Migrator[T]) Apply(direction types.MigrationDirection, version *string, case SimpleMigration[T]: migrationFunc = t.Change default: - logger.Error(events.MessageEvent{Message: fmt.Sprintf("Migration %s is not a valid migration", - migration.Name())}) + reflectionType := fmt.Sprintf("%T", migration) + driverValue := fmt.Sprintf("%v", reflect.TypeOf(new(T)).Elem()) + + logger.Error(events.MessageEvent{Message: fmt.Sprintf("Migration %s is not a valid migration type, found %s (driver is %s). Did you set DSN correctly ?", + migration.Name(), reflectionType, driverValue)}) return false } diff --git a/pkg/schema/sql_migration_impl.go b/pkg/schema/sql_migration_impl.go index e2b4964..a55567a 100644 --- a/pkg/schema/sql_migration_impl.go +++ b/pkg/schema/sql_migration_impl.go @@ -14,8 +14,8 @@ type SQLMigration[T Schema] struct { delimiter string } -func NewSQLMigration[T Schema](fs embed.FS, name string, time string, delimiter string) SQLMigration[T] { - return SQLMigration[T]{fs: fs, name: name, time: time, delimiter: delimiter} +func NewSQLMigration[T Schema](fs embed.FS, name string, time string, delimiter string) DetailedMigration[T] { + return &SQLMigration[T]{fs: fs, name: name, time: time, delimiter: delimiter} } func (s SQLMigration[T]) Up(x T) {