summaryrefslogtreecommitdiff
path: root/model/database.go
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 /model/database.go
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 'model/database.go')
-rw-r--r--model/database.go19
1 files changed, 17 insertions, 2 deletions
diff --git a/model/database.go b/model/database.go
index 7021181..3d8a0c4 100644
--- a/model/database.go
+++ b/model/database.go
@@ -52,12 +52,23 @@ func InitDatabase() {
func InjectTestRecipes() {
recipes := RecipeTestData()
+ tx, err := NewTx()
+ if err != nil {
+ log.Fatalf("Failed to inject test recipes: %v\n", err)
+ }
+
for _, recipe := range recipes {
- err := recipe.Create()
+ err = recipe.Create(tx)
if err != nil {
+ Rollback(tx)
log.Fatalf("Failed to inject test recipe: %v\n", err)
}
}
+
+ err = tx.Commit()
+ if err != nil {
+ log.Fatalf("Failed to inject test recipe: %v\n", err)
+ }
}
func CloseDatabase() {
@@ -69,7 +80,11 @@ func CloseDatabase() {
}
}
-func rollback(tx *sql.Tx) {
+func NewTx() (*sql.Tx, error) {
+ return db.Begin()
+}
+
+func Rollback(tx *sql.Tx) {
err := tx.Rollback()
if err != nil {
log.Printf("Failed to rollback transaction: %v\n", err)