|
11 | 11 | from sqlalchemy.future import select |
12 | 12 | import os |
13 | 13 | import logging |
| 14 | +from sqlalchemy.exc import IntegrityError |
14 | 15 |
|
15 | 16 | from ..utilities import ( |
16 | 17 | has_access_to_inst_or_err, |
@@ -910,27 +911,52 @@ def validation_helper( |
910 | 911 | + str(e), |
911 | 912 | ) from e |
912 | 913 |
|
913 | | - try: |
914 | | - new_file_record = FileTable( |
| 914 | + existing_file = ( |
| 915 | + local_session.get() |
| 916 | + .query(FileTable) |
| 917 | + .filter_by( |
915 | 918 | name=file_name, |
916 | 919 | inst_id=str_to_uuid(inst_id), |
917 | | - uploader=str_to_uuid(current_user.user_id), |
918 | | - source=source_str, |
919 | | - sst_generated=False, |
920 | | - schemas=list(inferred_schemas), |
921 | | - valid=True, |
922 | 920 | ) |
923 | | - local_session.get().add(new_file_record) |
| 921 | + .first() |
| 922 | + ) |
| 923 | + |
| 924 | + if existing_file: |
| 925 | + logging.info(f"File '{file_name}' already exists for institution {inst_id}.") |
| 926 | + db_status = f"File '{file_name}' already exists for institution {inst_id}." |
| 927 | + else: |
| 928 | + try: |
| 929 | + new_file_record = FileTable( |
| 930 | + name=file_name, |
| 931 | + inst_id=str_to_uuid(inst_id), |
| 932 | + uploader=str_to_uuid(current_user.user_id), |
| 933 | + source=source_str, |
| 934 | + sst_generated=False, |
| 935 | + schemas=list(inferred_schemas), |
| 936 | + valid=True, |
| 937 | + ) |
| 938 | + local_session.get().add(new_file_record) |
| 939 | + local_session.get().flush() |
| 940 | + logging.info(f"File record inserted for '{file_name}'") |
| 941 | + db_status = f"File record inserted for '{file_name}'" |
| 942 | + except IntegrityError as e: |
| 943 | + local_session.get().rollback() |
| 944 | + logging.warning(f"IntegrityError: {e}") |
| 945 | + db_status = "Already exists" |
| 946 | + except Exception as e: |
| 947 | + local_session.get().rollback() |
| 948 | + logging.error(f"Unexpected DB error: {e}") |
| 949 | + raise HTTPException( |
| 950 | + status_code=500, |
| 951 | + detail=f"Unexpected database error while inserting file record: {e}", |
| 952 | + ) |
924 | 953 |
|
925 | | - logging.debug("!!!!!!!!!!File Record was successful") |
926 | | - except Exception as e: |
927 | | - logging.error(f"Error message: {str(e)}") |
928 | | - logging.debug("!!!!!!!!!!All runs successful") |
929 | 954 | return { |
930 | 955 | "name": file_name, |
931 | 956 | "inst_id": inst_id, |
932 | 957 | "file_types": list(inferred_schemas), |
933 | 958 | "source": source_str, |
| 959 | + "status": db_status, |
934 | 960 | } |
935 | 961 |
|
936 | 962 |
|
|
0 commit comments