Update only if ASN is unique (#7756)
* checking if an asn already exists before updating it.
* added test
* edited test
* updated tc-fixtures
diff --git a/traffic_ops/testing/api/v5/asns_test.go b/traffic_ops/testing/api/v5/asns_test.go
index 91e8859..cbd69ba 100644
--- a/traffic_ops/testing/api/v5/asns_test.go
+++ b/traffic_ops/testing/api/v5/asns_test.go
@@ -77,6 +77,16 @@
},
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": {
diff --git a/traffic_ops/testing/api/v5/tc-fixtures.json b/traffic_ops/testing/api/v5/tc-fixtures.json
index 5e97ee5..e79a1c3 100644
--- a/traffic_ops/testing/api/v5/tc-fixtures.json
+++ b/traffic_ops/testing/api/v5/tc-fixtures.json
@@ -7,6 +7,10 @@
{
"asn": 9999,
"cachegroupName": "multiOriginCachegroup"
+ },
+ {
+ "asn": 5555,
+ "cachegroupName": "originCachegroup"
}
],
"cachegroups": [
diff --git a/traffic_ops/traffic_ops_golang/asn/asns.go b/traffic_ops/traffic_ops_golang/asn/asns.go
index 3e1e694..5954594 100644
--- a/traffic_ops/traffic_ops_golang/asn/asns.go
+++ b/traffic_ops/traffic_ops_golang/asn/asns.go
@@ -340,6 +340,18 @@
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,
@@ -347,7 +359,7 @@
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)