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:
+75
-49
@@ -10,6 +10,7 @@ use std::collections::HashMap;
|
|||||||
use crate::api::middleware::UserAuth;
|
use crate::api::middleware::UserAuth;
|
||||||
use crate::api::types::AppState;
|
use crate::api::types::AppState;
|
||||||
use crate::core::db::schema;
|
use crate::core::db::schema;
|
||||||
|
use crate::core::file_profile::FaceFilterSettings;
|
||||||
|
|
||||||
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
|
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
|
||||||
if a.len() != b.len() || a.is_empty() {
|
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_face = format!("face_track_{}", params.trace_id);
|
||||||
let external_id_trace = format!("trace_{}", 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!(
|
sqlx::query_as(&format!(
|
||||||
"SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, \
|
"SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, \
|
||||||
tp.properties, tn.properties \
|
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)?;
|
let (name, _ext_id, tp_props, tn_props) = row.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
|
||||||
// Merge properties: tp_props takes precedence, tn_props as fallback
|
// Merge properties: tp_props takes precedence, tn_props as fallback
|
||||||
let mut properties = tn_props.clone();
|
let mut properties = tn_props.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));
|
||||||
if let Some(tp_obj) = tp_props.as_object() {
|
if let Some(tp_obj) = tp_props.as_ref().and_then(|v| v.as_object()) {
|
||||||
if let Some(props_obj) = properties.as_object_mut() {
|
if let Some(props_obj) = properties.as_object_mut() {
|
||||||
for (k, v) in tp_obj {
|
for (k, v) in tp_obj {
|
||||||
if !v.is_null() {
|
if !v.is_null() {
|
||||||
@@ -960,6 +961,7 @@ pub struct FileProfile {
|
|||||||
pub height: i32,
|
pub height: i32,
|
||||||
pub fps: f64,
|
pub fps: f64,
|
||||||
pub total_frames: i64,
|
pub total_frames: i64,
|
||||||
|
pub face_filter: FaceFilterSettings,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub birth: Option<serde_json::Value>,
|
pub birth: Option<serde_json::Value>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
@@ -977,6 +979,7 @@ pub struct UpdateFileProfileRequest {
|
|||||||
pub file_uuid: String,
|
pub file_uuid: String,
|
||||||
pub file_path: Option<String>,
|
pub file_path: Option<String>,
|
||||||
pub file_name: Option<String>,
|
pub file_name: Option<String>,
|
||||||
|
pub face_filter: Option<FaceFilterSettings>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_file_profile_handler(
|
pub async fn get_file_profile_handler(
|
||||||
@@ -986,10 +989,20 @@ pub async fn get_file_profile_handler(
|
|||||||
) -> Result<Json<FileProfile>, StatusCode> {
|
) -> Result<Json<FileProfile>, StatusCode> {
|
||||||
let videos_table = schema::table_name("videos");
|
let videos_table = schema::table_name("videos");
|
||||||
|
|
||||||
let row: Option<(String, String, String, String, f64, i32, i32, f64, i64)> =
|
let row: Option<(
|
||||||
sqlx::query_as(&format!(
|
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, \
|
"SELECT file_uuid, file_name, file_path, status, duration, width, height, fps, \
|
||||||
COALESCE(total_frames, 0) FROM {} WHERE file_uuid = $1",
|
COALESCE(total_frames, 0), face_filter FROM {} WHERE file_uuid = $1",
|
||||||
videos_table
|
videos_table
|
||||||
))
|
))
|
||||||
.bind(¶ms.file_uuid)
|
.bind(¶ms.file_uuid)
|
||||||
@@ -1000,8 +1013,22 @@ pub async fn get_file_profile_handler(
|
|||||||
StatusCode::INTERNAL_SERVER_ERROR
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let (file_uuid, file_name, file_path, status, duration, width, height, fps, total_frames) =
|
let (
|
||||||
row.ok_or(StatusCode::NOT_FOUND)?;
|
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)
|
// Enrich with on-disk profile data (birth, history, key_frame)
|
||||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||||
@@ -1036,6 +1063,7 @@ pub async fn get_file_profile_handler(
|
|||||||
height,
|
height,
|
||||||
fps,
|
fps,
|
||||||
total_frames,
|
total_frames,
|
||||||
|
face_filter,
|
||||||
birth: disk_profile
|
birth: disk_profile
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|p| serde_json::to_value(&p.birth).ok()),
|
.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 videos_table = schema::table_name("videos");
|
||||||
|
|
||||||
let mut updates: Vec<String> = Vec::new();
|
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()) {
|
if let Some(s) = req.file_path.as_ref().filter(|s| !s.is_empty()) {
|
||||||
updates.push(format!("file_path = ${}", param_idx));
|
updates.push(format!("file_path = ${}", updates.len() + 1));
|
||||||
param_idx += 1;
|
binds.push(s.clone());
|
||||||
|
}
|
||||||
|
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 req.file_name.as_ref().is_some_and(|s| !s.is_empty()) {
|
|
||||||
updates.push(format!("file_name = ${}", param_idx));
|
|
||||||
param_idx += 1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if updates.is_empty() {
|
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());
|
updates.push("updated_at = CURRENT_TIMESTAMP".to_string());
|
||||||
|
|
||||||
let sql = format!(
|
let sql = format!(
|
||||||
"UPDATE {} SET {} WHERE file_uuid = ${}",
|
"UPDATE {} SET {} WHERE file_uuid = ${}",
|
||||||
videos_table,
|
videos_table,
|
||||||
updates.join(", "),
|
updates.join(", "),
|
||||||
param_idx
|
file_uuid_idx
|
||||||
);
|
);
|
||||||
|
|
||||||
// Build the SQL and execute with correct bind order
|
let mut query = sqlx::query(&sql);
|
||||||
let has_path = req.file_path.as_ref().is_some_and(|s| !s.is_empty());
|
for b in &binds {
|
||||||
let has_name = req.file_name.as_ref().is_some_and(|s| !s.is_empty());
|
query = query.bind(b);
|
||||||
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());
|
if let Some(fb) = &face_filter_bind {
|
||||||
|
query = query.bind(fb);
|
||||||
|
}
|
||||||
|
query = query.bind(&req.file_uuid);
|
||||||
|
|
||||||
let result = match (has_path, has_name) {
|
let result = query.execute(state.db.pool()).await;
|
||||||
(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!(),
|
|
||||||
};
|
|
||||||
|
|
||||||
match result {
|
match result {
|
||||||
Ok(res) if res.rows_affected() > 0 => {
|
Ok(res) if res.rows_affected() > 0 => {
|
||||||
// Update on-disk profile if path or name changed
|
// Update on-disk profile if path/name/face_filter changed
|
||||||
if req.file_path.is_some() || req.file_name.is_some() {
|
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();
|
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||||
if let Some(mut profile) = crate::core::file_profile::FileProfile::load_from_disk(
|
if let Some(mut profile) = crate::core::file_profile::FileProfile::load_from_disk(
|
||||||
output_dir,
|
output_dir,
|
||||||
@@ -1136,6 +1155,9 @@ pub async fn update_file_profile_handler(
|
|||||||
.clone()
|
.clone()
|
||||||
.unwrap_or_else(|| profile.current.file_name.clone());
|
.unwrap_or_else(|| profile.current.file_name.clone());
|
||||||
profile.update_current_path(&new_path, &new_name);
|
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) {
|
if let Err(e) = profile.save_to_disk(output_dir) {
|
||||||
tracing::warn!("[FileProfile] Failed to update on-disk profile: {}", e);
|
tracing::warn!("[FileProfile] Failed to update on-disk profile: {}", e);
|
||||||
}
|
}
|
||||||
@@ -1378,7 +1400,11 @@ pub async fn get_cluster_results_handler(
|
|||||||
) {
|
) {
|
||||||
map.insert(
|
map.insert(
|
||||||
cid.to_string(),
|
cid.to_string(),
|
||||||
ClusterSimilarityInfo { min, avg, threshold },
|
ClusterSimilarityInfo {
|
||||||
|
min,
|
||||||
|
avg,
|
||||||
|
threshold,
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,12 +58,12 @@ pub async fn upsert_trace_profile(
|
|||||||
LEFT JOIN {tp_table} tp ON tp.file_uuid = $1 AND tp.trace_id = $2 \
|
LEFT JOIN {tp_table} tp ON tp.file_uuid = $1 AND tp.trace_id = $2 \
|
||||||
ON CONFLICT (file_uuid, trace_id) \
|
ON CONFLICT (file_uuid, trace_id) \
|
||||||
DO UPDATE SET name = EXCLUDED.name{update_props}, \
|
DO UPDATE SET name = EXCLUDED.name{update_props}, \
|
||||||
start_frame = COALESCE(EXCLUDED.start_frame, tp.start_frame), \
|
start_frame = COALESCE(EXCLUDED.start_frame, {tp_table}.start_frame), \
|
||||||
end_frame = COALESCE(EXCLUDED.end_frame, tp.end_frame), \
|
end_frame = COALESCE(EXCLUDED.end_frame, {tp_table}.end_frame), \
|
||||||
frame_count = COALESCE(EXCLUDED.frame_count, tp.frame_count), \
|
frame_count = COALESCE(EXCLUDED.frame_count, {tp_table}.frame_count), \
|
||||||
key_frame = COALESCE(EXCLUDED.key_frame, tp.key_frame), \
|
key_frame = COALESCE(EXCLUDED.key_frame, {tp_table}.key_frame), \
|
||||||
key_face = COALESCE(EXCLUDED.key_face, tp.key_face), \
|
key_face = COALESCE(EXCLUDED.key_face, {tp_table}.key_face), \
|
||||||
avg_confidence = COALESCE(EXCLUDED.avg_confidence, tp.avg_confidence), \
|
avg_confidence = COALESCE(EXCLUDED.avg_confidence, {tp_table}.avg_confidence), \
|
||||||
updated_at = NOW()",
|
updated_at = NOW()",
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user