package repositories import ( "os" "path/filepath" "go-eve-pi/options" "go-eve-pi/types" "gorm.io/driver/sqlite" "gorm.io/gorm" logger "git.site.quack-lab.dev/dave/cylogger" ) // Database manages all repositories and provides a unified interface // Implements DatabaseInterface type Database struct { *gorm.DB character *CharacterRepository cache *CacheRepository } // NewDatabase creates a new database instance with all repositories func NewDatabase() (*Database, error) { // Get database path from options dbPath := options.GlobalOptions.DBPath // Ensure directory exists dir := filepath.Dir(dbPath) if err := os.MkdirAll(dir, 0755); err != nil { return nil, err } // Connect to database db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{}) if err != nil { logger.Error("Failed to connect to database: %v", err) return nil, err } logger.Info("Connected to database: %s", dbPath) // Create repositories characterRepo := NewCharacterRepository(db) cacheRepo := NewCacheRepository(db) database := &Database{ DB: db, character: characterRepo, cache: cacheRepo, } // Run migrations if err := database.AutoMigrate(&types.Character{}, &types.CacheEntry{}); err != nil { logger.Error("Failed to run database migrations: %v", err) return nil, err } logger.Info("Database initialized successfully") return database, nil } // Character returns the character repository func (d *Database) Character() CharacterRepositoryInterface { return d.character } // Cache returns the cache repository func (d *Database) Cache() CacheRepositoryInterface { return d.cache }