Debian Codegraph @

www/wal.html

raw
1 <!DOCTYPE html>
2 <html><head>
3 <meta name="viewport" content="width=device-width, initial-scale=1.0">
4 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
5 <link href="sqlite.css" rel="stylesheet">
6 <title>Write-Ahead Logging</title>
7 <!-- path= -->
8 </head>
9 <body>
10 <div class=nosearch>
11 <a href="index.html">
12 <img class="logo" src="images/sqlite370_banner.gif" alt="SQLite" border="0">
13 </a>
14 <div><!-- IE hack to prevent disappearing logo --></div>
15 <div class="tagline desktoponly">
16 Small. Fast. Reliable.<br>Choose any three.
17 </div>
18 <div class="menu mainmenu">
19 <ul>
20 <li><a href="index.html">Home</a>
21 <li class='mobileonly'><a href="javascript:void(0)" onclick='toggle_div("submenu")'>Menu</a>
22 <li class='wideonly'><a href='about.html'>About</a>
23 <li class='desktoponly'><a href="docs.html">Documentation</a>
24 <li class='desktoponly'><a href="download.html">Download</a>
25 <li class='wideonly'><a href='copyright.html'>License</a>
26 <li class='desktoponly'><a href="support.html">Support</a>
27 <li class='desktoponly'><a href="prosupport.html">Purchase</a>
28 <li class='search' id='search_menubutton'>
29 <a href="javascript:void(0)" onclick='toggle_search()'>Search</a>
30 </ul>
31 </div>
32 <div class="menu submenu" id="submenu">
33 <ul>
34 <li><a href='about.html'>About</a>
35 <li><a href='docs.html'>Documentation</a>
36 <li><a href='download.html'>Download</a>
37 <li><a href='support.html'>Support</a>
38 <li><a href='prosupport.html'>Purchase</a>
39 </ul>
40 </div>
41 <div class="searchmenu" id="searchmenu">
42 <form method="GET" action="search">
43 <select name="s" id="searchtype">
44 <option value="d">Search Documentation</option>
45 <option value="c">Search Changelog</option>
46 </select>
47 <input type="text" name="q" id="searchbox" value="">
48 <input type="submit" value="Go">
49 </form>
50 </div>
51 </div>
52 <script>
53 function toggle_div(nm) {
54 var w = document.getElementById(nm);
55 if( w.style.display=="block" ){
56 w.style.display = "none";
57 }else{
58 w.style.display = "block";
59 }
60 }
61 function toggle_search() {
62 var w = document.getElementById("searchmenu");
63 if( w.style.display=="block" ){
64 w.style.display = "none";
65 } else {
66 w.style.display = "block";
67 setTimeout(function(){
68 document.getElementById("searchbox").focus()
69 }, 30);
70 }
71 }
72 function div_off(nm){document.getElementById(nm).style.display="none";}
73 window.onbeforeunload = function(e){div_off("submenu");}
74 /* Disable the Search feature if we are not operating from CGI, since */
75 /* Search is accomplished using CGI and will not work without it. */
76 if( !location.origin || !location.origin.match || !location.origin.match(/http/) ){
77 document.getElementById("search_menubutton").style.display = "none";
78 }
79 /* Used by the Hide/Show button beside syntax diagrams, to toggle the */
80 function hideorshow(btn,obj){
81 var x = document.getElementById(obj);
82 var b = document.getElementById(btn);
83 if( x.style.display!='none' ){
84 x.style.display = 'none';
85 b.innerHTML='show';
86 }else{
87 x.style.display = '';
88 b.innerHTML='hide';
89 }
90 return false;
91 }
92 var antiRobot = 0;
93 function antiRobotGo(){
94 if( antiRobot!=3 ) return;
95 antiRobot = 7;
96 var j = document.getElementById("mtimelink");
97 if(j && j.hasAttribute("data-href")) j.href=j.getAttribute("data-href");
98 }
99 function antiRobotDefense(){
100 document.body.onmousedown=function(){
101 antiRobot |= 2;
102 antiRobotGo();
103 document.body.onmousedown=null;
104 }
105 document.body.onmousemove=function(){
106 antiRobot |= 2;
107 antiRobotGo();
108 document.body.onmousemove=null;
109 }
110 setTimeout(function(){
111 antiRobot |= 1;
112 antiRobotGo();
113 }, 100)
114 antiRobotGo();
115 }
116 antiRobotDefense();
117 </script>
118 <div class=fancy>
119 <div class=nosearch>
120 <div class="fancy_title">
121 Write-Ahead Logging
122 </div>
123 <div class="fancy_toc">
124 <a onclick="toggle_toc()">
125 <span class="fancy_toc_mark" id="toc_mk">&#x25ba;</span>
126 Table Of Contents
127 </a>
128 <div id="toc_sub"><div class="fancy-toc1"><a href="#overview">1. Overview</a></div>
129 <div class="fancy-toc1"><a href="#how_wal_works">2. How WAL Works</a></div>
130 <div class="fancy-toc2"><a href="#checkpointing">2.1. Checkpointing</a></div>
131 <div class="fancy-toc2"><a href="#concurrency">2.2. Concurrency</a></div>
132 <div class="fancy-toc2"><a href="#performance_considerations">2.3. Performance Considerations</a></div>
133 <div class="fancy-toc1"><a href="#activating_and_configuring_wal_mode">3. Activating And Configuring WAL Mode</a></div>
134 <div class="fancy-toc2"><a href="#automatic_checkpoint">3.1. Automatic Checkpoint</a></div>
135 <div class="fancy-toc2"><a href="#application_initiated_checkpoints">3.2. Application-Initiated Checkpoints</a></div>
136 <div class="fancy-toc2"><a href="#persistence_of_wal_mode">3.3. Persistence of WAL mode</a></div>
137 <div class="fancy-toc1"><a href="#the_wal_file">4. The WAL File</a></div>
138 <div class="fancy-toc1"><a href="#read_only_databases">5. Read-Only Databases</a></div>
139 <div class="fancy-toc1"><a href="#avoiding_excessively_large_wal_files">6. Avoiding Excessively Large WAL Files</a></div>
140 <div class="fancy-toc1"><a href="#implementation_of_shared_memory_for_the_wal_index">7. Implementation Of Shared-Memory For The WAL-Index</a></div>
141 <div class="fancy-toc1"><a href="#use_of_wal_without_shared_memory">8. Use of WAL Without Shared-Memory</a></div>
142 <div class="fancy-toc1"><a href="#sometimes_queries_return_sqlite_busy_in_wal_mode">9. Sometimes Queries Return SQLITE_BUSY In WAL Mode</a></div>
143 <div class="fancy-toc1"><a href="#backwards_compatibility">10. Backwards Compatibility</a></div>
144 </div>
145 </div>
146 <script>
147 function toggle_toc(){
148 var sub = document.getElementById("toc_sub")
149 var mk = document.getElementById("toc_mk")
150 if( sub.style.display!="block" ){
151 sub.style.display = "block";
152 mk.innerHTML = "&#x25bc;";
153 } else {
154 sub.style.display = "none";
155 mk.innerHTML = "&#x25ba;";
156 }
157 }
158 </script>
159 </div>
160
161
162
163
164
165 <h1 id="overview"><span>1. </span>Overview</h1>
166
167 <p>The default method by which SQLite implements
168 <a href="atomiccommit.html">atomic commit and rollback</a> is a <a href="lockingv3.html#rollback">rollback journal</a>.
169 Beginning with <a href="releaselog/3_7_0.html">version 3.7.0</a> (2010-07-21), a new "Write-Ahead Log" option
170 (hereafter referred to as "WAL") is available.</p>
171
172 <p>There are advantages and disadvantages to using WAL instead of
173 a rollback journal. Advantages include:</p>
174
175 <a name="advantages"></a>
176
177 <ol>
178 <li>WAL is significantly faster in most scenarios.
179 </li><li>WAL provides more concurrency as readers do not block writers and
180 a writer does not block readers. Reading and writing can proceed
181 concurrently.
182 </li><li>Disk I/O operations tends to be more sequential using WAL.
183 </li><li>WAL uses many fewer fsync() operations and is thus less vulnerable to
184 problems on systems where the fsync() system call is broken.
185 </li></ol>
186
187 <p>But there are also disadvantages:</p>
188
189 <ol>
190 <li>All processes using a database must be on the same host computer;
191 WAL does not work over a network filesystem. This is because WAL requires
192 all processes to share a small amount of memory and processes on
193 separate host machines obviously cannot share memory with each other.
194 </li><li>Transactions that involve changes against multiple <a href="lang_attach.html">ATTACHed</a>
195 databases are atomic for each individual database, but are not
196 atomic across all databases as a set.
197 </li><li>It is not possible to change the <a href="pragma.html#pragma_page_size">page_size</a> after entering WAL
198 mode, either on an empty database or by using <a href="lang_vacuum.html">VACUUM</a> or by restoring
199 from a backup using the <a href="backup.html">backup API</a>. You must be in a rollback journal
200 mode to change the page size.
201 </li><li><s>It is not possible to open <a href="wal.html#readonly">read-only WAL databases</a>.
202 The opening process must have write privileges for "<tt>-shm</tt>"
203 <a href="walformat.html#shm">wal-index</a> shared memory file associated with the database, if that
204 file exists, or else write access on the directory containing
205 the database file if the "<tt>-shm</tt>" file does not exist.</s>
206 Beginning with <a href="releaselog/3_22_0.html">version 3.22.0</a> (2018-01-22), a read-only
207 WAL-mode database file can be opened if
208 the <tt>-shm</tt> and <tt>-wal</tt> files
209 already exists or those files can be created or the
210 <a href="uri.html#uriimmutable">database is immutable</a>.
211 </li><li>WAL might be very slightly slower (perhaps 1% or 2% slower)
212 than the traditional rollback-journal approach
213 in applications that do mostly reads and seldom write.
214 </li><li>There is an additional quasi-persistent "<tt>-wal</tt>" file and
215 "<tt>-shm</tt>" shared memory file associated with each
216 database, which can make SQLite less appealing for use as an
217 <a href="appfileformat.html">application file-format</a>.
218 </li><li>There is the extra operation of <a href="wal.html#ckpt">checkpointing</a> which, though automatic
219 by default, is still something that application developers need to
220 be mindful of.
221 </li><li><s>WAL works best with smaller transactions. WAL does
222 not work well for very large transactions. For transactions larger than
223 about 100 megabytes, traditional rollback journal modes will likely
224 be faster. For transactions in excess of a gigabyte, WAL mode may
225 fail with an I/O or disk-full error.
226 It is recommended that one of the rollback journal modes be used for
227 transactions larger than a few dozen megabytes.</s>
228 Beginning with <a href="releaselog/3_11_0.html">version 3.11.0</a> (2016-02-15),
229 WAL mode works as efficiently with
230 large transactions as does rollback mode.
231
232 </li></ol>
233
234 <h1 id="how_wal_works"><span>2. </span>How WAL Works</h1>
235
236 <p>The traditional rollback journal works by writing a copy of the
237 original unchanged database content into a separate rollback journal file
238 and then writing changes directly into the database file. In the
239 event of a crash or <a href="lang_transaction.html">ROLLBACK</a>, the original content contained in the
240 rollback journal is played back into the database file to
241 revert the database file to its original state. The <a href="lang_transaction.html">COMMIT</a> occurs
242 when the rollback journal is deleted.</p>
243
244 <p>The WAL approach inverts this. The original content is preserved
245 in the database file and the changes are appended into a separate
246 WAL file. A <a href="lang_transaction.html">COMMIT</a> occurs when a special record indicating a commit
247 is appended to the WAL. Thus a COMMIT can happen without ever writing
248 to the original database, which allows readers to continue operating
249 from the original unaltered database while changes are simultaneously being
250 committed into the WAL. Multiple transactions can be appended to the
251 end of a single WAL file.</p>
252
253 <a name="ckpt"></a>
254
255 <h2 id="checkpointing"><span>2.1. </span>Checkpointing</h2>
256
257 <p>Of course, one wants to eventually transfer all the transactions that
258 are appended in the WAL file back into the original database. Moving
259 the WAL file transactions back into the database is called a
260 "<i>checkpoint</i>".</p><p>
261
262 </p><p>Another way to think about the difference between rollback and
263 write-ahead log is that in the rollback-journal
264 approach, there are two primitive operations, reading and writing,
265 whereas with a write-ahead log
266 there are now three primitive operations: reading, writing, and
267 checkpointing.</p>
268
269 <p>By default, SQLite does a checkpoint automatically when the WAL file
270 reaches a threshold size of 1000 pages. (The
271 <a href="compile.html#default_wal_autocheckpoint">SQLITE_DEFAULT_WAL_AUTOCHECKPOINT</a> compile-time option can be used to
272 specify a different default.) Applications using WAL do
273 not have to do anything in order to for these checkpoints to occur.
274 But if they want to, applications can adjust the automatic checkpoint
275 threshold. Or they can turn off the automatic checkpoints and run
276 checkpoints during idle moments or in a separate thread or process.</p>
277
278 <a name="concurrency"></a>
279
280 <h2 id="concurrency"><span>2.2. </span>Concurrency</h2>
281
282 <p>When a read operation begins on a WAL-mode database, it first
283 remembers the location of the last valid commit record in the WAL.
284 Call this point the "end mark". Because the WAL can be growing and
285 adding new commit records while various readers connect to the database,
286 each reader can potentially have its own end mark. But for any
287 particular reader, the end mark is unchanged for the duration of the
288 transaction, thus ensuring that a single read transaction only sees
289 the database content as it existed at a single point in time.</p>
290
291 <p>When a reader needs a page of content, it first checks the WAL to
292 see if that page appears there, and if so it pulls in the last copy
293 of the page that occurs in the WAL prior to the reader's end mark.
294 If no copy of the page exists in the WAL prior to the reader's end mark,
295 then the page is read from the original database file. Readers can
296 exist in separate processes, so to avoid forcing every reader to scan
297 the entire WAL looking for pages (the WAL file can grow to
298 multiple megabytes, depending on how often checkpoints are run), a
299 data structure called the "wal-index" is maintained in shared memory
300 which helps readers locate pages in the WAL quickly and with a minimum
301 of I/O. The wal-index greatly improves the performance of readers,
302 but the use of shared memory means that all readers must exist on the
303 same machine. This is why the write-ahead log implementation will not
304 work on a network filesystem.</p>
305
306 <p>Writers merely append new content to the end of the WAL file.
307 Because writers do nothing that would interfere with the actions of
308 readers, writers and readers can run at the same time. However,
309 since there is only one WAL file, there can only be one writer at
310 a time.</p>
311
312 <p>A checkpoint operation takes content from the WAL file
313 and transfers it back into the original database file.
314 A checkpoint can run concurrently with readers, however the checkpoint
315 must stop when it reaches a page in the WAL that is past the end mark
316 of any current reader. The checkpoint has to stop at that point because
317 otherwise it might overwrite part of the database file that the reader
318 is actively using. The checkpoint remembers (in the wal-index) how far
319 it got and will resume transferring content from the WAL to the database
320 from where it left off on the next invocation.</p>
321
322 <p>Thus a long-running read transaction can prevent a checkpointer from
323 making progress. But presumably every read transaction will eventually
324 end and the checkpointer will be able to continue.</p>
325
326 <p>Whenever a write operation occurs, the writer checks how much progress
327 the checkpointer has made, and if the entire WAL has been transferred into
328 the database and synced and if no readers are making use of the WAL, then
329 the writer will rewind the WAL back to the beginning and start putting new
330 transactions at the beginning of the WAL. This mechanism prevents a WAL
331 file from growing without bound.</p>
332
333 <a name="fast"></a>
334
335 <h2 id="performance_considerations"><span>2.3. </span>Performance Considerations</h2>
336
337 <p>Write transactions are very fast since they only involve writing
338 the content once (versus twice for rollback-journal transactions)
339 and because the writes are all sequential. Further, syncing the
340 content to the disk is not required, as long as the application is
341 willing to sacrifice durability following a power loss or hard reboot.
342 (Writers sync the WAL on every transaction commit if
343 <a href="pragma.html#pragma_synchronous">PRAGMA synchronous</a> is set to FULL but omit this sync if
344 <a href="pragma.html#pragma_synchronous">PRAGMA synchronous</a> is set to NORMAL.)</p>
345
346 <p>On the other hand, read performance deteriorates as the WAL file
347 grows in size since each reader must check the WAL file for the content
348 and the time needed to check the WAL file is proportional
349 to the size of the WAL file. The wal-index helps find content
350 in the WAL file much faster, but performance still falls off with
351 increasing WAL file size. Hence, to maintain good read performance
352 it is important to keep the WAL file size down by
353 running checkpoints at regular intervals.</p>
354
355 <p>Checkpointing does require sync operations in order to avoid
356 the possibility of database corruption following a power loss
357 or hard reboot. The WAL must be synced to persistent storage
358 prior to moving content from the WAL into the database and the
359 database file must by synced prior to resetting the WAL.
360 Checkpoint also requires more seeking.
361 The checkpointer makes an effort to
362 do as many sequential page writes to the database as it can (the pages
363 are transferred from WAL to database in ascending order) but even
364 then there will typically be many seek operations interspersed among
365 the page writes. These factors combine to make checkpoints slower than
366 write transactions.</p>
367
368 <p>The default strategy is to allow successive write transactions to
369 grow the WAL until the WAL becomes about 1000 pages in size, then to
370 run a checkpoint operation for each subsequent COMMIT until the WAL
371 is reset to be smaller than 1000 pages. By default, the checkpoint will be
372 run automatically by the same thread that does the COMMIT that pushes
373 the WAL over its size limit. This has the effect of causing most
374 COMMIT operations to be very fast but an occasional COMMIT (those that trigger
375 a checkpoint) to be much slower. If that effect is undesirable, then
376 the application can disable automatic checkpointing and run the
377 periodic checkpoints in a separate thread, or separate process.
378 (Links to commands and interfaces to accomplish this are
379 <a href="#how_to_checkpoint">shown below</a>.)</p>
380
381
382 <p>Note that with <a href="pragma.html#pragma_synchronous">PRAGMA synchronous</a> set to NORMAL, the checkpoint
383 is the only operation to issue an I/O barrier or sync operation
384 (fsync() on unix or FlushFileBuffers() on windows). If an application
385 therefore runs checkpoint in a separate thread or process, the main
386 thread or process that is doing database queries and updates will never
387 block on a sync operation. This helps to prevent "latch-up" in applications
388 running on a busy disk drive. The downside to
389 this configuration is that transactions are no longer durable and
390 might rollback following a power failure or hard reset.</p>
391
392
393 <p>Notice too that there is a tradeoff between average read performance
394 and average write performance. To maximize the read performance,
395 one wants to keep the WAL as small as possible and hence run checkpoints
396 frequently, perhaps as often as every COMMIT. To maximize
397 write performance, one wants to amortize the cost of each checkpoint
398 over as many writes as possible, meaning that one wants to run checkpoints
399 infrequently and let the WAL grow as large as possible before each
400 checkpoint. The decision of how often to run checkpoints may therefore
401 vary from one application to another depending on the relative read
402 and write performance requirements of the application.
403 The default strategy is to run a checkpoint once the WAL
404 reaches 1000 pages and this strategy seems to work well in test applications on
405 workstations, but other strategies might work better on different
406 platforms or for different workloads.</p>
407
408 <h1 id="activating_and_configuring_wal_mode"><span>3. </span>Activating And Configuring WAL Mode</h1>
409
410 <p>An SQLite database connection defaults to
411 <a href="pragma.html#pragma_journal_mode">journal_mode=DELETE</a>. To convert to WAL mode, use the
412 following pragma:</p>
413
414 <blockquote><pre>
415 PRAGMA journal_mode=WAL;
416 </pre></blockquote>
417
418 <p>The journal_mode pragma returns a string which is the new journal mode.
419 On success, the pragma will return the string "<tt>wal</tt>". If
420 the conversion to WAL could not be completed (for example, if the <a href="vfs.html">VFS</a>
421 does not support the necessary shared-memory primitives) then the
422 journaling mode will be unchanged and the string returned from the
423 primitive will be the prior journaling mode (for example "<tt>delete</tt>").
424
425 <a name="how_to_checkpoint"></a>
426 </p><h2 id="automatic_checkpoint"><span>3.1. </span>Automatic Checkpoint</h2>
427
428 <p>By default, SQLite will automatically checkpoint whenever a <a href="lang_transaction.html">COMMIT</a>
429 occurs that causes the WAL file to be 1000 pages or more in size, or when the
430 last database connection on a database file closes. The default
431 configuration is intended to work well for most applications.
432 But programs that want more control can force a checkpoint
433 using the <a href="pragma.html#pragma_wal_checkpoint">wal_checkpoint pragma</a> or by calling the
434 <a href="c3ref/wal_checkpoint.html">sqlite3_wal_checkpoint()</a> C interface. The automatic checkpoint
435 threshold can be changed or automatic checkpointing can be completely
436 disabled using the <a href="pragma.html#pragma_wal_autocheckpoint">wal_autocheckpoint pragma</a> or by calling the
437 <a href="c3ref/wal_autocheckpoint.html">sqlite3_wal_autocheckpoint()</a> C interface. A program can also
438 use <a href="c3ref/wal_hook.html">sqlite3_wal_hook()</a> to register a callback to be invoked whenever
439 any transaction commits to the WAL. This callback can then invoke
440 <a href="c3ref/wal_checkpoint.html">sqlite3_wal_checkpoint()</a> or <a href="c3ref/wal_checkpoint_v2.html">sqlite3_wal_checkpoint_v2()</a> based on whatever
441 criteria it thinks is appropriate. (The automatic checkpoint mechanism
442 is implemented as a simple wrapper around <a href="c3ref/wal_hook.html">sqlite3_wal_hook()</a>.)</p>
443
444 <h2 id="application_initiated_checkpoints"><span>3.2. </span>Application-Initiated Checkpoints</h2>
445
446 <p>An application can initiate a checkpoint using any writable database
447 connection on the database simply by invoking
448 <a href="c3ref/wal_checkpoint.html">sqlite3_wal_checkpoint()</a> or <a href="c3ref/wal_checkpoint_v2.html">sqlite3_wal_checkpoint_v2()</a>.
449 There are three subtypes of checkpoints that vary in their aggressiveness:
450 PASSIVE, FULL, and RESTART. The default checkpoint style is PASSIVE, which
451 does as much work as it can without interfering with other database
452 connections, and which might not run to completion if there are
453 concurrent readers or writers.
454 All checkpoints initiated by <a href="c3ref/wal_checkpoint.html">sqlite3_wal_checkpoint()</a> and
455 by the automatic checkpoint mechanism are PASSIVE. FULL and RESTART
456 checkpoints try harder to run the checkpoint to completion and can only
457 be initiated by a call to <a href="c3ref/wal_checkpoint_v2.html">sqlite3_wal_checkpoint_v2()</a>. See the
458 <a href="c3ref/wal_checkpoint_v2.html">sqlite3_wal_checkpoint_v2()</a> documentation for additional information
459 on FULL and RESET checkpoints.
460
461 </p><h2 id="persistence_of_wal_mode"><span>3.3. </span>Persistence of WAL mode</h2>
462
463 <p>Unlike the other journaling modes,
464 <a href="pragma.html#pragma_journal_mode">PRAGMA journal_mode=WAL</a> is
465 persistent. If a process sets WAL mode, then closes and reopens the
466 database, the database will come back in WAL mode. In contrast, if
467 a process sets (for example) PRAGMA journal_mode=TRUNCATE and then closes and
468 reopens the database will come back up in the default rollback mode of
469 DELETE rather than the previous TRUNCATE setting.</p>
470
471 <p>The persistence of WAL mode means that applications can be converted
472 to using SQLite in WAL mode without making any changes to the application
473 itself. One has merely to run "<tt>PRAGMA journal_mode=WAL;</tt>" on the
474 database file(s) using the <a href="cli.html">command-line shell</a> or other utility, then
475 restart the application.</p>
476
477 <p>The WAL journal mode will be set on all
478 connections to the same database file if it is set on any one connection.
479 </p>
480
481 <a name="walfile"></a>
482
483 <h1 id="the_wal_file"><span>4. </span>The WAL File</h1>
484
485 <p>While a <a href="c3ref/sqlite3.html">database connection</a> is open on a WAL-mode database, SQLite
486 maintains an extra journal file called a "Write Ahead Log" or "WAL File".
487 The name of this file on disk is usually the name of the database file
488 with an extra "<tt>-wal</tt>" suffix, though different naming rules may
489 apply if SQLite is compiled with <a href="compile.html#enable_8_3_names">SQLITE_ENABLE_8_3_NAMES</a>.
490
491 </p><p>The WAL file exists for as long as any <a href="c3ref/sqlite3.html">database connection</a> has the
492 database open. Usually, the WAL file is deleted automatically when the
493 last connection to the database closes. However, if the last process to
494 have the database open exits without cleanly
495 shutting down the database connection, or if the
496 <a href="c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal">SQLITE_FCNTL_PERSIST_WAL</a> <a href="c3ref/file_control.html">file control</a> is used, then the WAL file
497 might be retained on disk after all connections to the database have
498 been closed. The WAL file is part of the persistent state of the
499 database and should be kept with the database if the database is copied
500 or moved. If a database file is separated from its WAL file, then
501 transactions that were previously committed to the database might be lost,
502 or the database file might become corrupted.
503 The only safe way to remove a WAL file is
504 to open the database file using one of the <a href="c3ref/open.html">sqlite3_open()</a> interfaces
505 then immediately close the database using <a href="c3ref/close.html">sqlite3_close()</a>.
506
507 </p><p>The <a href="fileformat2.html#walformat">WAL file format</a> is precisely defined and is cross-platform.
508
509 <a name="readonly"></a>
510
511 </p><h1 id="read_only_databases"><span>5. </span>Read-Only Databases</h1>
512
513 <p>Older versions of SQLite could not read a WAL-mode database that was
514 read-only. In other words, write access was required in order to read a
515 WAL-mode database. This constraint was relaxed beginning with
516 SQLite <a href="releaselog/3_22_0.html">version 3.22.0</a> (2018-01-22).
517
518 </p><p>On newer versions of SQLite,
519 a WAL-mode database on read-only media, or a WAL-mode database that lacks
520 write permission, can still be read as long as one or more of the following
521 conditions are met:
522 </p><ol>
523 <li>The <tt>-shm</tt> and <tt>-wal</tt> files already exists and are readable
524 </li><li>There is write permission on the directory containing the database so
525 that the <tt>-shm</tt> and <tt>-wal</tt> files can be created.
526 </li><li>The database connection is opened using the
527 <a href="uri.html#uriimmutable">immutable query parameter</a>.
528 </li></ol>
529
530 <p>Even though it is possible to open a read-only WAL-mode database,
531 it is good practice to converted to
532 <a href="pragma.html#pragma_journal_mode">PRAGMA journal_mode=DELETE</a> prior to burning an
533 SQLite database image onto read-only media.</p>
534
535 <a name="bigwal"></a>
536
537 <h1 id="avoiding_excessively_large_wal_files"><span>6. </span>Avoiding Excessively Large WAL Files</h1>
538
539 <p>In normal cases, new content is appended to the WAL file until the
540 WAL file accumulates about 1000 pages (and is thus about 4MB
541 in size) at which point a checkpoint is automatically run and the WAL file
542 is recycled. The checkpoint does not normally truncate the WAL file
543 (unless the <a href="pragma.html#pragma_journal_size_limit">journal_size_limit pragma</a> is set). Instead, it merely
544 causes SQLite to start overwriting the WAL file from the beginning.
545 This is done because it is normally faster to overwrite an existing file
546 than to append. When the last connection to a database closes, that
547 connection does one last checkpoint and then deletes the WAL and its
548 associated shared-memory file, to clean up the disk.
549
550 </p><p>So in the vast majority of cases, applications need not worry about
551 the WAL file at all. SQLite will automatically take care of it. But
552 it is possible to get SQLite into a state where the WAL file will grow
553 without bound, causing excess disk space usage and slow queries speeds.
554 The following bullets enumerate some of the ways that this can happen
555 and how to avoid them.
556
557 </p><ul>
558 <li><p>
559 <b>Disabling the automatic checkpoint mechanism.</b>
560 In its default configuration, SQLite will checkpoint the WAL file at the
561 conclusion of any transaction when the WAL file is more than 1000 pages
562 long. However, compile-time and run-time options exist that can disable
563 or defer this automatic checkpoint. If an application disables the
564 automatic checkpoint, then there is nothing to prevent the WAL file
565 from growing excessively.
566
567 </p></li><li><p>
568 <b>Checkpoint starvation.</b>
569 A checkpoint is only able to run to completion, and reset the WAL file,
570 if there are no other database connections using the WAL file. If another
571 connection has a read transaction open,
572 then the checkpoint cannot reset the WAL file because
573 doing so might delete content out from under the reader.
574 The checkpoint will do as much work as it can without upsetting the
575 reader, but it cannot run to completion.
576 The checkpoint will start up again where it left off after the next
577 write transaction. This repeats until some checkpoint is able to complete.
578
579 </p><p>However, if a database has many concurrent overlapping readers
580 and there is always at least one active reader, then
581 no checkpoints will be able to complete
582 and hence the WAL file will grow without bound.
583
584 </p><p>This scenario can be avoided by ensuring that there are "reader gaps":
585 times when no processes are reading from the
586 database and that checkpoints are attempted during those times.
587 In applications with many concurrent readers, one might also consider
588 running manual checkpoints with the <a href="c3ref/c_checkpoint_full.html">SQLITE_CHECKPOINT_RESTART</a> or
589 <a href="c3ref/c_checkpoint_full.html">SQLITE_CHECKPOINT_TRUNCATE</a> option which will ensure that the checkpoint
590 runs to completion before returning. The disadvantage of using
591 <a href="c3ref/c_checkpoint_full.html">SQLITE_CHECKPOINT_RESTART</a> and <a href="c3ref/c_checkpoint_full.html">SQLITE_CHECKPOINT_TRUNCATE</a> is that
592 readers might block while the checkpoint is running.
593
594 </p></li><li><p>
595 <b>Very large write transactions.</b>
596 A checkpoint can only complete when no other transactions are running,
597 which means the WAL file cannot be reset in the middle of a write
598 transaction. So a large change to a large database
599 might result in a large WAL file. The WAL file will be checkpointed
600 once the write transaction completes (assuming there are no other readers
601 blocking it) but in the meantime, the file can grow very big.
602
603 </p><p>As of SQLite <a href="releaselog/3_11_0.html">version 3.11.0</a> (2016-02-15),
604 the WAL file for a single transaction
605 should be proportional in size to the transaction itself. Pages that
606 are changed by the transaction should only be written into the WAL file
607 once. However, with older versions of SQLite, the same page might be
608 written into the WAL file multiple times if the transaction grows larger
609 than the page cache.
610 </p></li></ul>
611
612 <h1 id="implementation_of_shared_memory_for_the_wal_index"><span>7. </span>Implementation Of Shared-Memory For The WAL-Index</h1>
613
614 <p>The <a href="walformat.html#shm">wal-index</a> is implemented using an ordinary file that is
615 mmapped for robustness. Early (pre-release) implementations of WAL mode
616 stored the wal-index in volatile shared-memory, such as files created in
617 /dev/shm on Linux or /tmp on other unix systems. The problem
618 with that approach is that processes with a different root directory
619 (changed via <a href="http://en.wikipedia.org/wiki/Chroot">chroot</a>)
620 will see different files and hence use different shared memory areas,
621 leading to database corruption. Other methods for creating nameless
622 shared memory blocks are not portable across the various flavors of
623 unix. And we could not find any method to create nameless shared
624 memory blocks on windows. The only way we have found to guarantee
625 that all processes accessing the same database file use the same shared
626 memory is to create the shared memory by mmapping a file in the same
627 directory as the database itself.</p>
628
629 <p>Using an ordinary disk file to provide shared memory has the
630 disadvantage that it might actually do unnecessary disk I/O by
631 writing the shared memory to disk. However, the developers do not
632 think this is a major concern since the wal-index rarely exceeds
633 32 KiB in size and is never synced. Furthermore, the wal-index
634 backing file is deleted when the last database connection disconnects,
635 which often prevents any real disk I/O from ever happening.</p>
636
637 <p>Specialized applications for which the default implementation of
638 shared memory is unacceptable can devise alternative methods via a
639 custom <a href="vfs.html">VFS</a>.
640 For example, if it is known that a particular database
641 will only be accessed by threads within a single process, the wal-index
642 can be implemented using heap memory instead of true shared memory.</p>
643
644 <a name="noshm"></a>
645
646 <h1 id="use_of_wal_without_shared_memory"><span>8. </span>Use of WAL Without Shared-Memory</h1>
647
648 <p>Beginning in SQLite <a href="releaselog/3_7_4.html">version 3.7.4</a> (2010-12-07),
649 WAL databases can be created, read, and
650 written even if shared memory is unavailable as long as the
651 <a href="pragma.html#pragma_locking_mode">locking_mode</a> is set to EXCLUSIVE before the first attempted access.
652 In other words, a process can interact with
653 a WAL database without using shared memory if that
654 process is guaranteed to be the only process accessing the database.
655 This feature allows WAL databases to be created, read, and written
656 by legacy <a href="vfs.html">VFSes</a> that lack the "version 2" shared-memory
657 methods xShmMap, xShmLock, xShmBarrier, and xShmUnmap on the
658 <a href="c3ref/io_methods.html">sqlite3_io_methods</a> object.</p>
659
660 <p>If <a href="pragma.html#pragma_locking_mode">EXCLUSIVE locking mode</a>
661 is set prior to the first WAL-mode
662 database access, then SQLite never attempts to call any of the
663 shared-memory methods and hence no shared-memory
664 wal-index is ever created.
665 In that case, the database connection remains in EXCLUSIVE mode
666 as long as the journal mode is WAL; attempts to change the locking
667 mode using "<tt>PRAGMA locking_mode=NORMAL;</tt>" are no-ops.
668 The only way to change out of EXCLUSIVE locking mode is to first
669 change out of WAL journal mode.</p>
670
671 <p>If NORMAL locking mode is in effect for the first WAL-mode database
672 access, then the shared-memory wal-index is created. This means that the
673 underlying VFS must support the "version 2" shared-memory.
674 If the VFS does not support shared-memory methods, then the attempt to
675 open a database that is already in WAL mode, or the attempt convert a
676 database into WAL mode, will fail.
677 As long as exactly one connection is using a shared-memory wal-index,
678 the locking mode can be changed freely between NORMAL and EXCLUSIVE.
679 It is only when the shared-memory wal-index is omitted, when the locking
680 mode is EXCLUSIVE prior to the first WAL-mode database access, that the
681 locking mode is stuck in EXCLUSIVE.</p>
682
683 <a name="busy"></a>
684
685 <h1 id="sometimes_queries_return_sqlite_busy_in_wal_mode"><span>9. </span>Sometimes Queries Return SQLITE_BUSY In WAL Mode</h1>
686
687 <p>The <a href="wal.html#advantages">second advantage of WAL-mode</a> is that
688 writers do not block readers and readers to do not block writers.
689 This is <u>mostly</u> true.
690 But there are some obscure cases where a query against a WAL-mode
691 database can return <a href="rescode.html#busy">SQLITE_BUSY</a>, so applications should be prepared
692 for that happenstance.
693
694 </p><p>Cases where a query against a WAL-mode database can return <a href="rescode.html#busy">SQLITE_BUSY</a>
695 include the following:
696
697 </p><ul>
698 <li><p>If another database connection has the database mode open
699 in <a href="pragma.html#pragma_locking_mode">exclusive locking mode</a> then all queries against the
700 database will return <a href="rescode.html#busy">SQLITE_BUSY</a>. Both Chrome and Firefox open their
701 database files in exclusive locking mode, so attempts to read Chrome or
702 Firefox databases while the applications are running will run into this
703 problem, for example.
704
705 </p></li><li><p> When the last connection to a particular database is closing,
706 that connection will acquire an exclusive lock for a short time while
707 it cleans up the WAL and shared-memory files. If a separate attempt
708 is made to open and query the database while the first connection is
709 still in the middle of its cleanup process, the second connection
710 might get an <a href="rescode.html#busy">SQLITE_BUSY</a> error.
711
712 </p></li><li><p>
713 If the last connection to a database crashed, then the first new
714 connection to open the database will start a recovery process. An
715 exclusive lock is held during recovery. So if a third database connection
716 tries to jump in and query while the second connection is running recovery,
717 the third connection will get an <a href="rescode.html#busy">SQLITE_BUSY</a> error.
718 </p></li></ul>
719
720 <a name="bkwrds"></a>
721
722 <h1 id="backwards_compatibility"><span>10. </span>Backwards Compatibility</h1>
723
724 <p>The database file format is unchanged for WAL mode. However, the
725 WAL file and the <a href="walformat.html#shm">wal-index</a> are new concepts and so older versions of
726 SQLite will not know
727 how to recover a crashed SQLite database that was operating in WAL mode
728 when the crash occurred.
729 To prevent older versions of SQLite (prior to version 3.7.0, 2010-07-22)
730 from trying to recover
731 a WAL-mode database (and making matters worse) the database file format
732 version numbers (bytes 18 and 19 in the <a href="fileformat2.html#database_header">database header</a>)
733 are increased from 1 to 2 in WAL mode.
734 Thus, if an older version of SQLite attempts to connect to an SQLite
735 database that is operating in WAL mode, it will report an error along
736 the lines of "file is encrypted or is not a database".</p>
737
738 <p>One can explicitly change out of WAL mode using a pragma such as
739 this:</p>
740
741 <blockquote><pre>
742 PRAGMA journal_mode=DELETE;
743 </pre></blockquote>
744
745
746 <p>Deliberately changing out of WAL mode changes the database file format
747 version numbers back to 1 so that older versions of SQLite can once again
748 access the database file.</p>
749 <p align="center"><small><i>This page last modified on <a href="https://sqlite.org/docsrc/honeypot" id="mtimelink" data-href="https://sqlite.org/docsrc/finfo/pages/wal.in?m=9082744b12">2024-07-14 23:07:20</a> UTC </small></i></p>
750