package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) // Define the Box model type Box struct { gorm.Model Name string `json:"name"` } // Define the Item model type Item struct { gorm.Model Name string `json:"name"` Description string `json:"description"` BoxID uint `json:"box_id"` ImagePath string `json:"image_path"` } // Define the User model type User struct { gorm.Model Username string `json:"username"` Password string `json:"password"` Email string `json:"email"` } // ConnectDB establishes a connection to the database and sets up the schema func ConnectDB(dbPath string) (*gorm.DB, error) { log := GetLogger() if log != nil { log.Info("Attempting to connect to database at: %s", dbPath) } db, err := gorm.Open("sqlite3", dbPath) if err != nil { if log != nil { log.Error("Failed to connect to database: %v", err) } return nil, fmt.Errorf("failed to connect to database: %v", err) } // Enable detailed SQL logging if we're in DEBUG mode if log != nil && log.GetLogLevel() == "DEBUG" { db.LogMode(true) } if log != nil { log.Info("Successfully connected to database") } // Set auto_vacuum mode to ON if err := db.Exec("PRAGMA auto_vacuum = ON;").Error; err != nil { if log != nil { log.Error("Failed to set auto_vacuum pragma: %v", err) } return nil, fmt.Errorf("failed to set auto_vacuum pragma: %v", err) } if log != nil { log.Info("Auto-vacuum mode enabled") } // AutoMigrate will create the tables if they don't exist if err := autoMigrateSchema(db); err != nil { if log != nil { log.Error("Schema migration failed: %v", err) } return nil, err } if log != nil { log.Info("Database schema migration completed successfully") } return db, nil } // autoMigrateSchema handles the database schema migration func autoMigrateSchema(db *gorm.DB) error { log := GetLogger() if log != nil { log.Info("Starting schema migration") } // List of models to migrate models := []interface{}{ &Box{}, &Item{}, &User{}, } for _, model := range models { if err := db.AutoMigrate(model).Error; err != nil { if log != nil { log.Error("Failed to migrate model %T: %v", model, err) } return fmt.Errorf("failed to migrate model %T: %v", model, err) } if log != nil { log.Debug("Successfully migrated model: %T", model) } } return nil }