summaryrefslogtreecommitdiff
path: root/controller
diff options
context:
space:
mode:
authorxengineering <me@xengineering.eu>2024-04-06 13:12:17 +0200
committerxengineering <me@xengineering.eu>2024-04-06 13:12:17 +0200
commitf65b11a5b3011f370df5b4d32239225f3708ecd5 (patch)
tree360261244c95e80cf2a56160527f5be7c6f5e2d7 /controller
parent9985d6f86fcee9d3c1d1148a5977190b673a8e8e (diff)
downloadceres-f65b11a5b3011f370df5b4d32239225f3708ecd5.tar
ceres-f65b11a5b3011f370df5b4d32239225f3708ecd5.tar.zst
ceres-f65b11a5b3011f370df5b4d32239225f3708ecd5.zip
model: Always pass *sql.Tx to CRUD methods
When nesting objects like steps into other objects like recipes it is required to pass a *sql.Tx value to the CRUD methods of the inner object to be able to roll back the whole transaction. The top level object used to be responsible for the creation of this *sql.Tx inside its CRUD methods. This is now moved to the caller of the CRUD methods (here the HTTP handler function). The advantage is that all CRUD methods now accept a *sql.Tx as only argument which makes those methods more consistent.
Diffstat (limited to 'controller')
-rw-r--r--controller/recipe.go45
1 files changed, 42 insertions, 3 deletions
diff --git a/controller/recipe.go b/controller/recipe.go
index 09f65a7..da58d35 100644
--- a/controller/recipe.go
+++ b/controller/recipe.go
@@ -18,7 +18,20 @@ func RecipeCreate(w http.ResponseWriter, r *http.Request) {
recipe.LastChanged = fmt.Sprint(time.Now().Unix())
recipe.Created = recipe.LastChanged
- err := recipe.Create()
+ tx, err := model.NewTx()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ err = recipe.Create(tx)
+ if err != nil {
+ model.Rollback(tx)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ err = tx.Commit()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@@ -48,7 +61,20 @@ func RecipeUpdate(w http.ResponseWriter, r *http.Request) {
recipe.LastChanged = fmt.Sprint(time.Now().Unix())
- err = recipe.Update()
+ tx, err := model.NewTx()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ err = recipe.Update(tx)
+ if err != nil {
+ model.Rollback(tx)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ err = tx.Commit()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@@ -61,7 +87,20 @@ func RecipeDelete(w http.ResponseWriter, r *http.Request) {
recipe := model.Recipe{}
recipe.Id = mux.Vars(r)[`id`]
- err := recipe.Delete()
+ tx, err := model.NewTx()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ err = recipe.Delete(tx)
+ if err != nil {
+ model.Rollback(tx)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ err = tx.Commit()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return