Files
momentry_core/src/core/db/schema.rs
T
Accusys cd8df324be fix: tkg.rs avg_confidence moved before props construction + schema.rs ON CONFLICT backfill derived fields
- tkg.rs: avg_confidence calculation moved to line 1207 (before props json)
- tkg.rs: Added 'avg_confidence' to props json (round4)
- schema.rs: ON CONFLICT DO UPDATE expanded to backfill start_frame, end_frame,
  frame_count, key_frame, key_face, avg_confidence from tkg_nodes.properties

This fixes trace_profiles.avg_confidence always being NULL, and enables
automatic self-healing when upsert_trace_profile is called from any caller.
2026-08-07 14:04:54 +08:00

129 lines
4.4 KiB
Rust

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<u64> {
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::<String>::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<u64> {
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())
}