diff --git a/COMPAT.md b/COMPAT.md index 7cd85a867..c062d52b3 100644 --- a/COMPAT.md +++ b/COMPAT.md @@ -287,7 +287,7 @@ avoid this window. | PRAGMA vdbe_debug | ❌ No | | | PRAGMA vdbe_listing | ❌ No | | | PRAGMA vdbe_trace | ✅ Yes | | -| PRAGMA wal_autocheckpoint | ❌ No | | +| PRAGMA wal_autocheckpoint | ✅ Yes | | | PRAGMA wal_checkpoint | 🚧 Partial | Not Needed calling with param (pragma-value) | | PRAGMA writable_schema | ❌ No | | diff --git a/core/connection.rs b/core/connection.rs index 8ac2cf96c..98ad8812e 100644 --- a/core/connection.rs +++ b/core/connection.rs @@ -2507,6 +2507,11 @@ impl Connection { self.wal_autocheckpoint.load(Ordering::SeqCst) } + pub(crate) fn set_wal_autocheckpoint(&self, frames: u32) { + self.wal_autocheckpoint.store(frames, Ordering::SeqCst); + self.bump_prepare_context_generation(); + } + /// Publish the connection's current schema snapshot to the shared database /// cache after a successful commit so other live connections can refresh. pub fn publish_schema_if_newer(&self) { diff --git a/core/pragma.rs b/core/pragma.rs index cfd85d986..26a863138 100644 --- a/core/pragma.rs +++ b/core/pragma.rs @@ -141,6 +141,7 @@ pub fn pragma_for(pragma: &PragmaName) -> Pragma { PragmaFlags::NoColumns1 | PragmaFlags::Result0, &["user_version"], ), + WalAutocheckpoint => Pragma::new(PragmaFlags::empty(), &["wal_autocheckpoint"]), WalCheckpoint => Pragma::new(PragmaFlags::NeedSchema, &["busy", "log", "checkpointed"]), AutoVacuum => Pragma::new( PragmaFlags::NoColumns1 | PragmaFlags::Result0, diff --git a/core/storage/wal.rs b/core/storage/wal.rs index 41bfebe0e..1f1ce279e 100644 --- a/core/storage/wal.rs +++ b/core/storage/wal.rs @@ -4097,8 +4097,11 @@ impl Wal for WalFile { #[instrument(skip_all, level = Level::DEBUG)] fn should_checkpoint(&self, checkpoint_threshold: u32) -> bool { + if checkpoint_threshold == 0 { + return false; + } let snapshot = self.load_coordination_snapshot(); - snapshot.max_frame as usize > checkpoint_threshold as usize + snapshot.nbackfills as usize + snapshot.max_frame > u64::from(checkpoint_threshold) + snapshot.nbackfills } #[instrument(skip_all, level = Level::DEBUG)] diff --git a/core/translate/pragma.rs b/core/translate/pragma.rs index b7f0bb479..43b07cd81 100644 --- a/core/translate/pragma.rs +++ b/core/translate/pragma.rs @@ -442,6 +442,29 @@ fn update_pragma( PragmaName::LegacyFileFormat | PragmaName::EmptyResultCallbacks => { Ok(TransactionMode::None) } + PragmaName::WalAutocheckpoint => { + let data = parse_signed_number(&value)?; + let frames = match data { + Value::Numeric(Numeric::Integer(i)) => i, + Value::Numeric(Numeric::Float(f)) => f64::from(f) as i64, + _ => bail_parse_error!("expected integer, got {:?}", data), + }; + let frames = i32::try_from(frames) + .ok() + .and_then(|frames| u32::try_from(frames).ok()) + .unwrap_or(0); + connection.set_wal_autocheckpoint(frames); + query_pragma( + PragmaName::WalAutocheckpoint, + resolver, + None, + pager, + connection, + database_id, + schema_was_explicit, + program, + ) + } PragmaName::WalCheckpoint => query_pragma( PragmaName::WalCheckpoint, resolver, @@ -931,6 +954,12 @@ fn query_pragma( PragmaName::LegacyFileFormat | PragmaName::EmptyResultCallbacks => { Ok(TransactionMode::None) } + PragmaName::WalAutocheckpoint => { + program.emit_int(i64::from(connection.get_wal_autocheckpoint()), register); + program.emit_result_row(register, 1); + program.add_pragma_result_column(pragma.to_string()); + Ok(TransactionMode::None) + } PragmaName::WalCheckpoint => { // Checkpoint uses 3 registers: P1, P2, P3. Ref Insn::Checkpoint for more info. // Allocate two more here as one was allocated at the top. diff --git a/docs/sql-reference/pragmas.mdx b/docs/sql-reference/pragmas.mdx index f099fad4e..b6e22679a 100644 --- a/docs/sql-reference/pragmas.mdx +++ b/docs/sql-reference/pragmas.mdx @@ -378,6 +378,18 @@ PRAGMA wal_checkpoint; A checkpoint writes pages from the WAL file back to the database file. +### wal_autocheckpoint + +Returns or sets how many pages the WAL can hold before a commit on this connection runs a checkpoint. The default is 1000 pages. Zero or a negative value turns automatic checkpoints off. + +```sql +PRAGMA wal_autocheckpoint; +PRAGMA wal_autocheckpoint = 1000; +PRAGMA wal_autocheckpoint = 0; -- turn automatic checkpoints off +``` + +The setting applies only to the connection that sets it. Closing the last connection to the database still checkpoints the WAL. In MVCC mode the setting has no effect; use `mvcc_checkpoint_threshold` instead. + ## MVCC Tuning diff --git a/sqlite/conformance/sqlite-sqltests/pragma/memory.sqltest b/sqlite/conformance/sqlite-sqltests/pragma/memory.sqltest index d7609bcd3..32b5ea8fd 100644 --- a/sqlite/conformance/sqlite-sqltests/pragma/memory.sqltest +++ b/sqlite/conformance/sqlite-sqltests/pragma/memory.sqltest @@ -323,3 +323,46 @@ test pragma-page-size-set-uninitialized-db { expect { 1024 } + +test pragma-wal-autocheckpoint-default { + PRAGMA wal_autocheckpoint; +} +expect { + 1000 +} + +test pragma-wal-autocheckpoint-update { + PRAGMA wal_autocheckpoint = 100; + PRAGMA wal_autocheckpoint; +} +expect { + 100 + 100 +} + +test pragma-wal-autocheckpoint-zero { + PRAGMA wal_autocheckpoint = 0; + PRAGMA wal_autocheckpoint; +} +expect { + 0 + 0 +} + +test pragma-wal-autocheckpoint-negative-value-reads-back-as-zero { + PRAGMA wal_autocheckpoint = -5; + PRAGMA wal_autocheckpoint; +} +expect { + 0 + 0 +} + +test pragma-wal-autocheckpoint-value-above-int-range-reads-back-as-zero { + PRAGMA wal_autocheckpoint = 2147483648; + PRAGMA wal_autocheckpoint; +} +expect { + 0 + 0 +} diff --git a/sqlite/parser/src/ast.rs b/sqlite/parser/src/ast.rs index a26131e47..ed8419cdf 100644 --- a/sqlite/parser/src/ast.rs +++ b/sqlite/parser/src/ast.rs @@ -1971,6 +1971,8 @@ pub enum PragmaName { UnstableCaptureDataChangesConn, /// Returns the user version of the database file. UserVersion, + /// Sets or queries the number of WAL frames after which a commit runs an automatic checkpoint. + WalAutocheckpoint, /// trigger a checkpoint to run on database(s) if WAL is enabled WalCheckpoint, /// Sets or queries the threshold (in bytes) at which MVCC triggers an automatic checkpoint. diff --git a/tests/integration/pragma.rs b/tests/integration/pragma.rs index e2b0ad284..a2cb51517 100644 --- a/tests/integration/pragma.rs +++ b/tests/integration/pragma.rs @@ -300,6 +300,50 @@ fn test_pragma_wal_checkpoint_targets_attached_database(db: TempDatabase) { ); } +#[turso_macros::test] +fn test_pragma_wal_autocheckpoint_zero_keeps_every_frame_in_the_wal(db: TempDatabase) { + let conn = db.connect_limbo(); + conn.execute("PRAGMA wal_autocheckpoint = 0").unwrap(); + conn.execute("CREATE TABLE t1(a)").unwrap(); + conn.execute("INSERT INTO t1 SELECT randomblob(4000) FROM generate_series(1, 1500)") + .unwrap(); + conn.execute("INSERT INTO t1 VALUES (1)").unwrap(); + + assert_that!(limbo_exec_rows(&conn, "PRAGMA wal_checkpoint")) + .single_element() + .satisfies_with_message( + "keep a frame for each of the 1500 rows in the WAL", + |row| matches!(row[..], [RValue::Integer(0), RValue::Integer(log), _] if log > 1500), + ); +} + +#[turso_macros::test] +fn test_pragma_wal_autocheckpoint_small_threshold_checkpoints_after_commit(db: TempDatabase) { + let conn = db.connect_limbo(); + conn.execute("PRAGMA wal_autocheckpoint = 10").unwrap(); + conn.execute("CREATE TABLE t1(a)").unwrap(); + conn.execute("INSERT INTO t1 SELECT randomblob(4000) FROM generate_series(1, 20)") + .unwrap(); + conn.execute("INSERT INTO t1 VALUES (1)").unwrap(); + + assert_that!(limbo_exec_rows(&conn, "PRAGMA wal_checkpoint")) + .single_element() + .satisfies_with_message( + "restart the WAL after the 20 rows were checkpointed", + |row| matches!(row[..], [RValue::Integer(0), RValue::Integer(log), _] if log < 20), + ); +} + +#[turso_macros::test] +fn test_pragma_wal_autocheckpoint_is_per_connection(db: TempDatabase) { + let conn1 = db.connect_limbo(); + let conn2 = db.connect_limbo(); + conn1.execute("PRAGMA wal_autocheckpoint = 0").unwrap(); + + assert_that!(limbo_exec_rows(&conn2, "PRAGMA wal_autocheckpoint")) + .is_equal_to(vec![row![1000]]); +} + // Regression tests for https://github.com/tursodatabase/turso/issues/7466: // querying a pragma virtual table (pragma_table_info, pragma_function_list, ...) // left the connection's implicit read transaction open, so every subsequent