package db import ( "fmt" "time" "gorm.io/driver/postgres" "gorm.io/gorm" gormlogger "gorm.io/gorm/logger" "tercul/internal/platform/config" "tercul/internal/platform/log" ) // DB is a global database connection instance var DB *gorm.DB // Connect establishes a connection to the database using configuration settings // It returns the database connection and any error encountered func Connect() (*gorm.DB, error) { log.LogInfo("Connecting to database", log.F("host", config.Cfg.DBHost), log.F("database", config.Cfg.DBName)) dsn := config.Cfg.GetDSN() db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{ Logger: gormlogger.Default.LogMode(gormlogger.Warn), }) if err != nil { return nil, fmt.Errorf("failed to connect to database: %w", err) } // Set the global DB instance DB = db // Get the underlying SQL DB instance sqlDB, err := db.DB() if err != nil { return nil, fmt.Errorf("failed to get SQL DB instance: %w", err) } // Set connection pool settings sqlDB.SetMaxOpenConns(20) // Connection pooling sqlDB.SetMaxIdleConns(5) // Idle connections sqlDB.SetConnMaxLifetime(30 * time.Minute) log.LogInfo("Successfully connected to database", log.F("host", config.Cfg.DBHost), log.F("database", config.Cfg.DBName)) return db, nil } // Close closes the database connection func Close() error { if DB == nil { return nil } sqlDB, err := DB.DB() if err != nil { return fmt.Errorf("failed to get SQL DB instance: %w", err) } return sqlDB.Close() } // InitDB initializes the database connection and runs migrations // It returns the database connection and any error encountered func InitDB() (*gorm.DB, error) { // Connect to the database db, err := Connect() if err != nil { return nil, err } // Migrations are now handled by a separate tool return db, nil }