SQLite's WAL (Write-Ahead Logging) mode is an important performance optimization mechanism:
-
WAL Mode Principle
- Traditional rollback journal mode: Write operations directly modify the database file, using rollback journal to record changes
- WAL mode: Write operations write changes to the WAL file instead of directly modifying the database file
- During checkpoint, the contents of the WAL file are merged into the main database file
-
Advantages of WAL Mode
- Improved Concurrency: Read operations do not block write operations, write operations do not block read operations
- Reduced Disk I/O: Write operations are usually sequential, faster than random writes
- Better Crash Recovery: The WAL file contains all uncommitted changes, recovery is more reliable
- Improved Write Performance: Multiple writes can be batch committed, reducing synchronization operations
-
Enabling WAL Mode
sqlPRAGMA journal_mode = WAL; -
WAL File Management
- WAL files are in the same directory as the database file, with suffixes
-waland-shm -walfile stores the actual WAL data-shmfile is a shared memory file used to coordinate concurrent access
- WAL files are in the same directory as the database file, with suffixes
-
Checkpoint Mechanism
- Automatic checkpoint: Automatically triggered when the WAL file reaches a certain size
- Manual checkpoint: Use
PRAGMA wal_checkpoint(TRUNCATE);to manually trigger - Checkpoint merges valid changes from the WAL file into the main database file
-
Limitations of WAL Mode
- Not supported by some older SQLite versions
- May be unreliable on network file systems
- Requires additional disk space to store WAL files
- May cause database file growth in some cases
-
Applicable Scenarios
- High concurrent read-write scenarios
- Need better crash recovery capabilities
- Write-intensive applications
- Mobile applications and desktop applications
WAL mode is the recommended default configuration for SQLite, which can significantly improve performance in most application scenarios.