@@ -12,6 +12,11 @@ use std::sync::Arc;
1212use std:: sync:: atomic:: { AtomicBool , Ordering } ;
1313use tracing:: error;
1414
15+ /// Analysis limit for PRAGMA optimize on close.
16+ /// SQLite recommends 100-1000 for older versions; 3.46.0+ handles automatically.
17+ /// See: https://www.sqlite.org/lang_analyze.html#recommended_usage_pattern
18+ const OPTIMIZE_ANALYSIS_LIMIT : u32 = 400 ;
19+
1520/// SQLite database with connection pooling for concurrent reads and optional exclusive writes.
1621///
1722/// Once the database is opened it can be used for read-only operations by calling `read_pool()`.
@@ -144,16 +149,11 @@ impl SqliteDatabase {
144149 drop ( conn) ; // Close immediately after creating the file
145150 }
146151
147- // Enable PRAGMA optimize on close as recommended by SQLite for long-lived databases.
148- // SQLite recommends analysis_limit values between 100-1000 for older versions;
149- // SQLite 3.46.0+ handles limits automatically.
150- // https://www.sqlite.org/lang_analyze.html#recommended_usage_pattern
151- //
152152 // Create read pool with read-only connections
153153 let read_options = SqliteConnectOptions :: new ( )
154154 . filename ( & path)
155155 . read_only ( true )
156- . optimize_on_close ( true , 400 ) ;
156+ . optimize_on_close ( true , OPTIMIZE_ANALYSIS_LIMIT ) ;
157157
158158 let read_pool = SqlitePoolOptions :: new ( )
159159 . max_connections ( config. max_read_connections )
@@ -168,7 +168,7 @@ impl SqliteDatabase {
168168 let write_options = SqliteConnectOptions :: new ( )
169169 . filename ( & path)
170170 . read_only ( false )
171- . optimize_on_close ( true , 400 ) ;
171+ . optimize_on_close ( true , OPTIMIZE_ANALYSIS_LIMIT ) ;
172172
173173 let write_conn = SqlitePoolOptions :: new ( )
174174 . max_connections ( 1 )
@@ -250,8 +250,12 @@ impl SqliteDatabase {
250250 // Acquire connection from pool (max=1 ensures exclusive access)
251251 let mut conn = self . write_conn . acquire ( ) . await ?;
252252
253- // Initialize WAL mode on first use (idempotent and safe)
254- if !self . wal_initialized . load ( Ordering :: SeqCst ) {
253+ // Initialize WAL mode on first use (atomic check-and-set)
254+ if self
255+ . wal_initialized
256+ . compare_exchange ( false , true , Ordering :: SeqCst , Ordering :: SeqCst )
257+ . is_ok ( )
258+ {
255259 sqlx:: query ( "PRAGMA journal_mode = WAL" )
256260 . execute ( & mut * conn)
257261 . await ?;
@@ -260,8 +264,6 @@ impl SqliteDatabase {
260264 sqlx:: query ( "PRAGMA synchronous = NORMAL" )
261265 . execute ( & mut * conn)
262266 . await ?;
263-
264- self . wal_initialized . store ( true , Ordering :: SeqCst ) ;
265267 }
266268
267269 // Return WriteGuard wrapping the pool connection
0 commit comments