diff options
author | xengineering <me@xengineering.eu> | 2024-04-04 14:54:21 +0200 |
---|---|---|
committer | xengineering <me@xengineering.eu> | 2024-05-12 20:52:25 +0200 |
commit | 87ae71413e47ef34da57bc1e0b8dddbf84b0c66a (patch) | |
tree | f8711576d7098d21e48eafd9df3ab6f3ed679b88 /model/ingredient.go | |
parent | fec2fea87615e6ee3a6e73f7f98e021eee1b7098 (diff) | |
download | ceres-87ae71413e47ef34da57bc1e0b8dddbf84b0c66a.tar ceres-87ae71413e47ef34da57bc1e0b8dddbf84b0c66a.tar.zst ceres-87ae71413e47ef34da57bc1e0b8dddbf84b0c66a.zip |
model: Add per-step ingredients
Diffstat (limited to 'model/ingredient.go')
-rw-r--r-- | model/ingredient.go | 121 |
1 files changed, 121 insertions, 0 deletions
diff --git a/model/ingredient.go b/model/ingredient.go new file mode 100644 index 0000000..85a4729 --- /dev/null +++ b/model/ingredient.go @@ -0,0 +1,121 @@ +package model + +import ( + "database/sql" + "errors" + "fmt" +) + +type Ingredient struct { + Id string `json:"id"` + Index string `json:"index"` + Amount string `json:"amount"` + Unit string `json:"unit"` + Type string `json:"type"` + Step string `json:"step"` +} + +func (i *Ingredient) Create(tx *sql.Tx) error { + if i.Id != "" { + return fmt.Errorf("Cannot create ingredient if ID is given") + } + + cmd := ` +INSERT INTO ingredients + ('index', amount, unit, 'type', step) +VALUES + (?, ?, ?, ?, ?) +` + + result, err := tx.Exec(cmd, i.Index, i.Amount, i.Unit, i.Type, i.Step) + if err != nil { + return err + } + + id, err := result.LastInsertId() + if err != nil { + return err + } + + i.Id = fmt.Sprint(id) + + return nil +} + +func (i *Ingredient) Read(tx *sql.Tx) error { + cmd := ` +SELECT + "index", amount, unit, "type", step +FROM + ingredients +WHERE + id = ? +` + + rows, err := tx.Query(cmd, i.Id) + if err != nil { + return err + } + defer rows.Close() + + if !rows.Next() { + return sql.ErrNoRows + } + + err = rows.Scan(&i.Index, &i.Amount, &i.Unit, &i.Type, &i.Step) + if err != nil { + return err + } + + return nil +} + +func (i *Ingredient) Update(tx *sql.Tx) error { + cmd := ` +UPDATE + ingredients +SET + index = ?, + amount = ?, + unit = ?, + type = ?, + step = ? +WHERE + id = ?` + + res, err := tx.Exec(cmd, i.Index, i.Amount, i.Unit, i.Type, i.Step, i.Id) + if err != nil { + return err + } + + affected, err := res.RowsAffected() + if err != nil { + return err + } + if affected != 1 { + return fmt.Errorf("Ingredient update affected %d rows instead of 1", affected) + } + + return nil +} + +func (i *Ingredient) Delete(tx *sql.Tx) error { + cmd := ` +DELETE FROM + ingredients +WHERE + id = ? +` + + result, err := tx.Exec(cmd, i.Id) + if err != nil { + return err + } + + rows, err := result.RowsAffected() + if rows != 1 { + return errors.New("Ingredient deletion did not affect exactly one row") + } + + return nil +} |