tercul-backend/db/db.go
Damir Mukimov 4957117cb6 Initial commit: Tercul Go project with comprehensive architecture
- Core Go application with GraphQL API using gqlgen
- Comprehensive data models for literary works, authors, translations
- Repository pattern with caching layer
- Authentication and authorization system
- Linguistics analysis capabilities with multiple adapters
- Vector search integration with Weaviate
- Docker containerization support
- Python data migration and analysis scripts
- Clean architecture with proper separation of concerns
- Production-ready configuration and middleware
- Proper .gitignore excluding vendor/, database files, and build artifacts
2025-08-13 07:42:32 +02:00

83 lines
1.9 KiB
Go

package db
import (
"fmt"
"time"
"gorm.io/driver/postgres"
"gorm.io/gorm"
gormlogger "gorm.io/gorm/logger"
"tercul/config"
"tercul/logger"
)
// 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) {
logger.LogInfo("Connecting to database",
logger.F("host", config.Cfg.DBHost),
logger.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)
logger.LogInfo("Successfully connected to database",
logger.F("host", config.Cfg.DBHost),
logger.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
}
// Run migrations
if err := RunMigrations(db); err != nil {
return nil, fmt.Errorf("failed to run migrations: %w", err)
}
return db, nil
}