diff options
Diffstat (limited to 'model/step.go')
-rw-r--r-- | model/step.go | 96 |
1 files changed, 65 insertions, 31 deletions
diff --git a/model/step.go b/model/step.go index 24a11f4..f689fb9 100644 --- a/model/step.go +++ b/model/step.go @@ -1,89 +1,123 @@ package model import ( + "errors" + "encoding/json" "database/sql" + "fmt" ) type Step struct { + Id string `json:"id"` + Index string `json:"index"` Text string `json:"text"` + Recipe string `json:"recipe"` } -func (r *Recipe) CreateSteps(tx *sql.Tx) error { - err := r.DeleteSteps(tx) - if err != nil { - return err +func (s Step) String() string { + b, _ := json.MarshalIndent(s, "", " ") + return string(b) +} + +func (s *Step) Create(tx *sql.Tx) error { + if s.Id != "" { + return fmt.Errorf("Cannot create step if ID is given") } cmd := ` INSERT INTO steps - (recipe, 'index', text) + ('index', text, recipe) VALUES (?, ?, ?) ` - for i, s := range r.Steps { - _, err := tx.Exec(cmd, r.Id, i, s.Text) - if err != nil { - return err - } + result, err := tx.Exec(cmd, s.Index, s.Text, s.Recipe) + if err != nil { + return err } + id, err := result.LastInsertId() + if err != nil { + return err + } + + s.Id = fmt.Sprint(id) + return nil } -func (r *Recipe) ReadSteps(tx *sql.Tx) error { +func (s *Step) Read(tx *sql.Tx) error { cmd := ` SELECT - text + "index", text, recipe FROM steps WHERE - recipe = ? -ORDER BY - 'index' ASC + id = ? ` - rows, err := tx.Query(cmd, r.Id) + rows, err := tx.Query(cmd, s.Id) if err != nil { return err } + defer rows.Close() - r.Steps = make([]Step, 0) - for rows.Next() { - s := Step{} - - err = rows.Scan(&s.Text) - if err != nil { - return err - } + if !rows.Next() { + return sql.ErrNoRows + } - r.Steps = append(r.Steps, s) + err = rows.Scan(&s.Index, &s.Text, &s.Recipe) + if err != nil { + return err } return nil } -func (r *Recipe) UpdateSteps(tx *sql.Tx) error { - err := r.DeleteSteps(tx) +func (s *Step) Update(tx *sql.Tx) error { + cmd := ` +UPDATE + steps +SET + index = ?, + text = ?, + recipe = ? +WHERE + id = ?` + + res, err := tx.Exec(cmd, s.Index, s.Text, s.Recipe, s.Id) if err != nil { return err } - return r.CreateSteps(tx) + affected, err := res.RowsAffected() + if err != nil { + return err + } + if affected != 1 { + return fmt.Errorf("Recipe update affected %d rows instead of 1", affected) + } + + return nil } -func (r *Recipe) DeleteSteps(tx *sql.Tx) error { +func (s *Step) Delete(tx *sql.Tx) error { cmd := ` DELETE FROM steps WHERE - recipe = ? + id = ? ` - _, err := tx.Exec(cmd, r.Id) + result, err := tx.Exec(cmd, s.Id) if err != nil { return err } + rows, err := result.RowsAffected() + if rows != 1 { + return errors.New("Recipe deletion did not affect exactly one row") + } + return nil } |