boxes-api/db.go

47 lines
994 B
Go

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"`
}
func ConnectDB(dbPath string) (*gorm.DB, error) {
db, err := gorm.Open("sqlite3", dbPath)
if err != nil {
return nil, fmt.Errorf("failed to connect to database: %v", err)
}
// set auto_vacuum mode to ON
// this automagically removes old rows from the database when idle
db.Exec("PRAGMA auto_vacuum = ON;")
// AutoMigrate will create the tables if they don't exist
db.AutoMigrate(&Box{}, &Item{}, &User{})
return db, nil
}