Improved SQL INSERT and UPDATE with JSON or dict values.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import datetime, pytz, redis, secrets
|
||||
import datetime, json, pytz, redis, secrets
|
||||
from timeit import default_timer as timer
|
||||
|
||||
from app.config import settings
|
||||
@@ -98,7 +98,7 @@ def sql_connect(
|
||||
|
||||
# ### BEGIN ### API DB SQL ### sql_insert() ###
|
||||
# NOTE: Possible future change... Try to look up a duplicate entry if there is one on INSERT.
|
||||
# Updated 2021-09-07
|
||||
# Updated 2023-02-08
|
||||
@logger_reset
|
||||
def sql_insert(
|
||||
sql: str|None = None,
|
||||
@@ -139,6 +139,10 @@ def sql_insert(
|
||||
for key, value in data.items():
|
||||
if key != 'id': # Creating a special exception for the id field.
|
||||
field_list.append('`'+str(key) + '` = :' + str(key))
|
||||
|
||||
if isinstance(value, dict):
|
||||
data[key] = json.dumps(value)
|
||||
|
||||
set_values_string = ', '.join(field_list)
|
||||
|
||||
sql_insert = text(f"""
|
||||
@@ -233,7 +237,7 @@ def sql_insert(
|
||||
|
||||
|
||||
# ### BEGIN ### API DB SQL ### sql_update() ###
|
||||
# Updated 2021-09-07
|
||||
# Updated 2023-02-08
|
||||
@logger_reset
|
||||
def sql_update(
|
||||
sql: str|None = None,
|
||||
@@ -262,6 +266,9 @@ def sql_update(
|
||||
if key != 'id': # Creating a special exception for the id field.
|
||||
fields_string.append('`'+str(key) + '` = :' + str(key))
|
||||
|
||||
if isinstance(value, dict):
|
||||
data[key] = json.dumps(value)
|
||||
|
||||
sql_set = ', '.join(fields_string)
|
||||
log.debug(sql_set)
|
||||
|
||||
|
||||
@@ -145,7 +145,7 @@ def load_event_exhibit_obj(
|
||||
inc_event_exhibit_tracking_list: bool = False,
|
||||
inc_event_person: bool = False,
|
||||
) -> Event_Exhibit_Base|dict|bool:
|
||||
log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
|
||||
log.setLevel(logging.INFO) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
|
||||
log.debug(locals())
|
||||
|
||||
# if event_exhibit_id := redis_lookup_id_random(record_id_random=event_exhibit_id, table_name='event_exhibit'): pass
|
||||
|
||||
@@ -121,8 +121,8 @@ def update_event_exhibit_tracking_obj(
|
||||
|
||||
# NOTE: This is needed for the SQL update to work.
|
||||
# NOTE: Should something like this be moved to the sql_update and sql_insert functions? If a field ends in _json or the field data type is a dict?
|
||||
if responses_json := event_exhibit_tracking_dict.get('responses_json'):
|
||||
event_exhibit_tracking_dict['responses_json'] = json.dumps(responses_json)
|
||||
# if responses_json := event_exhibit_tracking_dict.get('responses_json'):
|
||||
# event_exhibit_tracking_dict['responses_json'] = json.dumps(responses_json)
|
||||
|
||||
# ### SECTION ### Process data
|
||||
if event_exhibit_tracking_dict_up_result := sql_update(
|
||||
|
||||
Reference in New Issue
Block a user