fix(store): reads use their own connections, so a long write no longer freezes the UI
- Three read-only WAL connections serve the 52 select-only store methods - The writer mutex stays for writes; the UI read of meta() waited 7-11 s behind message upserts and the forward heal scan (hang dumps 2026-11-25) - In-memory stores keep the single connection Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -43,7 +43,7 @@ impl Store {
43
43
44
44
/// Newest first.
45
45
pub fn activity(&self) -> Result<Vec<ActivityRecord>> {
46
let connection = self.lock()?;
46
let connection = self.read()?;
47
47
let mut statement = connection.prepare_cached(&format!(
48
48
"SELECT {ACTIVITY_COLUMNS} FROM activity ORDER BY updated_at DESC, id DESC"
49
49
))?;
@@ -43,7 +43,7 @@ impl Store {43
43
44
/// Newest first.44
/// Newest first.45
pub fn activity(&self) -> Result<Vec<ActivityRecord>> {45
pub fn activity(&self) -> Result<Vec<ActivityRecord>> {46
let connection = self.lock()?;46
let connection = self.read()?;47
let mut statement = connection.prepare_cached(&format!(47
let mut statement = connection.prepare_cached(&format!(48
"SELECT {ACTIVITY_COLUMNS} FROM activity ORDER BY updated_at DESC, id DESC"48
"SELECT {ACTIVITY_COLUMNS} FROM activity ORDER BY updated_at DESC, id DESC"49
))?;49
))?;@@ -8,7 +8,7 @@ use crate::time::{from_millis, to_millis};
8
8
9
9
impl Store {
10
10
pub fn avatar(&self, user_id: &str) -> Result<Option<AvatarRecord>> {
11
let connection = self.lock()?;
11
let connection = self.read()?;
12
12
Ok(connection
13
13
.query_row(
14
14
"SELECT user_id, bytes, content_type, fetched_at FROM avatars WHERE user_id = ?1",
@@ -47,7 +47,7 @@ impl Store {
47
47
user_ids: &[String],
48
48
cutoff: DateTime<Utc>,
49
49
) -> Result<Vec<String>> {
50
let connection = self.lock()?;
50
let connection = self.read()?;
51
51
let mut statement = connection.prepare_cached(
52
52
"SELECT value FROM json_each(?1)
53
53
WHERE value NOT IN (SELECT user_id FROM avatars WHERE fetched_at >= ?2)",
@@ -8,7 +8,7 @@ use crate::time::{from_millis, to_millis};8
8
9
impl Store {9
impl Store {10
pub fn avatar(&self, user_id: &str) -> Result<Option<AvatarRecord>> {10
pub fn avatar(&self, user_id: &str) -> Result<Option<AvatarRecord>> {11
let connection = self.lock()?;11
let connection = self.read()?;12
Ok(connection12
Ok(connection13
.query_row(13
.query_row(14
"SELECT user_id, bytes, content_type, fetched_at FROM avatars WHERE user_id = ?1",14
"SELECT user_id, bytes, content_type, fetched_at FROM avatars WHERE user_id = ?1",@@ -47,7 +47,7 @@ impl Store {47
user_ids: &[String],47
user_ids: &[String],48
cutoff: DateTime<Utc>,48
cutoff: DateTime<Utc>,49
) -> Result<Vec<String>> {49
) -> Result<Vec<String>> {50
let connection = self.lock()?;50
let connection = self.read()?;51
let mut statement = connection.prepare_cached(51
let mut statement = connection.prepare_cached(52
"SELECT value FROM json_each(?1)52
"SELECT value FROM json_each(?1)53
WHERE value NOT IN (SELECT user_id FROM avatars WHERE fetched_at >= ?2)",53
WHERE value NOT IN (SELECT user_id FROM avatars WHERE fetched_at >= ?2)",@@ -84,7 +84,7 @@ impl Store {
84
84
&self,
85
85
chat_ids: &[String],
86
86
) -> Result<HashMap<String, Option<DateTime<Utc>>>> {
87
let connection = self.lock()?;
87
let connection = self.read()?;
88
88
let mut statement = connection.prepare_cached(
89
89
"SELECT id, last_message_at FROM chats WHERE id IN (SELECT value FROM json_each(?1))",
90
90
)?;
@@ -95,7 +95,7 @@ impl Store {
95
95
}
96
96
97
97
pub fn chat_count(&self) -> Result<usize> {
98
let connection = self.lock()?;
98
let connection = self.read()?;
99
99
let count: i64 =
100
100
connection.query_row("SELECT COUNT(*) FROM chats", [], |row| row.get(0))?;
101
101
Ok(count as usize)
@@ -195,7 +195,7 @@ impl Store {
195
195
}
196
196
197
197
pub fn recent_chats(&self, limit: usize) -> Result<Vec<ChatRecord>> {
198
let connection = self.lock()?;
198
let connection = self.read()?;
199
199
let mut statement = connection.prepare_cached(&format!(
200
200
"SELECT {CHAT_COLUMNS} FROM chats ORDER BY last_message_at IS NULL, last_message_at DESC, id LIMIT ?1"
201
201
))?;
@@ -207,7 +207,7 @@ impl Store {
207
207
}
208
208
209
209
pub fn chat(&self, chat_id: &str) -> Result<Option<ChatRecord>> {
210
let connection = self.lock()?;
210
let connection = self.read()?;
211
211
let mut statement = connection
212
212
.prepare_cached(&format!("SELECT {CHAT_COLUMNS} FROM chats WHERE id = ?1"))?;
213
213
let mut chats = statement
@@ -84,7 +84,7 @@ impl Store {84
&self,84
&self,85
chat_ids: &[String],85
chat_ids: &[String],86
) -> Result<HashMap<String, Option<DateTime<Utc>>>> {86
) -> Result<HashMap<String, Option<DateTime<Utc>>>> {87
let connection = self.lock()?;87
let connection = self.read()?;88
let mut statement = connection.prepare_cached(88
let mut statement = connection.prepare_cached(89
"SELECT id, last_message_at FROM chats WHERE id IN (SELECT value FROM json_each(?1))",89
"SELECT id, last_message_at FROM chats WHERE id IN (SELECT value FROM json_each(?1))",90
)?;90
)?;@@ -95,7 +95,7 @@ impl Store {95
}95
}96
96
97
pub fn chat_count(&self) -> Result<usize> {97
pub fn chat_count(&self) -> Result<usize> {98
let connection = self.lock()?;98
let connection = self.read()?;99
let count: i64 =99
let count: i64 =100
connection.query_row("SELECT COUNT(*) FROM chats", [], |row| row.get(0))?;100
connection.query_row("SELECT COUNT(*) FROM chats", [], |row| row.get(0))?;101
Ok(count as usize)101
Ok(count as usize)@@ -195,7 +195,7 @@ impl Store {195
}195
}196
196
197
pub fn recent_chats(&self, limit: usize) -> Result<Vec<ChatRecord>> {197
pub fn recent_chats(&self, limit: usize) -> Result<Vec<ChatRecord>> {198
let connection = self.lock()?;198
let connection = self.read()?;199
let mut statement = connection.prepare_cached(&format!(199
let mut statement = connection.prepare_cached(&format!(200
"SELECT {CHAT_COLUMNS} FROM chats ORDER BY last_message_at IS NULL, last_message_at DESC, id LIMIT ?1"200
"SELECT {CHAT_COLUMNS} FROM chats ORDER BY last_message_at IS NULL, last_message_at DESC, id LIMIT ?1"201
))?;201
))?;@@ -207,7 +207,7 @@ impl Store {207
}207
}208
208
209
pub fn chat(&self, chat_id: &str) -> Result<Option<ChatRecord>> {209
pub fn chat(&self, chat_id: &str) -> Result<Option<ChatRecord>> {210
let connection = self.lock()?;210
let connection = self.read()?;211
let mut statement = connection211
let mut statement = connection212
.prepare_cached(&format!("SELECT {CHAT_COLUMNS} FROM chats WHERE id = ?1"))?;212
.prepare_cached(&format!("SELECT {CHAT_COLUMNS} FROM chats WHERE id = ?1"))?;213
let mut chats = statement213
let mut chats = statement@@ -50,7 +50,7 @@ impl Store {
50
50
}
51
51
52
52
pub fn draft(&self, conversation_id: &str) -> Result<Option<DraftRecord>> {
53
let connection = self.lock()?;
53
let connection = self.read()?;
54
54
let found = connection
55
55
.query_row(
56
56
"SELECT payload, preview, updated_at FROM drafts WHERE conversation_id = ?1",
@@ -86,7 +86,7 @@ impl Store {
86
86
}
87
87
88
88
pub fn draft_previews(&self) -> Result<HashMap<String, String>> {
89
let connection = self.lock()?;
89
let connection = self.read()?;
90
90
let mut statement =
91
91
connection.prepare_cached("SELECT conversation_id, preview FROM drafts")?;
92
92
let previews = statement
@@ -50,7 +50,7 @@ impl Store {50
}50
}51
51
52
pub fn draft(&self, conversation_id: &str) -> Result<Option<DraftRecord>> {52
pub fn draft(&self, conversation_id: &str) -> Result<Option<DraftRecord>> {53
let connection = self.lock()?;53
let connection = self.read()?;54
let found = connection54
let found = connection55
.query_row(55
.query_row(56
"SELECT payload, preview, updated_at FROM drafts WHERE conversation_id = ?1",56
"SELECT payload, preview, updated_at FROM drafts WHERE conversation_id = ?1",@@ -86,7 +86,7 @@ impl Store {86
}86
}87
87
88
pub fn draft_previews(&self) -> Result<HashMap<String, String>> {88
pub fn draft_previews(&self) -> Result<HashMap<String, String>> {89
let connection = self.lock()?;89
let connection = self.read()?;90
let mut statement =90
let mut statement =91
connection.prepare_cached("SELECT conversation_id, preview FROM drafts")?;91
connection.prepare_cached("SELECT conversation_id, preview FROM drafts")?;92
let previews = statement92
let previews = statement@@ -6,7 +6,7 @@ use crate::store::Store;
6
6
impl Store {
7
7
/// People of other organizations, with their organization's name when Teams gave one.
8
8
pub fn external_people(&self) -> Result<Vec<(String, Option<String>)>> {
9
let connection = self.lock()?;
9
let connection = self.read()?;
10
10
let mut statement =
11
11
connection.prepare_cached("SELECT user_id, tenant_name FROM external_people")?;
12
12
let rows = statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;
@@ -6,7 +6,7 @@ use crate::store::Store;6
impl Store {6
impl Store {7
/// People of other organizations, with their organization's name when Teams gave one.7
/// People of other organizations, with their organization's name when Teams gave one.8
pub fn external_people(&self) -> Result<Vec<(String, Option<String>)>> {8
pub fn external_people(&self) -> Result<Vec<(String, Option<String>)>> {9
let connection = self.lock()?;9
let connection = self.read()?;10
let mut statement =10
let mut statement =11
connection.prepare_cached("SELECT user_id, tenant_name FROM external_people")?;11
connection.prepare_cached("SELECT user_id, tenant_name FROM external_people")?;12
let rows = statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;12
let rows = statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;@@ -48,7 +48,7 @@ impl Store {
48
48
}
49
49
50
50
pub fn folders(&self) -> Result<Vec<FolderRecord>> {
51
let connection = self.lock()?;
51
let connection = self.read()?;
52
52
let mut statement = connection
53
53
.prepare_cached("SELECT id, name, kind, expanded FROM folders ORDER BY position")?;
54
54
let mut folders = statement
@@ -83,7 +83,7 @@ impl Store {
83
83
}
84
84
85
85
pub fn pinned_channel_ids(&self) -> Result<Vec<String>> {
86
let connection = self.lock()?;
86
let connection = self.read()?;
87
87
let mut statement = connection
88
88
.prepare_cached("SELECT channel_id FROM pinned_channels ORDER BY position")?;
89
89
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
@@ -48,7 +48,7 @@ impl Store {48
}48
}49
49
50
pub fn folders(&self) -> Result<Vec<FolderRecord>> {50
pub fn folders(&self) -> Result<Vec<FolderRecord>> {51
let connection = self.lock()?;51
let connection = self.read()?;52
let mut statement = connection52
let mut statement = connection53
.prepare_cached("SELECT id, name, kind, expanded FROM folders ORDER BY position")?;53
.prepare_cached("SELECT id, name, kind, expanded FROM folders ORDER BY position")?;54
let mut folders = statement54
let mut folders = statement@@ -83,7 +83,7 @@ impl Store {83
}83
}84
84
85
pub fn pinned_channel_ids(&self) -> Result<Vec<String>> {85
pub fn pinned_channel_ids(&self) -> Result<Vec<String>> {86
let connection = self.lock()?;86
let connection = self.read()?;87
let mut statement = connection87
let mut statement = connection88
.prepare_cached("SELECT channel_id FROM pinned_channels ORDER BY position")?;88
.prepare_cached("SELECT channel_id FROM pinned_channels ORDER BY position")?;89
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;89
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;@@ -8,7 +8,7 @@ use crate::time::{from_millis, to_millis};
8
8
9
9
impl Store {
10
10
pub fn image(&self, key: &str) -> Result<Option<ImageRecord>> {
11
let connection = self.lock()?;
11
let connection = self.read()?;
12
12
Ok(connection
13
13
.query_row(
14
14
"SELECT key, bytes, content_type, fetched_at FROM images WHERE key = ?1",
@@ -26,7 +26,7 @@ impl Store {
26
26
}
27
27
28
28
pub fn has_image(&self, key: &str) -> Result<bool> {
29
let connection = self.lock()?;
29
let connection = self.read()?;
30
30
Ok(connection
31
31
.query_row("SELECT 1 FROM images WHERE key = ?1", [key], |_| Ok(()))
32
32
.optional()?
@@ -75,7 +75,7 @@ impl Store {
75
75
}
76
76
77
77
pub fn image_cache_bytes(&self) -> Result<u64> {
78
let connection = self.lock()?;
78
let connection = self.read()?;
79
79
let total: i64 =
80
80
connection.query_row("SELECT COALESCE(SUM(size), 0) FROM images", [], |row| {
81
81
row.get(0)
@@ -8,7 +8,7 @@ use crate::time::{from_millis, to_millis};8
8
9
impl Store {9
impl Store {10
pub fn image(&self, key: &str) -> Result<Option<ImageRecord>> {10
pub fn image(&self, key: &str) -> Result<Option<ImageRecord>> {11
let connection = self.lock()?;11
let connection = self.read()?;12
Ok(connection12
Ok(connection13
.query_row(13
.query_row(14
"SELECT key, bytes, content_type, fetched_at FROM images WHERE key = ?1",14
"SELECT key, bytes, content_type, fetched_at FROM images WHERE key = ?1",@@ -26,7 +26,7 @@ impl Store {26
}26
}27
27
28
pub fn has_image(&self, key: &str) -> Result<bool> {28
pub fn has_image(&self, key: &str) -> Result<bool> {29
let connection = self.lock()?;29
let connection = self.read()?;30
Ok(connection30
Ok(connection31
.query_row("SELECT 1 FROM images WHERE key = ?1", [key], |_| Ok(()))31
.query_row("SELECT 1 FROM images WHERE key = ?1", [key], |_| Ok(()))32
.optional()?32
.optional()?@@ -75,7 +75,7 @@ impl Store {75
}75
}76
76
77
pub fn image_cache_bytes(&self) -> Result<u64> {77
pub fn image_cache_bytes(&self) -> Result<u64> {78
let connection = self.lock()?;78
let connection = self.read()?;79
let total: i64 =79
let total: i64 =80
connection.query_row("SELECT COALESCE(SUM(size), 0) FROM images", [], |row| {80
connection.query_row("SELECT COALESCE(SUM(size), 0) FROM images", [], |row| {81
row.get(0)81
row.get(0)@@ -39,7 +39,7 @@ impl Store {
39
39
40
40
/// Oldest first.
41
41
pub fn agent_meetings(&self) -> Result<Vec<AgentMeetingRecord>> {
42
let connection = self.lock()?;
42
let connection = self.read()?;
43
43
let mut statement = connection.prepare_cached(&format!(
44
44
"SELECT {MEETING_COLUMNS} FROM agent_meeting_proposals ORDER BY created_at ASC, id ASC"
45
45
))?;
@@ -39,7 +39,7 @@ impl Store {39
39
40
/// Oldest first.40
/// Oldest first.41
pub fn agent_meetings(&self) -> Result<Vec<AgentMeetingRecord>> {41
pub fn agent_meetings(&self) -> Result<Vec<AgentMeetingRecord>> {42
let connection = self.lock()?;42
let connection = self.read()?;43
let mut statement = connection.prepare_cached(&format!(43
let mut statement = connection.prepare_cached(&format!(44
"SELECT {MEETING_COLUMNS} FROM agent_meeting_proposals ORDER BY created_at ASC, id ASC"44
"SELECT {MEETING_COLUMNS} FROM agent_meeting_proposals ORDER BY created_at ASC, id ASC"45
))?;45
))?;@@ -80,7 +80,7 @@ impl Store {
80
80
after: Option<DateTime<Utc>>,
81
81
not_from_user_id: &str,
82
82
) -> Result<usize> {
83
let connection = self.lock()?;
83
let connection = self.read()?;
84
84
let count: i64 = connection.query_row(
85
85
"SELECT COUNT(*) FROM messages
86
86
WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
@@ -103,7 +103,7 @@ impl Store {
103
103
after: Option<DateTime<Utc>>,
104
104
not_from_user_id: &str,
105
105
) -> Result<MessageImportance> {
106
let connection = self.lock()?;
106
let connection = self.read()?;
107
107
let last: Option<(Option<String>, Option<String>, i64)> = connection
108
108
.query_row(
109
109
"SELECT importance, sender_id, created_at FROM messages
@@ -131,7 +131,7 @@ impl Store {
131
131
after: Option<DateTime<Utc>>,
132
132
not_from_user_id: &str,
133
133
) -> Result<Option<String>> {
134
let connection = self.lock()?;
134
let connection = self.read()?;
135
135
Ok(connection
136
136
.query_row(
137
137
"SELECT message_id FROM messages
@@ -156,7 +156,7 @@ impl Store {
156
156
before: Option<DateTime<Utc>>,
157
157
limit: usize,
158
158
) -> Result<Vec<MessageRecord>> {
159
let connection = self.lock()?;
159
let connection = self.read()?;
160
160
let mut statement = connection.prepare_cached(&format!(
161
161
"SELECT {MESSAGE_COLUMNS} FROM messages
162
162
WHERE conversation_id = ?1 AND (?2 IS NULL OR created_at < ?2)
@@ -178,7 +178,7 @@ impl Store {
178
178
from: DateTime<Utc>,
179
179
to: DateTime<Utc>,
180
180
) -> Result<Vec<MessageRecord>> {
181
let connection = self.lock()?;
181
let connection = self.read()?;
182
182
let mut statement = connection.prepare_cached(&format!(
183
183
"SELECT {MESSAGE_COLUMNS} FROM messages
184
184
WHERE conversation_id = ?1 AND created_at >= ?2 AND created_at <= ?3
@@ -200,7 +200,7 @@ impl Store {
200
200
after: DateTime<Utc>,
201
201
limit: usize,
202
202
) -> Result<Vec<MessageRecord>> {
203
let connection = self.lock()?;
203
let connection = self.read()?;
204
204
let mut statement = connection.prepare_cached(&format!(
205
205
"SELECT {MESSAGE_COLUMNS} FROM messages
206
206
WHERE conversation_id = ?1 AND created_at > ?2
@@ -221,7 +221,7 @@ impl Store {
221
221
conversation_id: &str,
222
222
root_id: &str,
223
223
) -> Result<Vec<MessageRecord>> {
224
let connection = self.lock()?;
224
let connection = self.read()?;
225
225
let mut statement = connection.prepare_cached(&format!(
226
226
"SELECT {MESSAGE_COLUMNS} FROM messages
227
227
WHERE conversation_id = ?1 AND (message_id = ?2 OR reply_to_id = ?2)
@@ -259,7 +259,7 @@ impl Store {
259
259
),
260
260
None => (None, None, None),
261
261
};
262
let connection = self.lock()?;
262
let connection = self.read()?;
263
263
let mut statement = connection.prepare_cached(&format!(
264
264
"SELECT {MESSAGE_COLUMNS} FROM messages
265
265
JOIN json_each(?1) AS scope
@@ -288,7 +288,7 @@ impl Store {
288
288
conversation_id: &str,
289
289
content_type: &str,
290
290
) -> Result<Vec<MessageRecord>> {
291
let connection = self.lock()?;
291
let connection = self.read()?;
292
292
let mut statement = connection.prepare_cached(&format!(
293
293
"SELECT {MESSAGE_COLUMNS} FROM messages
294
294
WHERE conversation_id = ?1 AND instr(attachments_json, ?2) > 0"
@@ -302,7 +302,7 @@ impl Store {
302
302
303
303
/// Chats, newest first, holding an attachment of `content_type` without content that is not marked unavailable.
304
304
pub fn conversations_with_stale_attachments(&self, content_type: &str) -> Result<Vec<String>> {
305
let connection = self.lock()?;
305
let connection = self.read()?;
306
306
let mut statement = connection.prepare_cached(
307
307
"SELECT chats.id FROM chats
308
308
WHERE EXISTS (
@@ -327,7 +327,7 @@ impl Store {
327
327
conversation_id: &str,
328
328
message_ids: &[String],
329
329
) -> Result<HashMap<String, MessageRecord>> {
330
let connection = self.lock()?;
330
let connection = self.read()?;
331
331
let mut statement = connection.prepare_cached(&format!(
332
332
"SELECT {MESSAGE_COLUMNS} FROM messages
333
333
WHERE conversation_id = ?1 AND message_id IN (SELECT value FROM json_each(?2))"
@@ -352,7 +352,7 @@ impl Store {
352
352
sender_id: &str,
353
353
limit: usize,
354
354
) -> Result<Vec<(String, String)>> {
355
let connection = self.lock()?;
355
let connection = self.read()?;
356
356
let mut statement = connection.prepare_cached(
357
357
"SELECT message_id, reactions_json FROM messages
358
358
WHERE conversation_id = ?1 AND sender_id = ?2 AND deleted = 0
@@ -372,7 +372,7 @@ impl Store {
372
372
conversation_id: &str,
373
373
scan: usize,
374
374
) -> Result<Vec<(String, String)>> {
375
let connection = self.lock()?;
375
let connection = self.read()?;
376
376
let mut statement = connection.prepare_cached(
377
377
"WITH recent AS (
378
378
SELECT sender_id, sender_name, mentions_json FROM messages
@@ -397,7 +397,7 @@ impl Store {
397
397
if user_ids.is_empty() {
398
398
return Ok(HashMap::new());
399
399
}
400
let connection = self.lock()?;
400
let connection = self.read()?;
401
401
let mut statement = connection.prepare_cached(
402
402
"SELECT value, COALESCE(
403
403
(SELECT display_name FROM chat_members
@@ -426,7 +426,7 @@ impl Store {
426
426
root_id: &str,
427
427
user_id: &str,
428
428
) -> Result<bool> {
429
let connection = self.lock()?;
429
let connection = self.read()?;
430
430
Ok(connection.query_row(
431
431
"SELECT EXISTS (
432
432
SELECT 1 FROM messages
@@ -438,7 +438,7 @@ impl Store {
438
438
}
439
439
440
440
pub fn message_count(&self, conversation_id: &str) -> Result<usize> {
441
let connection = self.lock()?;
441
let connection = self.read()?;
442
442
let count: i64 = connection.query_row(
443
443
"SELECT COUNT(*) FROM messages WHERE conversation_id = ?1",
444
444
[conversation_id],
@@ -80,7 +80,7 @@ impl Store {80
after: Option<DateTime<Utc>>,80
after: Option<DateTime<Utc>>,81
not_from_user_id: &str,81
not_from_user_id: &str,82
) -> Result<usize> {82
) -> Result<usize> {83
let connection = self.lock()?;83
let connection = self.read()?;84
let count: i64 = connection.query_row(84
let count: i64 = connection.query_row(85
"SELECT COUNT(*) FROM messages85
"SELECT COUNT(*) FROM messages86
WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?286
WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2@@ -103,7 +103,7 @@ impl Store {103
after: Option<DateTime<Utc>>,103
after: Option<DateTime<Utc>>,104
not_from_user_id: &str,104
not_from_user_id: &str,105
) -> Result<MessageImportance> {105
) -> Result<MessageImportance> {106
let connection = self.lock()?;106
let connection = self.read()?;107
let last: Option<(Option<String>, Option<String>, i64)> = connection107
let last: Option<(Option<String>, Option<String>, i64)> = connection108
.query_row(108
.query_row(109
"SELECT importance, sender_id, created_at FROM messages109
"SELECT importance, sender_id, created_at FROM messages@@ -131,7 +131,7 @@ impl Store {131
after: Option<DateTime<Utc>>,131
after: Option<DateTime<Utc>>,132
not_from_user_id: &str,132
not_from_user_id: &str,133
) -> Result<Option<String>> {133
) -> Result<Option<String>> {134
let connection = self.lock()?;134
let connection = self.read()?;135
Ok(connection135
Ok(connection136
.query_row(136
.query_row(137
"SELECT message_id FROM messages137
"SELECT message_id FROM messages@@ -156,7 +156,7 @@ impl Store {156
before: Option<DateTime<Utc>>,156
before: Option<DateTime<Utc>>,157
limit: usize,157
limit: usize,158
) -> Result<Vec<MessageRecord>> {158
) -> Result<Vec<MessageRecord>> {159
let connection = self.lock()?;159
let connection = self.read()?;160
let mut statement = connection.prepare_cached(&format!(160
let mut statement = connection.prepare_cached(&format!(161
"SELECT {MESSAGE_COLUMNS} FROM messages161
"SELECT {MESSAGE_COLUMNS} FROM messages162
WHERE conversation_id = ?1 AND (?2 IS NULL OR created_at < ?2)162
WHERE conversation_id = ?1 AND (?2 IS NULL OR created_at < ?2)@@ -178,7 +178,7 @@ impl Store {178
from: DateTime<Utc>,178
from: DateTime<Utc>,179
to: DateTime<Utc>,179
to: DateTime<Utc>,180
) -> Result<Vec<MessageRecord>> {180
) -> Result<Vec<MessageRecord>> {181
let connection = self.lock()?;181
let connection = self.read()?;182
let mut statement = connection.prepare_cached(&format!(182
let mut statement = connection.prepare_cached(&format!(183
"SELECT {MESSAGE_COLUMNS} FROM messages183
"SELECT {MESSAGE_COLUMNS} FROM messages184
WHERE conversation_id = ?1 AND created_at >= ?2 AND created_at <= ?3184
WHERE conversation_id = ?1 AND created_at >= ?2 AND created_at <= ?3@@ -200,7 +200,7 @@ impl Store {200
after: DateTime<Utc>,200
after: DateTime<Utc>,201
limit: usize,201
limit: usize,202
) -> Result<Vec<MessageRecord>> {202
) -> Result<Vec<MessageRecord>> {203
let connection = self.lock()?;203
let connection = self.read()?;204
let mut statement = connection.prepare_cached(&format!(204
let mut statement = connection.prepare_cached(&format!(205
"SELECT {MESSAGE_COLUMNS} FROM messages205
"SELECT {MESSAGE_COLUMNS} FROM messages206
WHERE conversation_id = ?1 AND created_at > ?2206
WHERE conversation_id = ?1 AND created_at > ?2@@ -221,7 +221,7 @@ impl Store {221
conversation_id: &str,221
conversation_id: &str,222
root_id: &str,222
root_id: &str,223
) -> Result<Vec<MessageRecord>> {223
) -> Result<Vec<MessageRecord>> {224
let connection = self.lock()?;224
let connection = self.read()?;225
let mut statement = connection.prepare_cached(&format!(225
let mut statement = connection.prepare_cached(&format!(226
"SELECT {MESSAGE_COLUMNS} FROM messages226
"SELECT {MESSAGE_COLUMNS} FROM messages227
WHERE conversation_id = ?1 AND (message_id = ?2 OR reply_to_id = ?2)227
WHERE conversation_id = ?1 AND (message_id = ?2 OR reply_to_id = ?2)@@ -259,7 +259,7 @@ impl Store {259
),259
),260
None => (None, None, None),260
None => (None, None, None),261
};261
};262
let connection = self.lock()?;262
let connection = self.read()?;263
let mut statement = connection.prepare_cached(&format!(263
let mut statement = connection.prepare_cached(&format!(264
"SELECT {MESSAGE_COLUMNS} FROM messages264
"SELECT {MESSAGE_COLUMNS} FROM messages265
JOIN json_each(?1) AS scope265
JOIN json_each(?1) AS scope@@ -288,7 +288,7 @@ impl Store {288
conversation_id: &str,288
conversation_id: &str,289
content_type: &str,289
content_type: &str,290
) -> Result<Vec<MessageRecord>> {290
) -> Result<Vec<MessageRecord>> {291
let connection = self.lock()?;291
let connection = self.read()?;292
let mut statement = connection.prepare_cached(&format!(292
let mut statement = connection.prepare_cached(&format!(293
"SELECT {MESSAGE_COLUMNS} FROM messages293
"SELECT {MESSAGE_COLUMNS} FROM messages294
WHERE conversation_id = ?1 AND instr(attachments_json, ?2) > 0"294
WHERE conversation_id = ?1 AND instr(attachments_json, ?2) > 0"@@ -302,7 +302,7 @@ impl Store {302
302
303
/// Chats, newest first, holding an attachment of `content_type` without content that is not marked unavailable.303
/// Chats, newest first, holding an attachment of `content_type` without content that is not marked unavailable.304
pub fn conversations_with_stale_attachments(&self, content_type: &str) -> Result<Vec<String>> {304
pub fn conversations_with_stale_attachments(&self, content_type: &str) -> Result<Vec<String>> {305
let connection = self.lock()?;305
let connection = self.read()?;306
let mut statement = connection.prepare_cached(306
let mut statement = connection.prepare_cached(307
"SELECT chats.id FROM chats307
"SELECT chats.id FROM chats308
WHERE EXISTS (308
WHERE EXISTS (@@ -327,7 +327,7 @@ impl Store {327
conversation_id: &str,327
conversation_id: &str,328
message_ids: &[String],328
message_ids: &[String],329
) -> Result<HashMap<String, MessageRecord>> {329
) -> Result<HashMap<String, MessageRecord>> {330
let connection = self.lock()?;330
let connection = self.read()?;331
let mut statement = connection.prepare_cached(&format!(331
let mut statement = connection.prepare_cached(&format!(332
"SELECT {MESSAGE_COLUMNS} FROM messages332
"SELECT {MESSAGE_COLUMNS} FROM messages333
WHERE conversation_id = ?1 AND message_id IN (SELECT value FROM json_each(?2))"333
WHERE conversation_id = ?1 AND message_id IN (SELECT value FROM json_each(?2))"@@ -352,7 +352,7 @@ impl Store {352
sender_id: &str,352
sender_id: &str,353
limit: usize,353
limit: usize,354
) -> Result<Vec<(String, String)>> {354
) -> Result<Vec<(String, String)>> {355
let connection = self.lock()?;355
let connection = self.read()?;356
let mut statement = connection.prepare_cached(356
let mut statement = connection.prepare_cached(357
"SELECT message_id, reactions_json FROM messages357
"SELECT message_id, reactions_json FROM messages358
WHERE conversation_id = ?1 AND sender_id = ?2 AND deleted = 0358
WHERE conversation_id = ?1 AND sender_id = ?2 AND deleted = 0@@ -372,7 +372,7 @@ impl Store {372
conversation_id: &str,372
conversation_id: &str,373
scan: usize,373
scan: usize,374
) -> Result<Vec<(String, String)>> {374
) -> Result<Vec<(String, String)>> {375
let connection = self.lock()?;375
let connection = self.read()?;376
let mut statement = connection.prepare_cached(376
let mut statement = connection.prepare_cached(377
"WITH recent AS (377
"WITH recent AS (378
SELECT sender_id, sender_name, mentions_json FROM messages378
SELECT sender_id, sender_name, mentions_json FROM messages@@ -397,7 +397,7 @@ impl Store {397
if user_ids.is_empty() {397
if user_ids.is_empty() {398
return Ok(HashMap::new());398
return Ok(HashMap::new());399
}399
}400
let connection = self.lock()?;400
let connection = self.read()?;401
let mut statement = connection.prepare_cached(401
let mut statement = connection.prepare_cached(402
"SELECT value, COALESCE(402
"SELECT value, COALESCE(403
(SELECT display_name FROM chat_members403
(SELECT display_name FROM chat_members@@ -426,7 +426,7 @@ impl Store {426
root_id: &str,426
root_id: &str,427
user_id: &str,427
user_id: &str,428
) -> Result<bool> {428
) -> Result<bool> {429
let connection = self.lock()?;429
let connection = self.read()?;430
Ok(connection.query_row(430
Ok(connection.query_row(431
"SELECT EXISTS (431
"SELECT EXISTS (432
SELECT 1 FROM messages432
SELECT 1 FROM messages@@ -438,7 +438,7 @@ impl Store {438
}438
}439
439
440
pub fn message_count(&self, conversation_id: &str) -> Result<usize> {440
pub fn message_count(&self, conversation_id: &str) -> Result<usize> {441
let connection = self.lock()?;441
let connection = self.read()?;442
let count: i64 = connection.query_row(442
let count: i64 = connection.query_row(443
"SELECT COUNT(*) FROM messages WHERE conversation_id = ?1",443
"SELECT COUNT(*) FROM messages WHERE conversation_id = ?1",444
[conversation_id],444
[conversation_id],@@ -7,7 +7,7 @@ use crate::time::{from_millis, to_millis};
7
7
8
8
impl Store {
9
9
pub fn meta(&self, key: &str) -> Result<Option<String>> {
10
let connection = self.lock()?;
10
let connection = self.read()?;
11
11
Ok(connection
12
12
.query_row("SELECT value FROM meta WHERE key = ?1", [key], |row| {
13
13
row.get(0)
@@ -7,7 +7,7 @@ use crate::time::{from_millis, to_millis};7
7
8
impl Store {8
impl Store {9
pub fn meta(&self, key: &str) -> Result<Option<String>> {9
pub fn meta(&self, key: &str) -> Result<Option<String>> {10
let connection = self.lock()?;10
let connection = self.read()?;11
Ok(connection11
Ok(connection12
.query_row("SELECT value FROM meta WHERE key = ?1", [key], |row| {12
.query_row("SELECT value FROM meta WHERE key = ?1", [key], |row| {13
row.get(0)13
row.get(0)@@ -38,7 +38,7 @@ impl Store {
38
38
}
39
39
40
40
pub fn outbox_for_conversation(&self, conversation_id: &str) -> Result<Vec<OutboxRecord>> {
41
let connection = self.lock()?;
41
let connection = self.read()?;
42
42
let mut statement = connection.prepare_cached(&format!(
43
43
"SELECT {OUTBOX_COLUMNS} FROM outbox WHERE conversation_id = ?1
44
44
ORDER BY created_at ASC, id ASC"
@@ -50,7 +50,7 @@ impl Store {
50
50
}
51
51
52
52
pub fn sending_outbox(&self) -> Result<Vec<OutboxRecord>> {
53
let connection = self.lock()?;
53
let connection = self.read()?;
54
54
let mut statement = connection.prepare_cached(&format!(
55
55
"SELECT {OUTBOX_COLUMNS} FROM outbox WHERE state = ?1 ORDER BY created_at ASC, id ASC"
56
56
))?;
@@ -61,7 +61,7 @@ impl Store {
61
61
}
62
62
63
63
pub fn failed_outbox_conversations(&self) -> Result<Vec<String>> {
64
let connection = self.lock()?;
64
let connection = self.read()?;
65
65
let mut statement = connection.prepare_cached(
66
66
"SELECT DISTINCT conversation_id FROM outbox WHERE state = ?1 ORDER BY conversation_id",
67
67
)?;
@@ -38,7 +38,7 @@ impl Store {38
}38
}39
39
40
pub fn outbox_for_conversation(&self, conversation_id: &str) -> Result<Vec<OutboxRecord>> {40
pub fn outbox_for_conversation(&self, conversation_id: &str) -> Result<Vec<OutboxRecord>> {41
let connection = self.lock()?;41
let connection = self.read()?;42
let mut statement = connection.prepare_cached(&format!(42
let mut statement = connection.prepare_cached(&format!(43
"SELECT {OUTBOX_COLUMNS} FROM outbox WHERE conversation_id = ?143
"SELECT {OUTBOX_COLUMNS} FROM outbox WHERE conversation_id = ?144
ORDER BY created_at ASC, id ASC"44
ORDER BY created_at ASC, id ASC"@@ -50,7 +50,7 @@ impl Store {50
}50
}51
51
52
pub fn sending_outbox(&self) -> Result<Vec<OutboxRecord>> {52
pub fn sending_outbox(&self) -> Result<Vec<OutboxRecord>> {53
let connection = self.lock()?;53
let connection = self.read()?;54
let mut statement = connection.prepare_cached(&format!(54
let mut statement = connection.prepare_cached(&format!(55
"SELECT {OUTBOX_COLUMNS} FROM outbox WHERE state = ?1 ORDER BY created_at ASC, id ASC"55
"SELECT {OUTBOX_COLUMNS} FROM outbox WHERE state = ?1 ORDER BY created_at ASC, id ASC"56
))?;56
))?;@@ -61,7 +61,7 @@ impl Store {61
}61
}62
62
63
pub fn failed_outbox_conversations(&self) -> Result<Vec<String>> {63
pub fn failed_outbox_conversations(&self) -> Result<Vec<String>> {64
let connection = self.lock()?;64
let connection = self.read()?;65
let mut statement = connection.prepare_cached(65
let mut statement = connection.prepare_cached(66
"SELECT DISTINCT conversation_id FROM outbox WHERE state = ?1 ORDER BY conversation_id",66
"SELECT DISTINCT conversation_id FROM outbox WHERE state = ?1 ORDER BY conversation_id",67
)?;67
)?;@@ -7,7 +7,7 @@ use crate::time::to_millis;
7
7
8
8
impl Store {
9
9
pub fn presences(&self) -> Result<Vec<(String, String)>> {
10
let connection = self.lock()?;
10
let connection = self.read()?;
11
11
let mut statement =
12
12
connection.prepare_cached("SELECT user_id, availability FROM presence")?;
13
13
let rows = statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;
@@ -7,7 +7,7 @@ use crate::time::to_millis;7
7
8
impl Store {8
impl Store {9
pub fn presences(&self) -> Result<Vec<(String, String)>> {9
pub fn presences(&self) -> Result<Vec<(String, String)>> {10
let connection = self.lock()?;10
let connection = self.read()?;11
let mut statement =11
let mut statement =12
connection.prepare_cached("SELECT user_id, availability FROM presence")?;12
connection.prepare_cached("SELECT user_id, availability FROM presence")?;13
let rows = statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;13
let rows = statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;@@ -61,7 +61,7 @@ impl Store {
61
61
62
62
/// Oldest first.
63
63
pub fn pending_agent_proposals(&self) -> Result<Vec<AgentProposalRecord>> {
64
let connection = self.lock()?;
64
let connection = self.read()?;
65
65
let mut statement = connection.prepare_cached(&format!(
66
66
"SELECT {PROPOSAL_COLUMNS} FROM agent_proposals WHERE state = ?1
67
67
ORDER BY created_at ASC, id ASC"
@@ -86,7 +86,7 @@ impl Store {
86
86
}
87
87
88
88
pub fn agent_proposal_image_count(&self, proposal_id: &str) -> Result<usize> {
89
let connection = self.lock()?;
89
let connection = self.read()?;
90
90
let count: i64 = connection.query_row(
91
91
"SELECT COUNT(*) FROM attachment_images WHERE owner_kind = ?1 AND owner_id = ?2",
92
92
params![PROPOSAL_OWNER, proposal_id],
@@ -132,7 +132,7 @@ impl Store {
132
132
133
133
/// Oldest first.
134
134
pub fn pending_agent_reactions(&self) -> Result<Vec<AgentReactionRecord>> {
135
let connection = self.lock()?;
135
let connection = self.read()?;
136
136
let mut statement = connection.prepare_cached(&format!(
137
137
"SELECT {REACTION_COLUMNS} FROM agent_reaction_proposals WHERE state = ?1
138
138
ORDER BY created_at ASC, id ASC"
@@ -61,7 +61,7 @@ impl Store {61
61
62
/// Oldest first.62
/// Oldest first.63
pub fn pending_agent_proposals(&self) -> Result<Vec<AgentProposalRecord>> {63
pub fn pending_agent_proposals(&self) -> Result<Vec<AgentProposalRecord>> {64
let connection = self.lock()?;64
let connection = self.read()?;65
let mut statement = connection.prepare_cached(&format!(65
let mut statement = connection.prepare_cached(&format!(66
"SELECT {PROPOSAL_COLUMNS} FROM agent_proposals WHERE state = ?166
"SELECT {PROPOSAL_COLUMNS} FROM agent_proposals WHERE state = ?167
ORDER BY created_at ASC, id ASC"67
ORDER BY created_at ASC, id ASC"@@ -86,7 +86,7 @@ impl Store {86
}86
}87
87
88
pub fn agent_proposal_image_count(&self, proposal_id: &str) -> Result<usize> {88
pub fn agent_proposal_image_count(&self, proposal_id: &str) -> Result<usize> {89
let connection = self.lock()?;89
let connection = self.read()?;90
let count: i64 = connection.query_row(90
let count: i64 = connection.query_row(91
"SELECT COUNT(*) FROM attachment_images WHERE owner_kind = ?1 AND owner_id = ?2",91
"SELECT COUNT(*) FROM attachment_images WHERE owner_kind = ?1 AND owner_id = ?2",92
params![PROPOSAL_OWNER, proposal_id],92
params![PROPOSAL_OWNER, proposal_id],@@ -132,7 +132,7 @@ impl Store {132
132
133
/// Oldest first.133
/// Oldest first.134
pub fn pending_agent_reactions(&self) -> Result<Vec<AgentReactionRecord>> {134
pub fn pending_agent_reactions(&self) -> Result<Vec<AgentReactionRecord>> {135
let connection = self.lock()?;135
let connection = self.read()?;136
let mut statement = connection.prepare_cached(&format!(136
let mut statement = connection.prepare_cached(&format!(137
"SELECT {REACTION_COLUMNS} FROM agent_reaction_proposals WHERE state = ?1137
"SELECT {REACTION_COLUMNS} FROM agent_reaction_proposals WHERE state = ?1138
ORDER BY created_at ASC, id ASC"138
ORDER BY created_at ASC, id ASC"@@ -7,7 +7,7 @@ use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_mill
7
7
8
8
impl Store {
9
9
pub fn read_horizons(&self, conversation_id: &str) -> Result<Vec<ReadHorizonRecord>> {
10
let connection = self.lock()?;
10
let connection = self.read()?;
11
11
let mut statement = connection.prepare_cached(
12
12
"SELECT member_id, read_until, read_at FROM read_horizons
13
13
WHERE conversation_id = ?1 ORDER BY member_id",
@@ -7,7 +7,7 @@ use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_mill7
7
8
impl Store {8
impl Store {9
pub fn read_horizons(&self, conversation_id: &str) -> Result<Vec<ReadHorizonRecord>> {9
pub fn read_horizons(&self, conversation_id: &str) -> Result<Vec<ReadHorizonRecord>> {10
let connection = self.lock()?;10
let connection = self.read()?;11
let mut statement = connection.prepare_cached(11
let mut statement = connection.prepare_cached(12
"SELECT member_id, read_until, read_at FROM read_horizons12
"SELECT member_id, read_until, read_at FROM read_horizons13
WHERE conversation_id = ?1 ORDER BY member_id",13
WHERE conversation_id = ?1 ORDER BY member_id",@@ -101,7 +101,7 @@ impl Store {
101
101
let Some(expression) = match_expression(query) else {
102
102
return Ok(Vec::new());
103
103
};
104
let connection = self.lock()?;
104
let connection = self.read()?;
105
105
let mut statement = connection.prepare_cached(&format!(
106
106
"SELECT k.conversation_id, k.message_id, m.sender_name, m.created_at,
107
107
snippet(message_search, 0, char({}), char({}), '...', {SNIPPET_TOKENS})
@@ -142,7 +142,7 @@ impl Store {
142
142
let Some(expression) = match_expression(query) else {
143
143
return Ok(Vec::new());
144
144
};
145
let connection = self.lock()?;
145
let connection = self.read()?;
146
146
let mut statement = connection.prepare_cached(&format!(
147
147
"SELECT k.conversation_id, k.message_id, m.sender_name, m.created_at,
148
148
snippet(message_search, 0, char({}), char({}), '...', {SNIPPET_TOKENS})
@@ -181,7 +181,7 @@ impl Store {
181
181
else {
182
182
return Ok(Vec::new());
183
183
};
184
let connection = self.lock()?;
184
let connection = self.read()?;
185
185
let mut statement = connection.prepare_cached(
186
186
"SELECT conversation_id, title FROM title_search WHERE title_search MATCH ?1 ORDER BY rank LIMIT ?2",
187
187
)?;
@@ -101,7 +101,7 @@ impl Store {101
let Some(expression) = match_expression(query) else {101
let Some(expression) = match_expression(query) else {102
return Ok(Vec::new());102
return Ok(Vec::new());103
};103
};104
let connection = self.lock()?;104
let connection = self.read()?;105
let mut statement = connection.prepare_cached(&format!(105
let mut statement = connection.prepare_cached(&format!(106
"SELECT k.conversation_id, k.message_id, m.sender_name, m.created_at,106
"SELECT k.conversation_id, k.message_id, m.sender_name, m.created_at,107
snippet(message_search, 0, char({}), char({}), '...', {SNIPPET_TOKENS})107
snippet(message_search, 0, char({}), char({}), '...', {SNIPPET_TOKENS})@@ -142,7 +142,7 @@ impl Store {142
let Some(expression) = match_expression(query) else {142
let Some(expression) = match_expression(query) else {143
return Ok(Vec::new());143
return Ok(Vec::new());144
};144
};145
let connection = self.lock()?;145
let connection = self.read()?;146
let mut statement = connection.prepare_cached(&format!(146
let mut statement = connection.prepare_cached(&format!(147
"SELECT k.conversation_id, k.message_id, m.sender_name, m.created_at,147
"SELECT k.conversation_id, k.message_id, m.sender_name, m.created_at,148
snippet(message_search, 0, char({}), char({}), '...', {SNIPPET_TOKENS})148
snippet(message_search, 0, char({}), char({}), '...', {SNIPPET_TOKENS})@@ -181,7 +181,7 @@ impl Store {181
else {181
else {182
return Ok(Vec::new());182
return Ok(Vec::new());183
};183
};184
let connection = self.lock()?;184
let connection = self.read()?;185
let mut statement = connection.prepare_cached(185
let mut statement = connection.prepare_cached(186
"SELECT conversation_id, title FROM title_search WHERE title_search MATCH ?1 ORDER BY rank LIMIT ?2",186
"SELECT conversation_id, title FROM title_search WHERE title_search MATCH ?1 ORDER BY rank LIMIT ?2",187
)?;187
)?;@@ -30,7 +30,7 @@ struct ChannelRow {
30
30
impl Store {
31
31
pub fn sidebar(&self) -> Result<Sidebar> {
32
32
let chats = self.recent_chats(usize::MAX >> 1)?;
33
let connection = self.lock()?;
33
let connection = self.read()?;
34
34
let mut team_rows: Vec<TeamRow> = connection
35
35
.prepare_cached(
36
36
"SELECT teams.id, teams.name, team_layout.position, COALESCE(team_layout.hidden, 0),
@@ -228,7 +228,7 @@ impl Store {
228
228
}
229
229
230
230
pub fn channel_substrate_group_id(&self, channel_id: &str) -> Result<Option<String>> {
231
let connection = self.lock()?;
231
let connection = self.read()?;
232
232
Ok(connection
233
233
.prepare_cached("SELECT substrate_group_id FROM channel_layout WHERE channel_id = ?1")?
234
234
.query_map([channel_id], |row| row.get::<_, Option<String>>(0))?
@@ -253,7 +253,7 @@ impl Store {
253
253
254
254
/// The team's own thread id, which Teams' CSA routes take: the id of its General channel.
255
255
pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {
256
let connection = self.lock()?;
256
let connection = self.read()?;
257
257
Ok(connection
258
258
.prepare_cached(
259
259
"SELECT channels.id FROM channels
@@ -311,7 +311,7 @@ impl Store {
311
311
312
312
impl Store {
313
313
pub fn channel_tabs(&self, channel_id: &str) -> Result<Vec<ChannelTabRecord>> {
314
let connection = self.lock()?;
314
let connection = self.read()?;
315
315
let tabs = connection
316
316
.prepare_cached(
317
317
"SELECT tab_id, name, definition_id, open_url FROM channel_tabs
@@ -30,7 +30,7 @@ struct ChannelRow {30
impl Store {30
impl Store {31
pub fn sidebar(&self) -> Result<Sidebar> {31
pub fn sidebar(&self) -> Result<Sidebar> {32
let chats = self.recent_chats(usize::MAX >> 1)?;32
let chats = self.recent_chats(usize::MAX >> 1)?;33
let connection = self.lock()?;33
let connection = self.read()?;34
let mut team_rows: Vec<TeamRow> = connection34
let mut team_rows: Vec<TeamRow> = connection35
.prepare_cached(35
.prepare_cached(36
"SELECT teams.id, teams.name, team_layout.position, COALESCE(team_layout.hidden, 0),36
"SELECT teams.id, teams.name, team_layout.position, COALESCE(team_layout.hidden, 0),@@ -228,7 +228,7 @@ impl Store {228
}228
}229
229
230
pub fn channel_substrate_group_id(&self, channel_id: &str) -> Result<Option<String>> {230
pub fn channel_substrate_group_id(&self, channel_id: &str) -> Result<Option<String>> {231
let connection = self.lock()?;231
let connection = self.read()?;232
Ok(connection232
Ok(connection233
.prepare_cached("SELECT substrate_group_id FROM channel_layout WHERE channel_id = ?1")?233
.prepare_cached("SELECT substrate_group_id FROM channel_layout WHERE channel_id = ?1")?234
.query_map([channel_id], |row| row.get::<_, Option<String>>(0))?234
.query_map([channel_id], |row| row.get::<_, Option<String>>(0))?@@ -253,7 +253,7 @@ impl Store {253
253
254
/// The team's own thread id, which Teams' CSA routes take: the id of its General channel.254
/// The team's own thread id, which Teams' CSA routes take: the id of its General channel.255
pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {255
pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {256
let connection = self.lock()?;256
let connection = self.read()?;257
Ok(connection257
Ok(connection258
.prepare_cached(258
.prepare_cached(259
"SELECT channels.id FROM channels259
"SELECT channels.id FROM channels@@ -311,7 +311,7 @@ impl Store {311
311
312
impl Store {312
impl Store {313
pub fn channel_tabs(&self, channel_id: &str) -> Result<Vec<ChannelTabRecord>> {313
pub fn channel_tabs(&self, channel_id: &str) -> Result<Vec<ChannelTabRecord>> {314
let connection = self.lock()?;314
let connection = self.read()?;315
let tabs = connection315
let tabs = connection316
.prepare_cached(316
.prepare_cached(317
"SELECT tab_id, name, definition_id, open_url FROM channel_tabs317
"SELECT tab_id, name, definition_id, open_url FROM channel_tabs@@ -5,7 +5,7 @@ use std::sync::{Mutex, MutexGuard, OnceLock};
5
5
use std::time::{Duration, Instant};
6
6
7
7
use directories::ProjectDirs;
8
use rusqlite::Connection;
8
use rusqlite::{Connection, OpenFlags};
9
9
10
10
use crate::error::{Error, Result};
11
11
use crate::migrations;
@@ -14,6 +14,7 @@ pub const DATA_DIR_NAME: &str = "ms-teams-linux";
14
14
const DATABASE_FILE: &str = "cache.sqlite3";
15
15
const SLOW_WAIT: Duration = Duration::from_millis(50);
16
16
const SLOW_HOLD: Duration = Duration::from_millis(100);
17
const READERS: usize = 3;
17
18
18
19
static SLOW_LOCK_REPORTER: OnceLock<fn(String)> = OnceLock::new();
19
20
@@ -34,6 +35,8 @@ pub fn default_database_path() -> Result<PathBuf> {
34
35
35
36
pub struct Store {
36
37
connection: Mutex<Connection>,
38
/// WAL lets these read while the writer holds `connection`; empty for an in-memory store.
39
readers: Vec<Mutex<Connection>>,
37
40
}
38
41
39
42
impl Store {
@@ -53,7 +56,11 @@ impl Store {
53
56
}
54
57
let connection = Connection::open(path)?;
55
58
connection.pragma_update(None, "journal_mode", "WAL")?;
56
Self::from_connection(connection)
59
let mut store = Self::from_connection(connection)?;
60
store.readers = (0..READERS)
61
.map(|_| open_reader(path).map(Mutex::new))
62
.collect::<Result<_>>()?;
63
Ok(store)
57
64
}
58
65
59
66
pub fn open_in_memory() -> Result<Self> {
@@ -66,6 +73,7 @@ impl Store {
66
73
migrations::migrate(&mut connection)?;
67
74
Ok(Store {
68
75
connection: Mutex::new(connection),
76
readers: Vec::new(),
69
77
})
70
78
}
71
79
@@ -80,22 +88,59 @@ impl Store {
80
88
let location = Location::caller();
81
89
let asked = Instant::now();
82
90
let connection = self.connection.lock().map_err(|_| Error::Poisoned)?;
83
let waited = asked.elapsed();
84
if waited >= SLOW_WAIT {
85
report_slow_lock(format!(
86
"store lock waited {} ms at {location} on {}",
87
waited.as_millis(),
88
thread_label()
89
));
90
}
91
Ok(StoreGuard {
92
connection,
93
location,
94
taken: Instant::now(),
95
})
91
guard(connection, location, asked)
92
}
93
94
/// A read-only connection, so a long write elsewhere does not block the caller.
95
#[track_caller]
96
pub(crate) fn read(&self) -> Result<StoreGuard<'_>> {
97
let location = Location::caller();
98
let asked = Instant::now();
99
let Some(first) = self.readers.first() else {
100
let connection = self.connection.lock().map_err(|_| Error::Poisoned)?;
101
return guard(connection, location, asked);
102
};
103
let free = self
104
.readers
105
.iter()
106
.find_map(|reader| reader.try_lock().ok());
107
let connection = match free {
108
Some(connection) => connection,
109
None => first.lock().map_err(|_| Error::Poisoned)?,
110
};
111
guard(connection, location, asked)
96
112
}
97
113
}
98
114
115
fn open_reader(path: &Path) -> Result<Connection> {
116
let connection = Connection::open_with_flags(
117
path,
118
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
119
)?;
120
connection.busy_timeout(Duration::from_secs(5))?;
121
Ok(connection)
122
}
123
124
fn guard<'a>(
125
connection: MutexGuard<'a, Connection>,
126
location: &'static Location<'static>,
127
asked: Instant,
128
) -> Result<StoreGuard<'a>> {
129
let waited = asked.elapsed();
130
if waited >= SLOW_WAIT {
131
report_slow_lock(format!(
132
"store lock waited {} ms at {location} on {}",
133
waited.as_millis(),
134
thread_label()
135
));
136
}
137
Ok(StoreGuard {
138
connection,
139
location,
140
taken: Instant::now(),
141
})
142
}
143
99
144
pub(crate) struct StoreGuard<'a> {
100
145
connection: MutexGuard<'a, Connection>,
101
146
location: &'static Location<'static>,
@@ -140,3 +185,23 @@ fn thread_label() -> String {
140
185
pub(crate) fn json_ids(ids: &[String]) -> String {
141
186
serde_json::to_string(ids).unwrap_or_else(|_| "[]".to_owned())
142
187
}
188
189
#[cfg(test)]
190
mod tests {
191
use super::Store;
192
193
#[test]
194
fn a_read_does_not_wait_for_a_held_write_lock() {
195
let directory = tempfile::tempdir().unwrap();
196
let store = Store::open(&directory.path().join("cache.sqlite3")).unwrap();
197
store.set_meta("key", "before").unwrap();
198
let writer = store.lock().unwrap();
199
writer
200
.execute_batch("BEGIN IMMEDIATE; UPDATE meta SET value = 'during' WHERE key = 'key';")
201
.unwrap();
202
assert_eq!(store.meta("key").unwrap().as_deref(), Some("before"));
203
writer.execute_batch("COMMIT;").unwrap();
204
drop(writer);
205
assert_eq!(store.meta("key").unwrap().as_deref(), Some("during"));
206
}
207
}
@@ -5,7 +5,7 @@ use std::sync::{Mutex, MutexGuard, OnceLock};5
use std::time::{Duration, Instant};5
use std::time::{Duration, Instant};6
6
7
use directories::ProjectDirs;7
use directories::ProjectDirs;8
use rusqlite::Connection;8
use rusqlite::{Connection, OpenFlags};9
9
10
use crate::error::{Error, Result};10
use crate::error::{Error, Result};11
use crate::migrations;11
use crate::migrations;@@ -14,6 +14,7 @@ pub const DATA_DIR_NAME: &str = "ms-teams-linux";14
const DATABASE_FILE: &str = "cache.sqlite3";14
const DATABASE_FILE: &str = "cache.sqlite3";15
const SLOW_WAIT: Duration = Duration::from_millis(50);15
const SLOW_WAIT: Duration = Duration::from_millis(50);16
const SLOW_HOLD: Duration = Duration::from_millis(100);16
const SLOW_HOLD: Duration = Duration::from_millis(100);17
const READERS: usize = 3;17
18
18
static SLOW_LOCK_REPORTER: OnceLock<fn(String)> = OnceLock::new();19
static SLOW_LOCK_REPORTER: OnceLock<fn(String)> = OnceLock::new();19
20
@@ -34,6 +35,8 @@ pub fn default_database_path() -> Result<PathBuf> {34
35
35
pub struct Store {36
pub struct Store {36
connection: Mutex<Connection>,37
connection: Mutex<Connection>,38
/// WAL lets these read while the writer holds `connection`; empty for an in-memory store.39
readers: Vec<Mutex<Connection>>,37
}40
}38
41
39
impl Store {42
impl Store {@@ -53,7 +56,11 @@ impl Store {53
}56
}54
let connection = Connection::open(path)?;57
let connection = Connection::open(path)?;55
connection.pragma_update(None, "journal_mode", "WAL")?;58
connection.pragma_update(None, "journal_mode", "WAL")?;56
Self::from_connection(connection)59
let mut store = Self::from_connection(connection)?;60
store.readers = (0..READERS)61
.map(|_| open_reader(path).map(Mutex::new))62
.collect::<Result<_>>()?;63
Ok(store)57
}64
}58
65
59
pub fn open_in_memory() -> Result<Self> {66
pub fn open_in_memory() -> Result<Self> {@@ -66,6 +73,7 @@ impl Store {66
migrations::migrate(&mut connection)?;73
migrations::migrate(&mut connection)?;67
Ok(Store {74
Ok(Store {68
connection: Mutex::new(connection),75
connection: Mutex::new(connection),76
readers: Vec::new(),69
})77
})70
}78
}71
79
@@ -80,22 +88,59 @@ impl Store {80
let location = Location::caller();88
let location = Location::caller();81
let asked = Instant::now();89
let asked = Instant::now();82
let connection = self.connection.lock().map_err(|_| Error::Poisoned)?;90
let connection = self.connection.lock().map_err(|_| Error::Poisoned)?;83
let waited = asked.elapsed();91
guard(connection, location, asked)84
if waited >= SLOW_WAIT {92
}85
report_slow_lock(format!(93
86
"store lock waited {} ms at {location} on {}",94
/// A read-only connection, so a long write elsewhere does not block the caller.87
waited.as_millis(),95
#[track_caller]88
thread_label()96
pub(crate) fn read(&self) -> Result<StoreGuard<'_>> {89
));97
let location = Location::caller();90
}98
let asked = Instant::now();91
Ok(StoreGuard {99
let Some(first) = self.readers.first() else {92
connection,100
let connection = self.connection.lock().map_err(|_| Error::Poisoned)?;93
location,101
return guard(connection, location, asked);94
taken: Instant::now(),102
};95
})103
let free = self104
.readers105
.iter()106
.find_map(|reader| reader.try_lock().ok());107
let connection = match free {108
Some(connection) => connection,109
None => first.lock().map_err(|_| Error::Poisoned)?,110
};111
guard(connection, location, asked)96
}112
}97
}113
}98
114
115
fn open_reader(path: &Path) -> Result<Connection> {116
let connection = Connection::open_with_flags(117
path,118
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,119
)?;120
connection.busy_timeout(Duration::from_secs(5))?;121
Ok(connection)122
}123
124
fn guard<'a>(125
connection: MutexGuard<'a, Connection>,126
location: &'static Location<'static>,127
asked: Instant,128
) -> Result<StoreGuard<'a>> {129
let waited = asked.elapsed();130
if waited >= SLOW_WAIT {131
report_slow_lock(format!(132
"store lock waited {} ms at {location} on {}",133
waited.as_millis(),134
thread_label()135
));136
}137
Ok(StoreGuard {138
connection,139
location,140
taken: Instant::now(),141
})142
}143
99
pub(crate) struct StoreGuard<'a> {144
pub(crate) struct StoreGuard<'a> {100
connection: MutexGuard<'a, Connection>,145
connection: MutexGuard<'a, Connection>,101
location: &'static Location<'static>,146
location: &'static Location<'static>,@@ -140,3 +185,23 @@ fn thread_label() -> String {140
pub(crate) fn json_ids(ids: &[String]) -> String {185
pub(crate) fn json_ids(ids: &[String]) -> String {141
serde_json::to_string(ids).unwrap_or_else(|_| "[]".to_owned())186
serde_json::to_string(ids).unwrap_or_else(|_| "[]".to_owned())142
}187
}188
189
#[cfg(test)]190
mod tests {191
use super::Store;192
193
#[test]194
fn a_read_does_not_wait_for_a_held_write_lock() {195
let directory = tempfile::tempdir().unwrap();196
let store = Store::open(&directory.path().join("cache.sqlite3")).unwrap();197
store.set_meta("key", "before").unwrap();198
let writer = store.lock().unwrap();199
writer200
.execute_batch("BEGIN IMMEDIATE; UPDATE meta SET value = 'during' WHERE key = 'key';")201
.unwrap();202
assert_eq!(store.meta("key").unwrap().as_deref(), Some("before"));203
writer.execute_batch("COMMIT;").unwrap();204
drop(writer);205
assert_eq!(store.meta("key").unwrap().as_deref(), Some("during"));206
}207
}@@ -7,7 +7,7 @@ use crate::time::{optional_from_millis, optional_to_millis};
7
7
8
8
impl Store {
9
9
pub fn sync_state(&self, conversation_id: &str) -> Result<Option<SyncState>> {
10
let connection = self.lock()?;
10
let connection = self.read()?;
11
11
let state = connection
12
12
.query_row(
13
13
"SELECT newest_seen, oldest_loaded, has_more, older_cursor, delta_link FROM sync_state WHERE conversation_id = ?1",
@@ -7,7 +7,7 @@ use crate::time::{optional_from_millis, optional_to_millis};7
7
8
impl Store {8
impl Store {9
pub fn sync_state(&self, conversation_id: &str) -> Result<Option<SyncState>> {9
pub fn sync_state(&self, conversation_id: &str) -> Result<Option<SyncState>> {10
let connection = self.lock()?;10
let connection = self.read()?;11
let state = connection11
let state = connection12
.query_row(12
.query_row(13
"SELECT newest_seen, oldest_loaded, has_more, older_cursor, delta_link FROM sync_state WHERE conversation_id = ?1",13
"SELECT newest_seen, oldest_loaded, has_more, older_cursor, delta_link FROM sync_state WHERE conversation_id = ?1",@@ -110,7 +110,7 @@ impl Store {
110
110
}
111
111
112
112
pub fn team(&self, team_id: &str) -> Result<Option<TeamRecord>> {
113
let connection = self.lock()?;
113
let connection = self.read()?;
114
114
Ok(connection
115
115
.query_row(
116
116
"SELECT id, name FROM teams WHERE id = ?1",
@@ -126,7 +126,7 @@ impl Store {
126
126
}
127
127
128
128
pub fn channel_read_until(&self, channel_id: &str) -> Result<Option<DateTime<Utc>>> {
129
let connection = self.lock()?;
129
let connection = self.read()?;
130
130
let read_until: Option<Option<i64>> = connection
131
131
.query_row(
132
132
"SELECT read_until FROM channels WHERE id = ?1",
@@ -138,7 +138,7 @@ impl Store {
138
138
}
139
139
140
140
pub fn channel(&self, channel_id: &str) -> Result<Option<ChannelRecord>> {
141
let connection = self.lock()?;
141
let connection = self.read()?;
142
142
let mut statement = connection.prepare_cached(&format!(
143
143
"SELECT {CHANNEL_COLUMNS} FROM channels WHERE id = ?1"
144
144
))?;
@@ -110,7 +110,7 @@ impl Store {110
}110
}111
111
112
pub fn team(&self, team_id: &str) -> Result<Option<TeamRecord>> {112
pub fn team(&self, team_id: &str) -> Result<Option<TeamRecord>> {113
let connection = self.lock()?;113
let connection = self.read()?;114
Ok(connection114
Ok(connection115
.query_row(115
.query_row(116
"SELECT id, name FROM teams WHERE id = ?1",116
"SELECT id, name FROM teams WHERE id = ?1",@@ -126,7 +126,7 @@ impl Store {126
}126
}127
127
128
pub fn channel_read_until(&self, channel_id: &str) -> Result<Option<DateTime<Utc>>> {128
pub fn channel_read_until(&self, channel_id: &str) -> Result<Option<DateTime<Utc>>> {129
let connection = self.lock()?;129
let connection = self.read()?;130
let read_until: Option<Option<i64>> = connection130
let read_until: Option<Option<i64>> = connection131
.query_row(131
.query_row(132
"SELECT read_until FROM channels WHERE id = ?1",132
"SELECT read_until FROM channels WHERE id = ?1",@@ -138,7 +138,7 @@ impl Store {138
}138
}139
139
140
pub fn channel(&self, channel_id: &str) -> Result<Option<ChannelRecord>> {140
pub fn channel(&self, channel_id: &str) -> Result<Option<ChannelRecord>> {141
let connection = self.lock()?;141
let connection = self.read()?;142
let mut statement = connection.prepare_cached(&format!(142
let mut statement = connection.prepare_cached(&format!(143
"SELECT {CHANNEL_COLUMNS} FROM channels WHERE id = ?1"143
"SELECT {CHANNEL_COLUMNS} FROM channels WHERE id = ?1"144
))?;144
))?;