package helpers import ( "code.lowsec.club/okawari/go-discord-bot/lib/models" "context" "github.com/rs/zerolog/log" "gorm.io/driver/postgres" "gorm.io/gorm" "os" ) func CreateConnection(config *gorm.Config) (*gorm.DB, error) { log.Debug().Msg("Connecting to DB") return gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), config) } func AddDb(ctx context.Context, db *gorm.DB) context.Context { return context.WithValue(ctx, "db", db) } func DB(ctx context.Context) *gorm.DB { if val, ok := ctx.Value("db").(*gorm.DB); ok { return val } log.Fatal().Msg("Could not find DB object") return nil } func AutoMigrate(db *gorm.DB) { hasError := false logger := log.With().Str("module", "sql-migrator").Logger() for _, model := range []any{ models.Commodity{}, } { err := db.AutoMigrate(model) if err != nil { logger.Error().Err(err).Interface("model", model).Msg("Failed to auto migrate") hasError = true } } if hasError { log.Panic().Msg("Exiting") } } func FindCommodity(db *gorm.DB, term string) (*models.Commodity, bool, error) { result := models.Commodity{} tx := db.Model(models.Commodity{}).Where("ticker = ?", term).First(&result) if tx.Error != nil { return nil, false, tx.Error } return &result, tx.RowsAffected > 0, nil }