add comprehensive delete, fix bug in changeparent
This commit is contained in:
parent
542932a98b
commit
ff1b804cd6
|
@ -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 {
|
||||
|
|
|
@ -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 {
|
||||
|
|
Loading…
Reference in New Issue