use sqlx::PgPool; /// Schema-qualified table name helper /// Returns `name` for public schema, `schema.name` for others pub fn t(name: &str) -> String { table_name(name) } /// Alias for t() - used by postgres_db.rs pub fn table_name(name: &str) -> String { let schema = std::env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "public".to_string()); if schema == "public" { name.to_string() } else { format!("{}.{}", schema, name) } } /// UPSERT a trace profile row (insert on missing, update name on existing). /// When inserting a new row, backfills start_frame/end_frame/frame_count/ /// key_frame/key_face/avg_confidence/properties from tkg_nodes face_track node /// so the created profile is complete. /// /// `properties`: when provided, also overwrites the properties column on conflict; /// when `None`, only `name` is updated on conflict and properties are preserved. pub async fn upsert_trace_profile( pool: &PgPool, file_uuid: &str, trace_id: i32, name: &str, properties: Option<&serde_json::Value>, ) -> anyhow::Result { let tp_table = table_name("trace_profiles"); let tkg_table = table_name("tkg_nodes"); let update_props = if properties.is_some() { ", properties = EXCLUDED.properties" } else { "" }; // Use LEFT JOIN to get tkg_nodes data for backfilling let sql = format!( "INSERT INTO {tp_table} (file_uuid, trace_id, name, start_frame, end_frame, \ frame_count, key_frame, key_face, status, avg_confidence, \ best_confidence, avg_capture_quality, best_capture_quality, avg_bbox, best_bbox, properties) \ SELECT $1, $2, $3, \ COALESCE((tn.properties->>'start_frame')::bigint, tp.start_frame), \ COALESCE((tn.properties->>'end_frame')::bigint, tp.end_frame), \ COALESCE((tn.properties->>'frame_count')::int, tp.frame_count), \ COALESCE(tn.properties->>'key_frame', tp.key_frame), \ COALESCE(tn.properties->>'key_face', tp.key_face), \ 'pending', \ COALESCE((tn.properties->>'avg_confidence')::double precision, tp.avg_confidence), \ COALESCE((tn.properties->>'best_confidence')::double precision, tp.best_confidence), \ COALESCE((tn.properties->>'avg_capture_quality')::double precision, tp.avg_capture_quality), \ COALESCE((tn.properties->>'best_capture_quality')::double precision, tp.best_capture_quality), \ COALESCE((tn.properties->>'avg_bbox')::jsonb, tp.avg_bbox), \ COALESCE((tn.properties->>'best_bbox')::jsonb, tp.best_bbox), \ COALESCE($4::jsonb, tn.properties, '{{}}'::jsonb) \ FROM (VALUES (1)) AS dummy \ LEFT JOIN {tkg_table} tn ON tn.file_uuid = $1 \ AND tn.node_type = 'face_track' AND (tn.properties->>'trace_id')::int = $2 \ LEFT JOIN {tp_table} tp ON tp.file_uuid = $1 AND tp.trace_id = $2 \ ON CONFLICT (file_uuid, trace_id) \ DO UPDATE SET name = EXCLUDED.name{update_props}, \ start_frame = COALESCE(EXCLUDED.start_frame, {tp_table}.start_frame), \ end_frame = COALESCE(EXCLUDED.end_frame, {tp_table}.end_frame), \ frame_count = COALESCE(EXCLUDED.frame_count, {tp_table}.frame_count), \ key_frame = COALESCE(EXCLUDED.key_frame, {tp_table}.key_frame), \ key_face = COALESCE(EXCLUDED.key_face, {tp_table}.key_face), \ avg_confidence = COALESCE(EXCLUDED.avg_confidence, {tp_table}.avg_confidence), \ best_confidence = COALESCE(EXCLUDED.best_confidence, {tp_table}.best_confidence), \ avg_capture_quality = COALESCE(EXCLUDED.avg_capture_quality, {tp_table}.avg_capture_quality), \ best_capture_quality = COALESCE(EXCLUDED.best_capture_quality, {tp_table}.best_capture_quality), \ avg_bbox = COALESCE(EXCLUDED.avg_bbox, {tp_table}.avg_bbox), \ best_bbox = COALESCE(EXCLUDED.best_bbox, {tp_table}.best_bbox), \ updated_at = NOW()", ); let mut query = sqlx::query(&sql).bind(file_uuid).bind(trace_id).bind(name); match properties { Some(p) => { let json = serde_json::to_string(p).unwrap_or_else(|_| "{}".to_string()); query = query.bind(json); } None => { query = query.bind(Option::::None); } } let res = query.execute(pool).await?; Ok(res.rows_affected()) } /// Ensure a face_track TKG node exists for the given trace. Self-healing: /// when a group is (re)named but its tkg_nodes row was previously removed, /// re-insert a default node so face-groups/cluster-results queries (which /// read FROM tkg_nodes) keep working. Keeps an existing node untouched. pub async fn ensure_face_track_node( pool: &PgPool, file_uuid: &str, trace_id: i32, name: &str, ) -> anyhow::Result { let tkg_table = table_name("tkg_nodes"); let ext_id_face = format!("face_track_{}", trace_id); let ext_id_trace = format!("trace_{}", trace_id); let props = serde_json::json!({ "trace_id": trace_id }); let existing: Option<(i64,)> = sqlx::query_as(&format!( "SELECT id FROM {tkg_table} WHERE file_uuid = $1 AND node_type = 'face_track' \ AND (external_id = $2 OR external_id = $3) LIMIT 1" )) .bind(file_uuid) .bind(&ext_id_face) .bind(&ext_id_trace) .fetch_optional(pool) .await?; if existing.is_some() { return Ok(0); } let sql = format!( "INSERT INTO {tkg_table} (file_uuid, node_type, external_id, label, properties) \ VALUES ($1, 'face_track', $2, $3, $4)" ); let res = sqlx::query(&sql) .bind(file_uuid) .bind(&ext_id_trace) .bind(name) .bind(&props) .execute(pool) .await?; Ok(res.rows_affected()) }