Skip to content

Commit c17f0d1

Browse files
committed
Refactor and clean up superfluous iterations in search() and load_relations().
1 parent 1dc058f commit c17f0d1

File tree

1 file changed

+13
-18
lines changed

1 file changed

+13
-18
lines changed

src/manager/mod.rs

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -130,17 +130,15 @@ impl Manager {
130130

131131
// Build ID list and index map.
132132
let ids: Vec<i64> = entries.iter().map(|e| e.id).collect();
133-
let id_json = serde_json::to_string(&ids).unwrap_or_default();
134133

135-
let mut id_map: HashMap<i64, usize> = HashMap::new();
136-
for (i, e) in entries.iter_mut().enumerate() {
137-
e.relations = Vec::new();
138-
id_map.insert(e.id, i);
139-
}
134+
entries.iter_mut().for_each(|e| e.relations = Vec::new());
135+
let id_map: HashMap<i64, usize> =
136+
entries.iter().enumerate().map(|(i, e)| (e.id, i)).collect();
140137

141-
let types_json =
142-
serde_json::to_string(&rel_query.types).unwrap_or_else(|_| "[]".to_string());
143-
let tags_json = serde_json::to_string(&rel_query.tags).unwrap_or_else(|_| "[]".to_string());
138+
// Serialize array types for SQLite query.
139+
let id_json = serde_json::to_string(&ids).unwrap_or_default();
140+
let types_json = serde_json::to_string(&rel_query.types).unwrap_or_default();
141+
let tags_json = serde_json::to_string(&rel_query.tags).unwrap_or_default();
144142

145143
let rel_entries: Vec<Entry> = sqlx::query_as(&q.search_relations.query)
146144
.bind(&id_json)
@@ -167,15 +165,12 @@ impl Manager {
167165
updated_at: r.relation_updated_at.take(),
168166
});
169167

170-
if let Some(idx) = id_map.get(&r.from_id) {
171-
entries[*idx].relations.push(r);
172-
}
173-
}
174-
175-
// Set total_relations from query results (computed per from_id via window function).
176-
for e in entries.iter_mut() {
177-
if let Some(first_rel) = e.relations.first() {
178-
e.total_relations = first_rel.total_relations;
168+
if let Some(&idx) = id_map.get(&r.from_id) {
169+
let entry = &mut entries[idx];
170+
if entry.relations.is_empty() {
171+
entry.total_relations = r.total_relations;
172+
}
173+
entry.relations.push(r);
179174
}
180175
}
181176

0 commit comments

Comments
 (0)