aboutsummaryrefslogtreecommitdiffstats
path: root/backend/internal/database/database.go
blob: 15228e2ad36abfcd3ef1056199d4133e51719220 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
}