package main import ( "log" "path" "time" "github.com/gofrs/uuid" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) const ( PRE_ORDER_STATE_CREATED = "CREATED" ) func initDB() (*gorm.DB, error) { log.Printf("Connect to DB on path: %v", path.Join(ROOT_DIR, "data/db/data.db")) db, err := gorm.Open("sqlite3", path.Join(ROOT_DIR, "data/db/data.db")) // Enable Logger, show detailed log db.LogMode(true) return db, err } type Product struct { gorm.Model Name string Image string Description string Price int } type Item struct { gorm.Model ProductID uint Product Product PreOrderID uuid.UUID PreOrder PreOrder } type MolliePayment struct { gorm.Model MolliePaymentID string Amount int Status string PreOrderID uuid.UUID PreOrder PreOrder } type PreOrder struct { ID uuid.UUID `sql:"type:string;primary_key;"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time `sql:"index"` Name string Email string Items []Item Address string Postcode string City string Status string MolliePayments []MolliePayment } func (base *PreOrder) BeforeCreate(scope *gorm.Scope) error { uuid, err := uuid.NewV4() if err != nil { return err } return scope.SetColumn("ID", uuid.String()) } func (po *PreOrder) CalcTotal() int { total := 0 for _, i := range po.Items { total += i.Product.Price } return total } func GetDB() *gorm.DB { db, err := initDB() if err != nil { panic("failed to connect database") } // Migrate the schema db.AutoMigrate( &Product{}, &Item{}, &PreOrder{}, &MolliePayment{}, ) return db }