diff options
Diffstat (limited to 'model/step.go')
-rw-r--r-- | model/step.go | 101 |
1 files changed, 95 insertions, 6 deletions
diff --git a/model/step.go b/model/step.go index f689fb9..74b4f48 100644 --- a/model/step.go +++ b/model/step.go @@ -8,10 +8,11 @@ import ( ) type Step struct { - Id string `json:"id"` - Index string `json:"index"` - Text string `json:"text"` - Recipe string `json:"recipe"` + Id string `json:"id"` + Index string `json:"index"` + Text string `json:"text"` + Recipe string `json:"recipe"` + Ingredients []Ingredient `json:"ingredients"` } func (s Step) String() string { @@ -43,9 +44,52 @@ VALUES s.Id = fmt.Sprint(id) + for i := range s.Ingredients { + s.Ingredients[i].Step = s.Id + s.Ingredients[i].Index = fmt.Sprint(i) + err = s.Ingredients[i].Create(tx) + if err != nil { + return err + } + } + return nil } +func (s *Step) getIngredientIds(tx *sql.Tx) ([]Ingredient, error) { + retval := make([]Ingredient, 0) + + cmd := ` +SELECT + id +FROM + ingredients +WHERE + step = ? +ORDER BY + 'index' ASC +` + + rows, err := tx.Query(cmd, s.Id) + if err != nil { + return retval, err + } + defer rows.Close() + + for rows.Next() { + i := Ingredient{} + + err = rows.Scan(&i.Id) + if err != nil { + return retval, err + } + + retval = append(retval, i) + } + + return retval, nil +} + func (s *Step) Read(tx *sql.Tx) error { cmd := ` SELECT @@ -71,10 +115,43 @@ WHERE return err } + s.Ingredients, err = s.getIngredientIds(tx) + if err != nil { + return err + } + + for i := range s.Ingredients { + err = s.Ingredients[i].Read(tx) + if err != nil { + return err + } + } + return nil } func (s *Step) Update(tx *sql.Tx) error { + oldIngredients, err := s.getIngredientIds(tx) + if err != nil { + return err + } + + for i := range oldIngredients { + err = oldIngredients[i].Delete(tx) + if err != nil { + return err + } + } + + for i := range s.Ingredients { + s.Ingredients[i].Index = fmt.Sprint(i) + s.Ingredients[i].Step = s.Id + s.Ingredients[i].Create(tx) + if err != nil { + return err + } + } + cmd := ` UPDATE steps @@ -95,13 +172,25 @@ WHERE return err } if affected != 1 { - return fmt.Errorf("Recipe update affected %d rows instead of 1", affected) + return fmt.Errorf("Step update affected %d rows instead of 1", affected) } return nil } func (s *Step) Delete(tx *sql.Tx) error { + oldIngredients, err := s.getIngredientIds(tx) + if err != nil { + return err + } + + for i := range oldIngredients { + err = oldIngredients[i].Delete(tx) + if err != nil { + return err + } + } + cmd := ` DELETE FROM steps @@ -116,7 +205,7 @@ WHERE rows, err := result.RowsAffected() if rows != 1 { - return errors.New("Recipe deletion did not affect exactly one row") + return errors.New("Step deletion did not affect exactly one row") } return nil |