mirror of
https://github.com/SamyRai/tercul-backend.git
synced 2025-12-27 05:11:34 +00:00
This commit includes the following changes: - Refactored all data repositories in `internal/data/sql/` to use a consistent `sql` package and to align with the new `domain` models. - Fixed the GraphQL structure by moving the server creation logic from `internal/app` to `cmd/api`, which resolved an import cycle. - Corrected numerous incorrect import paths for packages like `graph`, `linguistics`, `syncjob`, and the legacy `models` package. - Resolved several package and function redeclaration errors. - Removed legacy migration code.
80 lines
1.8 KiB
Go
80 lines
1.8 KiB
Go
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
|
|
}
|