Skip to content

Commit

Permalink
Fix potential errors in SQLite code
Browse files Browse the repository at this point in the history
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
  • Loading branch information
zecakeh committed Sep 1, 2024
1 parent b3b61fe commit 84d83d1
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions crates/matrix-sdk-sqlite/src/event_cache_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<i64>>(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",
Expand Down

0 comments on commit 84d83d1

Please sign in to comment.