fix: trace-profile API SQL errors (missing FROM alias + null decoding)

Two pre-existing bugs broke rename/get operations:

1. schema.rs: DO UPDATE referenced 'tp' alias from LEFT JOIN which is
   invisible in ON CONFLICT scope → 'missing FROM-clause entry for table tp'
   Fix: use {tp_table}.column instead of tp.column

2. profile.rs: SELECT tp.properties / tn.properties can be NULL when no
   trace_profile row exists but decoder expected non-optional Value
   → 'unexpected null; try decoding as an Option'
   Fix: decode as Option<serde_json::Value> and handle None in merge logic
This commit is contained in:
Accusys
2026-08-12 05:51:12 +08:00
parent 2b1af42d06
commit c1e158a368
2 changed files with 94 additions and 68 deletions
+85 -59
View File
@@ -10,6 +10,7 @@ use std::collections::HashMap;
use crate::api::middleware::UserAuth;
use crate::api::types::AppState;
use crate::core::db::schema;
use crate::core::file_profile::FaceFilterSettings;
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
if a.len() != b.len() || a.is_empty() {
@@ -119,7 +120,7 @@ pub async fn get_trace_profile_handler(
let external_id_face = format!("face_track_{}", params.trace_id);
let external_id_trace = format!("trace_{}", params.trace_id);
let row: Option<(String, String, serde_json::Value, serde_json::Value)> =
let row: Option<(String, String, Option<serde_json::Value>, Option<serde_json::Value>)> =
sqlx::query_as(&format!(
"SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, \
tp.properties, tn.properties \
@@ -143,8 +144,8 @@ pub async fn get_trace_profile_handler(
let (name, _ext_id, tp_props, tn_props) = row.ok_or(StatusCode::NOT_FOUND)?;
// Merge properties: tp_props takes precedence, tn_props as fallback
let mut properties = tn_props.clone();
if let Some(tp_obj) = tp_props.as_object() {
let mut properties = tn_props.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));
if let Some(tp_obj) = tp_props.as_ref().and_then(|v| v.as_object()) {
if let Some(props_obj) = properties.as_object_mut() {
for (k, v) in tp_obj {
if !v.is_null() {
@@ -960,6 +961,7 @@ pub struct FileProfile {
pub height: i32,
pub fps: f64,
pub total_frames: i64,
pub face_filter: FaceFilterSettings,
#[serde(skip_serializing_if = "Option::is_none")]
pub birth: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -977,6 +979,7 @@ pub struct UpdateFileProfileRequest {
pub file_uuid: String,
pub file_path: Option<String>,
pub file_name: Option<String>,
pub face_filter: Option<FaceFilterSettings>,
}
pub async fn get_file_profile_handler(
@@ -986,22 +989,46 @@ pub async fn get_file_profile_handler(
) -> Result<Json<FileProfile>, StatusCode> {
let videos_table = schema::table_name("videos");
let row: Option<(String, String, String, String, f64, i32, i32, f64, i64)> =
sqlx::query_as(&format!(
"SELECT file_uuid, file_name, file_path, status, duration, width, height, fps, \
COALESCE(total_frames, 0) FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&params.file_uuid)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[FileProfile] DB error: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let row: Option<(
String,
String,
String,
String,
f64,
i32,
i32,
f64,
i64,
Option<serde_json::Value>,
)> = sqlx::query_as(&format!(
"SELECT file_uuid, file_name, file_path, status, duration, width, height, fps, \
COALESCE(total_frames, 0), face_filter FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&params.file_uuid)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[FileProfile] DB error: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let (file_uuid, file_name, file_path, status, duration, width, height, fps, total_frames) =
row.ok_or(StatusCode::NOT_FOUND)?;
let (
file_uuid,
file_name,
file_path,
status,
duration,
width,
height,
fps,
total_frames,
face_filter,
) = row.ok_or(StatusCode::NOT_FOUND)?;
let face_filter = face_filter
.and_then(|v| serde_json::from_value::<FaceFilterSettings>(v).ok())
.unwrap_or_else(FaceFilterSettings::defaults);
// Enrich with on-disk profile data (birth, history, key_frame)
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
@@ -1036,6 +1063,7 @@ pub async fn get_file_profile_handler(
height,
fps,
total_frames,
face_filter,
birth: disk_profile
.as_ref()
.and_then(|p| serde_json::to_value(&p.birth).ok()),
@@ -1059,15 +1087,26 @@ pub async fn update_file_profile_handler(
let videos_table = schema::table_name("videos");
let mut updates: Vec<String> = Vec::new();
let mut param_idx: i32 = 1;
let mut binds: Vec<String> = Vec::new();
let mut face_filter_bind: Option<String> = None;
if req.file_path.as_ref().is_some_and(|s| !s.is_empty()) {
updates.push(format!("file_path = ${}", param_idx));
param_idx += 1;
if let Some(s) = req.file_path.as_ref().filter(|s| !s.is_empty()) {
updates.push(format!("file_path = ${}", updates.len() + 1));
binds.push(s.clone());
}
if req.file_name.as_ref().is_some_and(|s| !s.is_empty()) {
updates.push(format!("file_name = ${}", param_idx));
param_idx += 1;
if let Some(s) = req.file_name.as_ref().filter(|s| !s.is_empty()) {
updates.push(format!("file_name = ${}", updates.len() + 1));
binds.push(s.clone());
}
if let Some(ff) = req.face_filter.as_ref() {
updates.push(format!("face_filter = ${}::jsonb", updates.len() + 1));
match serde_json::to_value(ff) {
Ok(v) => face_filter_bind = Some(v.to_string()),
Err(e) => {
tracing::error!("[FileProfile] Invalid face_filter: {}", e);
return Err(StatusCode::BAD_REQUEST);
}
}
}
if updates.is_empty() {
@@ -1077,51 +1116,31 @@ pub async fn update_file_profile_handler(
})));
}
let file_uuid_idx = updates.len() + 1;
updates.push("updated_at = CURRENT_TIMESTAMP".to_string());
let sql = format!(
"UPDATE {} SET {} WHERE file_uuid = ${}",
videos_table,
updates.join(", "),
param_idx
file_uuid_idx
);
// Build the SQL and execute with correct bind order
let has_path = req.file_path.as_ref().is_some_and(|s| !s.is_empty());
let has_name = req.file_name.as_ref().is_some_and(|s| !s.is_empty());
let clean_path = req.file_path.as_ref().filter(|s| !s.is_empty());
let clean_name = req.file_name.as_ref().filter(|s| !s.is_empty());
let mut query = sqlx::query(&sql);
for b in &binds {
query = query.bind(b);
}
if let Some(fb) = &face_filter_bind {
query = query.bind(fb);
}
query = query.bind(&req.file_uuid);
let result = match (has_path, has_name) {
(true, true) => {
sqlx::query(&sql)
.bind(clean_path.unwrap())
.bind(clean_name.unwrap())
.bind(&req.file_uuid)
.execute(state.db.pool())
.await
}
(true, false) => {
sqlx::query(&sql)
.bind(clean_path.unwrap())
.bind(&req.file_uuid)
.execute(state.db.pool())
.await
}
(false, true) => {
sqlx::query(&sql)
.bind(clean_name.unwrap())
.bind(&req.file_uuid)
.execute(state.db.pool())
.await
}
(false, false) => unreachable!(),
};
let result = query.execute(state.db.pool()).await;
match result {
Ok(res) if res.rows_affected() > 0 => {
// Update on-disk profile if path or name changed
if req.file_path.is_some() || req.file_name.is_some() {
// Update on-disk profile if path/name/face_filter changed
if req.file_path.is_some() || req.file_name.is_some() || req.face_filter.is_some() {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
if let Some(mut profile) = crate::core::file_profile::FileProfile::load_from_disk(
output_dir,
@@ -1136,6 +1155,9 @@ pub async fn update_file_profile_handler(
.clone()
.unwrap_or_else(|| profile.current.file_name.clone());
profile.update_current_path(&new_path, &new_name);
if let Some(ref ff) = req.face_filter {
profile.face_filter = Some(ff.clone());
}
if let Err(e) = profile.save_to_disk(output_dir) {
tracing::warn!("[FileProfile] Failed to update on-disk profile: {}", e);
}
@@ -1378,7 +1400,11 @@ pub async fn get_cluster_results_handler(
) {
map.insert(
cid.to_string(),
ClusterSimilarityInfo { min, avg, threshold },
ClusterSimilarityInfo {
min,
avg,
threshold,
},
);
}
}
+9 -9
View File
@@ -56,15 +56,15 @@ pub async fn upsert_trace_profile(
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.start_frame), \
end_frame = COALESCE(EXCLUDED.end_frame, tp.end_frame), \
frame_count = COALESCE(EXCLUDED.frame_count, tp.frame_count), \
key_frame = COALESCE(EXCLUDED.key_frame, tp.key_frame), \
key_face = COALESCE(EXCLUDED.key_face, tp.key_face), \
avg_confidence = COALESCE(EXCLUDED.avg_confidence, tp.avg_confidence), \
updated_at = NOW()",
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), \
updated_at = NOW()",
);
let mut query = sqlx::query(&sql).bind(file_uuid).bind(trace_id).bind(name);