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(|_| "dev".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 tkg_sub = |col: &str| { format!( "(SELECT {col} FROM {tkg_table} tn WHERE tn.file_uuid = $1 \ AND tn.node_type = 'face_track' AND (tn.properties->>'trace_id')::int = $2)" ) }; let update_props = if properties.is_some() { ", properties = EXCLUDED.properties" } else { "" }; 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, properties) \ VALUES ($1, $2, $3, {sf}, {ef}, {fc}, {kf}, {kface}, 'pending', {avgc}, \ COALESCE($4::jsonb, {props_sub}, '{{}}'::jsonb)) \ ON CONFLICT (file_uuid, trace_id) \ DO UPDATE SET name = EXCLUDED.name{update_props}, \ start_frame = EXCLUDED.start_frame, \ end_frame = EXCLUDED.end_frame, \ frame_count = EXCLUDED.frame_count, \ key_frame = EXCLUDED.key_frame, \ key_face = EXCLUDED.key_face, \ avg_confidence = EXCLUDED.avg_confidence, \ updated_at = NOW()", sf = tkg_sub("(tn.properties->>'start_frame')::bigint"), ef = tkg_sub("(tn.properties->>'end_frame')::bigint"), fc = tkg_sub("(tn.properties->>'frame_count')::int"), kf = tkg_sub("tn.properties->>'key_frame'"), kface = tkg_sub("tn.properties->>'key_face'"), avgc = tkg_sub("(tn.properties->>'avg_confidence')::double precision"), props_sub = tkg_sub("tn.properties"), ); 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()) }