def set_finished_date_for_tasks(apps, schema_editor):
    sql = "\nWITH status_update AS(\n\tWITH status_update AS(\n\t\tWITH history_entries AS (\n\t\t\tSELECT\n\t\t\t\tdiff #>>'{status, 1}' new_status_id,\n\t\t\t\tregexp_split_to_array(key, ':') as split_key,\n\t\t\t\tcreated_at as date\n\t\t\tFROM history_historyentry\n\t\t\tWHERE diff #>>'{status, 1}' != ''\n\t\t)\n\t\tSELECT\n\t\t\tsplit_key[2] as object_id,\n\t\t\tnew_status_id::int,\n\t\t\tMAX(date) as status_change_datetime\n\t\tFROM history_entries\n\t\tWHERE split_key[1] = 'tasks.task'\n\t\tGROUP BY object_id, new_status_id, date\n\t)\n\tSELECT status_update.*\n\tFROM status_update\n\tINNER JOIN projects_taskstatus\n\tON projects_taskstatus.id = new_status_id AND projects_taskstatus.is_closed = True\n)\nUPDATE tasks_task\nSET finished_date = status_update.status_change_datetime\nFROM status_update\nWHERE tasks_task.id = status_update.object_id::int\n    "
    cursor = connection.cursor()
    cursor.execute(sql)
def set_finished_date_for_tasks(apps, schema_editor):
    sql = "\nWITH status_update AS(\n\tWITH status_update AS(\n\t\tWITH history_entries AS (\n\t\t\tSELECT\n\t\t\t\tdiff #>>'{status, 1}' new_status_id,\n\t\t\t\tregexp_split_to_array(key, ':') as split_key,\n\t\t\t\tcreated_at as date\n\t\t\tFROM history_historyentry\n\t\t\tWHERE diff #>>'{status, 1}' != \n\t\t)\n\t\tSELECT\n\t\t\tsplit_key[2] as object_id,\n\t\t\tnew_status_id::int,\n\t\t\tMAX(date) as status_change_datetime\n\t\tFROM history_entries\n\t\tWHERE split_key[1] = 'tasks.task'\n\t\tGROUP BY object_id, new_status_id, date\n\t)\n\tSELECT status_update.*\n\tFROM status_update\n\tINNER JOIN projects_taskstatus\n\tON projects_taskstatus.id = new_status_id AND projects_taskstatus.is_closed = True\n)\nUPDATE tasks_task\nSET finished_date = status_update.status_change_datetime\nFROM status_update\nWHERE tasks_task.id = status_update.object_id::int\n    "
    cursor = connection.cursor()
    cursor.execute(sql)