Files
momentry_core/sql/migration_backfill_trace_profiles.sql
T
Accusys aa28bf93fb fix: resolve merge silent failure by fixing upsert_trace_profile SQL and backfilling data
- Fixed upsert_trace_profile() SQL: changed trace_profiles.xxx to tp.xxx in ON CONFLICT DO UPDATE
  to fix invalid reference to FROM-clause entry error
- Fixed cluster_agent.rs error handling: replaced 'let _ =' with proper error logging
- Created migration script to backfill trace_profiles from tkg_nodes for existing files
- Migration successfully inserted 98 missing trace_profiles records
- Verified merge now works correctly: traces_merged > 0 instead of silent no-op

This fixes both the rename 500 error and the merge silent failure, as they share
the same root cause in upsert_trace_profile() SQL.
2026-08-10 01:42:34 +08:00

46 lines
1.7 KiB
SQL

-- 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;