Files
kontor/kontor-gin/pkg/schema/database.go
T
Thomas Peetz ba83d70764
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 4s
add reading configs
2026-09-23 23:19:10 +02:00

70 lines
1.7 KiB
Go

package schema
import (
"fmt"
"log"
"log/slog"
"time"
"github.com/spf13/viper"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var DB *gorm.DB
func Connect() {
// Build the connection string from environment variables
// This keeps sensitive credentials out of the codebase
dsn := fmt.Sprintf(
"host=%s user=%s password=%s dbname=%s port=%d sslmode=disable",
viper.GetString("db.host"),
viper.GetString("db.user"),
viper.GetString("db.password"),
viper.GetString("db.name"),
viper.GetInt("db.port"),
)
// Configure GORM with custom settings
// The logger helps with debugging SQL queries during development
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
log.Fatal("Failed to connect to database:", err)
}
// Get the underlying SQL database connection for pool configuration
sqlDB, err := db.DB()
if err != nil {
log.Fatal("Failed to get database instance:", err)
}
// Configure connection pool settings
// MaxIdleConns: number of connections kept open when idle
sqlDB.SetMaxIdleConns(10)
// MaxOpenConns: maximum total connections to the database
sqlDB.SetMaxOpenConns(100)
// ConnMaxLifetime: how long a connection can be reused
sqlDB.SetConnMaxLifetime(time.Hour)
DB = db
slog.Info("Database connected successfully")
}
func RunMigrations() {
// AutoMigrate creates tables, missing columns, and missing indexes
// It will NOT delete unused columns to protect your data
err := DB.AutoMigrate(
&MediaActor{},
&MediaFile{},
&MediaActorFile{},
)
if err != nil {
log.Fatal("Migration failed:", err)
}
slog.Info("Database migration completed")
}