package database import ( "log" "time" "finance/backend/internal/config" "finance/backend/internal/models" "gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger" ) var DB *gorm.DB // InitDatabase initializes the database connection and runs migrations. func InitDatabase(cfg *config.Config) error { var err error log.Println("Connecting to database...") // Configure GORM logger // You might want to adjust the log level based on environment (e.g., Silent in production) newLogger := logger.New( log.New(log.Writer(), "\r\n", log.LstdFlags), // io writer logger.Config{ SlowThreshold: 200 * time.Millisecond, // Explicitly set slow query threshold LogLevel: logger.Info, // Log all SQL IgnoreRecordNotFoundError: true, Colorful: false, // Disable color in logs, or true if terminal supports }, ) DB, err = gorm.Open(postgres.Open(cfg.DatabaseDSN), &gorm.Config{ Logger: newLogger, }) if err != nil { log.Printf("Failed to connect to database: %v\n", err) return err } log.Println("Database connection established.") // Run Migrations log.Println("Running database migrations...") err = DB.AutoMigrate( &models.User{}, &models.Account{}, &models.Transaction{}, &models.Loan{}, &models.Goal{}, ) if err != nil { log.Printf("Failed to run migrations: %v\n", err) return err } log.Println("Database migrations completed.") return nil }