+ # Self-referential tables may contain rows with foreign keys of other
+ # rows in the same table that do not yet exist. Pull these out and add
+ # them to the session last
+ # ASSUMPTION: Self-referential tables have a single PK called "id"
+ deferred_rows = [] # ( row referring to id, [foreign ids we need] )
+ seen_ids = {} # primary key we've seen => 1
+
+ # Fetch foreign key columns that point at this table, if any
+ self_ref_columns = []
+ for column in table_obj.c:
+ if any(_.references(table_obj) for _ in column.foreign_keys):
+ self_ref_columns.append(column)
+