BlueGit

ict rusty-teams

Files

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

store.rs

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