From 9fb525530ff31450692f666b6d011d7a3f61b6e5 Mon Sep 17 00:00:00 2001 From: Tobias Reisinger Date: Sat, 15 Aug 2020 16:26:46 +0200 Subject: [PATCH] add: transaction one layer higher --- CMakeLists.txt | 2 +- .../api_v1_controllers_STR_relays_INT.c | 29 +++++++++++++++++-- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index bc56696..b770482 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 3.7) project(core - VERSION 0.2.14 + VERSION 0.2.15 LANGUAGES C) add_executable(core src/main.c) diff --git a/src/endpoints/api_v1_controllers_STR_relays_INT.c b/src/endpoints/api_v1_controllers_STR_relays_INT.c index 9726d2d..35a6a66 100644 --- a/src/endpoints/api_v1_controllers_STR_relays_INT.c +++ b/src/endpoints/api_v1_controllers_STR_relays_INT.c @@ -117,6 +117,7 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess relay->active_schedule = relay->schedules[helper_get_weekday(time_struct)]; } + controller_free(controller); LOGGER_DEBUG("overwriting relay %d for controller %s\n", args[1].value.v_int, args[0].value.v_str); cJSON *json = cJSON_ParseWithLength(hm->body.p, hm->body.len); @@ -201,10 +202,17 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess } } + int opened_transaction = database_transaction_begin(); + if(relay_save(relay)) { LOGGER_ERR("failed to save relay\n"); - free(controller); + + if(opened_transaction) + { + database_transaction_rollback(); + } + cJSON_Delete(json); static const char content[] = "failed to save relay to database"; @@ -224,7 +232,18 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess if(!cJSON_IsString(json_tag) || (json_tag->valuestring == NULL)) { LOGGER_DEBUG("invalid tag in tags\n"); - continue; + + if(opened_transaction) + { + database_transaction_rollback(); + } + + relay_free(relay); + cJSON_Delete(json); + + static const char content[] = "invalid tag in tags"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; } const char *tag = json_tag->valuestring; int tag_id = tag_get_id(tag); @@ -236,6 +255,11 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess junction_tag_insert(tag_id, relay->id, 0); } + if(opened_transaction) + { + database_transaction_commit(); + } + cJSON_Delete(json); json = relay_to_json(relay); @@ -245,5 +269,4 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess endpoint_response_json(response, 200, json); cJSON_Delete(json); relay_free(relay); - controller_free(controller); }