core: implement PRAGMA wal_autocheckpoint

Applications that run checkpoints themselves, or that want the WAL to
grow more or less than 1000 pages, set PRAGMA wal_autocheckpoint as
SQLite documents it. Turso ignored the pragma as an unknown name, so a
connection that turned automatic checkpoints off still got one after
any commit that left more than 1000 frames in the WAL.

PRAGMA wal_autocheckpoint returns the connection's threshold, 1000 by
default. PRAGMA wal_autocheckpoint = N sets it for this connection only
and returns the new value. Zero, a negative value, or a value too large
for a 32-bit int turns automatic checkpoints off and reads back as 0,
as in SQLite.

Closing the last connection still checkpoints the WAL: SQLite runs that
checkpoint whatever this setting is. Like SQLite, the pragma has no
pragma_wal_autocheckpoint table-valued function.

Tests: cargo test -p core_tester --test integration_tests pragma_wal_autocheckpoint
Tests: sqltest run sqlite-sqltests/pragma/memory.sqltest -f 'pragma-wal-autocheckpoint-*'
This commit is contained in:
Iann29
2026-10-03 12:15:20 -03:00
parent 6c5ec2e1d0
commit d195edd38c
9 changed files with 141 additions and 2 deletions

View File

@@ -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 | |

View File

@@ -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) {

View File

@@ -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,

View File

@@ -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)]

View File

@@ -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.

View File

@@ -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
<Info>

View File

@@ -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
}

View File

@@ -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.

View File

@@ -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