Delete Records Recursively
Submitted by moxley on Mon, 2011-04-18 16:58
I needed to delete records from a PostgreSQL table that has descendant tables related by foreign keys. Some tables have multiple foreign keys which complicates the matter. Here's the pseudo code to do it:
def delete_records(table, parent_tables=[]):
"Pseudo code to delete all records from a table and its descendants"
parent_tables.append(table)
for child in child_tables(table):
delete_it = True
for fkey in foreign_keys_from(child):
if not (fkey.f_table in parent_tables):
delete_it = False
break
if delete_it:
delete_records(child)
execute_sql("DELETE FROM %s" % table)
