-- Migration: Backfill trace_profiles from tkg_nodes -- This script populates trace_profiles table for existing files that have -- tkg_nodes face_track nodes but no corresponding trace_profiles records. -- This is needed because upsert_trace_profile() had a SQL bug that was -- silently failing, leaving trace_profiles empty for many files. -- Step 1: Insert missing trace_profiles records INSERT INTO trace_profiles (file_uuid, trace_id, name, status, created_at, updated_at) SELECT tn.file_uuid, (tn.properties->>'trace_id')::int as trace_id, COALESCE(tn.label, CONCAT('Person_', (tn.properties->>'trace_id')::int)) as name, 'pending' as status, NOW() as created_at, NOW() as updated_at FROM tkg_nodes tn WHERE tn.node_type = 'face_track' AND tn.properties ? 'trace_id' AND (tn.file_uuid, (tn.properties->>'trace_id')::int) NOT IN ( SELECT file_uuid, trace_id FROM trace_profiles ) ON CONFLICT (file_uuid, trace_id) DO UPDATE SET name = EXCLUDED.name, updated_at = NOW(); -- Step 2: Verify migration DO $$ DECLARE v_count BIGINT; v_tkg_count BIGINT; BEGIN SELECT COUNT(*) INTO v_count FROM trace_profiles; SELECT COUNT(*) INTO v_tkg_count FROM tkg_nodes WHERE node_type = 'face_track' AND properties ? 'trace_id'; RAISE NOTICE 'Migration complete.'; RAISE NOTICE ' trace_profiles count: %', v_count; RAISE NOTICE ' tkg_nodes face_track count: %', v_tkg_count; IF v_count < v_tkg_count THEN RAISE WARNING 'Some trace_profiles records may still be missing. This could be due to tkg_nodes without trace_id in properties.'; END IF; END $$; -- Step 3: Analyze table for query optimization ANALYZE trace_profiles;