Skip to content

Commit 84d83d1

Browse files
committed
Fix potential errors in SQLite code
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
1 parent b3b61fe commit 84d83d1

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

crates/matrix-sdk-sqlite/src/event_cache_store.rs

+14-4
Original file line numberDiff line numberDiff line change
@@ -279,10 +279,20 @@ impl EventCacheStore for SqliteEventCacheStore {
279279

280280
// Finally, if the cache size is too big, remove old items until it fits.
281281
if let Some(max_cache_size) = policy.max_cache_size {
282-
let cache_size: usize =
283-
txn.query_row("SELECT sum(length(data)) FROM media", (), |row| row.get(0))?;
284-
285-
if cache_size > max_cache_size {
282+
// i64 is the integer type used by SQLite, use it here to avoid usize overflow
283+
// during the conversion of the result.
284+
let cache_size_int = txn
285+
.query_row("SELECT sum(length(data)) FROM media", (), |row| {
286+
// `sum()` returns `NULL` if there are no rows.
287+
row.get::<_, Option<i64>>(0)
288+
})?
289+
.unwrap_or_default();
290+
let cache_size_usize = usize::try_from(cache_size_int);
291+
292+
// If the cache size is overflowing or bigger than max cache size, clean up.
293+
if cache_size_usize.is_err()
294+
|| cache_size_usize.is_ok_and(|cache_size| cache_size > max_cache_size)
295+
{
286296
// Get the sizes of the media contents ordered by last access.
287297
let mut cached_stmt = txn.prepare_cached(
288298
"SELECT rowid, length(data) FROM media ORDER BY last_access DESC",

0 commit comments

Comments
 (0)