def _generate_delete_orphans(fk_statement, fk_table):
    """
    Sometimes, upstream data is deleted. If there are foreign key
    references to deleted data, we must delete them before adding
    constraints back to the table. To accomplish this, parse the
    foreign key statement and generate the deletion statement.
    """
    fk_tokens = fk_statement.split(' ')
    fk_field_idx = fk_tokens.index('KEY') + 1
    fk_ref_idx = fk_tokens.index('REFERENCES') + 1
    fk_field = fk_tokens[fk_field_idx].replace('(', '').replace(')', '')
    fk_reference = fk_tokens[fk_ref_idx]
    ref_table, ref_field = fk_reference.split('(')
    ref_field = ref_field.replace(')', '')

    del_orphans = '''
        DELETE FROM {fk_table} fk_table WHERE not exists
        (select 1 from temp_import_{ref_table} r
        where r.{ref_field} = fk_table.{fk_field})
    '''.format(
        fk_table=fk_table,
        ref_table=ref_table,
        fk_field=fk_field,
        ref_field=ref_field
    )
    return del_orphans