From ff1b804cd6aed0f51b287db3c91f829e531a879a Mon Sep 17 00:00:00 2001 From: Dan Ballard Date: Thu, 9 Jul 2015 07:31:54 -0700 Subject: [PATCH] add comprehensive delete, fix bug in changeparent --- categories/categories.go | 36 +++++++++++++++++++++++++++++++++++- route_handlers.go | 2 ++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/categories/categories.go b/categories/categories.go index 97f2a21..c18178b 100644 --- a/categories/categories.go +++ b/categories/categories.go @@ -5,6 +5,7 @@ import ( _ "github.com/lib/pq" "fmt" "strings" + "errors" ) type Category struct { @@ -61,9 +62,42 @@ func Add(db *sql.DB, name string, parent int) error { return err } +// Get parent id +// Set parent of children to parent +// set category of news to parent +// finallly delete func Delete(db *sql.DB, id int) error { + rows, err := db.Query("SELECT parent_id FROM categories WHERE id=$1", id) + if err != nil { + fmt.Println("Categories DB Error loading category parent id: ", err) + return err + } - return nil + if !rows.Next() { + fmt.Println("Categories DB Error loading category parent id: no category") + return errors.New("No category") + } + var parent_id sql.NullInt64 + err = rows.Scan(&parent_id) + + _, err = db.Exec("UPDATE categories SET parent_id =$2 WHERE parent_id=$1", id, parent_id) + if err != nil { + fmt.Println("Categories DB error changing child parent: ", err) + return err + } + + + _, err = db.Exec("UPDATE news SET category_id =$2 WHERE category_id=$1", id, parent_id) + if err != nil { + fmt.Println("Categories DB error changing category of news: ", err) + return err + } + + _, err = db.Exec("DELETE FROM categories WHERE id=$1", id) + if err != nil { + fmt.Println("Categories DB Error Delete(): ", err) + } + return err } func (category *Category) ChangeParent(db *sql.DB, parent *Category) error { diff --git a/route_handlers.go b/route_handlers.go index fd537ab..ff16ee1 100644 --- a/route_handlers.go +++ b/route_handlers.go @@ -266,6 +266,8 @@ func categoryChangeParentHandler(w http.ResponseWriter, r *http.Request, user *u if category == nil { session.AddFlash("Invalid category", flash_err) + } else if parent != nil && category.Id == parent.Id { + session.AddFlash("Cannot set category parent to itself", flash_err) } else { err := category.ChangeParent(db, parent) if err != nil {