Skip to content

Commit 88b46ef

Browse files
committed
Prevent deleting upstream that is use
1 parent ef34f01 commit 88b46ef

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

backend/internal/api/handler/upstreams.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
c "npm/internal/api/context"
1010
h "npm/internal/api/http"
1111
"npm/internal/api/middleware"
12+
"npm/internal/entity/host"
1213
"npm/internal/entity/upstream"
1314
"npm/internal/jobqueue"
1415
"npm/internal/logger"
@@ -151,6 +152,12 @@ func DeleteUpstream() func(http.ResponseWriter, *http.Request) {
151152
case sql.ErrNoRows:
152153
h.ResultErrorJSON(w, r, http.StatusNotFound, "Not found", nil)
153154
case nil:
155+
// Ensure that this upstream isn't in use by a host
156+
cnt := host.GetUpstreamUseCount(upstreamID)
157+
if cnt > 0 {
158+
h.ResultErrorJSON(w, r, http.StatusBadRequest, "Cannot delete upstream that is in use by at least 1 host", nil)
159+
return
160+
}
154161
h.ResultResponseJSON(w, r, http.StatusOK, item.Delete())
155162
configureUpstream(item)
156163
default:

backend/internal/entity/host/methods.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ func create(host *Model) (int, error) {
2929

3030
db := database.GetInstance()
3131
// nolint: gosec
32-
result, err := db.NamedExec(`INSERT INTO `+fmt.Sprintf("`%s`", tableName)+` (
32+
result, err := db.NamedExec(`INSERT INTO `+tableName+` (
3333
created_on,
3434
modified_on,
3535
user_id,
@@ -198,6 +198,21 @@ func List(pageInfo model.PageInfo, filters []model.Filter, expand []string) (Lis
198198
return result, nil
199199
}
200200

201+
// GetUpstreamUseCount returns the number of hosts that are using
202+
// an upstream, and have not been deleted.
203+
func GetUpstreamUseCount(upstreamID int) int {
204+
db := database.GetInstance()
205+
query := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE upstream_id = ? AND is_deleted = ?", tableName)
206+
countRow := db.QueryRowx(query, upstreamID, 0)
207+
var totalRows int
208+
queryErr := countRow.Scan(&totalRows)
209+
if queryErr != nil && queryErr != sql.ErrNoRows {
210+
logger.Debug("%s", query)
211+
return 0
212+
}
213+
return totalRows
214+
}
215+
201216
// AddPendingJobs is intended to be used at startup to add
202217
// anything pending to the JobQueue just once, based on
203218
// the database row status

0 commit comments

Comments
 (0)