BlueGit

ict rusty-teams

Files

rusty-teams / crates / store / tests / store.rs

store.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
store.rs 24.0 KiB Download Raw
1use chrono::{DateTime, TimeZone, Utc};
2use rusqlite::Connection;
3use store::{
4 AvatarRecord, ChannelRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
5 MessageRecord, Store, SyncState, TeamRecord,
6};
7
8fn at(minute: u32) -> DateTime<Utc> {
9 Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap()
10}
11
12fn chat(id: &str, title: &str, last: Option<DateTime<Utc>>) -> ChatRecord {
13 ChatRecord {
14 id: id.to_owned(),
15 kind: "group".to_owned(),
16 title: title.to_owned(),
17 member_summary: "Ada Example, Bob Sample".to_owned(),
18 last_message_at: last,
19 last_read_at: Some(at(0)),
20 unread: true,
21 members: vec![
22 MemberRecord {
23 user_id: Some("user-ada".to_owned()),
24 display_name: "Ada Example".to_owned(),
25 },
26 MemberRecord {
27 user_id: None,
28 display_name: "Bob Sample".to_owned(),
29 },
30 ],
31 ..ChatRecord::default()
32 }
33}
34
35fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecord {
36 MessageRecord {
37 conversation_id: conversation_id.to_owned(),
38 message_id: message_id.to_owned(),
39 reply_to_id: None,
40 sender_id: Some("user-ada".to_owned()),
41 sender_name: Some("Ada Example".to_owned()),
42 created_at: at(minute),
43 edited_at: None,
44 deleted: false,
45 body_html: format!("<p>message {message_id}</p>"),
46 attachments_json: "[]".to_owned(),
47 reactions_json: "[]".to_owned(),
48 mentions_json: "[]".to_owned(),
49 }
50}
51
52fn ids(messages: &[MessageRecord]) -> Vec<&str> {
53 messages
54 .iter()
55 .map(|message| message.message_id.as_str())
56 .collect()
57}
58
59#[test]
60fn chats_round_trip_with_members() {
61 let store = Store::open_in_memory().unwrap();
62 let original = chat("chat-1", "Planning", Some(at(5)));
63 store.upsert_chats(std::slice::from_ref(&original)).unwrap();
64 assert_eq!(store.chat("chat-1").unwrap(), Some(original));
65 assert_eq!(store.chat("missing").unwrap(), None);
66}
67
68#[test]
69fn chat_upsert_replaces_fields_and_members() {
70 let store = Store::open_in_memory().unwrap();
71 store
72 .upsert_chats(&[chat("chat-1", "Old", Some(at(1)))])
73 .unwrap();
74 let mut changed = chat("chat-1", "New", Some(at(9)));
75 changed.members.truncate(1);
76 changed.unread = false;
77 store.upsert_chats(&[changed.clone()]).unwrap();
78 assert_eq!(store.recent_chats(10).unwrap(), vec![changed]);
79}
80
81#[test]
82fn recent_chats_are_newest_first_with_unknown_last() {
83 let store = Store::open_in_memory().unwrap();
84 store
85 .upsert_chats(&[
86 chat("old", "Old", Some(at(1))),
87 chat("none", "None", None),
88 chat("new", "New", Some(at(30))),
89 chat("mid", "Mid", Some(at(10))),
90 ])
91 .unwrap();
92 let recent = store.recent_chats(3).unwrap();
93 let order: Vec<&str> = recent.iter().map(|chat| chat.id.as_str()).collect();
94 assert_eq!(order, ["new", "mid", "old"]);
95 assert_eq!(store.recent_chats(10).unwrap().last().unwrap().id, "none");
96}
97
98#[test]
99fn messages_page_backwards_oldest_first() {
100 let store = Store::open_in_memory().unwrap();
101 let all: Vec<MessageRecord> = (1..=10)
102 .map(|minute| message("chat-1", &format!("m{minute:02}"), minute))
103 .collect();
104 store.upsert_messages(&all).unwrap();
105 store
106 .upsert_messages(&[message("chat-2", "other", 5)])
107 .unwrap();
108
109 let newest = store.messages("chat-1", None, 4).unwrap();
110 assert_eq!(ids(&newest), ["m07", "m08", "m09", "m10"]);
111
112 let older = store
113 .messages("chat-1", Some(newest[0].created_at), 4)
114 .unwrap();
115 assert_eq!(ids(&older), ["m03", "m04", "m05", "m06"]);
116
117 let oldest = store
118 .messages("chat-1", Some(older[0].created_at), 4)
119 .unwrap();
120 assert_eq!(ids(&oldest), ["m01", "m02"]);
121 assert!(
122 store
123 .messages("chat-1", Some(oldest[0].created_at), 4)
124 .unwrap()
125 .is_empty()
126 );
127 assert_eq!(store.message_count("chat-1").unwrap(), 10);
128}
129
130#[test]
131fn equal_timestamps_keep_a_stable_order() {
132 let store = Store::open_in_memory().unwrap();
133 store
134 .upsert_messages(&[
135 message("c", "b", 1),
136 message("c", "a", 1),
137 message("c", "c", 1),
138 ])
139 .unwrap();
140 assert_eq!(
141 ids(&store.messages("c", None, 10).unwrap()),
142 ["a", "b", "c"]
143 );
144}
145
146#[test]
147fn message_upsert_updates_in_place() {
148 let store = Store::open_in_memory().unwrap();
149 let mut edited = message("c", "m1", 1);
150 store
151 .upsert_messages(std::slice::from_ref(&edited))
152 .unwrap();
153 edited.body_html = "<p>edited</p>".to_owned();
154 edited.edited_at = Some(at(2));
155 edited.reactions_json = r#"[{"type":"like"}]"#.to_owned();
156 store
157 .upsert_messages(std::slice::from_ref(&edited))
158 .unwrap();
159
160 let stored = store.messages("c", None, 10).unwrap();
161 assert_eq!(stored, vec![edited.clone()]);
162 let by_id = store
163 .messages_by_id("c", &["m1".to_owned(), "nope".to_owned()])
164 .unwrap();
165 assert_eq!(by_id.len(), 1);
166 assert_eq!(by_id["m1"], edited);
167}
168
169#[test]
170fn deleted_flag_and_json_columns_round_trip() {
171 let store = Store::open_in_memory().unwrap();
172 let mut record = message("c", "m1", 1);
173 record.deleted = true;
174 record.reply_to_id = Some("m0".to_owned());
175 record.attachments_json = r#"[{"name":"a.pdf"}]"#.to_owned();
176 record.mentions_json = r#"[{"id":"u1","name":"Ada Example"}]"#.to_owned();
177 store
178 .upsert_messages(std::slice::from_ref(&record))
179 .unwrap();
180 assert_eq!(store.messages("c", None, 1).unwrap(), vec![record]);
181}
182
183#[test]
184fn sync_state_round_trip() {
185 let store = Store::open_in_memory().unwrap();
186 assert_eq!(store.sync_state("c").unwrap(), None);
187 let state = SyncState {
188 newest_seen: Some(at(9)),
189 oldest_loaded: Some(at(1)),
190 has_more: false,
191 older_cursor: Some("https://graph.microsoft.com/v1.0/next".to_owned()),
192 delta_link: Some("https://graph.microsoft.com/v1.0/delta".to_owned()),
193 };
194 store.set_sync_state("c", &state).unwrap();
195 assert_eq!(store.sync_state("c").unwrap(), Some(state));
196 let reset = SyncState {
197 has_more: true,
198 ..SyncState::default()
199 };
200 store.set_sync_state("c", &reset).unwrap();
201 assert_eq!(store.sync_state("c").unwrap(), Some(reset));
202}
203
204#[test]
205fn sidebar_groups_channels_under_teams() {
206 let store = Store::open_in_memory().unwrap();
207 store
208 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
209 .unwrap();
210 store
211 .upsert_teams(&[
212 TeamRecord {
213 id: "t2".to_owned(),
214 name: "beta".to_owned(),
215 },
216 TeamRecord {
217 id: "t1".to_owned(),
218 name: "Alpha".to_owned(),
219 },
220 ])
221 .unwrap();
222 let channel = |id: &str, team_id: &str, name: &str| ChannelRecord {
223 id: id.to_owned(),
224 team_id: team_id.to_owned(),
225 name: name.to_owned(),
226 membership_type: Some("standard".to_owned()),
227 last_message_at: None,
228 unread: false,
229 };
230 store
231 .upsert_channels(&[
232 channel("c2", "t1", "Random"),
233 channel("c1", "t1", "General"),
234 channel("c3", "t2", "General"),
235 ])
236 .unwrap();
237
238 let sidebar = store.sidebar().unwrap();
239 assert_eq!(sidebar.chats.len(), 1);
240 let team_names: Vec<&str> = sidebar
241 .teams
242 .iter()
243 .map(|entry| entry.team.name.as_str())
244 .collect();
245 assert_eq!(team_names, ["Alpha", "beta"]);
246 let alpha_channels: Vec<&str> = sidebar.teams[0]
247 .channels
248 .iter()
249 .map(|entry| entry.name.as_str())
250 .collect();
251 assert_eq!(alpha_channels, ["General", "Random"]);
252 assert_eq!(store.channel("c3").unwrap().unwrap().team_id, "t2");
253}
254
255#[test]
256fn channel_upsert_keeps_known_last_message_time() {
257 let store = Store::open_in_memory().unwrap();
258 store
259 .upsert_teams(&[TeamRecord {
260 id: "t1".to_owned(),
261 name: "A".to_owned(),
262 }])
263 .unwrap();
264 let mut channel = ChannelRecord {
265 id: "c1".to_owned(),
266 team_id: "t1".to_owned(),
267 name: "General".to_owned(),
268 membership_type: None,
269 last_message_at: Some(at(7)),
270 unread: false,
271 };
272 store
273 .upsert_channels(std::slice::from_ref(&channel))
274 .unwrap();
275 channel.last_message_at = None;
276 store
277 .upsert_channels(std::slice::from_ref(&channel))
278 .unwrap();
279 assert_eq!(
280 store.channel("c1").unwrap().unwrap().last_message_at,
281 Some(at(7))
282 );
283}
284
285#[test]
286fn pruning_removes_departed_teams_and_channels() {
287 let store = Store::open_in_memory().unwrap();
288 store
289 .upsert_teams(&[
290 TeamRecord {
291 id: "t1".to_owned(),
292 name: "A".to_owned(),
293 },
294 TeamRecord {
295 id: "t2".to_owned(),
296 name: "B".to_owned(),
297 },
298 ])
299 .unwrap();
300 let channel = |id: &str| ChannelRecord {
301 id: id.to_owned(),
302 team_id: "t1".to_owned(),
303 name: id.to_owned(),
304 membership_type: None,
305 last_message_at: None,
306 unread: false,
307 };
308 store
309 .upsert_channels(&[channel("c1"), channel("c2")])
310 .unwrap();
311 assert_eq!(
312 store
313 .remove_channels_except("t1", &["c1".to_owned()])
314 .unwrap(),
315 1
316 );
317 assert_eq!(store.remove_teams_except(&["t1".to_owned()]).unwrap(), 1);
318 let sidebar = store.sidebar().unwrap();
319 assert_eq!(sidebar.teams.len(), 1);
320 assert_eq!(sidebar.teams[0].channels.len(), 1);
321}
322
323#[test]
324fn file_database_uses_wal_persists_and_migrates_once() {
325 let directory = tempfile::tempdir().unwrap();
326 let path = directory.path().join("nested").join("cache.sqlite3");
327 {
328 let store = Store::open(&path).unwrap();
329 assert_eq!(store.schema_version().unwrap(), 5);
330 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
331 }
332 let reopened = Store::open(&path).unwrap();
333 assert_eq!(reopened.schema_version().unwrap(), 5);
334 assert_eq!(reopened.message_count("c").unwrap(), 1);
335 drop(reopened);
336 let mode: String = rusqlite_open(&path)
337 .pragma_query_value(None, "journal_mode", |row| row.get(0))
338 .unwrap();
339 assert_eq!(mode, "wal");
340}
341
342#[test]
343fn newer_schema_is_refused() {
344 let directory = tempfile::tempdir().unwrap();
345 let path = directory.path().join("cache.sqlite3");
346 drop(Store::open(&path).unwrap());
347 let connection = rusqlite_open(&path);
348 connection
349 .execute_batch("PRAGMA user_version = 99")
350 .unwrap();
351 drop(connection);
352 let error = Store::open(&path).err().expect("must refuse");
353 assert!(error.to_string().contains("99"), "{error}");
354}
355
356#[test]
357fn old_schema_is_upgraded_in_place() {
358 let directory = tempfile::tempdir().unwrap();
359 let path = directory.path().join("cache.sqlite3");
360 drop(Store::open(&path).unwrap());
361 let connection = rusqlite_open(&path);
362 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; PRAGMA user_version = 0").unwrap();
363 drop(connection);
364 let store = Store::open(&path).unwrap();
365 assert_eq!(store.schema_version().unwrap(), 5);
366 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
367}
368
369fn rusqlite_open(path: &std::path::Path) -> Connection {
370 Connection::open(path).unwrap()
371}
372
373#[test]
374fn meta_values_and_times_round_trip() {
375 let store = Store::open_in_memory().unwrap();
376 assert_eq!(store.meta("k").unwrap(), None);
377 store.set_meta("k", "one").unwrap();
378 store.set_meta("k", "two").unwrap();
379 assert_eq!(store.meta("k").unwrap().as_deref(), Some("two"));
380 assert_eq!(store.meta_time("t").unwrap(), None);
381 store.set_meta_time("t", at(7)).unwrap();
382 assert_eq!(store.meta_time("t").unwrap(), Some(at(7)));
383 store.set_meta("bad", "not a number").unwrap();
384 assert_eq!(store.meta_time("bad").unwrap(), None);
385}
386
387#[test]
388fn chats_can_be_pruned_and_marked_read() {
389 let store = Store::open_in_memory().unwrap();
390 store
391 .upsert_chats(&[
392 chat("a", "A", Some(at(1))),
393 chat("b", "B", Some(at(2))),
394 chat("c", "C", None),
395 ])
396 .unwrap();
397 let times = store
398 .chat_last_message_times(&["a".to_owned(), "c".to_owned(), "zzz".to_owned()])
399 .unwrap();
400 assert_eq!(times.len(), 2);
401 assert_eq!(times["a"], Some(at(1)));
402 assert_eq!(times["c"], None);
403
404 assert_eq!(store.remove_chats(&["a".to_owned()]).unwrap(), 1);
405 assert_eq!(store.remove_chats_except(&["b".to_owned()]).unwrap(), 1);
406 assert_eq!(store.chat_count().unwrap(), 1);
407
408 store.mark_chat_read("b", at(30)).unwrap();
409 let read = store.chat("b").unwrap().unwrap();
410 assert!(!read.unread);
411 assert_eq!(read.last_read_at, Some(at(30)));
412}
413
414#[test]
415fn migration_to_v2_keeps_existing_sync_state() {
416 let directory = tempfile::tempdir().unwrap();
417 let path = directory.path().join("old.sqlite3");
418 {
419 let connection = Connection::open(&path).unwrap();
420 connection
421 .execute_batch(include_str!("../src/migrations/0001_initial.sql"))
422 .unwrap();
423 connection.pragma_update(None, "user_version", 1).unwrap();
424 connection
425 .execute("INSERT INTO sync_state (conversation_id, newest_seen, has_more) VALUES ('c', 5, 1)", [])
426 .unwrap();
427 }
428 let store = Store::open(&path).unwrap();
429 let state = store.sync_state("c").unwrap().unwrap();
430 assert_eq!(state.delta_link, None);
431 assert_eq!(store.schema_version().unwrap(), 5);
432}
433
434#[test]
435fn preview_updates_only_for_newer_messages() {
436 let store = Store::open_in_memory().unwrap();
437 store.upsert_chats(&[chat("a", "A", Some(at(5)))]).unwrap();
438 let preview = |text| ChatPreview {
439 text: Some(text),
440 sender_id: Some("user-ada"),
441 sender_name: Some("Ada Example"),
442 deleted: false,
443 };
444 assert!(
445 !store
446 .update_chat_preview("a", at(4), &preview("older"))
447 .unwrap()
448 );
449 assert!(
450 store
451 .update_chat_preview("a", at(6), &preview("newer"))
452 .unwrap()
453 );
454 let record = store.chat("a").unwrap().unwrap();
455 assert_eq!(record.last_message_preview.as_deref(), Some("newer"));
456 assert_eq!(
457 record.last_message_sender_name.as_deref(),
458 Some("Ada Example")
459 );
460 assert_eq!(record.last_message_at, Some(at(6)));
461 assert!(!record.last_message_deleted);
462}
463
464#[test]
465fn avatars_round_trip_and_report_stale_ids() {
466 let store = Store::open_in_memory().unwrap();
467 store
468 .upsert_avatar(&AvatarRecord {
469 user_id: "fresh".into(),
470 bytes: Some(vec![1, 2, 3]),
471 content_type: "image/jpeg".into(),
472 fetched_at: at(50),
473 })
474 .unwrap();
475 store
476 .upsert_avatar(&AvatarRecord {
477 user_id: "missing".into(),
478 bytes: None,
479 content_type: String::new(),
480 fetched_at: at(1),
481 })
482 .unwrap();
483 assert_eq!(
484 store.avatar("fresh").unwrap().unwrap().bytes,
485 Some(vec![1, 2, 3])
486 );
487 assert_eq!(store.avatar("missing").unwrap().unwrap().bytes, None);
488 assert!(store.avatar("unknown").unwrap().is_none());
489 let ids: Vec<String> = ["fresh", "missing", "unknown"].map(String::from).to_vec();
490 assert_eq!(
491 store.avatar_ids_needing_fetch(&ids, at(10)).unwrap(),
492 ["missing", "unknown"]
493 );
494}
495
496#[test]
497fn folders_and_pinned_channels_are_replaced_in_order() {
498 let store = Store::open_in_memory().unwrap();
499 let folder = |id: &str, kind: &str, items: &[&str]| FolderRecord {
500 id: id.into(),
501 name: id.into(),
502 kind: kind.into(),
503 conversation_ids: items.iter().map(|item| item.to_string()).collect(),
504 };
505 let first = [
506 folder("f1", "Favorites", &["b", "a"]),
507 folder("f2", "UserCreated", &[]),
508 ];
509 store
510 .replace_folders(&first, &["c2".into(), "c1".into()])
511 .unwrap();
512 assert_eq!(store.folders().unwrap(), first);
513 assert_eq!(store.pinned_channel_ids().unwrap(), ["c2", "c1"]);
514 store
515 .replace_folders(&[folder("f3", "UserCreated", &["z"])], &[])
516 .unwrap();
517 assert_eq!(store.folders().unwrap().len(), 1);
518 assert!(store.pinned_channel_ids().unwrap().is_empty());
519}
520
521#[test]
522fn counts_messages_after_a_time_from_others() {
523 let store = Store::open_in_memory().unwrap();
524 let mut mine = message("c", "m3", 3);
525 mine.sender_id = Some("me".into());
526 store
527 .upsert_messages(&[message("c", "m1", 1), message("c", "m2", 2), mine])
528 .unwrap();
529 assert_eq!(
530 store.count_messages_after("c", Some(at(1)), "me").unwrap(),
531 1
532 );
533 assert_eq!(store.count_messages_after("c", None, "me").unwrap(), 2);
534}
535
536fn html_message(
537 conversation_id: &str,
538 message_id: &str,
539 minute: u32,
540 sender: &str,
541 html: &str,
542) -> MessageRecord {
543 MessageRecord {
544 sender_name: Some(sender.to_owned()),
545 body_html: html.to_owned(),
546 ..message(conversation_id, message_id, minute)
547 }
548}
549
550#[test]
551fn fts5_is_available_and_matches_prefixes_with_highlights() {
552 let store = Store::open_in_memory().unwrap();
553 store
554 .upsert_messages(&[
555 html_message(
556 "c1",
557 "m1",
558 1,
559 "Ada Example",
560 "<p>The <b>budget</b> planning is done</p>",
561 ),
562 html_message("c1", "m2", 2, "Bob Sample", "<p>Lunch at noon</p>"),
563 html_message("c2", "m3", 3, "Bob Sample", "<p>Budget approved</p>"),
564 ])
565 .unwrap();
566 let hits = store.search_messages("budg plan", None, 10).unwrap();
567 assert_eq!(hits.len(), 1);
568 assert_eq!(hits[0].message_id, "m1");
569 assert_eq!(hits[0].sender_name.as_deref(), Some("Ada Example"));
570 assert_eq!(hits[0].created_at, at(1));
571 assert!(
572 hits[0].snippet.contains("\u{1}budget\u{2}"),
573 "{}",
574 hits[0].snippet
575 );
576 let all = store.search_messages("budget", None, 10).unwrap();
577 assert_eq!(ids_of(&all), ["m3", "m1"]);
578 let scoped = store.search_messages("budget", Some("c1"), 10).unwrap();
579 assert_eq!(ids_of(&scoped), ["m1"]);
580 assert_eq!(store.search_messages("budget", None, 1).unwrap().len(), 1);
581}
582
583fn ids_of(hits: &[store::SearchHit]) -> Vec<&str> {
584 hits.iter().map(|hit| hit.message_id.as_str()).collect()
585}
586
587#[test]
588fn search_filters_by_sender_and_ignores_unsearchable_input() {
589 let store = Store::open_in_memory().unwrap();
590 store
591 .upsert_messages(&[
592 html_message("c1", "m1", 1, "Ada Example", "<p>report</p>"),
593 html_message("c1", "m2", 2, "Bob Sample", "<p>report</p>"),
594 ])
595 .unwrap();
596 assert_eq!(
597 ids_of(&store.search_messages("from:bob report", None, 10).unwrap()),
598 ["m2"]
599 );
600 assert!(store.search_messages(" ", None, 10).unwrap().is_empty());
601 assert!(store.search_messages("\"-*", None, 10).unwrap().is_empty());
602 assert!(store.search_messages("rep) OR (", None, 10).is_ok());
603}
604
605#[test]
606fn search_follows_edits_and_deletes() {
607 let store = Store::open_in_memory().unwrap();
608 store
609 .upsert_messages(&[html_message("c1", "m1", 1, "Ada", "<p>alpha</p>")])
610 .unwrap();
611 store
612 .upsert_messages(&[html_message("c1", "m1", 1, "Ada", "<p>beta</p>")])
613 .unwrap();
614 assert!(store.search_messages("alpha", None, 10).unwrap().is_empty());
615 assert_eq!(store.search_messages("beta", None, 10).unwrap().len(), 1);
616 let mut deleted = html_message("c1", "m1", 1, "Ada", "");
617 deleted.deleted = true;
618 store.upsert_messages(&[deleted]).unwrap();
619 assert!(store.search_messages("beta", None, 10).unwrap().is_empty());
620}
621
622#[test]
623fn title_search_follows_chat_renames() {
624 let store = Store::open_in_memory().unwrap();
625 store
626 .upsert_chats(&[chat("c1", "Budget planning", None)])
627 .unwrap();
628 assert_eq!(
629 store.search_conversations("budg", 10).unwrap()[0].conversation_id,
630 "c1"
631 );
632 store.upsert_chats(&[chat("c1", "Holiday", None)]).unwrap();
633 assert!(store.search_conversations("budget", 10).unwrap().is_empty());
634 assert_eq!(store.search_conversations("holi", 10).unwrap().len(), 1);
635 assert!(
636 store
637 .search_conversations("from:holi", 10)
638 .unwrap()
639 .is_empty()
640 );
641}
642
643#[test]
644fn migration_indexes_rows_that_predate_search() {
645 let directory = tempfile::tempdir().unwrap();
646 let path = directory.path().join("cache.sqlite3");
647 {
648 let store = Store::open(&path).unwrap();
649 store.upsert_chats(&[chat("c1", "Old chat", None)]).unwrap();
650 store
651 .upsert_messages(&[html_message("c1", "m1", 1, "Ada", "<p>legacy text</p>")])
652 .unwrap();
653 }
654 {
655 let connection = Connection::open(&path).unwrap();
656 connection
657 .execute_batch(
658 "DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
659 DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
660 DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
661 DROP TABLE team_layout; DROP TABLE channel_layout;
662 PRAGMA user_version = 3;",
663 )
664 .unwrap();
665 }
666 let store = Store::open(&path).unwrap();
667 assert_eq!(store.search_messages("legacy", None, 10).unwrap().len(), 1);
668 assert_eq!(store.search_conversations("old", 10).unwrap().len(), 1);
669}
670
671fn image(key: &str, minute: u32, size: usize) -> store::ImageRecord {
672 store::ImageRecord {
673 key: key.to_owned(),
674 bytes: vec![7; size],
675 content_type: "image/png".to_owned(),
676 fetched_at: at(minute),
677 }
678}
679
680#[test]
681fn images_round_trip_and_evict_the_oldest_over_the_cap() {
682 let store = Store::open_in_memory().unwrap();
683 store.put_image(&image("a", 1, 40), 100).unwrap();
684 store.put_image(&image("b", 2, 40), 100).unwrap();
685 assert_eq!(store.image("a").unwrap().unwrap().bytes.len(), 40);
686 store.put_image(&image("c", 3, 40), 100).unwrap();
687 assert!(store.image("a").unwrap().is_none());
688 assert!(store.has_image("b").unwrap());
689 assert!(store.has_image("c").unwrap());
690 assert_eq!(store.image_cache_bytes().unwrap(), 80);
691 store.put_image(&image("big", 0, 500), 100).unwrap();
692 assert!(store.has_image("big").unwrap());
693 assert_eq!(store.image_cache_bytes().unwrap(), 500);
694}
695
696#[test]
697fn first_message_after_from_others_skips_own_and_deleted() {
698 let store = Store::open_in_memory().unwrap();
699 let mut own = message("c1", "own", 2);
700 own.sender_id = Some("me".to_owned());
701 let mut gone = message("c1", "gone", 3);
702 gone.deleted = true;
703 store
704 .upsert_messages(&[message("c1", "old", 1), own, gone, message("c1", "new", 4)])
705 .unwrap();
706 assert_eq!(
707 store
708 .first_message_after_from_others("c1", Some(at(1)), "me")
709 .unwrap()
710 .as_deref(),
711 Some("new")
712 );
713 assert_eq!(
714 store
715 .first_message_after_from_others("c1", None, "me")
716 .unwrap()
717 .as_deref(),
718 Some("old")
719 );
720 assert!(
721 store
722 .first_message_after_from_others("c1", Some(at(4)), "me")
723 .unwrap()
724 .is_none()
725 );
726}
727
728#[test]
729fn a_team_is_found_by_id() {
730 let store = Store::open_in_memory().unwrap();
731 store
732 .upsert_teams(&[TeamRecord {
733 id: "t1".to_owned(),
734 name: "Alpha".to_owned(),
735 }])
736 .unwrap();
737 assert_eq!(store.team("t1").unwrap().unwrap().name, "Alpha");
738 assert!(store.team("nope").unwrap().is_none());
739}