Skip to content

Commit

Permalink
Update only if ASN is unique (#7756)
Browse files Browse the repository at this point in the history
* checking if an asn already exists before updating it.

* added test

* edited test

* updated tc-fixtures
  • Loading branch information
rimashah25 committed Aug 29, 2023
1 parent 3735399 commit 2aa7a60
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
10 changes: 10 additions & 0 deletions traffic_ops/testing/api/v5/asns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@ func TestASN(t *testing.T) {
},
Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)),
},
"BAD REQUEST when ASN is not unique": {
ClientSession: TOSession,
EndpointID: GetASNId(t, "5555"),
RequestBody: map[string]interface{}{
"asn": 9999,
"cachegroupName": "originCachegroup",
"cachegroupId": -1,
},
Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)),
},
},
"GET AFTER CHANGES": {
"OK when CHANGES made": {
Expand Down
4 changes: 4 additions & 0 deletions traffic_ops/testing/api/v5/tc-fixtures.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
{
"asn": 9999,
"cachegroupName": "multiOriginCachegroup"
},
{
"asn": 5555,
"cachegroupName": "originCachegroup"
}
],
"cachegroups": [
Expand Down
14 changes: 13 additions & 1 deletion traffic_ops/traffic_ops_golang/asn/asns.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,14 +340,26 @@ func Update(w http.ResponseWriter, r *http.Request) {
return
}

// check if asn already exists
var count int
err := tx.QueryRow("SELECT count(*) from asn where asn=$1", asn.ASN).Scan(&count)
if err != nil {
api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("error: %w, when checking if asn '%d' exists", err, asn.ASN))
return
}
if count == 1 {
api.HandleErr(w, r, tx, http.StatusBadRequest, fmt.Errorf("asn:'%d' already exists", asn.ASN), nil)
return
}

//update asn and cachegroup of an asn
query := `UPDATE asn SET
asn = $1,
cachegroup = $2
WHERE id = $3
RETURNING id, last_updated, (select name FROM cachegroup where id = $2)`

err := tx.QueryRow(query, asn.ASN, asn.CachegroupID, requestedAsnId).Scan(&asn.ID, &asn.LastUpdated, &asn.Cachegroup)
err = tx.QueryRow(query, asn.ASN, asn.CachegroupID, requestedAsnId).Scan(&asn.ID, &asn.LastUpdated, &asn.Cachegroup)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
api.HandleErr(w, r, tx, http.StatusBadRequest, fmt.Errorf("asn: %d not found", asn.ASN), nil)
Expand Down

0 comments on commit 2aa7a60

Please sign in to comment.