70 lines · 2.6 KB · RustRaw
//! Extra typed facts for person records.use cotton_core::definitions::TableDefinition;use rusqlite::types::Value as SqlValue;use serde_json::Value;use super::Stored;use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::Valid;fn people_engine(definition: &TableDefinition) -> bool { definition.id == "person" && definition.engine.as_deref() == Some("people")}/// Answer the handles as stored, once for this batch.pub(super) fn person_handles(ctx: &Ctx<'_>, definition: &TableDefinition, records: &mut [Stored]) -> Valid<()> { if !people_engine(definition) || records.is_empty() { return Ok(()); } let mut lists: std::collections::HashMap<(String, String), Vec<Value>> = std::collections::HashMap::new(); for chunk in records.chunks(400) { let holes = vec!["?"; chunk.len()].join(", "); let params: Vec<SqlValue> = chunk.iter().map(|record| SqlValue::Text(record.id.clone())).collect(); for row in ctx .read .driver() .all( &format!( "SELECT person_id, kind, value FROM cotton_person_handles \ WHERE person_id IN ({holes}) AND kind IN ('phone', 'email', 'instagram') \ ORDER BY person_id, kind, position, created_at, id" ), ¶ms, ) .map_err(super::sql_err)? { let (Some(person), Some(kind), Some(value)) = (row.text("person_id"), row.text("kind"), row.text("value")) else { continue; }; lists .entry((person.into(), kind.into())) .or_default() .push(Value::from(value)); } } for record in records { for (kind, key) in [("phone", "phones"), ("email", "emails"), ("instagram", "instagrams")] { record.data.insert( key.into(), lists .remove(&(record.id.clone(), kind.into())) .map_or(Value::Null, Value::Array), ); } } Ok(())}#[cfg(test)]mod tests { /// RULE: Person enrichment belongs only to the people engine, so a data-only /// table called person never receives private contact facts. #[test] fn enrichment_requires_people_engine() { let mut definition = cotton_core::definitions::builtin_table_definitions().iter().find(|d| d.id == "person").unwrap().clone(); assert!(super::people_engine(&definition)); definition.engine = None; assert!(!super::people_engine(&definition)); }}