Files
bamort/template/backend/database/config.go
T
2026-04-01 15:16:12 +02:00

80 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package database
import (
"myapp/config"
"myapp/logger"
"path/filepath"
"runtime"
"log"
"gorm.io/driver/mysql"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// DB is the global database connection used by all packages.
var DB *gorm.DB
// getBackendDir returns the absolute path to the backend root directory.
func getBackendDir() string {
_, filename, _, _ := runtime.Caller(0)
return filepath.Dir(filepath.Dir(filename))
}
// PreparedTestDB is the path to the snapshot SQLite database used in tests.
var PreparedTestDB = filepath.Join(getBackendDir(), "testdata", "prepared_test_data.db")
// ConnectDatabase selects the appropriate database backend based on environment.
func ConnectDatabase() *gorm.DB {
cfg := config.Cfg
logger.Debug("ConnectDatabase: Environment=%s DevTesting=%s", cfg.Environment, cfg.DevTesting)
if cfg.Environment == "test" || cfg.DevTesting == "yes" {
logger.Debug("Test environment detected using SQLite test database")
SetupTestDB()
} else {
return connectProduction()
}
return DB
}
func connectProduction() *gorm.DB {
cfg := config.Cfg
dbURL := cfg.DatabaseURL
if dbURL == "" {
dbURL = "myapp:password@tcp(localhost:3306)/myapp?charset=utf8mb4&parseTime=True&loc=Local"
logger.Warn("DATABASE_URL not configured falling back to default MySQL DSN")
cfg.DatabaseType = "mysql"
}
var db *gorm.DB
var err error
switch cfg.DatabaseType {
case "mysql":
logger.Debug("Connecting to MySQL database...")
db, err = gorm.Open(mysql.Open(dbURL), &gorm.Config{})
case "sqlite":
logger.Debug("Connecting to SQLite database...")
db, err = gorm.Open(sqlite.Open(dbURL), &gorm.Config{})
default:
logger.Error("Unsupported database type %q falling back to MySQL", cfg.DatabaseType)
db, err = gorm.Open(mysql.Open(dbURL), &gorm.Config{})
}
if err != nil {
logger.Error("Failed to connect to database: %s", err.Error())
log.Fatal("database connection failed:", err)
}
logger.Info("Connected to %s database", cfg.DatabaseType)
DB = db
if err := MigrateStructure(); err != nil {
logger.Error("Auto-migration failed: %s", err.Error())
}
return DB
}