Skip to content

Commit 28d5e57

Browse files
committed
fix(event cache): enable foreign keys on a connection basis
As opposed to WAL mode, foreign keys must be enabled for each database connection, according to https://www.sqlite.org/foreignkeys.html#fk_enable Unfortunately, we can't track which connection objects have already executed the pragma, so the safer we can do is enable it everytime we try to acquire a connection from the pool. Fixes #4785.
1 parent 6a1e1e8 commit 28d5e57

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

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

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,15 @@ impl SqliteEventCacheStore {
156156
}
157157

158158
async fn acquire(&self) -> Result<SqliteAsyncConn> {
159-
Ok(self.pool.get().await?)
159+
let connection = self.pool.get().await?;
160+
161+
// Per https://www.sqlite.org/foreignkeys.html#fk_enable, foreign key support must be
162+
// enabled on a per-connection basis. Execute it every time we try to get a
163+
// connection, since we can't guarantee a previous connection did
164+
// enabled it before.
165+
connection.execute_batch("PRAGMA foreign_keys = ON;").await?;
166+
167+
Ok(connection)
160168
}
161169

162170
fn map_row_to_chunk(
@@ -302,6 +310,9 @@ async fn run_migrations(conn: &SqliteAsyncConn, version: u8) -> Result<()> {
302310
return Ok(());
303311
}
304312

313+
// Always enable foreign keys for the current connection.
314+
conn.execute_batch("PRAGMA foreign_keys = ON;").await?;
315+
305316
if version < 1 {
306317
// First turn on WAL mode, this can't be done in the transaction, it fails with
307318
// the error message: "cannot change into wal mode from within a transaction".
@@ -322,9 +333,6 @@ async fn run_migrations(conn: &SqliteAsyncConn, version: u8) -> Result<()> {
322333
}
323334

324335
if version < 3 {
325-
// Enable foreign keys for this database.
326-
conn.execute_batch("PRAGMA foreign_keys = ON;").await?;
327-
328336
conn.with_transaction(|txn| {
329337
txn.execute_batch(include_str!("../migrations/event_cache_store/003_events.sql"))?;
330338
txn.set_db_version(3)

0 commit comments

Comments
 (0)