Set all campaign templates to default when a used template is deleted

This commit is contained in:
Kailash Nadh 2018-11-02 00:07:02 +05:30
parent 67d65b3a8b
commit 595bdb241a
2 changed files with 19 additions and 4 deletions

View File

@ -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

View File

@ -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.")
}