From 42594918ef428810acb841fc85f18c96d0b89e22 Mon Sep 17 00:00:00 2001 From: Garritt McCune Date: Thu, 9 Sep 2021 15:02:05 -0500 Subject: [PATCH] Updated the category creation to include optional subcategories. First iteration of working with Go's SQL transaction setup. --- category.go | 59 +++++++++++++++++++++++++++++++++++++++++++++++++---- main.go | 2 +- 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/category.go b/category.go index abc780b..9e8b57c 100644 --- a/category.go +++ b/category.go @@ -1,5 +1,10 @@ package main +import ( + "context" + "fmt" +) + type Category struct { ID int64 `json:"id"` Name string `json:"name"` @@ -46,20 +51,66 @@ func getAllCategories() (categories []Category, ok bool) { return categories, true } -func insertNewCategory(name string) (recordID int32, ok bool) { +func insertNewCategory(name string, subcategories []Subcategory) (recordID int64, ok bool) { db := getSQLConnection() defer db.Close() - err := db.QueryRow("INSERT INTO category (category_name) VALUES ($1) RETURNING category_id;", name).Scan(&recordID) + context := context.Background() + transaction, err := db.BeginTx(context, nil) if err != nil { - //TODO: log this error println(err.Error()) return 0, false - //panic(err) } + { + statement, err := transaction.Prepare("INSERT INTO category (category_name) VALUES ($1) RETURNING category_id;") + + if err != nil { + println(err.Error()) + return 0, false + } + + defer statement.Close() + + statement.QueryRow(name).Scan(&recordID) + + if recordID == 0 { + transaction.Rollback() + println("Failed to get the last record ID") + return 0, false + } + } + + if len(subcategories) == 0 { + return recordID, true + } + + { + statement, err := transaction.Prepare("INSERT INTO subcategory(subcategory_name, category_id) VALUES($1, $2);") + + if err != nil { + println(err.Error()) + return 0, false + } + + defer statement.Close() + + for _, subcategory := range subcategories { + println(fmt.Sprintf("For cat %d, add sub '%s'.", recordID, subcategory.Name)) + _, err := statement.Exec(subcategory.Name, recordID) + + if err != nil { + transaction.Rollback() + println(err.Error()) + return 0, false + } + } + } + + transaction.Commit() + return recordID, true } diff --git a/main.go b/main.go index 7adeaf9..e419851 100644 --- a/main.go +++ b/main.go @@ -164,7 +164,7 @@ func insertCategoryHandler(w http.ResponseWriter, r *http.Request) { return } - id, ok := insertNewCategory(category.Name) + id, ok := insertNewCategory(category.Name, category.Subcategories) if !ok { w.WriteHeader(http.StatusInternalServerError)