summaryrefslogtreecommitdiff
path: root/model/recipe.go
blob: 1510379a57fa84744475dcbd6cc247475957ff82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package model

import (
	"database/sql"
	"errors"
	"time"
)

type Recipe struct {
	Id          int64  `json:"id"`
	Title       string `json:"title"`
	Portions    int    `json:"portions"`
	Url         string `json:"url"`
	Notes       string `json:"notes"`
	Created     int64  `json:"created"`
	LastChanged int64  `json:"last_changed"`
}

func (r *Recipe) Create() error {
	now := time.Now().Unix()
	r.Created = now
	r.LastChanged = now

	query := `INSERT INTO recipes
    (title, portions, url, notes, created, last_changed)
VALUES
    (?, ?, ?, ?, ?, ?)`

	result, err := db.Exec(query, r.Title, r.Portions, r.Url, r.Notes,
		r.Created, r.LastChanged)
	if err != nil {
		return err
	}

	r.Id, err = result.LastInsertId()
	if err != nil {
		return err
	}

	return nil
}

func (r *Recipe) Read() error {
	query := `SELECT id, title, portions, url, notes, created, last_changed
FROM recipes
WHERE id = ?`

	rows, err := db.Query(query, r.Id)
	if err != nil {
		return err
	}
	defer rows.Close()

	if !rows.Next() {
		return sql.ErrNoRows
	}

	err = rows.Scan(
		&r.Id,
		&r.Title,
		&r.Portions,
		&r.Url,
		&r.Notes,
		&r.Created,
		&r.LastChanged,
	)
	if err != nil {
		return err
	}

	if rows.Next() {
		return errors.New("model: More than one object found on read")
	}

	return nil
}

func (r *Recipe) Update() error {
	query := `UPDATE
    recipes
SET
    title = ?,
	portions = ?,
	url = ?,
	notes = ?,
	created = ?,
	last_changed = ?
WHERE
    id = ?`

	_, err := db.Exec(query, r.Title, r.Portions, r.Url, r.Notes,
		r.Created, r.LastChanged, r.Id)
	if err != nil {
		return err
	}

	return nil
}

func (r *Recipe) Delete() error {
	query := `DELETE FROM recipes WHERE id = ?`

	result, err := db.Exec(query, r.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
}