Working on the basic SQL select API CRUD and lots of models
This commit is contained in:
@@ -1,5 +1,8 @@
|
||||
from __future__ import annotations
|
||||
import secrets
|
||||
from app.config import settings
|
||||
from .log import *
|
||||
#from .lib_general import lookup_id_random_pop
|
||||
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||
@@ -19,10 +22,83 @@ db = engine.connect()
|
||||
|
||||
|
||||
# ### BEGIN ### Core Help CRUD ### sql_insert() ###
|
||||
def sql_insert(sql=None, data=None, table_name=None, rm_id_random=None, id_random_length=None):
|
||||
log.setLevel(logging.ERROR) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
|
||||
def sql_insert(sql:str=None, data:dict=None, table_name:str=None, id_random_length:int=8):
|
||||
log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
|
||||
log.debug(locals())
|
||||
|
||||
if sql:
|
||||
sql_insert = text(sql)
|
||||
elif table_name and data:
|
||||
#if rm_id_random:
|
||||
#data = lookup_id_random_pop(obj_data=data)
|
||||
if not data.get('id_random', None) and id_random_length:
|
||||
data['id_random'] = secrets.token_urlsafe(id_random_length)
|
||||
|
||||
log.debug(data)
|
||||
|
||||
fields = []
|
||||
values = []
|
||||
for key, value in data.items():
|
||||
if key != 'id': # A special exception for the id auto increment field.
|
||||
fields.append('`'+str(key)+'`')
|
||||
values.append(':'+str(key))
|
||||
fields_string = ', '.join(fields)
|
||||
values_string = ', '.join(values)
|
||||
|
||||
log.debug(fields_string)
|
||||
log.debug(values_string)
|
||||
|
||||
field_list = []
|
||||
for key, value in data.items():
|
||||
if key != 'id': # Creating a special exception for the id field.
|
||||
field_list.append('`'+str(key) + '` = :' + str(key))
|
||||
set_values_string = ', '.join(field_list)
|
||||
|
||||
sql_insert = text(f"""
|
||||
INSERT INTO `{table_name}` ({fields_string}) VALUES ({values_string});
|
||||
"""
|
||||
)
|
||||
print(sql_insert)
|
||||
|
||||
log.debug(f"""
|
||||
INSERT INTO `{table_name}` ({fields_string}) VALUES ({values_string});
|
||||
"""
|
||||
)
|
||||
|
||||
trans = db.begin()
|
||||
try:
|
||||
result_insert = db.execute(sql_insert, data)
|
||||
trans.commit()
|
||||
except Exception as e:
|
||||
trans.rollback()
|
||||
log.exception('*** An exception happened. ***')
|
||||
log.exception(repr(e))
|
||||
log.exception('***')
|
||||
log.exception(str(e))
|
||||
log.exception('^^^ exception ^^^')
|
||||
return False
|
||||
else:
|
||||
log.debug(result_insert)
|
||||
log.debug(result_insert.rowcount)
|
||||
if result_insert.rowcount == 1 and result_insert.lastrowid > 0: # insert
|
||||
log.info('Insert record')
|
||||
log.debug(result_insert.lastrowid)
|
||||
record_id = result_insert.lastrowid
|
||||
return record_id
|
||||
#elif result_insert.rowcount == 1 and result_insert.lastrowid == 0: # update with no change
|
||||
#log.info('Update record with no change')
|
||||
#return True
|
||||
#elif result_insert.rowcount == 2 and result_insert.lastrowid > 0: # update with change
|
||||
#log.info('Update record with changes')
|
||||
#record_id = result_insert.lastrowid
|
||||
#return record_id
|
||||
else:
|
||||
log.debug(result_insert)
|
||||
log.debug(vars(result_insert))
|
||||
log.debug(dir(result_insert))
|
||||
log.debug(result_insert.rowcount) # returns 1 on insert and 2 on update with change
|
||||
log.debug(result_insert.lastrowid) # returns last row ID on insert and update with a change and returns 0 if nothing changed
|
||||
return False
|
||||
return False
|
||||
# ### END ### Core Help CRUD ### sql_insert() ###
|
||||
|
||||
@@ -71,14 +147,12 @@ def sql_insert_or_update(sql:str=None, data:dict=None, table_name:str=None, rm_i
|
||||
field_list.append('`'+str(key) + '` = :' + str(key))
|
||||
set_values_string = ', '.join(field_list)
|
||||
|
||||
sql_insert_or_update = text(
|
||||
f"""
|
||||
sql_insert_or_update = text(f"""
|
||||
INSERT INTO `{table_name}` ({fields_string}) VALUES ({values_string})
|
||||
ON DUPLICATE KEY UPDATE
|
||||
{set_values_string}
|
||||
;
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
log.debug(f"""
|
||||
INSERT INTO `{table_name}` ({fields_string}) VALUES ({values_string})
|
||||
@@ -497,3 +571,4 @@ def sql_result_proxy_to_dict_simple(result_proxy=None):
|
||||
record[key] = value
|
||||
return record
|
||||
return False
|
||||
|
||||
|
||||
Reference in New Issue
Block a user