In my PostgreSQL table, when I try to delete a record, I encounter the following error:
SQL Error [23503]: ERROR: update or delete on table "parent_table" violates foreign key constraint "parent_table_header_ref_id_id_4fd15d08_fk" on table "child_table"
Detail: Key (id)=(1) is still referenced from table "child_table".
This happens even with ON DELETE RESTRICT enabled. Is there any script or a PostgreSQL function/loop that can be used to recursively delete data, ensuring that all related records across multiple levels are deleted safely when foreign key constraints are in place?
Python Pseudo code:
def delete_record(query):
while True:
try:
cursor.execute(query)
break
except Exception as exception:
# exception = 'SQL Error [23503]: ERROR: update or delete on table "parent_table" violates foreign key constraint "parent_table_header_ref_id_id_4fd15d08_fk" on table "child_table"'
child_table_delete_query = get_delete_query(exception)
# child_table_delete_query = 'delete from child_table where header_ref_id_id = 1'
delete_record(child_table_delete_query)
delete_record('delete from parent_table where id = 1')