summaryrefslogtreecommitdiff
path: root/backend
diff options
context:
space:
mode:
authorTucker Evans <tuckerevans24@gmail.com>2019-11-12 10:03:35 -0500
committerTucker Evans <tuckerevans24@gmail.com>2019-11-12 10:03:35 -0500
commitba3a25fe2a98bbf63264c47c8013a6d4d271e1c1 (patch)
tree3b9bb15abadedc13d911432c9f4b9fc1465b7b6d /backend
parent9e81f2af7f4c0130217658c4c2fc73f8a933e183 (diff)
Add transactions to Insert sql statement
Transactions allow us to rollback inserts ensuring that the database is in sync with our application.
Diffstat (limited to 'backend')
-rw-r--r--backend/recipe.go9
1 files changed, 6 insertions, 3 deletions
diff --git a/backend/recipe.go b/backend/recipe.go
index ab1b631..89a01df 100644
--- a/backend/recipe.go
+++ b/backend/recipe.go
@@ -145,7 +145,8 @@ func AddRecipeDB(r *Recipe, db *sql.DB) error {
keywords.WriteRune('|')
}
- err := db.QueryRow(`INSERT INTO recipes (title, photo_urls,
+ tx := db.Begin()
+ err := tx.QueryRow(`INSERT INTO recipes (title, photo_urls,
keywords, description, serving_size, cook_time,
rating, num_cooked)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
@@ -160,11 +161,12 @@ func AddRecipeDB(r *Recipe, db *sql.DB) error {
r.Num_cooked, //8
).Scan(&id)
if err != nil {
+ tx.Rollback()
return err
}
for i, ingr := range r.Ingredients {
- res, err := db.Exec(`INSERT INTO ingredients
+ res, err := tx.Exec(`INSERT INTO ingredients
(id, name, amount, unit, recipe_id)
VALUES ($1, $2, $3, $4, $5)`,
i,
@@ -181,7 +183,7 @@ func AddRecipeDB(r *Recipe, db *sql.DB) error {
}
for i, step := range r.Steps {
- res, err := db.Exec(`INSERT INTO steps
+ res, err := tx.Exec(`INSERT INTO steps
(step, description, timer, recipe_id)
VALUES ($1, $2, $3, $4)`,
step.Num,
@@ -197,5 +199,6 @@ func AddRecipeDB(r *Recipe, db *sql.DB) error {
}
r.Id = id
+ tx.Commit()
return nil
}