From 595bdb241aec2c568b2103dcbdfa79dcd2b9eebf Mon Sep 17 00:00:00 2001 From: Kailash Nadh Date: Fri, 2 Nov 2018 00:07:02 +0530 Subject: [PATCH] Set all campaign templates to default when a used template is deleted --- queries.sql | 13 +++++++++++-- templates.go | 10 ++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/queries.sql b/queries.sql index acf8996..e93da46 100644 --- a/queries.sql +++ b/queries.sql @@ -335,8 +335,17 @@ WITH u AS ( UPDATE templates SET is_default=false WHERE id != $1; -- name: delete-template --- Delete a template as long as there's more than one. -DELETE FROM templates WHERE id=$1 AND (SELECT COUNT(id) FROM templates) > 1 AND is_default = false; +-- Delete a template as long as there's more than one. One deletion, set all campaigns +-- with that template to the default template instead. +WITH tpl AS ( + DELETE FROM templates WHERE id = $1 AND (SELECT COUNT(id) FROM templates) > 1 AND is_default = false RETURNING id +), +def AS ( + SELECT id FROM templates WHERE is_default = true LIMIT 1 +) +UPDATE campaigns SET template_id = (SELECT id FROM def) WHERE (SELECT id FROM tpl) > 0 AND template_id = $1 + RETURNING (SELECT id FROM tpl); + -- media -- name: insert-media diff --git a/templates.go b/templates.go index 664f4c0..c9b71e6 100644 --- a/templates.go +++ b/templates.go @@ -1,6 +1,7 @@ package main import ( + "database/sql" "errors" "fmt" "net/http" @@ -209,13 +210,18 @@ func handleDeleteTemplate(c echo.Context) error { return echo.NewHTTPError(http.StatusBadRequest, "Cannot delete the primordial template.") } - res, err := app.Queries.DeleteTemplate.Exec(id) + var delID int + err := app.Queries.DeleteTemplate.Get(&delID, id) if err != nil { + if err == sql.ErrNoRows { + return c.JSON(http.StatusOK, okResp{true}) + } + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Error deleting template: %v", err)) } - if n, _ := res.RowsAffected(); n == 0 { + if delID == 0 { return echo.NewHTTPError(http.StatusBadRequest, "Cannot delete the last, default, or non-existent template.") }