diff --git a/crates/matrix-sdk-sqlite/src/event_cache_store.rs b/crates/matrix-sdk-sqlite/src/event_cache_store.rs index 54acde4814..bf325dd0bb 100644 --- a/crates/matrix-sdk-sqlite/src/event_cache_store.rs +++ b/crates/matrix-sdk-sqlite/src/event_cache_store.rs @@ -279,10 +279,20 @@ impl EventCacheStore for SqliteEventCacheStore { // Finally, if the cache size is too big, remove old items until it fits. if let Some(max_cache_size) = policy.max_cache_size { - let cache_size: usize = - txn.query_row("SELECT sum(length(data)) FROM media", (), |row| row.get(0))?; - - if cache_size > max_cache_size { + // i64 is the integer type used by SQLite, use it here to avoid usize overflow + // during the conversion of the result. + let cache_size_int = txn + .query_row("SELECT sum(length(data)) FROM media", (), |row| { + // `sum()` returns `NULL` if there are no rows. + row.get::<_, Option>(0) + })? + .unwrap_or_default(); + let cache_size_usize = usize::try_from(cache_size_int); + + // If the cache size is overflowing or bigger than max cache size, clean up. + if cache_size_usize.is_err() + || cache_size_usize.is_ok_and(|cache_size| cache_size > max_cache_size) + { // Get the sizes of the media contents ordered by last access. let mut cached_stmt = txn.prepare_cached( "SELECT rowid, length(data) FROM media ORDER BY last_access DESC",