fix: prevent duplicate face group cards - deduplicate tkg_nodes and DISTINCT ON in get_face_groups_handler
This commit is contained in:
+36
-5
@@ -112,6 +112,9 @@ pub async fn upsert_trace_profile(
|
||||
/// 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.
|
||||
///
|
||||
/// FIX: Prevent duplicate nodes by checking for both external_id formats
|
||||
/// and only creating one node per trace_id.
|
||||
pub async fn ensure_face_track_node(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
@@ -123,17 +126,45 @@ pub async fn ensure_face_track_node(
|
||||
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"
|
||||
// Check for existing nodes with either external_id format
|
||||
let existing: Vec<(i64, String)> = sqlx::query_as(&format!(
|
||||
"SELECT id, external_id FROM {tkg_table} WHERE file_uuid = $1 AND node_type = 'face_track' \
|
||||
AND (external_id = $2 OR external_id = $3)",
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.bind(&ext_id_face)
|
||||
.bind(&ext_id_trace)
|
||||
.fetch_optional(pool)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
if let Some((node_id,)) = existing {
|
||||
if existing.len() >= 2 {
|
||||
// Duplicate nodes exist - remove the face_track_* variant, keep trace_*
|
||||
let to_delete: Vec<i64> = existing.iter()
|
||||
.filter(|(_, ext_id)| ext_id.starts_with("face_track_"))
|
||||
.map(|(id, _)| *id)
|
||||
.collect();
|
||||
|
||||
for node_id in to_delete {
|
||||
let _ = sqlx::query(&format!("DELETE FROM {tkg_table} WHERE id = $1"))
|
||||
.bind(node_id)
|
||||
.execute(pool)
|
||||
.await;
|
||||
}
|
||||
|
||||
// Update the remaining node
|
||||
let remaining = existing.iter().find(|(_, ext_id)| ext_id.starts_with("trace_"));
|
||||
if let Some((node_id, _)) = remaining {
|
||||
let res = sqlx::query(&format!(
|
||||
"UPDATE {tkg_table} SET label = $1, properties = $2 WHERE id = $3"
|
||||
))
|
||||
.bind(name)
|
||||
.bind(&props)
|
||||
.bind(node_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
return Ok(res.rows_affected());
|
||||
}
|
||||
} else if let Some((node_id, _)) = existing.first() {
|
||||
// Node exists - update the label
|
||||
let res = sqlx::query(&format!(
|
||||
"UPDATE {tkg_table} SET label = $1, properties = $2 WHERE id = $3"
|
||||
|
||||
Reference in New Issue
Block a user