diff --git a/src/server/BreCal/api/times.py b/src/server/BreCal/api/times.py index 23537bd..a22eabb 100644 --- a/src/server/BreCal/api/times.py +++ b/src/server/BreCal/api/times.py @@ -72,7 +72,7 @@ def PutTimes(): # validate the request InputValidationTimes.evaluate_put_data(user_data, loadedModel, content) - return impl.times.PutTimes(loadedModel) + return impl.times.PutTimes(loadedModel, content) except ValidationError as ex: return create_validation_error_response(ex=ex, status_code=400) diff --git a/src/server/BreCal/impl/times.py b/src/server/BreCal/impl/times.py index c7f99bc..32496bb 100644 --- a/src/server/BreCal/impl/times.py +++ b/src/server/BreCal/impl/times.py @@ -115,7 +115,7 @@ def PostTimes(schemaModel): pooledConnection.close() -def PutTimes(schemaModel): +def PutTimes(schemaModel, original_payload=None): """ :param schemaModel: The deserialized model of the record to be inserted @@ -127,24 +127,33 @@ def PutTimes(schemaModel): pooledConnection = local_db.getPoolConnection() commands = pydapper.using(pooledConnection) - query = "UPDATE times SET " - isNotFirst = False + sentinel = object() + existing_times = commands.query_single_or_default("SELECT * FROM times WHERE id = ?id?", sentinel, param={"id": schemaModel["id"]}) + if existing_times is sentinel: + return json.dumps("no such record"), 404, {'Content-Type': 'application/json; charset=utf-8'} + + provided_keys = set(original_payload.keys()) if isinstance(original_payload, dict) else None + + if "shipcall_id" not in schemaModel or (provided_keys is not None and "shipcall_id" not in provided_keys): + schemaModel["shipcall_id"] = existing_times["shipcall_id"] + + schemaModel = {k:v.value if isinstance(v, (Enum, Flag)) else v for k,v in schemaModel.items()} + + update_clauses = [] for key in schemaModel.keys(): + if provided_keys is not None and key not in provided_keys: + continue if key == "id": continue if key == "created": continue if key == "modified": continue - if isNotFirst: - query += ", " - isNotFirst = True - query += key + " = ?" + key + "? " + update_clauses.append(f"{key} = ?{key}?") - query += "WHERE id = ?id?" - - schemaModel = {k:v.value if isinstance(v, (Enum, Flag)) else v for k,v in schemaModel.items()} - affected_rows = commands.execute(query, param=schemaModel) + if update_clauses: + query = "UPDATE times SET " + ", ".join(update_clauses) + " WHERE id = ?id?" + commands.execute(query, param=schemaModel) # apply 'Traffic Light' evaluation to obtain 'GREEN', 'YELLOW' or 'RED' evaluation state. The function internally updates the mysql database 'shipcall' evaluate_shipcall_state(mysql_connector_instance=pooledConnection, shipcall_id=schemaModel["shipcall_id"]) # every times data object refers to the 'shipcall_id'