15357fd3c0
yalarbacreate and moove into new directories for BegushiyBashkir and yalarbacreate and moove into new directories for BegushiyBashkir and yalarbacreate and moove into new directories for BegushiyBashkir and yalarbacreate and moove into new directories for BegushiyBashkir and yalarbacreate and moove into new directories for BegushiyBashkir and yalarbacreate and moove into new directories for BegushiyBashkir and yalarbacreate and moove into new directories for BegushiyBashkir and yalarbacreate and moove into new directories for BegushiyBashkir and yalarba
50 lines
1.3 KiB
Go
50 lines
1.3 KiB
Go
package database
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"time"
|
|
|
|
"api_bb/internal/models"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func InitDB(dsn string) (*gorm.DB, error) {
|
|
// Используем PostgreSQL драйвер
|
|
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to connect to database: %w", err)
|
|
}
|
|
|
|
// Получаем underlying sql.DB для настройки пула соединений
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get database instance: %w", err)
|
|
}
|
|
|
|
// Настраиваем пул соединений
|
|
sqlDB.SetMaxIdleConns(10)
|
|
sqlDB.SetMaxOpenConns(100)
|
|
sqlDB.SetConnMaxLifetime(time.Hour)
|
|
|
|
// Проверяем соединение
|
|
if err := sqlDB.Ping(); err != nil {
|
|
return nil, fmt.Errorf("database ping failed: %w", err)
|
|
}
|
|
|
|
log.Println("PostgreSQL connection established successfully")
|
|
|
|
// Auto migrate models
|
|
err = db.AutoMigrate(
|
|
&models.User{},
|
|
// Добавьте другие модели здесь по мере расширения
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to auto-migrate models: %w", err)
|
|
}
|
|
|
|
log.Println("Database migration completed successfully")
|
|
|
|
return db, nil
|
|
} |