BlueGit

ict rusty-teams

Files

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

store.rs

store.rs 66.5 KiB Download Raw
1use chrono::{DateTime, TimeZone, Utc};
2use rusqlite::Connection;
3use store::{
4 AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
5 ChannelNotifications, ChannelReadState, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,
6 MemberRecord, MessageImportance, MessageRecord, ReadHorizonRecord, RecentScope, Store,
7 SyncState, TeamLayoutRecord, TeamRecord, TeamRights, UNKNOWN_USER_NAME,
8};
9
10#[test]
11fn a_system_event_keeps_the_previous_unread_state() {
12 let store = Store::open_in_memory().unwrap();
13 for (previous, expected) in [(true, true), (false, false)] {
14 let id = format!("chat-{previous}");
15 let mut seeded = chat(&id, "Planning", Some(at(5)));
16 seeded.unread = previous;
17 store.upsert_chats(&[seeded]).unwrap();
18
19 let mut event = chat(&id, "Planning", Some(at(12)));
20 event.unread = false;
21 event.last_event_system = true;
22 store.upsert_chats(&[event]).unwrap();
23 assert_eq!(store.chat(&id).unwrap().unwrap().unread, expected);
24 }
25}
26
27#[test]
28fn a_call_event_keeps_the_previous_preview() {
29 let store = Store::open_in_memory().unwrap();
30 let mut seeded = chat("chat-call", "Planning", Some(at(5)));
31 seeded.last_message_preview = Some("See you there".to_owned());
32 seeded.last_message_sender_id = Some("user-ada".to_owned());
33 seeded.last_message_sender_name = Some("Ada Example".to_owned());
34 store.upsert_chats(&[seeded]).unwrap();
35
36 let mut call = chat("chat-call", "Planning", Some(at(12)));
37 call.last_event_system = true;
38 call.keeps_stored_preview = true;
39 store.upsert_chats(&[call]).unwrap();
40 let stored = store.chat("chat-call").unwrap().unwrap();
41 assert_eq!(
42 stored.last_message_preview.as_deref(),
43 Some("See you there")
44 );
45 assert_eq!(
46 stored.last_message_sender_name.as_deref(),
47 Some("Ada Example")
48 );
49 assert_eq!(stored.last_message_at, Some(at(12)));
50
51 let mut recording = chat("chat-call", "Planning", Some(at(14)));
52 recording.last_event_system = true;
53 recording.last_message_preview = Some("Recording is ready".to_owned());
54 store.upsert_chats(&[recording]).unwrap();
55 let stored = store.chat("chat-call").unwrap().unwrap();
56 assert_eq!(
57 stored.last_message_preview.as_deref(),
58 Some("Recording is ready")
59 );
60 assert_eq!(stored.last_message_sender_name, None);
61}
62
63fn at(minute: u32) -> DateTime<Utc> {
64 Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap()
65}
66
67fn chat(id: &str, title: &str, last: Option<DateTime<Utc>>) -> ChatRecord {
68 ChatRecord {
69 id: id.to_owned(),
70 kind: "group".to_owned(),
71 title: title.to_owned(),
72 member_summary: "Ada Example, Bob Sample".to_owned(),
73 last_message_at: last,
74 last_read_at: Some(at(0)),
75 unread: true,
76 members: vec![
77 MemberRecord {
78 user_id: Some("user-ada".to_owned()),
79 display_name: "Ada Example".to_owned(),
80 },
81 MemberRecord {
82 user_id: None,
83 display_name: "Bob Sample".to_owned(),
84 },
85 ],
86 ..ChatRecord::default()
87 }
88}
89
90fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecord {
91 MessageRecord {
92 conversation_id: conversation_id.to_owned(),
93 message_id: message_id.to_owned(),
94 reply_to_id: None,
95 sender_id: Some("user-ada".to_owned()),
96 sender_name: Some("Ada Example".to_owned()),
97 created_at: at(minute),
98 edited_at: None,
99 deleted: false,
100 body_html: format!("<p>message {message_id}</p>"),
101 attachments_json: "[]".to_owned(),
102 reactions_json: "[]".to_owned(),
103 mentions_json: "[]".to_owned(),
104 sender_application_id: None,
105 links_json: "[]".to_owned(),
106 subject: None,
107 call_event_json: None,
108 importance: MessageImportance::Normal,
109 }
110}
111
112#[test]
113fn importance_round_trips_and_survives_an_upsert_without_one() {
114 let store = Store::open_in_memory().unwrap();
115 let urgent = MessageRecord {
116 importance: MessageImportance::Urgent,
117 ..message("c1", "m1", 1)
118 };
119 store
120 .upsert_messages(std::slice::from_ref(&urgent))
121 .unwrap();
122 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
123 assert_eq!(found["m1"].importance, MessageImportance::Urgent);
124
125 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
126 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
127 assert_eq!(found["m1"].importance, MessageImportance::Urgent);
128}
129
130#[test]
131fn unread_marker_follows_the_last_message_from_others() {
132 let store = Store::open_in_memory().unwrap();
133 let important = MessageRecord {
134 importance: MessageImportance::High,
135 ..message("c1", "m2", 2)
136 };
137 store
138 .upsert_messages(&[message("c1", "m1", 1), important])
139 .unwrap();
140 let marker = |after: Option<u32>, me: &str| {
141 store
142 .unread_last_message_importance("c1", after.map(at), me)
143 .unwrap()
144 };
145 assert_eq!(marker(None, "me"), MessageImportance::High);
146 assert_eq!(marker(Some(1), "me"), MessageImportance::High);
147 assert_eq!(marker(Some(2), "me"), MessageImportance::Normal);
148 assert_eq!(marker(None, "user-ada"), MessageImportance::Normal);
149
150 store.upsert_messages(&[message("c1", "m3", 3)]).unwrap();
151 assert_eq!(marker(None, "me"), MessageImportance::Normal);
152}
153
154#[test]
155fn subject_round_trips_and_survives_an_upsert_without_one() {
156 let store = Store::open_in_memory().unwrap();
157 let post = MessageRecord {
158 subject: Some("Release plan".to_owned()),
159 ..message("c1", "m1", 1)
160 };
161 store.upsert_messages(std::slice::from_ref(&post)).unwrap();
162 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
163 assert_eq!(found["m1"], post);
164
165 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
166 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
167 assert_eq!(found["m1"].subject.as_deref(), Some("Release plan"));
168}
169
170#[test]
171fn thread_messages_return_root_and_replies_oldest_first_beyond_any_page() {
172 let store = Store::open_in_memory().unwrap();
173 let reply = |id: &str, minute: u32, root: &str| MessageRecord {
174 reply_to_id: Some(root.to_owned()),
175 ..message("c1", id, minute)
176 };
177 store
178 .upsert_messages(&[
179 reply("r2", 30, "root"),
180 message("c1", "root", 1),
181 message("c1", "other", 2),
182 reply("r1", 10, "root"),
183 reply("o1", 11, "other"),
184 ])
185 .unwrap();
186 let thread = store.thread_messages("c1", "root").unwrap();
187 assert_eq!(ids(&thread), ["root", "r1", "r2"]);
188}
189
190#[test]
191fn sender_application_round_trips() {
192 let store = Store::open_in_memory().unwrap();
193 let bot_message = MessageRecord {
194 sender_application_id: Some("bot-guid".to_owned()),
195 ..message("c1", "m1", 1)
196 };
197 store
198 .upsert_messages(std::slice::from_ref(&bot_message))
199 .unwrap();
200 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
201 assert_eq!(found["m1"], bot_message);
202}
203
204#[test]
205fn an_upsert_without_links_keeps_the_stored_links() {
206 let store = Store::open_in_memory().unwrap();
207 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
208 let links = r#"[{"url":"https://a.example"}]"#;
209 assert!(store.set_message_links("c1", "m1", links).unwrap());
210 assert!(!store.set_message_links("c1", "m1", links).unwrap());
211
212 let edited = MessageRecord {
213 body_html: "<p>edited</p>".to_owned(),
214 ..message("c1", "m1", 1)
215 };
216 store.upsert_messages(&[edited]).unwrap();
217 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
218 assert_eq!(found["m1"].links_json, links);
219 assert_eq!(found["m1"].body_html, "<p>edited</p>");
220
221 let replaced = MessageRecord {
222 links_json: r#"[{"url":"https://b.example"}]"#.to_owned(),
223 ..message("c1", "m1", 1)
224 };
225 store
226 .upsert_messages(std::slice::from_ref(&replaced))
227 .unwrap();
228 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
229 assert_eq!(found["m1"].links_json, replaced.links_json);
230}
231
232#[test]
233fn new_messages_start_without_links() {
234 let store = Store::open_in_memory().unwrap();
235 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
236 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
237 assert_eq!(found["m1"].links_json, "[]");
238}
239
240fn ids(messages: &[MessageRecord]) -> Vec<&str> {
241 messages
242 .iter()
243 .map(|message| message.message_id.as_str())
244 .collect()
245}
246
247#[test]
248fn chats_round_trip_with_members() {
249 let store = Store::open_in_memory().unwrap();
250 let original = chat("chat-1", "Planning", Some(at(5)));
251 store.upsert_chats(std::slice::from_ref(&original)).unwrap();
252 assert_eq!(store.chat("chat-1").unwrap(), Some(original));
253 assert_eq!(store.chat("missing").unwrap(), None);
254}
255
256#[test]
257fn chat_upsert_replaces_fields_and_members() {
258 let store = Store::open_in_memory().unwrap();
259 store
260 .upsert_chats(&[chat("chat-1", "Old", Some(at(1)))])
261 .unwrap();
262 let mut changed = chat("chat-1", "New", Some(at(9)));
263 changed.members.truncate(1);
264 changed.unread = false;
265 store.upsert_chats(&[changed.clone()]).unwrap();
266 assert_eq!(store.recent_chats(10).unwrap(), vec![changed]);
267}
268
269#[test]
270fn chat_upsert_keeps_a_real_title_over_the_only_you_fallback() {
271 let store = Store::open_in_memory().unwrap();
272 store
273 .upsert_chats(&[chat("chat-1", "Sample Bot", Some(at(1)))])
274 .unwrap();
275 store
276 .upsert_chats(&[chat("chat-1", "(only you)", Some(at(2)))])
277 .unwrap();
278 assert_eq!(store.chat("chat-1").unwrap().unwrap().title, "Sample Bot");
279 store
280 .upsert_chats(&[chat("chat-2", "(only you)", Some(at(2)))])
281 .unwrap();
282 store
283 .upsert_chats(&[chat("chat-2", "Sample Bot", Some(at(3)))])
284 .unwrap();
285 assert_eq!(store.chat("chat-2").unwrap().unwrap().title, "Sample Bot");
286 store
287 .upsert_chats(&[chat("chat-3", "?", Some(at(1)))])
288 .unwrap();
289 store
290 .upsert_chats(&[chat("chat-3", UNKNOWN_USER_NAME, Some(at(2)))])
291 .unwrap();
292 assert_eq!(store.chat("chat-3").unwrap().unwrap().title, UNKNOWN_USER_NAME);
293}
294
295#[test]
296fn recent_chats_are_newest_first_with_unknown_last() {
297 let store = Store::open_in_memory().unwrap();
298 store
299 .upsert_chats(&[
300 chat("old", "Old", Some(at(1))),
301 chat("none", "None", None),
302 chat("new", "New", Some(at(30))),
303 chat("mid", "Mid", Some(at(10))),
304 ])
305 .unwrap();
306 let recent = store.recent_chats(3).unwrap();
307 let order: Vec<&str> = recent.iter().map(|chat| chat.id.as_str()).collect();
308 assert_eq!(order, ["new", "mid", "old"]);
309 assert_eq!(store.recent_chats(10).unwrap().last().unwrap().id, "none");
310}
311
312#[test]
313fn messages_page_backwards_oldest_first() {
314 let store = Store::open_in_memory().unwrap();
315 let all: Vec<MessageRecord> = (1..=10)
316 .map(|minute| message("chat-1", &format!("m{minute:02}"), minute))
317 .collect();
318 store.upsert_messages(&all).unwrap();
319 store
320 .upsert_messages(&[message("chat-2", "other", 5)])
321 .unwrap();
322
323 let newest = store.messages("chat-1", None, 4).unwrap();
324 assert_eq!(ids(&newest), ["m07", "m08", "m09", "m10"]);
325
326 let older = store
327 .messages("chat-1", Some(newest[0].created_at), 4)
328 .unwrap();
329 assert_eq!(ids(&older), ["m03", "m04", "m05", "m06"]);
330
331 let oldest = store
332 .messages("chat-1", Some(older[0].created_at), 4)
333 .unwrap();
334 assert_eq!(ids(&oldest), ["m01", "m02"]);
335 assert!(
336 store
337 .messages("chat-1", Some(oldest[0].created_at), 4)
338 .unwrap()
339 .is_empty()
340 );
341 assert_eq!(store.message_count("chat-1").unwrap(), 10);
342}
343
344#[test]
345fn equal_timestamps_keep_a_stable_order() {
346 let store = Store::open_in_memory().unwrap();
347 store
348 .upsert_messages(&[
349 message("c", "b", 1),
350 message("c", "a", 1),
351 message("c", "c", 1),
352 ])
353 .unwrap();
354 assert_eq!(
355 ids(&store.messages("c", None, 10).unwrap()),
356 ["a", "b", "c"]
357 );
358}
359
360#[test]
361fn message_upsert_updates_in_place() {
362 let store = Store::open_in_memory().unwrap();
363 let mut edited = message("c", "m1", 1);
364 store
365 .upsert_messages(std::slice::from_ref(&edited))
366 .unwrap();
367 edited.body_html = "<p>edited</p>".to_owned();
368 edited.edited_at = Some(at(2));
369 edited.reactions_json = r#"[{"type":"like"}]"#.to_owned();
370 store
371 .upsert_messages(std::slice::from_ref(&edited))
372 .unwrap();
373
374 let stored = store.messages("c", None, 10).unwrap();
375 assert_eq!(stored, vec![edited.clone()]);
376 let by_id = store
377 .messages_by_id("c", &["m1".to_owned(), "nope".to_owned()])
378 .unwrap();
379 assert_eq!(by_id.len(), 1);
380 assert_eq!(by_id["m1"], edited);
381}
382
383#[test]
384fn deleted_flag_and_json_columns_round_trip() {
385 let store = Store::open_in_memory().unwrap();
386 let mut record = message("c", "m1", 1);
387 record.deleted = true;
388 record.reply_to_id = Some("m0".to_owned());
389 record.attachments_json = r#"[{"name":"a.pdf"}]"#.to_owned();
390 record.mentions_json = r#"[{"id":"u1","name":"Ada Example"}]"#.to_owned();
391 store
392 .upsert_messages(std::slice::from_ref(&record))
393 .unwrap();
394 assert_eq!(store.messages("c", None, 1).unwrap(), vec![record]);
395}
396
397#[test]
398fn thread_has_sender_checks_root_and_replies() {
399 let store = Store::open_in_memory().unwrap();
400 let mut reply = message("c", "r1", 2);
401 reply.reply_to_id = Some("root".to_owned());
402 reply.sender_id = Some("user-bob".to_owned());
403 let mut other_reply = message("c", "r2", 3);
404 other_reply.reply_to_id = Some("other".to_owned());
405 other_reply.sender_id = Some("user-carl".to_owned());
406 store
407 .upsert_messages(&[message("c", "root", 1), reply, other_reply])
408 .unwrap();
409 assert!(store.thread_has_sender("c", "root", "user-ada").unwrap());
410 assert!(store.thread_has_sender("c", "root", "user-bob").unwrap());
411 assert!(!store.thread_has_sender("c", "root", "user-carl").unwrap());
412 assert!(!store.thread_has_sender("d", "root", "user-ada").unwrap());
413}
414
415#[test]
416fn sync_state_round_trip() {
417 let store = Store::open_in_memory().unwrap();
418 assert_eq!(store.sync_state("c").unwrap(), None);
419 let state = SyncState {
420 newest_seen: Some(at(9)),
421 oldest_loaded: Some(at(1)),
422 has_more: false,
423 older_cursor: Some("https://graph.microsoft.com/v1.0/next".to_owned()),
424 delta_link: Some("https://graph.microsoft.com/v1.0/delta".to_owned()),
425 };
426 store.set_sync_state("c", &state).unwrap();
427 assert_eq!(store.sync_state("c").unwrap(), Some(state));
428 let reset = SyncState {
429 has_more: true,
430 ..SyncState::default()
431 };
432 store.set_sync_state("c", &reset).unwrap();
433 assert_eq!(store.sync_state("c").unwrap(), Some(reset));
434}
435
436#[test]
437fn sidebar_groups_channels_under_teams() {
438 let store = Store::open_in_memory().unwrap();
439 store
440 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
441 .unwrap();
442 store
443 .upsert_teams(&[
444 TeamRecord {
445 id: "t2".to_owned(),
446 name: "beta".to_owned(),
447 },
448 TeamRecord {
449 id: "t1".to_owned(),
450 name: "Alpha".to_owned(),
451 },
452 ])
453 .unwrap();
454 let channel = |id: &str, team_id: &str, name: &str| ChannelRecord {
455 id: id.to_owned(),
456 team_id: team_id.to_owned(),
457 name: name.to_owned(),
458 membership_type: Some("standard".to_owned()),
459 last_message_at: None,
460 unread: false,
461 };
462 store
463 .upsert_channels(&[
464 channel("c2", "t1", "Random"),
465 channel("c1", "t1", "General"),
466 channel("c3", "t2", "General"),
467 ])
468 .unwrap();
469
470 let sidebar = store.sidebar().unwrap();
471 assert_eq!(sidebar.chats.len(), 1);
472 let team_names: Vec<&str> = sidebar
473 .teams
474 .iter()
475 .map(|entry| entry.team.name.as_str())
476 .collect();
477 assert_eq!(team_names, ["Alpha", "beta"]);
478 let alpha_channels: Vec<&str> = sidebar.teams[0]
479 .channels
480 .iter()
481 .map(|entry| entry.name.as_str())
482 .collect();
483 assert_eq!(alpha_channels, ["General", "Random"]);
484 assert_eq!(store.channel("c3").unwrap().unwrap().team_id, "t2");
485}
486
487#[test]
488fn channel_upsert_keeps_known_last_message_time() {
489 let store = Store::open_in_memory().unwrap();
490 store
491 .upsert_teams(&[TeamRecord {
492 id: "t1".to_owned(),
493 name: "A".to_owned(),
494 }])
495 .unwrap();
496 let mut channel = ChannelRecord {
497 id: "c1".to_owned(),
498 team_id: "t1".to_owned(),
499 name: "General".to_owned(),
500 membership_type: None,
501 last_message_at: Some(at(7)),
502 unread: false,
503 };
504 store
505 .upsert_channels(std::slice::from_ref(&channel))
506 .unwrap();
507 channel.last_message_at = None;
508 store
509 .upsert_channels(std::slice::from_ref(&channel))
510 .unwrap();
511 assert_eq!(
512 store.channel("c1").unwrap().unwrap().last_message_at,
513 Some(at(7))
514 );
515}
516
517#[test]
518fn channel_read_state_survives_a_metadata_refresh() {
519 let store = Store::open_in_memory().unwrap();
520 store
521 .upsert_teams(&[TeamRecord {
522 id: "t1".to_owned(),
523 name: "A".to_owned(),
524 }])
525 .unwrap();
526 let channel = ChannelRecord {
527 id: "c1".to_owned(),
528 team_id: "t1".to_owned(),
529 name: "General".to_owned(),
530 membership_type: None,
531 last_message_at: None,
532 unread: false,
533 };
534 store
535 .upsert_channels(std::slice::from_ref(&channel))
536 .unwrap();
537 store
538 .apply_channel_read_states(&[
539 ChannelReadState {
540 channel_id: "c1".to_owned(),
541 unread: true,
542 last_message_at: Some(at(9)),
543 read_until: Some(at(7)),
544 },
545 ChannelReadState {
546 channel_id: "unknown".to_owned(),
547 unread: true,
548 last_message_at: None,
549 read_until: None,
550 },
551 ])
552 .unwrap();
553 store
554 .upsert_channels(std::slice::from_ref(&channel))
555 .unwrap();
556 let stored = store.channel("c1").unwrap().unwrap();
557 assert!(stored.unread);
558 assert_eq!(stored.last_message_at, Some(at(9)));
559 assert_eq!(store.channel_read_until("c1").unwrap(), Some(at(7)));
560 assert_eq!(store.channel_read_until("unknown").unwrap(), None);
561 assert!(store.channel("unknown").unwrap().is_none());
562
563 store.mark_channel_read("c1").unwrap();
564 assert!(!store.channel("c1").unwrap().unwrap().unread);
565}
566
567#[test]
568fn pruning_removes_departed_teams_and_channels() {
569 let store = Store::open_in_memory().unwrap();
570 store
571 .upsert_teams(&[
572 TeamRecord {
573 id: "t1".to_owned(),
574 name: "A".to_owned(),
575 },
576 TeamRecord {
577 id: "t2".to_owned(),
578 name: "B".to_owned(),
579 },
580 ])
581 .unwrap();
582 let channel = |id: &str| ChannelRecord {
583 id: id.to_owned(),
584 team_id: "t1".to_owned(),
585 name: id.to_owned(),
586 membership_type: None,
587 last_message_at: None,
588 unread: false,
589 };
590 store
591 .upsert_channels(&[channel("c1"), channel("c2")])
592 .unwrap();
593 assert_eq!(
594 store
595 .remove_channels_except("t1", &["c1".to_owned()])
596 .unwrap(),
597 1
598 );
599 assert_eq!(store.remove_teams_except(&["t1".to_owned()]).unwrap(), 1);
600 let sidebar = store.sidebar().unwrap();
601 assert_eq!(sidebar.teams.len(), 1);
602 assert_eq!(sidebar.teams[0].channels.len(), 1);
603}
604
605#[test]
606fn file_database_uses_wal_persists_and_migrates_once() {
607 let directory = tempfile::tempdir().unwrap();
608 let path = directory.path().join("nested").join("cache.sqlite3");
609 {
610 let store = Store::open(&path).unwrap();
611 assert_eq!(store.schema_version().unwrap(), store::latest_version());
612 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
613 }
614 let reopened = Store::open(&path).unwrap();
615 assert_eq!(reopened.schema_version().unwrap(), store::latest_version());
616 assert_eq!(reopened.message_count("c").unwrap(), 1);
617 drop(reopened);
618 let mode: String = rusqlite_open(&path)
619 .pragma_query_value(None, "journal_mode", |row| row.get(0))
620 .unwrap();
621 assert_eq!(mode, "wal");
622}
623
624#[test]
625fn newer_schema_is_refused() {
626 let directory = tempfile::tempdir().unwrap();
627 let path = directory.path().join("cache.sqlite3");
628 drop(Store::open(&path).unwrap());
629 let connection = rusqlite_open(&path);
630 connection
631 .execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; PRAGMA user_version = 99")
632 .unwrap();
633 drop(connection);
634 let error = Store::open(&path).err().expect("must refuse");
635 assert!(error.to_string().contains("99"), "{error}");
636}
637
638#[test]
639fn old_schema_is_upgraded_in_place() {
640 let directory = tempfile::tempdir().unwrap();
641 let path = directory.path().join("cache.sqlite3");
642 drop(Store::open(&path).unwrap());
643 let connection = rusqlite_open(&path);
644 connection.execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; 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; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
645 drop(connection);
646 let store = Store::open(&path).unwrap();
647 assert_eq!(store.schema_version().unwrap(), store::latest_version());
648 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
649}
650
651fn rusqlite_open(path: &std::path::Path) -> Connection {
652 Connection::open(path).unwrap()
653}
654
655#[test]
656fn meta_values_and_times_round_trip() {
657 let store = Store::open_in_memory().unwrap();
658 assert_eq!(store.meta("k").unwrap(), None);
659 store.set_meta("k", "one").unwrap();
660 store.set_meta("k", "two").unwrap();
661 assert_eq!(store.meta("k").unwrap().as_deref(), Some("two"));
662 assert_eq!(store.meta_time("t").unwrap(), None);
663 store.set_meta_time("t", at(7)).unwrap();
664 assert_eq!(store.meta_time("t").unwrap(), Some(at(7)));
665 store.set_meta("bad", "not a number").unwrap();
666 assert_eq!(store.meta_time("bad").unwrap(), None);
667}
668
669#[test]
670fn chats_can_be_pruned_and_marked_read() {
671 let store = Store::open_in_memory().unwrap();
672 store
673 .upsert_chats(&[
674 chat("a", "A", Some(at(1))),
675 chat("b", "B", Some(at(2))),
676 chat("c", "C", None),
677 ])
678 .unwrap();
679 let times = store
680 .chat_last_message_times(&["a".to_owned(), "c".to_owned(), "zzz".to_owned()])
681 .unwrap();
682 assert_eq!(times.len(), 2);
683 assert_eq!(times["a"], Some(at(1)));
684 assert_eq!(times["c"], None);
685
686 assert_eq!(store.remove_chats(&["a".to_owned()]).unwrap(), 1);
687 assert_eq!(store.remove_chats_except(&["b".to_owned()]).unwrap(), 1);
688 assert_eq!(store.chat_count().unwrap(), 1);
689
690 store.mark_chat_read("b", at(30)).unwrap();
691 let read = store.chat("b").unwrap().unwrap();
692 assert!(!read.unread);
693 assert_eq!(read.last_read_at, Some(at(30)));
694}
695
696#[test]
697fn migration_to_v2_keeps_existing_sync_state() {
698 let directory = tempfile::tempdir().unwrap();
699 let path = directory.path().join("old.sqlite3");
700 {
701 let connection = Connection::open(&path).unwrap();
702 connection
703 .execute_batch(include_str!("../src/migrations/0001_initial.sql"))
704 .unwrap();
705 connection.pragma_update(None, "user_version", 1).unwrap();
706 connection
707 .execute("INSERT INTO sync_state (conversation_id, newest_seen, has_more) VALUES ('c', 5, 1)", [])
708 .unwrap();
709 }
710 let store = Store::open(&path).unwrap();
711 let state = store.sync_state("c").unwrap().unwrap();
712 assert_eq!(state.delta_link, None);
713 assert_eq!(store.schema_version().unwrap(), store::latest_version());
714}
715
716#[test]
717fn migration_to_v13_clears_channel_delta_links_only() {
718 let directory = tempfile::tempdir().unwrap();
719 let path = directory.path().join("old.sqlite3");
720 {
721 let store = Store::open(&path).unwrap();
722 drop(store);
723 let connection = Connection::open(&path).unwrap();
724 connection
725 .execute_batch(
726 "ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; INSERT INTO teams (id, name) VALUES ('t', 'T');
727 INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');
728 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
729 ALTER TABLE messages DROP COLUMN subject;
730 ALTER TABLE messages DROP COLUMN call_event_json;
731 ALTER TABLE messages DROP COLUMN importance;
732 ALTER TABLE folders DROP COLUMN expanded;
733 DROP TABLE channel_tabs;
734 DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;
735 ALTER TABLE channel_layout DROP COLUMN notification_level;
736 ALTER TABLE channel_layout DROP COLUMN include_replies;
737 ALTER TABLE channels DROP COLUMN read_until;
738 ALTER TABLE chats DROP COLUMN preview_at; PRAGMA user_version = 12",
739 )
740 .unwrap();
741 }
742 let store = Store::open(&path).unwrap();
743 assert_eq!(
744 store
745 .sync_state("ch")
746 .unwrap()
747 .and_then(|state| state.delta_link),
748 None
749 );
750 assert_eq!(
751 store
752 .sync_state("chat")
753 .unwrap()
754 .unwrap()
755 .delta_link
756 .as_deref(),
757 Some("link")
758 );
759}
760
761#[test]
762fn preview_updates_only_for_newer_messages() {
763 let store = Store::open_in_memory().unwrap();
764 store.upsert_chats(&[chat("a", "A", Some(at(5)))]).unwrap();
765 let preview = |text| ChatPreview {
766 text: Some(text),
767 sender_id: Some("user-ada"),
768 sender_name: Some("Ada Example"),
769 deleted: false,
770 };
771 assert!(
772 !store
773 .update_chat_preview("a", at(4), &preview("older"))
774 .unwrap()
775 );
776 assert!(
777 store
778 .update_chat_preview("a", at(6), &preview("newer"))
779 .unwrap()
780 );
781 let record = store.chat("a").unwrap().unwrap();
782 assert_eq!(record.last_message_preview.as_deref(), Some("newer"));
783 assert_eq!(
784 record.last_message_sender_name.as_deref(),
785 Some("Ada Example")
786 );
787 assert_eq!(record.last_message_at, Some(at(6)));
788 assert!(!record.last_message_deleted);
789}
790
791#[test]
792fn a_call_moves_the_chat_time_and_keeps_the_line() {
793 let store = Store::open_in_memory().unwrap();
794 store.upsert_chats(&[chat("a", "A", Some(at(5)))]).unwrap();
795 let before = store.chat("a").unwrap().unwrap().last_message_preview;
796 assert!(!store.touch_chat_time("a", at(4)).unwrap());
797 assert!(store.touch_chat_time("a", at(7)).unwrap());
798 let record = store.chat("a").unwrap().unwrap();
799 assert_eq!(record.last_message_at, Some(at(7)));
800 assert_eq!(record.last_message_preview, before);
801}
802
803#[test]
804fn the_kept_line_keeps_its_own_time_after_a_call() {
805 let store = Store::open_in_memory().unwrap();
806 let mut line = chat("a", "A", Some(at(5)));
807 line.preview_at = Some(at(5));
808 store.upsert_chats(&[line]).unwrap();
809 store.touch_chat_time("a", at(7)).unwrap();
810 let mut call_sync = chat("a", "A", Some(at(9)));
811 call_sync.keeps_stored_preview = true;
812 store.upsert_chats(&[call_sync]).unwrap();
813 let record = store.chat("a").unwrap().unwrap();
814 assert_eq!(record.last_message_at, Some(at(9)));
815 assert_eq!(record.preview_at, Some(at(5)));
816}
817
818#[test]
819fn avatars_round_trip_and_report_stale_ids() {
820 let store = Store::open_in_memory().unwrap();
821 store
822 .upsert_avatar(&AvatarRecord {
823 user_id: "fresh".into(),
824 bytes: Some(vec![1, 2, 3]),
825 content_type: "image/jpeg".into(),
826 fetched_at: at(50),
827 })
828 .unwrap();
829 store
830 .upsert_avatar(&AvatarRecord {
831 user_id: "missing".into(),
832 bytes: None,
833 content_type: String::new(),
834 fetched_at: at(1),
835 })
836 .unwrap();
837 assert_eq!(
838 store.avatar("fresh").unwrap().unwrap().bytes,
839 Some(vec![1, 2, 3])
840 );
841 assert_eq!(store.avatar("missing").unwrap().unwrap().bytes, None);
842 assert!(store.avatar("unknown").unwrap().is_none());
843 let ids: Vec<String> = ["fresh", "missing", "unknown"].map(String::from).to_vec();
844 assert_eq!(
845 store.avatar_ids_needing_fetch(&ids, at(10)).unwrap(),
846 ["missing", "unknown"]
847 );
848}
849
850#[test]
851fn folders_and_pinned_channels_are_replaced_in_order() {
852 let store = Store::open_in_memory().unwrap();
853 let folder = |id: &str, kind: &str, items: &[&str]| FolderRecord {
854 id: id.into(),
855 name: id.into(),
856 kind: kind.into(),
857 expanded: kind != "MutedChats",
858 conversation_ids: items.iter().map(|item| item.to_string()).collect(),
859 };
860 let first = [
861 folder("f1", "Favorites", &["b", "a"]),
862 folder("f2", "UserCreated", &[]),
863 folder("f4", "MutedChats", &[]),
864 ];
865 store
866 .replace_folders(&first, &["c2".into(), "c1".into()])
867 .unwrap();
868 assert_eq!(store.folders().unwrap(), first);
869 assert_eq!(store.pinned_channel_ids().unwrap(), ["c2", "c1"]);
870 store.set_folder_expanded("f2", false).unwrap();
871 assert!(!store.folders().unwrap()[1].expanded);
872 store
873 .replace_folders(&[folder("f3", "UserCreated", &["z"])], &[])
874 .unwrap();
875 assert_eq!(store.folders().unwrap().len(), 1);
876 assert!(store.pinned_channel_ids().unwrap().is_empty());
877}
878
879#[test]
880fn counts_messages_after_a_time_from_others() {
881 let store = Store::open_in_memory().unwrap();
882 let mut mine = message("c", "m3", 3);
883 mine.sender_id = Some("me".into());
884 store
885 .upsert_messages(&[message("c", "m1", 1), message("c", "m2", 2), mine])
886 .unwrap();
887 assert_eq!(
888 store.count_messages_after("c", Some(at(1)), "me").unwrap(),
889 1
890 );
891 assert_eq!(store.count_messages_after("c", None, "me").unwrap(), 2);
892}
893
894#[test]
895fn messages_between_is_inclusive_and_oldest_first() {
896 let store = Store::open_in_memory().unwrap();
897 store
898 .upsert_messages(&[
899 message("c", "m4", 4),
900 message("c", "m1", 1),
901 message("c", "m3", 3),
902 message("c", "m2", 2),
903 message("other", "o3", 3),
904 ])
905 .unwrap();
906 let ids: Vec<String> = store
907 .messages_between("c", at(2), at(3))
908 .unwrap()
909 .into_iter()
910 .map(|record| record.message_id)
911 .collect();
912 assert_eq!(ids, ["m2", "m3"]);
913}
914
915fn html_message(
916 conversation_id: &str,
917 message_id: &str,
918 minute: u32,
919 sender: &str,
920 html: &str,
921) -> MessageRecord {
922 MessageRecord {
923 sender_name: Some(sender.to_owned()),
924 body_html: html.to_owned(),
925 ..message(conversation_id, message_id, minute)
926 }
927}
928
929#[test]
930fn fts5_is_available_and_matches_prefixes_with_highlights() {
931 let store = Store::open_in_memory().unwrap();
932 store
933 .upsert_messages(&[
934 html_message(
935 "c1",
936 "m1",
937 1,
938 "Ada Example",
939 "<p>The <b>budget</b> planning is done</p>",
940 ),
941 html_message("c1", "m2", 2, "Bob Sample", "<p>Lunch at noon</p>"),
942 html_message("c2", "m3", 3, "Bob Sample", "<p>Budget approved</p>"),
943 ])
944 .unwrap();
945 let hits = store.search_messages("budg plan", None, 10).unwrap();
946 assert_eq!(hits.len(), 1);
947 assert_eq!(hits[0].message_id, "m1");
948 assert_eq!(hits[0].sender_name.as_deref(), Some("Ada Example"));
949 assert_eq!(hits[0].created_at, at(1));
950 assert!(
951 hits[0].snippet.contains("\u{1}budget\u{2}"),
952 "{}",
953 hits[0].snippet
954 );
955 let all = store.search_messages("budget", None, 10).unwrap();
956 assert_eq!(ids_of(&all), ["m3", "m1"]);
957 let scoped = store.search_messages("budget", Some("c1"), 10).unwrap();
958 assert_eq!(ids_of(&scoped), ["m1"]);
959 assert_eq!(store.search_messages("budget", None, 1).unwrap().len(), 1);
960}
961
962fn ids_of(hits: &[store::SearchHit]) -> Vec<&str> {
963 hits.iter().map(|hit| hit.message_id.as_str()).collect()
964}
965
966#[test]
967fn search_filters_by_sender_and_ignores_unsearchable_input() {
968 let store = Store::open_in_memory().unwrap();
969 store
970 .upsert_messages(&[
971 html_message("c1", "m1", 1, "Ada Example", "<p>report</p>"),
972 html_message("c1", "m2", 2, "Bob Sample", "<p>report</p>"),
973 ])
974 .unwrap();
975 assert_eq!(
976 ids_of(&store.search_messages("from:bob report", None, 10).unwrap()),
977 ["m2"]
978 );
979 assert!(store.search_messages(" ", None, 10).unwrap().is_empty());
980 assert!(store.search_messages("\"-*", None, 10).unwrap().is_empty());
981 assert!(store.search_messages("rep) OR (", None, 10).is_ok());
982}
983
984#[test]
985fn search_follows_edits_and_deletes() {
986 let store = Store::open_in_memory().unwrap();
987 store
988 .upsert_messages(&[html_message("c1", "m1", 1, "Ada", "<p>alpha</p>")])
989 .unwrap();
990 store
991 .upsert_messages(&[html_message("c1", "m1", 1, "Ada", "<p>beta</p>")])
992 .unwrap();
993 assert!(store.search_messages("alpha", None, 10).unwrap().is_empty());
994 assert_eq!(store.search_messages("beta", None, 10).unwrap().len(), 1);
995 let mut deleted = html_message("c1", "m1", 1, "Ada", "");
996 deleted.deleted = true;
997 store.upsert_messages(&[deleted]).unwrap();
998 assert!(store.search_messages("beta", None, 10).unwrap().is_empty());
999}
1000
1001#[test]
1002fn title_search_follows_chat_renames() {
1003 let store = Store::open_in_memory().unwrap();
1004 store
1005 .upsert_chats(&[chat("c1", "Budget planning", None)])
1006 .unwrap();
1007 assert_eq!(
1008 store.search_conversations("budg", 10).unwrap()[0].conversation_id,
1009 "c1"
1010 );
1011 store.upsert_chats(&[chat("c1", "Holiday", None)]).unwrap();
1012 assert!(store.search_conversations("budget", 10).unwrap().is_empty());
1013 assert_eq!(store.search_conversations("holi", 10).unwrap().len(), 1);
1014 assert!(
1015 store
1016 .search_conversations("from:holi", 10)
1017 .unwrap()
1018 .is_empty()
1019 );
1020}
1021
1022#[test]
1023fn migration_indexes_rows_that_predate_search() {
1024 let directory = tempfile::tempdir().unwrap();
1025 let path = directory.path().join("cache.sqlite3");
1026 {
1027 let store = Store::open(&path).unwrap();
1028 store.upsert_chats(&[chat("c1", "Old chat", None)]).unwrap();
1029 store
1030 .upsert_messages(&[html_message("c1", "m1", 1, "Ada", "<p>legacy text</p>")])
1031 .unwrap();
1032 }
1033 {
1034 let connection = Connection::open(&path).unwrap();
1035 connection
1036 .execute_batch(
1037 "ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
1038 DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
1039 DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
1040 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;
1041 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
1042 ALTER TABLE messages DROP COLUMN sender_application_id;
1043 ALTER TABLE messages DROP COLUMN links_json;
1044 ALTER TABLE messages DROP COLUMN subject;
1045 ALTER TABLE messages DROP COLUMN call_event_json;
1046 ALTER TABLE messages DROP COLUMN importance;
1047 ALTER TABLE chats DROP COLUMN muted;
1048 ALTER TABLE folders DROP COLUMN expanded;
1049 ALTER TABLE channels DROP COLUMN read_until;
1050 ALTER TABLE chats DROP COLUMN preview_at; PRAGMA user_version = 3;",
1051 )
1052 .unwrap();
1053 }
1054 let store = Store::open(&path).unwrap();
1055 assert_eq!(store.search_messages("legacy", None, 10).unwrap().len(), 1);
1056 assert_eq!(store.search_conversations("old", 10).unwrap().len(), 1);
1057}
1058
1059fn image(key: &str, minute: u32, size: usize) -> store::ImageRecord {
1060 store::ImageRecord {
1061 key: key.to_owned(),
1062 bytes: vec![7; size],
1063 content_type: "image/png".to_owned(),
1064 fetched_at: at(minute),
1065 }
1066}
1067
1068#[test]
1069fn images_round_trip_and_evict_the_oldest_over_the_cap() {
1070 let store = Store::open_in_memory().unwrap();
1071 store.put_image(&image("a", 1, 40), 100).unwrap();
1072 store.put_image(&image("b", 2, 40), 100).unwrap();
1073 assert_eq!(store.image("a").unwrap().unwrap().bytes.len(), 40);
1074 store.put_image(&image("c", 3, 40), 100).unwrap();
1075 assert!(store.image("a").unwrap().is_none());
1076 assert!(store.has_image("b").unwrap());
1077 assert!(store.has_image("c").unwrap());
1078 assert_eq!(store.image_cache_bytes().unwrap(), 80);
1079 store.put_image(&image("big", 0, 500), 100).unwrap();
1080 assert!(store.has_image("big").unwrap());
1081 assert_eq!(store.image_cache_bytes().unwrap(), 500);
1082}
1083
1084#[test]
1085fn first_message_after_from_others_skips_own_and_deleted() {
1086 let store = Store::open_in_memory().unwrap();
1087 let mut own = message("c1", "own", 2);
1088 own.sender_id = Some("me".to_owned());
1089 let mut gone = message("c1", "gone", 3);
1090 gone.deleted = true;
1091 store
1092 .upsert_messages(&[message("c1", "old", 1), own, gone, message("c1", "new", 4)])
1093 .unwrap();
1094 assert_eq!(
1095 store
1096 .first_message_after_from_others("c1", Some(at(1)), "me")
1097 .unwrap()
1098 .as_deref(),
1099 Some("new")
1100 );
1101 assert_eq!(
1102 store
1103 .first_message_after_from_others("c1", None, "me")
1104 .unwrap()
1105 .as_deref(),
1106 Some("old")
1107 );
1108 assert!(
1109 store
1110 .first_message_after_from_others("c1", Some(at(4)), "me")
1111 .unwrap()
1112 .is_none()
1113 );
1114}
1115
1116#[test]
1117fn a_team_is_found_by_id() {
1118 let store = Store::open_in_memory().unwrap();
1119 store
1120 .upsert_teams(&[TeamRecord {
1121 id: "t1".to_owned(),
1122 name: "Alpha".to_owned(),
1123 }])
1124 .unwrap();
1125 assert_eq!(store.team("t1").unwrap().unwrap().name, "Alpha");
1126 assert!(store.team("nope").unwrap().is_none());
1127}
1128
1129#[test]
1130fn sync_does_not_resurrect_a_locally_read_chat() {
1131 let store = Store::open_in_memory().unwrap();
1132 store
1133 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
1134 .unwrap();
1135 store.mark_chat_read("chat-1", at(10)).unwrap();
1136
1137 store
1138 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
1139 .unwrap();
1140 let stale = store.chat("chat-1").unwrap().unwrap();
1141 assert!(!stale.unread);
1142 assert_eq!(stale.last_read_at, Some(at(10)));
1143
1144 store
1145 .upsert_chats(&[chat("chat-1", "Planning", Some(at(12)))])
1146 .unwrap();
1147 assert!(store.chat("chat-1").unwrap().unwrap().unread);
1148}
1149
1150#[test]
1151fn mark_chat_unread_sets_the_flag_and_horizon() {
1152 let store = Store::open_in_memory().unwrap();
1153 store
1154 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
1155 .unwrap();
1156 store.mark_chat_read("chat-1", at(10)).unwrap();
1157
1158 store.mark_chat_unread("chat-1", at(4)).unwrap();
1159 let unread = store.chat("chat-1").unwrap().unwrap();
1160 assert!(unread.unread);
1161 assert_eq!(unread.last_read_at, Some(at(4)));
1162}
1163
1164#[test]
1165fn muted_flag_survives_a_chat_refresh() {
1166 let store = Store::open_in_memory().unwrap();
1167 store
1168 .upsert_chats(&[chat("a", "A", Some(at(1))), chat("b", "B", Some(at(2)))])
1169 .unwrap();
1170 assert!(!store.chat("a").unwrap().unwrap().muted);
1171
1172 store.set_chat_muted("a", true).unwrap();
1173 store
1174 .upsert_chats(&[chat("a", "A", Some(at(3))), chat("b", "B", Some(at(2)))])
1175 .unwrap();
1176 assert!(store.chat("a").unwrap().unwrap().muted);
1177 assert!(!store.chat("b").unwrap().unwrap().muted);
1178
1179 store.set_chat_muted("a", false).unwrap();
1180 assert!(!store.chat("a").unwrap().unwrap().muted);
1181}
1182
1183#[test]
1184fn muted_states_touch_only_the_listed_chats() {
1185 let store = Store::open_in_memory().unwrap();
1186 store
1187 .upsert_chats(&[
1188 chat("a", "A", Some(at(1))),
1189 chat("b", "B", Some(at(2))),
1190 chat("c", "C", Some(at(3))),
1191 ])
1192 .unwrap();
1193 store.set_chat_muted("a", true).unwrap();
1194 store.set_chat_muted("c", true).unwrap();
1195
1196 store
1197 .apply_muted_states(&[
1198 ("a".to_owned(), false),
1199 ("b".to_owned(), true),
1200 ("gone".to_owned(), true),
1201 ])
1202 .unwrap();
1203 assert!(!store.chat("a").unwrap().unwrap().muted);
1204 assert!(store.chat("b").unwrap().unwrap().muted);
1205 assert!(store.chat("c").unwrap().unwrap().muted);
1206}
1207
1208#[test]
1209fn presence_upsert_keeps_the_latest_availability() {
1210 let store = Store::open_in_memory().unwrap();
1211 let first = [("ada".to_owned(), "Available".to_owned())];
1212 store.upsert_presences(&first, at(1)).unwrap();
1213 let second = [
1214 ("ada".to_owned(), "Away".to_owned()),
1215 ("bob".to_owned(), "Busy".to_owned()),
1216 ];
1217 store.upsert_presences(&second, at(2)).unwrap();
1218 let mut presences = store.presences().unwrap();
1219 presences.sort();
1220 assert_eq!(presences, second.to_vec());
1221}
1222
1223fn activity(id: i64, minute: u32) -> store::ActivityRecord {
1224 store::ActivityRecord {
1225 id,
1226 conversation_id: "c1".to_owned(),
1227 kind: "messages".to_owned(),
1228 message_id: format!("m{id}"),
1229 actors_json: r#"[{"user_id":"user-ada","name":"Ada Example"}]"#.to_owned(),
1230 preview: "hello".to_owned(),
1231 glyphs: String::new(),
1232 count: 1,
1233 updated_at: at(minute),
1234 read: false,
1235 }
1236}
1237
1238#[test]
1239fn activity_upsert_inserts_then_updates_in_place() {
1240 let store = Store::open_in_memory().unwrap();
1241 store
1242 .upsert_activity(&[activity(1, 5), activity(2, 9)])
1243 .unwrap();
1244 let mut changed = activity(1, 12);
1245 changed.count = 3;
1246 changed.read = true;
1247 store
1248 .upsert_activity(std::slice::from_ref(&changed))
1249 .unwrap();
1250 let records = store.activity().unwrap();
1251 assert_eq!(records.len(), 2);
1252 assert_eq!(records[0], changed);
1253 assert_eq!(records[1].id, 2);
1254}
1255
1256#[test]
1257fn activity_prune_drops_only_older_rows() {
1258 let store = Store::open_in_memory().unwrap();
1259 store
1260 .upsert_activity(&[activity(1, 5), activity(2, 9), activity(3, 20)])
1261 .unwrap();
1262 assert_eq!(store.prune_activity(at(9)).unwrap(), 1);
1263 let ids: Vec<i64> = store
1264 .activity()
1265 .unwrap()
1266 .iter()
1267 .map(|record| record.id)
1268 .collect();
1269 assert_eq!(ids, vec![3, 2]);
1270}
1271
1272#[test]
1273fn display_names_prefer_members_then_latest_sender_name() {
1274 let store = Store::open_in_memory().unwrap();
1275 let unnamed_member = ChatRecord {
1276 members: vec![MemberRecord {
1277 user_id: Some("user-sam".to_owned()),
1278 display_name: UNKNOWN_USER_NAME.to_owned(),
1279 }],
1280 ..chat("chat-2", "Review", Some(at(6)))
1281 };
1282 store
1283 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5))), unnamed_member])
1284 .unwrap();
1285 let sent_by = |message_id: &str, minute: u32, sender: &str, name: Option<&str>| MessageRecord {
1286 sender_id: Some(sender.to_owned()),
1287 sender_name: name.map(str::to_owned),
1288 ..message("channel", message_id, minute)
1289 };
1290 store
1291 .upsert_messages(&[
1292 sent_by("m1", 1, "user-ada", Some("Ada Sender")),
1293 sent_by("m2", 2, "user-sam", Some("Sam Old")),
1294 sent_by("m3", 3, "user-sam", Some("Sam New")),
1295 sent_by("m4", 4, "user-sam", None),
1296 sent_by("m5", 5, "user-blank", Some("")),
1297 ])
1298 .unwrap();
1299 let wanted: Vec<String> = ["user-ada", "user-sam", "user-blank", "user-none"]
1300 .map(str::to_owned)
1301 .to_vec();
1302 let names = store.display_names(&wanted).unwrap();
1303 assert_eq!(names.len(), 2);
1304 assert_eq!(names["user-ada"], "Ada Example");
1305 assert_eq!(names["user-sam"], "Sam New");
1306 assert!(store.display_names(&[]).unwrap().is_empty());
1307}
1308
1309#[test]
1310fn channel_tabs_keep_their_saved_order_and_are_replaced_on_refresh() {
1311 let store = Store::open_in_memory().unwrap();
1312 let tab = |tab_id: &str, open_url: Option<&str>| ChannelTabRecord {
1313 tab_id: tab_id.to_owned(),
1314 name: format!("Tab {tab_id}"),
1315 definition_id: "com.microsoft.teamspace.tab.web".to_owned(),
1316 open_url: open_url.map(str::to_owned),
1317 };
1318 let layout = |tabs: Vec<ChannelTabRecord>| {
1319 vec![TeamLayoutRecord {
1320 rights: Default::default(),
1321 team_id: "team".to_owned(),
1322 hidden: false,
1323 channels: vec![ChannelLayoutRecord {
1324 substrate_group_id: None,
1325 channel_id: "channel".to_owned(),
1326 general: false,
1327 hidden: false,
1328 tabs,
1329 notifications: ChannelNotifications::default(),
1330 }],
1331 }]
1332 };
1333 store
1334 .replace_team_layout(&layout(vec![
1335 tab("b", Some("https://b.example")),
1336 tab("a", None),
1337 ]))
1338 .unwrap();
1339 let tabs = store.channel_tabs("channel").unwrap();
1340 let ids: Vec<&str> = tabs.iter().map(|tab| tab.tab_id.as_str()).collect();
1341 assert_eq!(ids, ["b", "a"]);
1342 assert_eq!(tabs[0].open_url.as_deref(), Some("https://b.example"));
1343 assert!(store.channel_tabs("other").unwrap().is_empty());
1344 store.replace_team_layout(&layout(Vec::new())).unwrap();
1345 assert!(store.channel_tabs("channel").unwrap().is_empty());
1346}
1347
1348#[test]
1349fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {
1350 let store = Store::open_in_memory().unwrap();
1351 store
1352 .upsert_teams(&[TeamRecord {
1353 id: "t1".to_owned(),
1354 name: "Alpha".to_owned(),
1355 }])
1356 .unwrap();
1357 let channel = |id: &str, name: &str| ChannelRecord {
1358 id: id.to_owned(),
1359 team_id: "t1".to_owned(),
1360 name: name.to_owned(),
1361 membership_type: None,
1362 last_message_at: None,
1363 unread: false,
1364 };
1365 store
1366 .upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1367 .unwrap();
1368 let team = || store.sidebar().unwrap().teams.remove(0);
1369 assert_eq!(
1370 team().channel_notifications("c2"),
1371 ChannelNotifications::default()
1372 );
1373
1374 let banner = ChannelNotifications {
1375 level: ChannelNotificationLevel::BannerAndFeed,
1376 include_replies: true,
1377 };
1378 store.set_channel_notifications("c2", banner).unwrap();
1379 let sidebar_team = team();
1380 assert_eq!(sidebar_team.channel_notifications("c2"), banner);
1381 assert_eq!(sidebar_team.channels[0].name, "General");
1382
1383 let off = ChannelNotifications {
1384 level: ChannelNotificationLevel::Off,
1385 include_replies: false,
1386 };
1387 store
1388 .replace_team_layout(&[TeamLayoutRecord {
1389 rights: Default::default(),
1390 team_id: "t1".to_owned(),
1391 hidden: false,
1392 channels: vec![ChannelLayoutRecord {
1393 substrate_group_id: None,
1394 channel_id: "c2".to_owned(),
1395 general: false,
1396 hidden: false,
1397 tabs: Vec::new(),
1398 notifications: off,
1399 }],
1400 }])
1401 .unwrap();
1402 assert_eq!(team().channel_notifications("c2"), off);
1403}
1404
1405#[test]
1406fn channel_mentions_are_replaced_whole_and_cleared_per_channel() {
1407 let store = Store::open_in_memory().unwrap();
1408 store
1409 .upsert_teams(&[TeamRecord {
1410 id: "t1".to_owned(),
1411 name: "Alpha".to_owned(),
1412 }])
1413 .unwrap();
1414 let channel = |id: &str, name: &str| ChannelRecord {
1415 id: id.to_owned(),
1416 team_id: "t1".to_owned(),
1417 name: name.to_owned(),
1418 membership_type: None,
1419 last_message_at: None,
1420 unread: true,
1421 };
1422 store
1423 .upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1424 .unwrap();
1425 let counts = |personal, channel, team| ChannelMentions {
1426 personal,
1427 channel,
1428 team,
1429 };
1430 store
1431 .replace_channel_mentions(&[
1432 ("c1".to_owned(), counts(2, 0, 1)),
1433 ("c2".to_owned(), counts(0, 0, 0)),
1434 ])
1435 .unwrap();
1436 let team = || store.sidebar().unwrap().teams.remove(0);
1437 assert_eq!(team().channel_mentions("c1"), counts(2, 0, 1));
1438 assert!(!team().mentions.contains_key("c2"));
1439 store
1440 .replace_channel_mentions(&[("c2".to_owned(), counts(0, 1, 0))])
1441 .unwrap();
1442 assert_eq!(team().channel_mentions("c1"), ChannelMentions::default());
1443 assert_eq!(team().channel_mentions("c2"), counts(0, 1, 0));
1444 store.clear_channel_mentions("c2").unwrap();
1445 assert!(team().mentions.is_empty());
1446}
1447
1448#[test]
1449fn the_team_thread_id_is_the_general_channel_id() {
1450 let store = Store::open_in_memory().unwrap();
1451 store
1452 .upsert_teams(&["group-a", "group-b"].map(|id| TeamRecord {
1453 id: id.to_owned(),
1454 name: id.to_owned(),
1455 }))
1456 .unwrap();
1457 let channel = |id: &str, team_id: &str, name: &str| ChannelRecord {
1458 id: id.to_owned(),
1459 team_id: team_id.to_owned(),
1460 name: name.to_owned(),
1461 membership_type: None,
1462 last_message_at: None,
1463 unread: false,
1464 };
1465 store
1466 .upsert_channels(&[
1467 channel("19:a-random", "group-a", "Random"),
1468 channel("19:a-general", "group-a", "General"),
1469 channel("19:b-renamed", "group-b", "Allgemein"),
1470 channel("19:b-other", "group-b", "Other"),
1471 ])
1472 .unwrap();
1473 store
1474 .replace_team_layout(&[TeamLayoutRecord {
1475 rights: Default::default(),
1476 team_id: "group-b".to_owned(),
1477 hidden: false,
1478 channels: vec![ChannelLayoutRecord {
1479 substrate_group_id: None,
1480 channel_id: "19:b-renamed".to_owned(),
1481 general: true,
1482 hidden: false,
1483 tabs: Vec::new(),
1484 notifications: ChannelNotifications::default(),
1485 }],
1486 }])
1487 .unwrap();
1488 assert_eq!(
1489 store.team_thread_id("group-a").unwrap().as_deref(),
1490 Some("19:a-general")
1491 );
1492 assert_eq!(
1493 store.team_thread_id("group-b").unwrap().as_deref(),
1494 Some("19:b-renamed")
1495 );
1496 assert_eq!(store.team_thread_id("group-c").unwrap(), None);
1497}
1498
1499#[test]
1500fn recent_messages_run_newest_first_across_scopes_with_a_cursor() {
1501 let store = Store::open_in_memory().unwrap();
1502 let mut deleted = message("chat-a", "a3", 8);
1503 deleted.deleted = true;
1504 store
1505 .upsert_messages(&[
1506 message("chat-a", "a1", 1),
1507 message("chat-a", "a2", 6),
1508 deleted,
1509 message("chat-b", "b1", 5),
1510 message("chat-b", "b2", 7),
1511 message("chat-c", "c1", 9),
1512 ])
1513 .unwrap();
1514 let scope = |conversation_id: &str, minute: u32| RecentScope {
1515 conversation_id: conversation_id.to_owned(),
1516 after: at(minute),
1517 };
1518 let scopes = [scope("chat-a", 0), scope("chat-b", 5)];
1519 let ids = |messages: Vec<MessageRecord>| -> Vec<String> {
1520 messages
1521 .into_iter()
1522 .map(|message| message.message_id)
1523 .collect()
1524 };
1525 assert_eq!(
1526 ids(store.recent_messages(&scopes, None, 10).unwrap()),
1527 ["b2", "a2", "a1"]
1528 );
1529 assert_eq!(
1530 ids(store.recent_messages(&scopes, None, 2).unwrap()),
1531 ["b2", "a2"]
1532 );
1533 assert_eq!(
1534 ids(store
1535 .recent_messages(&scopes, Some((at(6), "a2", "chat-a")), 10)
1536 .unwrap()),
1537 ["a1"]
1538 );
1539 assert!(store.recent_messages(&[], None, 10).unwrap().is_empty());
1540}
1541
1542#[test]
1543fn recent_messages_break_ties_by_conversation_across_the_cursor() {
1544 let store = Store::open_in_memory().unwrap();
1545 store
1546 .upsert_messages(&[message("chat-a", "m1", 5), message("chat-b", "m1", 5)])
1547 .unwrap();
1548 let scopes: Vec<RecentScope> = ["chat-a", "chat-b"]
1549 .into_iter()
1550 .map(|conversation_id| RecentScope {
1551 conversation_id: conversation_id.to_owned(),
1552 after: at(0),
1553 })
1554 .collect();
1555 let first = store.recent_messages(&scopes, None, 1).unwrap();
1556 assert_eq!(first[0].conversation_id, "chat-b");
1557 let second = store
1558 .recent_messages(&scopes, Some((at(5), "m1", "chat-b")), 1)
1559 .unwrap();
1560 assert_eq!(second[0].conversation_id, "chat-a");
1561 assert!(
1562 store
1563 .recent_messages(&scopes, Some((at(5), "m1", "chat-a")), 1)
1564 .unwrap()
1565 .is_empty()
1566 );
1567}
1568
1569fn call_message(message_id: &str, minute: u32) -> MessageRecord {
1570 MessageRecord {
1571 sender_id: None,
1572 sender_name: None,
1573 body_html: String::new(),
1574 call_event_json: Some(r#"{"phase":"Ended"}"#.to_owned()),
1575 ..message("c", message_id, minute)
1576 }
1577}
1578
1579#[test]
1580fn call_event_round_trips_and_is_not_indexed_or_unread() {
1581 let store = Store::open_in_memory().unwrap();
1582 store
1583 .upsert_messages(&[call_message("call", 1), message("c", "text", 2)])
1584 .unwrap();
1585 let stored = store.messages("c", None, 10).unwrap();
1586 assert_eq!(
1587 stored[0].call_event_json.as_deref(),
1588 Some(r#"{"phase":"Ended"}"#)
1589 );
1590 assert_eq!(stored[1].call_event_json, None);
1591 assert_eq!(store.count_messages_after("c", None, "me").unwrap(), 1);
1592 assert_eq!(
1593 store
1594 .first_message_after_from_others("c", None, "me")
1595 .unwrap()
1596 .as_deref(),
1597 Some("text")
1598 );
1599}
1600
1601#[test]
1602fn migration_to_v20_adds_the_call_event_column() {
1603 let directory = tempfile::tempdir().unwrap();
1604 let path = directory.path().join("old.sqlite3");
1605 {
1606 let store = Store::open(&path).unwrap();
1607 store.upsert_messages(&[message("c", "old", 1)]).unwrap();
1608 store
1609 .upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1610 .unwrap();
1611 store.set_sync_state("c", &SyncState::default()).unwrap();
1612 store
1613 .set_sync_state("channel", &SyncState::default())
1614 .unwrap();
1615 drop(store);
1616 Connection::open(&path)
1617 .unwrap()
1618 .execute_batch(
1619 "ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; ALTER TABLE channels DROP COLUMN read_until; ALTER TABLE messages DROP COLUMN call_event_json; ALTER TABLE messages DROP COLUMN importance; ALTER TABLE chats DROP COLUMN preview_at; PRAGMA user_version = 19",
1620 )
1621 .unwrap();
1622 }
1623 let store = Store::open(&path).unwrap();
1624 assert_eq!(store.schema_version().unwrap(), store::latest_version());
1625 let old = store.messages("c", None, 10).unwrap();
1626 assert_eq!(old[0].call_event_json, None);
1627 assert!(store.sync_state("c").unwrap().is_none());
1628 assert!(store.sync_state("channel").unwrap().is_some());
1629 store.upsert_messages(&[call_message("call", 2)]).unwrap();
1630 assert!(
1631 store.messages("c", None, 10).unwrap()[1]
1632 .call_event_json
1633 .is_some()
1634 );
1635}
1636
1637#[test]
1638fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1639 let directory = tempfile::tempdir().unwrap();
1640 let path = directory.path().join("old.sqlite3");
1641 {
1642 let store = Store::open(&path).unwrap();
1643 store
1644 .upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1645 .unwrap();
1646 store
1647 .upsert_teams(&[TeamRecord {
1648 id: "team".to_owned(),
1649 name: "Team".to_owned(),
1650 }])
1651 .unwrap();
1652 store
1653 .upsert_channels(&[ChannelRecord {
1654 id: "channel".to_owned(),
1655 team_id: "team".to_owned(),
1656 name: "General".to_owned(),
1657 membership_type: None,
1658 last_message_at: None,
1659 unread: false,
1660 }])
1661 .unwrap();
1662 for conversation_id in ["c", "channel", "other"] {
1663 store
1664 .set_sync_state(conversation_id, &SyncState::default())
1665 .unwrap();
1666 }
1667 drop(store);
1668 Connection::open(&path)
1669 .unwrap()
1670 .execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; ALTER TABLE channels DROP COLUMN read_until; ALTER TABLE messages DROP COLUMN importance; ALTER TABLE chats DROP COLUMN preview_at; PRAGMA user_version = 20")
1671 .unwrap();
1672 }
1673 let store = Store::open(&path).unwrap();
1674 assert_eq!(store.schema_version().unwrap(), store::latest_version());
1675 assert!(store.sync_state("c").unwrap().is_none());
1676 assert!(store.sync_state("channel").unwrap().is_none());
1677 assert!(store.sync_state("other").unwrap().is_some());
1678}
1679
1680fn horizon(member_id: &str, read_minute: u32, at_minute: Option<u32>) -> ReadHorizonRecord {
1681 ReadHorizonRecord {
1682 member_id: member_id.to_owned(),
1683 read_until: at(read_minute),
1684 read_at: at_minute.map(at),
1685 }
1686}
1687
1688#[test]
1689fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1690 let directory = tempfile::tempdir().unwrap();
1691 let path = directory.path().join("old.sqlite3");
1692 {
1693 let store = Store::open(&path).unwrap();
1694 store
1695 .upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1696 .unwrap();
1697 drop(store);
1698 Connection::open(&path)
1699 .unwrap()
1700 .execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; ALTER TABLE channels DROP COLUMN read_until; DROP TABLE read_horizons; ALTER TABLE messages DROP COLUMN importance; ALTER TABLE chats DROP COLUMN preview_at; PRAGMA user_version = 21")
1701 .unwrap();
1702 }
1703 let store = Store::open(&path).unwrap();
1704 assert_eq!(store.schema_version().unwrap(), store::latest_version());
1705 assert!(store.read_horizons("c").unwrap().is_empty());
1706 let horizons = [
1707 horizon("8:orgid:ada", 3, Some(4)),
1708 horizon("8:orgid:bob", 2, None),
1709 ];
1710 store.set_read_horizons("c", &horizons).unwrap();
1711 drop(store);
1712 let reopened = Store::open(&path).unwrap();
1713 assert_eq!(reopened.read_horizons("c").unwrap(), horizons);
1714}
1715
1716#[test]
1717fn setting_read_horizons_replaces_the_conversation_only() {
1718 let store = Store::open_in_memory().unwrap();
1719 let first = [
1720 horizon("8:orgid:ada", 3, None),
1721 horizon("8:orgid:bob", 2, None),
1722 ];
1723 store.set_read_horizons("c", &first).unwrap();
1724 store
1725 .set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)])
1726 .unwrap();
1727 let second = [horizon("8:orgid:ada", 5, Some(6))];
1728 store.set_read_horizons("c", &second).unwrap();
1729 assert_eq!(store.read_horizons("c").unwrap(), second);
1730 assert_eq!(store.read_horizons("other").unwrap().len(), 1);
1731}
1732
1733#[test]
1734fn local_show_hide_and_channel_pin_writes_reach_the_sidebar() {
1735 let store = Store::open_in_memory().unwrap();
1736 store
1737 .upsert_teams(&[TeamRecord {
1738 id: "t1".to_owned(),
1739 name: "Alpha".to_owned(),
1740 }])
1741 .unwrap();
1742 let channel = |id: &str, name: &str| ChannelRecord {
1743 id: id.to_owned(),
1744 team_id: "t1".to_owned(),
1745 name: name.to_owned(),
1746 membership_type: None,
1747 last_message_at: None,
1748 unread: false,
1749 };
1750 store
1751 .upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1752 .unwrap();
1753 let team = || store.sidebar().unwrap().teams.remove(0);
1754
1755 store.set_channel_hidden("c2", true).unwrap();
1756 store.set_team_hidden("t1", true).unwrap();
1757 let hidden = team();
1758 assert_eq!(hidden.hidden_channel_ids, vec!["c2".to_owned()]);
1759 assert!(hidden.hidden);
1760 assert_eq!(hidden.channels[0].name, "General");
1761
1762 store.set_channel_hidden("c2", false).unwrap();
1763 store.set_team_hidden("t1", false).unwrap();
1764 let shown = team();
1765 assert!(shown.hidden_channel_ids.is_empty());
1766 assert!(!shown.hidden);
1767
1768 store
1769 .replace_pinned_channels(&["c2".to_owned(), "c1".to_owned()])
1770 .unwrap();
1771 assert_eq!(store.pinned_channel_ids().unwrap(), vec!["c2", "c1"]);
1772}
1773
1774#[test]
1775fn migration_to_v25_drops_copies_stored_under_a_float_id() {
1776 let directory = tempfile::tempdir().unwrap();
1777 let path = directory.path().join("old.sqlite3");
1778 {
1779 let store = Store::open(&path).unwrap();
1780 store
1781 .upsert_messages(&[message("c", "1793871826192.0", 1), message("c", "1793871826192", 1)])
1782 .unwrap();
1783 drop(store);
1784 Connection::open(&path)
1785 .unwrap()
1786 .execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; ALTER TABLE channels DROP COLUMN read_until; ALTER TABLE chats DROP COLUMN preview_at; PRAGMA user_version = 24")
1787 .unwrap();
1788 }
1789 let store = Store::open(&path).unwrap();
1790 let ids = ["1793871826192.0".to_owned(), "1793871826192".to_owned()];
1791 let found = store.messages_by_id("c", &ids).unwrap();
1792 assert_eq!(found.len(), 1);
1793 assert!(found.contains_key("1793871826192"));
1794}
1795
1796#[test]
1797fn team_rights_come_back_with_the_sidebar() {
1798 let store = Store::open_in_memory().unwrap();
1799 store
1800 .upsert_teams(&[TeamRecord {
1801 id: "team".to_owned(),
1802 name: "Team".to_owned(),
1803 }])
1804 .unwrap();
1805 assert_eq!(store.sidebar().unwrap().teams[0].rights, TeamRights::default());
1806 let rights = TeamRights {
1807 owner: false,
1808 add_channel: true,
1809 add_private_channel: true,
1810 edit_channel: false,
1811 delete_channel: true,
1812 };
1813 store
1814 .replace_team_layout(&[TeamLayoutRecord {
1815 team_id: "team".to_owned(),
1816 hidden: false,
1817 rights,
1818 channels: Vec::new(),
1819 }])
1820 .unwrap();
1821 assert_eq!(store.sidebar().unwrap().teams[0].rights, rights);
1822}
1823
1824#[test]
1825fn migration_to_v29_names_departed_people_from_their_messages() {
1826 let directory = tempfile::tempdir().unwrap();
1827 let path = directory.path().join("old.sqlite3");
1828 {
1829 let store = Store::open(&path).unwrap();
1830 store.upsert_chats(&[chat("c", "?", Some(at(1)))]).unwrap();
1831 store.upsert_chats(&[chat("gone", "?", Some(at(2)))]).unwrap();
1832 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
1833 store.set_meta("me_user_id", "user-me").unwrap();
1834 drop(store);
1835 Connection::open(&path)
1836 .unwrap()
1837 .execute_batch(
1838 "UPDATE chats SET kind = 'oneOnOne', member_summary = '?';
1839 DELETE FROM chat_members;
1840 INSERT INTO chat_members VALUES ('c', 0, 'user-me', 'Me'), ('c', 1, 'user-ada', '?');
1841 INSERT INTO chat_members VALUES ('gone', 0, 'user-me', 'Me'), ('gone', 1, 'user-zed', '?');
1842 PRAGMA user_version = 28",
1843 )
1844 .unwrap();
1845 }
1846 let store = Store::open(&path).unwrap();
1847 let named = store.chat("c").unwrap().unwrap();
1848 assert_eq!(named.title, "Ada Example");
1849 assert_eq!(named.member_summary, "Ada Example");
1850 assert_eq!(store.chat("gone").unwrap().unwrap().title, UNKNOWN_USER_NAME);
1851}
1852
1853#[test]
1854fn a_chat_without_a_last_message_keeps_the_time_of_its_last_real_activity() {
1855 let store = Store::open_in_memory().unwrap();
1856 store.upsert_chats(&[chat("meeting", "Review", Some(at(1)))]).unwrap();
1857 let left = MessageRecord {
1858 call_event_json: Some(r#"{"roster":{"change":"Left","member_ids":["user-bob"]}}"#.to_owned()),
1859 ..call_message("left", 40)
1860 };
1861 store
1862 .upsert_messages(&[MessageRecord { conversation_id: "meeting".to_owned(), ..call_message("ended", 10) }, MessageRecord { conversation_id: "meeting".to_owned(), ..left }])
1863 .unwrap();
1864 let mut bumped = chat("meeting", "Review", Some(at(40)));
1865 bumped.without_last_message = true;
1866 store.upsert_chats(&[bumped]).unwrap();
1867 assert_eq!(store.chat("meeting").unwrap().unwrap().last_message_at, Some(at(10)));
1868
1869 let mut never_used = chat("empty", "Planning", Some(at(3)));
1870 never_used.without_last_message = true;
1871 store.upsert_chats(&[never_used.clone()]).unwrap();
1872 store.upsert_chats(&[never_used]).unwrap();
1873 assert_eq!(store.chat("empty").unwrap().unwrap().last_message_at, Some(at(3)));
1874}