package schema import ( "fmt" "log" "os" "time" "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=%s sslmode=disable", os.Getenv("DB_HOST"), os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_NAME"), os.Getenv("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 log.Println("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) } log.Println("Database migration completed") }