Updated the category creation to include optional subcategories. First iteration of working with Go's SQL transaction setup.

This commit is contained in:
2021-09-09 15:02:05 -05:00
parent 871484a8e5
commit 42594918ef
2 changed files with 56 additions and 5 deletions
+55 -4
View File
@@ -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
}
+1 -1
View File
@@ -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)