boxes-api/db.go

112 lines
2.4 KiB
Go
Raw Normal View History

2024-10-05 01:10:35 +00:00
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"`
2024-10-05 01:10:35 +00:00
}
// Define the User model
type User struct {
gorm.Model
Username string `json:"username"`
Password string `json:"password"`
2024-10-17 14:38:52 +00:00
Email string `json:"email"`
2024-10-05 01:10:35 +00:00
}
// ConnectDB establishes a connection to the database and sets up the schema
2024-10-05 01:10:35 +00:00
func ConnectDB(dbPath string) (*gorm.DB, error) {
log := GetLogger()
if log != nil {
log.Info("Attempting to connect to database at: %s", dbPath)
}
2024-10-05 01:10:35 +00:00
db, err := gorm.Open("sqlite3", dbPath)
if err != nil {
if log != nil {
log.Error("Failed to connect to database: %v", err)
}
2024-10-05 01:10:35 +00:00
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")
}
2024-10-05 01:10:35 +00:00
// 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")
}
2024-10-05 01:10:35 +00:00
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
}