-- Migration 007: Add sort_order and display_label to thesis_files
-- Also expand file type enum to cover audio and generic other types.

ALTER TABLE thesis_files ADD COLUMN sort_order  INTEGER NOT NULL DEFAULT 0;
ALTER TABLE thesis_files ADD COLUMN display_label TEXT;

-- Back-fill sort_order from existing insertion order so ORDER BY sort_order
-- is consistent with the old ORDER BY uploaded_at behaviour.
UPDATE thesis_files SET sort_order = (
    SELECT COUNT(*) FROM thesis_files tf2
    WHERE tf2.thesis_id = thesis_files.thesis_id
      AND (tf2.sort_order < thesis_files.sort_order
           OR (tf2.sort_order = 0 AND tf2.uploaded_at < thesis_files.uploaded_at)
           OR (tf2.sort_order = 0 AND tf2.uploaded_at = thesis_files.uploaded_at AND tf2.id < thesis_files.id))
) + 1
WHERE sort_order = 0;
