Debian Codegraph @

www/fileformat.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>Database File Format</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 Database File Format
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="#the_database_file">1. The Database File</a></div>
129 <div class="fancy-toc2"><a href="#hot_journals">1.1. Hot Journals</a></div>
130 <div class="fancy-toc2"><a href="#pages">1.2. Pages</a></div>
131 <div class="fancy-toc2"><a href="#the_database_header">1.3. The Database Header</a></div>
132 <div class="fancy-toc3"><a href="#magic_header_string">1.3.1. Magic Header String</a></div>
133 <div class="fancy-toc3"><a href="#page_size">1.3.2. Page Size</a></div>
134 <div class="fancy-toc3"><a href="#file_format_version_numbers">1.3.3. File format version numbers</a></div>
135 <div class="fancy-toc3"><a href="#reserved_bytes_per_page">1.3.4. Reserved bytes per page</a></div>
136 <div class="fancy-toc3"><a href="#payload_fractions">1.3.5. Payload fractions</a></div>
137 <div class="fancy-toc3"><a href="#file_change_counter">1.3.6. File change counter</a></div>
138 <div class="fancy-toc3"><a href="#in_header_database_size">1.3.7. In-header database size</a></div>
139 <div class="fancy-toc3"><a href="#free_page_list">1.3.8. Free page list</a></div>
140 <div class="fancy-toc3"><a href="#schema_cookie">1.3.9. Schema cookie</a></div>
141 <div class="fancy-toc3"><a href="#schema_format_number">1.3.10. Schema format number</a></div>
142 <div class="fancy-toc3"><a href="#suggested_cache_size">1.3.11. Suggested cache size</a></div>
143 <div class="fancy-toc3"><a href="#incremental_vacuum_settings">1.3.12. Incremental vacuum settings</a></div>
144 <div class="fancy-toc3"><a href="#text_encoding">1.3.13. Text encoding</a></div>
145 <div class="fancy-toc3"><a href="#user_version_number">1.3.14. User version number</a></div>
146 <div class="fancy-toc3"><a href="#application_id">1.3.15. Application ID</a></div>
147 <div class="fancy-toc3"><a href="#write_library_version_number_and_version_valid_for_number">1.3.16. Write library version number and version-valid-for number</a></div>
148 <div class="fancy-toc3"><a href="#header_space_reserved_for_expansion">1.3.17. Header space reserved for expansion</a></div>
149 <div class="fancy-toc2"><a href="#the_lock_byte_page">1.4. The Lock-Byte Page</a></div>
150 <div class="fancy-toc2"><a href="#the_freelist">1.5. The Freelist</a></div>
151 <div class="fancy-toc2"><a href="#b_tree_pages">1.6. B-tree Pages</a></div>
152 <div class="fancy-toc2"><a href="#cell_payload_overflow_pages">1.7. Cell Payload Overflow Pages</a></div>
153 <div class="fancy-toc2"><a href="#pointer_map_or_ptrmap_pages">1.8. Pointer Map or Ptrmap Pages</a></div>
154 <div class="fancy-toc1"><a href="#schema_layer">2. Schema Layer</a></div>
155 <div class="fancy-toc2"><a href="#record_format">2.1. Record Format</a></div>
156 <div class="fancy-toc2"><a href="#record_sort_order">2.2. Record Sort Order</a></div>
157 <div class="fancy-toc2"><a href="#representation_of_sql_tables">2.3. Representation Of SQL Tables</a></div>
158 <div class="fancy-toc2"><a href="#representation_of_without_rowid_tables">2.4. Representation of WITHOUT ROWID Tables</a></div>
159 <div class="fancy-toc3"><a href="#suppression_of_redundant_columns_in_the_primary_key_of_without_rowid_tables">2.4.1. Suppression of redundant columns in the PRIMARY KEY
160 of WITHOUT ROWID tables</a></div>
161 <div class="fancy-toc2"><a href="#representation_of_sql_indices">2.5. Representation Of SQL Indices</a></div>
162 <div class="fancy-toc3"><a href="#suppression_of_redundant_columns_in_without_rowid_secondary_indexes_">2.5.1. Suppression of redundant columns in WITHOUT ROWID secondary indexes
163 </a></div>
164 <div class="fancy-toc2"><a href="#storage_of_the_sql_database_schema">2.6. Storage Of The SQL Database Schema</a></div>
165 <div class="fancy-toc3"><a href="#alternative_names_for_the_schema_table">2.6.1. Alternative Names For The Schema Table</a></div>
166 <div class="fancy-toc3"><a href="#internal_schema_objects">2.6.2. Internal Schema Objects</a></div>
167 <div class="fancy-toc3"><a href="#the_sqlite_sequence_table">2.6.3. The sqlite_sequence table</a></div>
168 <div class="fancy-toc3"><a href="#the_sqlite_stat1_table">2.6.4. The sqlite_stat1 table</a></div>
169 <div class="fancy-toc3"><a href="#the_sqlite_stat2_table">2.6.5. The sqlite_stat2 table</a></div>
170 <div class="fancy-toc3"><a href="#the_sqlite_stat3_table">2.6.6. The sqlite_stat3 table</a></div>
171 <div class="fancy-toc3"><a href="#the_sqlite_stat4_table">2.6.7. The sqlite_stat4 table</a></div>
172 <div class="fancy-toc1"><a href="#the_rollback_journal">3. The Rollback Journal</a></div>
173 <div class="fancy-toc1"><a href="#the_write_ahead_log">4. The Write-Ahead Log</a></div>
174 <div class="fancy-toc2"><a href="#wal_file_format">4.1. WAL File Format</a></div>
175 <div class="fancy-toc2"><a href="#checksum_algorithm">4.2. Checksum Algorithm</a></div>
176 <div class="fancy-toc2"><a href="#checkpoint_algorithm">4.3. Checkpoint Algorithm</a></div>
177 <div class="fancy-toc2"><a href="#wal_reset">4.4. WAL Reset</a></div>
178 <div class="fancy-toc2"><a href="#reader_algorithm">4.5. Reader Algorithm</a></div>
179 <div class="fancy-toc2"><a href="#wal_index_format">4.6. WAL-Index Format</a></div>
180 </div>
181 </div>
182 <script>
183 function toggle_toc(){
184 var sub = document.getElementById("toc_sub")
185 var mk = document.getElementById("toc_mk")
186 if( sub.style.display!="block" ){
187 sub.style.display = "block";
188 mk.innerHTML = "&#x25bc;";
189 } else {
190 sub.style.display = "none";
191 mk.innerHTML = "&#x25ba;";
192 }
193 }
194 </script>
195 </div>
196
197
198
199
200
201
202 <p>This document describes and defines the on-disk database file
203 format used by all releases of SQLite since
204 version 3.0.0 (2004-06-18).</p>
205
206 <h1 id="the_database_file"><span>1. </span>The Database File</h1>
207
208 <p>The complete state of an SQLite database is usually
209 contained in a single file on disk called the "main database file".</p>
210
211 <p>During a transaction, SQLite stores additional information
212 in a second file called the "rollback journal", or if SQLite is in
213 <a href="wal.html">WAL mode</a>, a write-ahead log file.
214
215 <a name="hotjrnl"></a>
216
217 </p><h2 id="hot_journals"><span>1.1. </span>Hot Journals</h2>
218 <p>If the application or
219 host computer crashes before the transaction completes, then the rollback
220 journal or write-ahead log contains information needed
221 to restore the main database file to a consistent state. When a rollback
222 journal or write-ahead log contains information necessary for recovering
223 the state of the database, they are called a "hot journal" or "hot WAL file".
224 Hot journals and WAL files are only a factor during error recovery
225 scenarios and so are uncommon, but they are part of the state of an SQLite
226 database and so cannot be ignored. This document defines the format
227 of a rollback journal and the write-ahead log file, but the focus is
228 on the main database file.</p>
229
230 <h2 id="pages"><span>1.2. </span>Pages</h2>
231
232 <p>The main database file consists of one or more pages. The size of a
233 page is a power of two between 512 and 65536 inclusive. All pages within
234 the same database are the same size. The page size for a database file
235 is determined by the 2-byte integer located at an offset of
236 16 bytes from the beginning of the database file.</p>
237
238 <p>Pages are numbered beginning with 1. The maximum page number is
239 4294967294 (2<sup><small>32</small></sup> - 2). The minimum size
240 SQLite database is a single 512-byte page.
241 The maximum size database would be 4294967294 pages at 65536 bytes per
242 page or 281,474,976,579,584 bytes (about 281 terabytes). Usually SQLite will
243 hit the maximum file size limit of the underlying filesystem or disk
244 hardware long before it hits its own internal size limit.</p>
245
246 <p>In common use, SQLite databases tend to range in size from a few kilobytes
247 to a few gigabytes, though terabyte-size SQLite databases are known to exist
248 in production.</p>
249
250 <p>At any point in time, every page in the main database has a single
251 use which is one of the following:
252 </p><ul>
253 <li>A b-tree page
254 <ul>
255 <li>A table b-tree interior page
256 </li><li>A table b-tree leaf page
257 </li><li>An index b-tree interior page
258 </li><li>An index b-tree leaf page
259 </li></ul>
260 </li><li>A freelist page
261 <ul>
262 <li>A freelist trunk page
263 </li><li>A freelist leaf page
264 </li></ul>
265 </li><li>A payload overflow page
266 </li><li>A pointer map page
267 </li><li>The lock-byte page
268 </li></ul>
269
270
271 <p>All reads from and writes to the main database file begin at a page
272 boundary and all writes are an integer number of pages in size. Reads
273 are also usually an integer number of pages in size, with the one exception
274 that when the database is first opened, the first 100 bytes of the
275 database file (the database file header) are read as a sub-page size unit.</p>
276
277 <a name="database_header"></a>
278
279 <h2 id="the_database_header"><span>1.3. </span>The Database Header</h2>
280
281 <p>The first 100 bytes of the database file comprise the database file
282 header. The database file header is divided into fields as shown by
283 the table below. All multibyte fields in the database file header are
284 stored with the most significant byte first (big-endian).</p>
285
286 <center>
287 <i>Database Header Format</i><br>
288 <table width="80%" border="1">
289 <tr><th>Offset</th><th>Size</th><th>Description
290 </th></tr><tr><td valign="top" align="center">0</td><td valign="top" align="center">16</td><td align="left">
291 The header string: "SQLite format 3\000"
292 </td></tr><tr><td valign="top" align="center">16</td><td valign="top" align="center">2</td><td align="left">
293 The database page size in bytes. Must be a power of two between 512
294 and 32768 inclusive, or the value 1 representing a page size of 65536.
295 </td></tr><tr><td valign="top" align="center">18</td><td valign="top" align="center">1</td><td align="left">
296 File format write version. 1 for legacy; 2 for <a href="wal.html">WAL</a>.
297 </td></tr><tr><td valign="top" align="center">19</td><td valign="top" align="center">1</td><td align="left">
298 File format read version. 1 for legacy; 2 for <a href="wal.html">WAL</a>.
299 </td></tr><tr><td valign="top" align="center">20</td><td valign="top" align="center">1</td><td align="left">
300 Bytes of unused "reserved" space at the end of each page. Usually 0.
301 </td></tr><tr><td valign="top" align="center">21</td><td valign="top" align="center">1</td><td align="left">
302 Maximum embedded payload fraction. Must be 64.
303 </td></tr><tr><td valign="top" align="center">22</td><td valign="top" align="center">1</td><td align="left">
304 Minimum embedded payload fraction. Must be 32.
305 </td></tr><tr><td valign="top" align="center">23</td><td valign="top" align="center">1</td><td align="left">
306 Leaf payload fraction. Must be 32.
307 </td></tr><tr><td valign="top" align="center">24</td><td valign="top" align="center">4</td><td align="left">
308 File change counter.
309 </td></tr><tr><td valign="top" align="center">28</td><td valign="top" align="center">4</td><td align="left">
310 Size of the database file in pages. The "in-header database size".
311 </td></tr><tr><td valign="top" align="center">32</td><td valign="top" align="center">4</td><td align="left">
312 Page number of the first freelist trunk page.
313 </td></tr><tr><td valign="top" align="center">36</td><td valign="top" align="center">4</td><td align="left">
314 Total number of freelist pages.
315 </td></tr><tr><td valign="top" align="center">40</td><td valign="top" align="center">4</td><td align="left">
316 The schema cookie.
317 </td></tr><tr><td valign="top" align="center">44</td><td valign="top" align="center">4</td><td align="left">
318 The schema format number. Supported schema formats are 1, 2, 3, and 4.
319 </td></tr><tr><td valign="top" align="center">48</td><td valign="top" align="center">4</td><td align="left">
320 Default page cache size.
321 </td></tr><tr><td valign="top" align="center">52</td><td valign="top" align="center">4</td><td align="left">
322 The page number of the largest root b-tree page when in auto-vacuum or
323 incremental-vacuum modes, or zero otherwise.
324 </td></tr><tr><td valign="top" align="center">56</td><td valign="top" align="center">4</td><td align="left">
325 The database text encoding. A value of 1 means UTF-8. A value of 2
326 means UTF-16le. A value of 3 means UTF-16be.
327 </td></tr><tr><td valign="top" align="center">60</td><td valign="top" align="center">4</td><td align="left">
328 The "user version" as read and set by the <a href="pragma.html#pragma_user_version">user_version pragma</a>.
329 </td></tr><tr><td valign="top" align="center">64</td><td valign="top" align="center">4</td><td align="left">
330 True (non-zero) for incremental-vacuum mode. False (zero) otherwise.
331 </td></tr><tr><td valign="top" align="center">68</td><td valign="top" align="center">4</td><td align="left">
332 The "Application ID" set by <a href="pragma.html#pragma_application_id">PRAGMA application_id</a>.
333 </td></tr><tr><td valign="top" align="center">72</td><td valign="top" align="center">20</td><td align="left">
334 Reserved for expansion. Must be zero.
335 </td></tr><tr><td valign="top" align="center">92</td><td valign="top" align="center">4</td><td align="left">
336 The <a href="fileformat2.html#validfor">version-valid-for number</a>.
337 </td></tr><tr><td valign="top" align="center">96</td><td valign="top" align="center">4</td><td align="left">
338 <a href="c3ref/c_source_id.html">SQLITE_VERSION_NUMBER</a>
339 </td></tr></table></center>
340
341 <h3 id="magic_header_string"><span>1.3.1. </span>Magic Header String</h3>
342
343 <p>Every valid SQLite database file begins with the following 16 bytes
344 (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d 61 74 20 33 00. This byte sequence
345 corresponds to the UTF-8 string "SQLite format 3" including the nul
346 terminator character at the end.</p>
347
348 <h3 id="page_size"><span>1.3.2. </span>Page Size</h3>
349
350 <p>The two-byte value beginning at offset 16 determines the page size of
351 the database. For SQLite versions 3.7.0.1 (2010-08-04)
352 and earlier, this value is
353 interpreted as a big-endian integer and must be a power of two between
354 512 and 32768, inclusive. Beginning with SQLite <a href="releaselog/3_7_1.html">version 3.7.1</a>
355 (2010-08-23), a page
356 size of 65536 bytes is supported. The value 65536 will not fit in a
357 two-byte integer, so to specify a 65536-byte page size, the value
358 at offset 16 is 0x00 0x01.
359 This value can be interpreted as a big-endian
360 1 and thought of as a magic number to represent the 65536 page size.
361 Or one can view the two-byte field as a little endian number and say
362 that it represents the page size divided by 256. These two
363 interpretations of the page-size field are equivalent.</p>
364
365 <a name="vnums"></a>
366
367 <h3 id="file_format_version_numbers"><span>1.3.3. </span>File format version numbers</h3>
368
369 <p>The file format write version and file format read version at offsets
370 18 and 19 are intended to allow for enhancements of the file format
371 in future versions of SQLite. In current versions of SQLite, both of
372 these values are 1 for rollback journalling modes and 2 for <a href="wal.html">WAL</a>
373 journalling mode. If a version of SQLite coded to the current
374 file format specification encounters a database file where the read
375 version is 1 or 2 but the write version is greater than 2, then the database
376 file must be treated as read-only. If a database file with a read version
377 greater than 2 is encountered, then that database cannot be read or written.</p>
378
379 <a name="resbyte"></a>
380
381 <h3 id="reserved_bytes_per_page"><span>1.3.4. </span>Reserved bytes per page</h3>
382
383 <p>SQLite has the ability to set aside a small number of extra bytes at
384 the end of every page for use by extensions. These extra bytes are
385 used, for example, by the SQLite Encryption Extension to store a nonce
386 and/or cryptographic checksum associated with each page. The
387 "reserved space" size in the 1-byte integer at offset 20 is the number
388 of bytes of space at the end of each page to reserve for extensions.
389 This value is usually 0. The value can be odd.</p>
390
391 <a name="usable_size"></a>
392
393 <p>The "usable size" of a database page is the page size specified by the
394 2-byte integer at offset 16 in the header less the "reserved" space size
395 recorded in the 1-byte integer at offset 20 in the header. The usable
396 size of a page might be an odd number. However, the usable size is not
397 allowed to be less than 480. In other words, if the page size is 512,
398 then the reserved space size cannot exceed 32.</p>
399
400 <h3 id="payload_fractions"><span>1.3.5. </span>Payload fractions</h3>
401
402 <p>The maximum and minimum embedded payload fractions and the leaf
403 payload fraction values must be 64, 32, and 32. These values were
404 originally intended to be tunable parameters that could be used to
405 modify the storage format of the b-tree algorithm. However, that
406 functionality is not supported and there are no current plans to add
407 support in the future. Hence, these three bytes are fixed at the
408 values specified.</p>
409
410 <h3 id="file_change_counter"><span>1.3.6. </span>File change counter</h3>
411
412 <a name="chngctr"></a>
413
414 <p>The file change counter is a 4-byte big-endian integer at
415 offset 24 that is incremented whenever the database file is unlocked
416 after having been modified.
417 When two or more processes are reading the same database file, each
418 process can detect database changes from other processes by monitoring
419 the change counter.
420 A process will normally want to flush its database page cache when
421 another process modified the database, since the cache has become stale.
422 The file change counter facilitates this.</p>
423
424 <p>In WAL mode, changes to the database are detected using the wal-index
425 and so the change counter is not needed. Hence, the change counter might
426 not be incremented on each transaction in WAL mode.</p>
427
428 <h3 id="in_header_database_size"><span>1.3.7. </span>In-header database size</h3>
429
430 <a name="filesize"></a>
431
432 <p>The 4-byte big-endian integer at offset 28 into the header
433 stores the size of the database file in pages. If this in-header
434 datasize size is not valid (see the next paragraph), then the database
435 size is computed by looking
436 at the actual size of the database file. Older versions of SQLite
437 ignored the in-header database size and used the actual file size
438 exclusively. Newer versions of SQLite use the in-header database
439 size if it is available but fall back to the actual file size if
440 the in-header database size is not valid.</p>
441
442 <p>The in-header database size is only considered to be valid if
443 it is non-zero and if the 4-byte <a href="fileformat2.html#chngctr">change counter</a> at offset 24
444 exactly matches the 4-byte <a href="fileformat2.html#validfor">version-valid-for number</a> at offset 92.
445 The in-header database size is always valid
446 when the database is only modified using recent versions of SQLite,
447 versions 3.7.0 (2010-07-21) and later.
448 If a legacy version of SQLite writes to the database, it will not
449 know to update the in-header database size and so the in-header
450 database size could be incorrect. But legacy versions of SQLite
451 will also leave the version-valid-for number at offset 92 unchanged
452 so it will not match the change-counter. Hence, invalid in-header
453 database sizes can be detected (and ignored) by observing when
454 the change-counter does not match the version-valid-for number.</p>
455
456 <h3 id="free_page_list"><span>1.3.8. </span>Free page list</h3>
457
458 <p>Unused pages in the database file are stored on a freelist. The
459 4-byte big-endian integer at offset 32 stores the page number of
460 the first page of the freelist, or zero if the freelist is empty.
461 The 4-byte big-endian integer at offset 36 stores the total
462 number of pages on the freelist.</p>
463
464 <h3 id="schema_cookie"><span>1.3.9. </span>Schema cookie</h3>
465
466 <p>The schema cookie is a 4-byte big-endian integer at offset 40
467 that is incremented whenever the database schema changes. A
468 prepared statement is compiled against a specific version of the
469 database schema. When the database schema changes, the statement
470 must be reprepared. When a prepared statement runs, it first checks
471 the schema cookie to ensure the value is the same as when the statement
472 was prepared and if the schema cookie has changed, the statement either
473 automatically reprepares and reruns or it aborts with an <a href="rescode.html#schema">SQLITE_SCHEMA</a>
474 error.</p>
475
476 <a name="schemaformat"></a>
477
478 <h3 id="schema_format_number"><span>1.3.10. </span>Schema format number</h3>
479
480 <p>The schema format number is a 4-byte big-endian integer at offset 44.
481 The schema format number is similar to the file format read and write
482 version numbers at offsets 18 and 19 except that the schema format number
483 refers to the high-level SQL formatting rather than the low-level b-tree
484 formatting. Four schema format numbers are currently defined:</p>
485
486 <ol>
487 <li value="1">Format 1 is understood by all versions of SQLite back to
488 <a href="releaselog/3_0_0.html">version 3.0.0</a> (2004-06-18).</li>
489 <li value="2">Format 2 adds the ability of rows within the same table
490 to have a varying number of columns, in order to support the
491 <a href="lang_altertable.html">ALTER TABLE ... ADD COLUMN</a> functionality. Support for
492 reading and writing format 2 was added in SQLite
493 <a href="releaselog/3_1_3.html">version 3.1.3</a> on 2005-02-20.</li>
494 <li value="3">Format 3 adds the ability of extra columns added by
495 <a href="lang_altertable.html">ALTER TABLE ... ADD COLUMN</a> to have non-NULL default
496 values. This capability was added in SQLite <a href="releaselog/3_1_4.html">version 3.1.4</a>
497 on 2005-03-11.</li>
498 <li value="4">Format 4 causes SQLite to respect the
499 <a href="lang_createindex.html#descidx">DESC keyword</a> on
500 index declarations. (The DESC keyword is ignored in indexes for
501 formats 1, 2, and 3.)
502 Format 4 also adds two new boolean record type values (<a href="fileformat2.html#serialtype">serial types</a>
503 8 and 9). Support for format 4 was added in SQLite 3.3.0 on
504 2006-01-10.</li>
505 </ol>
506
507 <p>New database files created by SQLite use format 4 by default.
508 The <a href="pragma.html#pragma_legacy_file_format">legacy_file_format pragma</a> can be used to cause SQLite
509 to create new database files using format 1.
510 The format version number can be made to default to 1 instead of 4 by
511 setting <a href="compile.html#default_file_format">SQLITE_DEFAULT_FILE_FORMAT</a>=1 at compile-time.
512 </p>
513
514 <p>If the database is completely empty, if it has no schema, then the
515 schema format number can be zero.
516
517 </p><h3 id="suggested_cache_size"><span>1.3.11. </span>Suggested cache size</h3>
518
519 <p>The 4-byte big-endian signed integer at offset 48 is the suggested
520 cache size in pages for the database file. The value is a suggestion
521 only and SQLite is under no obligation to honor it. The absolute value
522 of the integer is used as the suggested size. The suggested cache size
523 can be set using the <a href="pragma.html#pragma_default_cache_size">default_cache_size pragma</a>.</p>
524
525 <h3 id="incremental_vacuum_settings"><span>1.3.12. </span>Incremental vacuum settings</h3>
526
527 <p>The two 4-byte big-endian integers at offsets 52 and 64 are used
528 to manage the <a href="pragma.html#pragma_auto_vacuum">auto_vacuum</a> and <a href="pragma.html#pragma_incremental_vacuum">incremental_vacuum</a> modes. If
529 the integer at offset 52 is zero then pointer-map (ptrmap) pages are
530 omitted from the database file and neither auto_vacuum nor
531 incremental_vacuum are supported. If the integer at offset 52 is
532 non-zero then it is the page number of the largest root page in the
533 database file, the database file will contain ptrmap pages, and the
534 mode must be either auto_vacuum or incremental_vacuum. In this latter
535 case, the integer at offset 64 is true for incremental_vacuum and
536 false for auto_vacuum. If the integer at offset 52 is zero then
537 the integer at offset 64 must also be zero.</p>
538
539 <a name="enc"></a>
540
541 <h3 id="text_encoding"><span>1.3.13. </span>Text encoding</h3>
542
543 <p>The 4-byte big-endian integer at offset 56 determines the encoding
544 used for all text strings stored in the database.
545 A value of 1 means UTF-8.
546 A value of 2 means UTF-16le.
547 A value of 3 means UTF-16be.
548 No other values are allowed.
549 The sqlite3.h header file defines C-preprocessor macros SQLITE_UTF8 as 1,
550 SQLITE_UTF16LE as 2, and SQLITE_UTF16BE as 3, to use in place of
551 the numeric codes for the text encoding.</p>
552
553 <h3 id="user_version_number"><span>1.3.14. </span>User version number</h3>
554
555 <p>The 4-byte big-endian integer at offset 60 is the user version which
556 is set and queried by the <a href="pragma.html#pragma_user_version">user_version pragma</a>. The user version is
557 not used by SQLite.</p>
558
559 <a name="appid"></a>
560
561 <h3 id="application_id"><span>1.3.15. </span>Application ID</h3>
562
563 <p>The 4-byte big-endian integer at offset 68 is an "Application ID" that
564 can be set by the <a href="pragma.html#pragma_application_id">PRAGMA application_id</a> command in order to identify the
565 database as belonging to or associated with a particular application.
566 The application ID is intended for database files used as an
567 <a href="appfileformat.html">application file-format</a>. The application ID can be used by utilities
568 such as <a href="http://www.darwinsys.com/file/">file(1)</a> to determine the specific
569 file type rather than just reporting "SQLite3 Database". A list of
570 assigned application IDs can be seen by consulting the
571 <a href="https://www.sqlite.org/src/artifact?ci=trunk&filename=magic.txt">magic.txt</a>
572 file in the SQLite source repository.</p>
573
574 <a name="validfor"></a>
575
576 <h3 id="write_library_version_number_and_version_valid_for_number"><span>1.3.16. </span>Write library version number and version-valid-for number</h3>
577
578 <p>The 4-byte big-endian integer at offset 96 stores the
579 <a href="c3ref/c_source_id.html">SQLITE_VERSION_NUMBER</a> value for the SQLite library that most
580 recently modified the database file. The 4-byte big-endian integer at
581 offset 92 is the value of the <a href="fileformat2.html#chngctr">change counter</a> when the version number
582 was stored. The integer at offset 92 indicates which transaction
583 the version number is valid for and is sometimes called the
584 "version-valid-for number".
585
586 </p><h3 id="header_space_reserved_for_expansion"><span>1.3.17. </span>Header space reserved for expansion</h3>
587
588 <p>All other bytes of the database file header are reserved for
589 future expansion and must be set to zero.</p>
590
591 <a name="lockbyte"></a>
592
593 <h2 id="the_lock_byte_page"><span>1.4. </span>The Lock-Byte Page</h2>
594
595 <p>The lock-byte page is the single page of the database file
596 that contains the bytes at offsets between 1073741824 and 1073742335,
597 inclusive. A database file that is less than or equal to 1073741824 bytes
598 in size contains no lock-byte page. A database file larger than
599 1073741824 contains exactly one lock-byte page.
600 </p>
601
602 <p>The lock-byte page is set aside for use by the operating-system specific
603 <a href="vfs.html">VFS</a> implementation in implementing the database file locking primitives.
604 SQLite does not use the lock-byte page. The SQLite core
605 will never read or write the lock-byte page,
606 though operating-system specific <a href="vfs.html">VFS</a>
607 implementations may choose to read or write bytes on the lock-byte
608 page according to the
609 needs and proclivities of the underlying system. The unix and win32
610 <a href="vfs.html">VFS</a> implementations that come built into SQLite do not write to the
611 lock-byte page, but third-party VFS implementations for
612 other operating systems might.</p>
613
614 <p>The lock-byte page arose from the need to support Win95 which was the
615 predominant operating system when this file format was designed and which
616 only supported mandatory file locking. All modern operating systems that
617 we know of support advisory file locking, and so the lock-byte page is
618 not really needed any more, but is retained for backwards compatibility.</p>
619
620 <a name="freelist"></a>
621
622 <h2 id="the_freelist"><span>1.5. </span>The Freelist</h2>
623
624 <p>A database file might contain one or more pages that are not in
625 active use. Unused pages can come about, for example, when information
626 is deleted from the database. Unused pages are stored on the freelist
627 and are reused when additional pages are required.</p>
628
629 <p>The freelist is organized as a linked list of freelist trunk pages
630 with each trunk page containing page numbers for zero or more freelist
631 leaf pages.</p>
632
633 <p>A freelist trunk page consists of an array of 4-byte big-endian integers.
634 The size of the array is as many integers as will fit in the usable space
635 of a page. The minimum usable space is 480 bytes so the array will always
636 be at least 120 entries in length. The first integer on a freelist trunk
637 page is the page number of the next freelist trunk page in the list or zero
638 if this is the last freelist trunk page. The second integer on a freelist
639 trunk page is the number of leaf page pointers to follow.
640 Call the second integer on a freelist trunk page L.
641 If L is greater than zero then integers with array indexes between 2 and
642 L+1 inclusive contain page numbers for freelist leaf pages.</p>
643
644 <p>Freelist leaf pages contain no information. SQLite avoids reading or
645 writing freelist leaf pages in order to reduce disk I/O.</p>
646
647 <p>A bug in SQLite versions prior to 3.6.0 (2008-07-16)
648 caused the database to be
649 reported as corrupt if any of the last 6 entries in the freelist trunk page
650 array contained non-zero values. Newer versions of SQLite do not have
651 this problem. However, newer versions of SQLite still avoid using the
652 last six entries in the freelist trunk page array in order that database
653 files created by newer versions of SQLite can be read by older versions
654 of SQLite.</p>
655
656 <p>The number of freelist pages is stored as a 4-byte big-endian integer
657 in the database header at an offset of 36 from the beginning of the file.
658 The database header also stores the page number of the first freelist trunk
659 page as a 4-byte big-endian integer at an offset of 32 from the beginning
660 of the file.</p>
661
662 <a name="btree"></a>
663
664 <h2 id="b_tree_pages"><span>1.6. </span>B-tree Pages</h2>
665
666 <p>The b-tree algorithm provides key/data storage with unique and
667 ordered keys on page-oriented storage devices.
668 For background information on b-trees, see
669 Knuth, <u>The Art Of Computer Programming</u>, Volume 3 "Sorting
670 and Searching", pages 471-479. Two variants of b-trees are used by
671 SQLite. "Table b-trees" use a 64-bit signed integer key and store
672 all data in the leaves. "Index b-trees" use arbitrary keys and store no
673 data at all.
674
675 </p><p>A b-tree page is either an interior page or a leaf page.
676 A leaf page contains keys and in the case of a table b-tree each
677 key has associated data. An interior page contains
678 K keys together with K+1 pointers to child b-tree pages.
679 A "pointer" in an interior b-tree page is just the 32-bit
680 unsigned integer page number of the child page.</p><p>
681
682 </p><p>The number of keys on an interior b-tree page, K,
683 is almost always at least 2 and is usually much more than 2.
684 The only exception is when page 1 is an interior b-tree page.
685 Page 1 has 100 fewer bytes of storage space available,
686 due to the presence of the database header at the beginning of that page,
687 and so sometimes (rarely) if page 1 is an interior b-tree page, it can
688 end up holding just a single key. In all other cases, K is 2 or more.
689 The upper bound on K is as many keys as will fit on the page. Large keys
690 on index b-trees are split up into <a href="fileformat2.html#ovflpgs">overflow pages</a> so that no single key
691 uses more than one fourth of the available storage space on the page
692 and hence every internal page is able to store at least 4 keys.
693 The integer keys of table b-trees are never large enough to
694 require overflow, so key overflow only occurs on index b-trees.</p>
695
696 <p>Define the depth
697 of a leaf b-tree to be 1 and the depth of any interior b-tree to be one
698 more than the maximum depth of any of its children. In a well-formed
699 database, all children of an interior b-tree have the same depth.</p>
700
701 <p>In an interior b-tree page, the pointers and keys logically alternate
702 with a pointer on both ends. (The previous sentence is to be understood
703 conceptually - the actual layout of the keys and
704 pointers within the page is more complicated and will be described in
705 the sequel.) All keys within the same page are unique and are logically
706 organized in ascending order from left to right. (Again, this ordering
707 is logical, not physical. The actual location of keys within the page
708 is arbitrary.) For any key X, pointers to the left
709 of a X refer to b-tree pages on which all keys are less than or equal to X.
710 Pointers to the right of X refer to pages where all keys are
711 greater than X.</p>
712
713 <p>Within an interior b-tree page, each key and the pointer to its
714 immediate left are combined into a structure called a "cell". The
715 right-most pointer is held separately. A leaf b-tree page has no
716 pointers, but it still uses the cell structure to hold keys for
717 index b-trees or keys and content for table b-trees. Data is also
718 contained in the cell.
719 </p>
720
721 <p>Every b-tree page has at most one parent b-tree page.
722 A b-tree page without a parent is called a root page. A root b-tree page
723 together with the closure of its children form a complete b-tree.
724 It is possible (and in fact rather common) to have a complete b-tree
725 that consists of a single page that is both a leaf and the root.
726 Because there are pointers from parents to children, every page of a
727 complete b-tree can be located if only the root page is known. Hence,
728 b-trees are identified by their root page number.</p>
729
730 <a name="btypes"></a>
731
732 <p>A b-tree page is either a table b-tree page or an index b-tree page.
733 All pages within each complete b-tree are of the same type: either table
734 or index. There is one table b-trees in the database file
735 for each rowid table in the database schema, including system tables
736 such as <a href="schematab.html">sqlite_schema</a>. There is one index b-tree
737 in the database file for each index in the schema, including implied indexes
738 created by uniqueness constraints. There are no b-trees associated with
739 <a href="vtab.html">virtual tables</a>. Specific virtual table implementations might make use
740 of <a href="vtab.html#xshadowname">shadow tables</a> for storage, but those shadow tables will have separate
741 entries in the database schema. <a href="withoutrowid.html">WITHOUT ROWID</a> tables use index b-trees
742 rather than a table b-trees, so there is one
743 index b-tree in the database file for each <a href="withoutrowid.html">WITHOUT ROWID</a> table.
744 The b-tree corresponding to the sqlite_schema table is always a table
745 b-tree and always has a root page of 1.
746 The sqlite_schema table contains the root page number for every other
747 table and index in the database file.</p>
748
749 <p>Each entry in a table b-tree consists of a 64-bit signed integer key
750 and up to 2147483647 bytes of arbitrary data. (The key of a table b-tree
751 corresponds to the <a href="lang_createtable.html#rowid">rowid</a> of the SQL table that the b-tree implements.)
752 Interior table b-trees hold only keys and pointers to children.
753 All data is contained in the table b-tree leaves.</p>
754
755 <p>Each entry in an index b-tree consists of an arbitrary key of up
756 to 2147483647 bytes in length and no data.</p>
757
758 <a name="cell_payload"></a>
759
760 <p>Define the "payload" of a cell to be the arbitrary length section
761 of the cell. For an index b-tree, the key is always arbitrary in length
762 and hence the payload is the key. There are no arbitrary length elements
763 in the cells of interior table b-tree pages and so those cells have no
764 payload. Table b-tree leaf pages contain arbitrary length content and
765 so for cells on those pages the payload is the content.
766 </p><p>When the size of payload for a cell exceeds a certain threshold (to
767 be defined later) then only the first few bytes of the payload
768 are stored on the b-tree page and the balance is stored in a linked list
769 of content overflow pages.</p>
770
771 <p>A b-tree page is divided into regions in the following order:
772
773 </p><ol>
774 <li>The 100-byte database file header (found on page 1 only)
775 </li><li>The 8 or 12 byte b-tree page header
776 </li><li>The cell pointer array
777 </li><li>Unallocated space
778 </li><li>The cell content area
779 </li><li>The reserved region.
780 </li></ol>
781
782
783 <p>The 100-byte database file header is found only on page 1, which is
784 always a table b-tree page. All other b-tree pages in the database file
785 omit this 100-byte header.</p>
786
787 <p>The reserved region is an area of unused space at the end of every
788 page (except the locking page) that extensions can use to hold per-page
789 information. The size of the reserved region is determined by the one-byte
790 unsigned integer found at an offset of 20 into the database file header.
791 The size of the reserved region is usually zero.</p>
792
793 <p>The b-tree page header is 8 bytes in size for leaf pages and 12
794 bytes for interior pages. All multibyte values in the page header
795 are big-endian.
796 The b-tree page header is composed of the following fields:</p>
797
798 <center>
799 <i>B-tree Page Header Format</i><br>
800 <table border="1" width="80%">
801 <tr><th>Offset</th><th>Size</th><th>Description
802 </th></tr><tr><td align="center" valign="top">0</td><td align="center" valign="top">1</td><td align="left">
803 The one-byte flag at offset 0 indicating the b-tree page type.<ul>
804 <li>A value of 2 (0x02) means the page is an interior index b-tree page.
805 </li><li>A value of 5 (0x05) means the page is an interior table b-tree page.
806 </li><li>A value of 10 (0x0a) means the page is a leaf index b-tree page.
807 </li><li>A value of 13 (0x0d) means the page is a leaf table b-tree page.</li></ul>
808 Any other value for the b-tree page type is an error.
809 </td></tr><tr><td align="center" valign="top">1</td><td align="center" valign="top">2</td><td align="left">
810 The two-byte integer at offset 1 gives the start of the
811 first freeblock on the page, or is zero if there are no freeblocks.
812 </td></tr><tr><td align="center" valign="top">3</td><td align="center" valign="top">2</td><td align="left">
813 The two-byte integer at offset 3 gives the number of cells on the page.
814 </td></tr><tr><td align="center" valign="top">5</td><td align="center" valign="top">2</td><td align="left">
815 The two-byte integer at offset 5 designates the start of the cell content
816 area. A zero value for this integer is interpreted as 65536.
817 </td></tr><tr><td align="center" valign="top">7</td><td align="center" valign="top">1</td><td align="left">
818 The one-byte integer at offset 7 gives the number of fragmented free
819 bytes within the cell content area.
820 </td></tr><tr><td align="center" valign="top">8</td><td align="center" valign="top">4</td><td align="left">
821 The four-byte page number at offset 8 is the right-most pointer. This
822 value appears in the header of interior b-tree pages only and is omitted from
823 all other pages.
824 </td></tr></table></center>
825
826 <p>The cell pointer array of a b-tree page immediately follows the b-tree
827 page header. Let K be the number of cells on the btree. The cell pointer
828 array consists of K 2-byte integer offsets to the cell contents. The
829 cell pointers are arranged in key order with left-most cell (the cell with the
830 smallest key) first and the right-most cell (the cell with the largest
831 key) last.</p>
832
833 <p>Cell content is stored in the cell content region of the b-tree page.
834 SQLite strives to place cells as far toward the end of the b-tree page as
835 it can, in order to leave space for future growth of the cell pointer array.
836 The area in between the last cell pointer array entry and the beginning of
837 the first cell is the unallocated region.
838 </p>
839
840 <p>If a page contains no cells (which is only possible for a root page
841 of a table that contains no rows) then the offset to the
842 cell content area will equal the page size minus the bytes of reserved space.
843 If the database uses a 65536-byte page size and the reserved space is zero
844 (the usual value for reserved space) then the cell content offset of an
845 empty page wants to be 65536.
846 However, that integer is too large to be stored in a
847 2-byte unsigned integer, so a value of 0 is used in its place.
848
849 </p><p>A freeblock is a structure used to identify unallocated space within
850 a b-tree page. Freeblocks are organized as a chain. The first 2 bytes of
851 a freeblock are a big-endian integer which is the offset in the b-tree page
852 of the next freeblock in the chain, or zero if the freeblock is the last on
853 the chain. The third and fourth bytes of each freeblock form
854 a big-endian integer which is the size of the freeblock in bytes, including
855 the 4-byte header. Freeblocks are always connected in order
856 of increasing offset. The second field of the b-tree page header is the
857 offset of the first freeblock, or zero if there are no freeblocks on the
858 page. In a well-formed b-tree page, there will always be at least one cell
859 before the first freeblock.</p>
860
861 <p>A freeblock requires at least 4 bytes of space. If there is an isolated
862 group of 1, 2, or 3 unused bytes within the cell content area, those bytes
863 comprise a fragment. The total number of bytes in all fragments is stored
864 in the fifth field of the b-tree page header. In a well-formed b-tree page,
865 the total number of bytes in fragments may not exceed 60.</p>
866
867 <p>The total amount of free space on a b-tree page consists of the size
868 of the unallocated region plus the total size of all freeblocks plus the
869 number of fragmented free bytes. SQLite may from time to time reorganize
870 a b-tree page so that there are no freeblocks or fragment bytes, all
871 unused bytes are contained in the unallocated space region, and all
872 cells are packed tightly at the end of the page. This is called
873 "defragmenting" the b-tree page.</p>
874
875 <a name="varint"></a>
876
877
878 <p>A variable-length integer or "varint" is a static Huffman encoding
879 of 64-bit twos-complement integers that uses less space for small positive
880 values.
881 A varint is between 1 and 9 bytes in length. The varint consists of either
882 zero or more bytes which have the high-order bit set followed by a single byte
883 with the high-order bit clear, or nine bytes, whichever is shorter.
884 The lower seven bits of each of the first eight bytes and all 8 bits of
885 the ninth byte are used to reconstruct the 64-bit twos-complement integer.
886 Varints are big-endian: bits taken from the earlier byte of the varint
887 are more significant than bits taken from the later bytes. </p>
888
889 <p>The format of a cell depends on which kind of b-tree page the cell
890 appears on. The following table shows the elements of a cell, in
891 order of appearance, for the various b-tree page types.
892
893 </p><dl>
894 <dt><p>Table B-Tree Leaf Cell (header 0x0d):</p></dt>
895 <dd><p></p><ul>
896 <li>A varint which is the total number of bytes of payload, including any
897 overflow
898 </li><li>A varint which is the integer key, a.k.a. "<a href="lang_createtable.html#rowid">rowid</a>"
899 </li><li>The initial portion of the payload that does not spill to overflow
900 pages.
901 </li><li>A 4-byte big-endian integer page number for the first page of the
902 overflow page list - omitted if all payload fits on the b-tree page.
903 </li></ul></dd>
904
905 <dt><p>Table B-Tree Interior Cell (header 0x05):</p></dt>
906 <dd><p></p><ul>
907 <li>A 4-byte big-endian page number which is the left child pointer.
908 </li><li>A varint which is the integer key
909 </li></ul></dd>
910
911 <dt><p>Index B-Tree Leaf Cell (header 0x0a):</p></dt>
912 <dd><p></p><ul>
913 <li>A varint which is the total number of bytes of key payload, including any
914 overflow
915 </li><li>The initial portion of the payload that does not spill to overflow
916 pages.
917 </li><li>A 4-byte big-endian integer page number for the first page of the
918 overflow page list - omitted if all payload fits on the b-tree page.
919 </li></ul></dd>
920
921 <dt><p>Index B-Tree Interior Cell (header 0x02):</p></dt>
922 <dd><p></p><ul>
923 <li>A 4-byte big-endian page number which is the left child pointer.
924 </li><li>A varint which is the total number of bytes of key payload, including any
925 overflow
926 </li><li>The initial portion of the payload that does not spill to overflow
927 pages.
928 </li><li>A 4-byte big-endian integer page number for the first page of the
929 overflow page list - omitted if all payload fits on the b-tree page.
930 </li></ul></dd>
931 </dl>
932
933 <p>The information above can be recast into a table format as follows:</p>
934
935 <a name="cellformat"></a>
936
937 <center>
938 <i>B-tree Cell Format</i>
939 <table border="1" width="80%">
940 <tr><th rowspan="2">Datatype
941 </th><th colspan="4">Appears in...
942 </th><th rowspan="2">Description
943 </th></tr><tr><th>Table Leaf (0x0d)
944 </th><th>Table Interior (0x05)
945 </th><th>Index Leaf (0x0a)
946 </th><th>Index Interior (0x02)
947 </th></tr><tr><td align="center" valign="top">4-byte integer
948 </td><td align="center" valign="top">&nbsp;
949 </td><td align="center" valign="top">&#x2714;
950 </td><td align="center" valign="top">&nbsp;
951 </td><td align="center" valign="top">&#x2714;
952 </td><td align="left">Page number of left child
953 </td></tr><tr><td align="center" valign="top">varint
954 </td><td align="center" valign="top">&#x2714;
955 </td><td align="center" valign="top">&nbsp;
956 </td><td align="center" valign="top">&#x2714;
957 </td><td align="center" valign="top">&#x2714;
958 </td><td align="left">Number of bytes of payload
959 </td></tr><tr><td align="center" valign="top">varint
960 </td><td align="center" valign="top">&#x2714;
961 </td><td align="center" valign="top">&#x2714;
962 </td><td align="center" valign="top">&nbsp;
963 </td><td align="center" valign="top">&nbsp;
964 </td><td align="left">Rowid
965 </td></tr><tr><td align="center" valign="top">byte array
966 </td><td align="center" valign="top">&#x2714;
967 </td><td align="center" valign="top">&nbsp;
968 </td><td align="center" valign="top">&#x2714;
969 </td><td align="center" valign="top">&#x2714;
970 </td><td align="left">Payload
971 </td></tr><tr><td align="center" valign="top">4-byte integer
972 </td><td align="center" valign="top">&#x2714;
973 </td><td align="center" valign="top">&nbsp;
974 </td><td align="center" valign="top">&#x2714;
975 </td><td align="center" valign="top">&#x2714;
976 </td><td align="left">Page number of first overflow page
977 </td></tr></table></center>
978
979
980 <p>The amount of payload that spills onto overflow pages also depends on
981 the page type. For the following computations, let U be the usable size
982 of a database page, the total page size less the reserved space at the
983 end of each page. And let P be the payload size. In the following,
984 symbol X represents the maximum amount of payload that can be stored directly
985 on the b-tree page without spilling onto an overflow page and symbol M
986 represents the minimum amount of payload that must be stored on the btree
987 page before spilling is allowed.
988
989 </p><dl>
990 <dt><p>Table B-Tree Leaf Cell:</p></dt>
991 <dd><p>
992 Let X be U-35. If the payload size P is less than or equal to X then
993 the entire payload is stored on the b-tree leaf page.
994 Let M be ((U-12)*32/255)-23 and let K be M+((P-M)%(U-4)).
995 If P is greater than X
996 then the number of bytes stored on the table b-tree leaf page is K
997 if K is less or equal to X or M otherwise.
998 The number of bytes stored on the leaf page is never less than M.
999 </p></dd>
1000
1001 <dt><p>Table B-Tree Interior Cell:</p></dt>
1002 <dd><p>
1003 Interior pages of table b-trees have no payload and so there is never
1004 any payload to spill.
1005 </p></dd>
1006
1007 <dt><p>Index B-Tree Leaf Or Interior Cell:</p></dt>
1008 <dd><p>
1009 Let X be ((U-12)*64/255)-23. If the payload size P is less than
1010 or equal to X then the entire payload is stored on the b-tree page.
1011 Let M be ((U-12)*32/255)-23 and let K be M+((P-M)%(U-4)).
1012 If P is greater than X then the number
1013 of bytes stored on the index b-tree page is K if K is less than or
1014 equal to X or M otherwise.
1015 The number of bytes stored on the index page is never less than M.
1016 </p></dd>
1017 </dl>
1018
1019 <p>Here is an alternative description of the same computation:
1020
1021 </p><ul>
1022 <li>X is U-35 for table btree leaf pages or
1023 ((U-12)*64/255)-23 for index pages.
1024 </li><li>M is always ((U-12)*32/255)-23.
1025 </li><li>Let K be M+((P-M)%(U-4)).
1026 </li><li>If P&lt;=X then all P bytes of payload are stored directly on the
1027 btree page without overflow.
1028 </li><li>If P&gt;X and K&lt;=X then the first K bytes of P are stored on the
1029 btree page and the remaining P-K bytes are stored on overflow pages.
1030 </li><li>If P&gt;X and K&gt;X then the first M bytes of P are stored on the
1031 btree page and the remaining P-M bytes are stored on overflow pages.
1032 </li></ul>
1033
1034 <p>The overflow thresholds are designed to give a minimum fanout of
1035 4 for index b-trees and to make sure enough of the payload
1036 is on the b-tree page that the record header can usually be accessed
1037 without consulting an overflow page. In hindsight, the designer of
1038 the SQLite b-tree logic realized that these thresholds could have been
1039 made much simpler. However, the computations cannot be changed
1040 without resulting in an incompatible file format. And the current computations
1041 work well, even if they are a little complex.</p>
1042
1043 <a name="ovflpgs"></a>
1044
1045 <h2 id="cell_payload_overflow_pages"><span>1.7. </span>Cell Payload Overflow Pages</h2>
1046
1047 <p>When the payload of a b-tree cell is too large for the b-tree page,
1048 the surplus is spilled onto overflow pages. Overflow pages form a linked
1049 list. The first four bytes of each overflow page are a big-endian
1050 integer which is the page number of the next page in the chain, or zero
1051 for the final page in the chain. The fifth byte through the last usable
1052 byte are used to hold overflow content.</p>
1053
1054 <h2 id="pointer_map_or_ptrmap_pages"><span>1.8. </span>Pointer Map or Ptrmap Pages</h2>
1055
1056 <p>Pointer map or ptrmap pages are extra pages inserted into the database
1057 to make the operation of <a href="pragma.html#pragma_auto_vacuum">auto_vacuum</a> and <a href="pragma.html#pragma_incremental_vacuum">incremental_vacuum</a> modes
1058 more efficient. Other page types in the database typically have pointers
1059 from parent to child. For example, an interior b-tree page contains pointers
1060 to its child b-tree pages and an overflow chain has a pointer
1061 from earlier to later links in the chain. A ptrmap page contains linkage
1062 information going in the opposite direction, from child to parent.</p>
1063
1064 <p>Ptrmap pages must exist in any database file which has a non-zero
1065 largest root b-tree page value at offset 52 in the database header.
1066 If the largest root b-tree page value is zero, then the database must not
1067 contain ptrmap pages.</p>
1068
1069 <p>In a database with ptrmap pages, the first ptrmap page is page 2.
1070 A ptrmap page consists of an array of 5-byte entries. Let J be the
1071 number of 5-byte entries that will fit in the usable space of a page.
1072 (In other words, J=U/5.) The first ptrmap page will contain back pointer
1073 information for pages 3 through J+2, inclusive. The second pointer map
1074 page will be on page J+3 and that ptrmap page will provide back pointer
1075 information for pages J+4 through 2*J+3 inclusive. And so forth for
1076 the entire database file.</p>
1077
1078 <p>In a database that uses ptrmap pages, all pages at locations identified
1079 by the computation in the previous paragraph must be ptrmap page and no
1080 other page may be a ptrmap page. Except, if the byte-lock page happens to
1081 fall on the same page number as a ptrmap page, then the ptrmap is moved
1082 to the following page for that one case.</p>
1083
1084 <p>Each 5-byte entry on a ptrmap page provides back-link information about
1085 one of the pages that immediately follow the pointer map. If page B is a
1086 ptrmap page then back-link information about page B+1 is provided by
1087 the first entry on the pointer map. Information about page B+2 is
1088 provided by the second entry. And so forth.</p>
1089
1090 <p>Each 5-byte ptrmap entry consists of one byte of "page type" information
1091 followed by a 4-byte big-endian page number. Five page types are recognized:
1092 </p>
1093
1094 <ol>
1095 <li>A b-tree root page. The
1096 page number should be zero.
1097 </li><li>A freelist page. The page number should be
1098 zero.
1099 </li><li>The first page of a
1100 cell payload overflow chain. The page number is the b-tree page that
1101 contains the cell whose content has overflowed.
1102 </li><li>A page in an overflow chain
1103 other than the first page. The page number is the prior page of the
1104 overflow chain.
1105 </li><li>A non-root b-tree page. The
1106 page number is the parent b-tree page.
1107 </li></ol>
1108
1109 <p>In any database file that contains ptrmap pages, all b-tree root pages
1110 must come before any non-root b-tree page, cell payload overflow page, or
1111 freelist page. This restriction ensures that a root page will never
1112 be moved during an auto-vacuum or incremental-vacuum. The auto-vacuum
1113 logic does not know how to update the root_page field of the sqlite_schema
1114 table and so it is necessary to prevent root pages from being moved
1115 during an auto-vacuum in order to preserve the integrity of the
1116 sqlite_schema table. Root pages are moved to the beginning of the
1117 database file by the CREATE TABLE, CREATE INDEX, DROP TABLE, and
1118 DROP INDEX operations.</p>
1119
1120 <h1 id="schema_layer"><span>2. </span>Schema Layer</h1>
1121
1122 <p>The foregoing text describes low-level aspects of the SQLite file
1123 format. The b-tree mechanism provides a powerful and efficient means of
1124 accessing a large data set. This section will describe how the
1125 low-level b-tree layer is used to implement higher-level SQL
1126 capabilities.</p>
1127
1128 <a name="record_format"></a>
1129
1130 <h2 id="record_format"><span>2.1. </span>Record Format</h2>
1131
1132 <p>The data for a table b-tree leaf page and the key
1133 of an index b-tree page was characterized above
1134 as an arbitrary sequence of bytes.
1135 The prior discussion mentioned one key being less than another, but
1136 did not define what "less than" meant. The current section will address
1137 these omissions.</p>
1138
1139 <p>Payload, either table b-tree data or index b-tree keys,
1140 is always in the "record format".
1141 The record format defines a sequence of values corresponding
1142 to columns in a table or index. The record format specifies the number
1143 of columns, the datatype of each column, and the content of each column.</p>
1144
1145 <p>The record format makes extensive use of the
1146 <a href="fileformat2.html#varint">variable-length integer</a> or <a href="fileformat2.html#varint">varint</a>
1147 representation of 64-bit signed integers defined above.</p>
1148
1149 <a name="serialtype"></a>
1150
1151 <p>A record contains a header and a body, in that order.
1152 The header begins with a single varint which determines the total number
1153 of bytes in the header. The varint value is the size of the header in
1154 bytes including the size varint itself. Following the size varint are
1155 one or more additional varints, one per column. These additional varints
1156 are called "serial type" numbers and
1157 determine the datatype of each column, according to the following chart:</p>
1158
1159 <center>
1160 <i>Serial Type Codes Of The Record Format</i><br>
1161 <table width="80%" border="1">
1162 <tr><th>Serial Type</th><th>Content Size</th><th>Meaning
1163 </th></tr><tr><td valign="top" align="center">0</td><td valign="top" align="center">0</td><td align="left">
1164 Value is a NULL.
1165 </td></tr><tr><td valign="top" align="center">1</td><td valign="top" align="center">1</td><td align="left">
1166 Value is an 8-bit twos-complement integer.
1167 </td></tr><tr><td valign="top" align="center">2</td><td valign="top" align="center">2</td><td align="left">
1168 Value is a big-endian 16-bit twos-complement integer.
1169 </td></tr><tr><td valign="top" align="center">3</td><td valign="top" align="center">3</td><td align="left">
1170 Value is a big-endian 24-bit twos-complement integer.
1171 </td></tr><tr><td valign="top" align="center">4</td><td valign="top" align="center">4</td><td align="left">
1172 Value is a big-endian 32-bit twos-complement integer.
1173 </td></tr><tr><td valign="top" align="center">5</td><td valign="top" align="center">6</td><td align="left">
1174 Value is a big-endian 48-bit twos-complement integer.
1175 </td></tr><tr><td valign="top" align="center">6</td><td valign="top" align="center">8</td><td align="left">
1176 Value is a big-endian 64-bit twos-complement integer.
1177 </td></tr><tr><td valign="top" align="center">7</td><td valign="top" align="center">8</td><td align="left">
1178 Value is a big-endian IEEE 754-2008 64-bit floating point number.
1179 </td></tr><tr><td valign="top" align="center">8</td><td valign="top" align="center">0</td><td align="left">
1180 Value is the integer 0. (Only available for <a href="fileformat2.html#schemaformat">schema format</a> 4 and higher.)
1181 </td></tr><tr><td valign="top" align="center">9</td><td valign="top" align="center">0</td><td align="left">
1182 Value is the integer 1. (Only available for <a href="fileformat2.html#schemaformat">schema format</a> 4 and higher.)
1183 </td></tr><tr><td valign="top" align="center">10,11
1184 </td><td valign="top" align="center"><i>variable</i></td><td align="left">
1185 <i>Reserved for internal use. These serial type codes will
1186 never appear in a well-formed database file, but they
1187 might be used in transient and temporary database files
1188 that SQLite sometimes generates for its own use.
1189 The meanings of these codes can shift from one release
1190 of SQLite to the next.</i>
1191 </td></tr><tr><td valign="top" align="center">N&#x2265;12 and even
1192 </td><td valign="top" align="center">(N-12)/2</td><td align="left">
1193 Value is a BLOB that is (N-12)/2 bytes in length.
1194 </td></tr><tr><td valign="top" align="center">N&#x2265;13 and odd
1195 </td><td valign="top" align="center">(N-13)/2</td><td align="left">
1196 Value is a string in the <a href="fileformat2.html#enc">text encoding</a> and (N-13)/2 bytes in length.
1197 The nul terminator is not stored.
1198 </td></tr></table></center>
1199
1200 <p>The header size varint
1201 and serial type varints will usually consist of a single byte. The
1202 serial type varints for large strings and BLOBs might extend to two or three
1203 byte varints, but that is the exception rather than the rule.
1204 The varint format is very efficient at coding the record header.</p>
1205
1206 <p>The values for each column in the record immediately follow the header.
1207 For serial types 0, 8, 9, 12, and 13, the value is zero bytes in
1208 length. If all columns are of these types then the body section of the
1209 record is empty.</p>
1210
1211 <p>A record might have fewer values than the number of columns in the
1212 corresponding table. This can happen, for example, after an
1213 <a href="lang_altertable.html">ALTER TABLE ... ADD COLUMN</a> SQL statement has increased
1214 the number of columns in the table schema without modifying preexisting rows
1215 in the table.
1216 Missing values at the end of the record are filled in using the
1217 <a href="lang_createtable.html#dfltval">default value</a> for the corresponding columns defined in the table schema.
1218 </p>
1219
1220
1221 <h2 id="record_sort_order"><span>2.2. </span>Record Sort Order</h2>
1222
1223 <p>The order of keys in an index b-tree is determined by the sort order of
1224 the records that the keys represent. Record comparison progresses column
1225 by column. Columns of a record are examined from left to right. The
1226 first pair of columns that are not equal determines the relative order
1227 of the two records. The sort order of individual columns is as
1228 follows:</p>
1229
1230 <ol>
1231 <li>NULL values (serial type 0) sort first.
1232 </li><li>Numeric values (serial types 1 through 9) sort after NULLs
1233 and in numeric order.
1234 </li><li>Text values (odd serial types 13 and larger) sort after numeric
1235 values in the order determined by the columns <a href="datatype3.html#collation">collating function</a>.
1236 </li><li>BLOB values (even serial types 12 and larger) sort last and in the order
1237 determined by memcmp().
1238 </li></ol>
1239
1240 <p>A <a href="datatype3.html#collation">collating function</a> for each column is necessary in order to compute
1241 the order of text fields.
1242 SQLite defines three built-in collating functions:
1243 </p>
1244
1245 <blockquote><table border="0" cellspacing="10">
1246 <tr><td valign="top">BINARY
1247 </td><td> The built-in BINARY collation compares strings byte by byte
1248 using the memcmp() function
1249 from the standard C library.
1250 </td></tr><tr><td valign="top">NOCASE
1251 </td><td> The NOCASE collation is like BINARY except that uppercase
1252 ASCII characters ('A' through 'Z')
1253 are folded into their lowercase equivalents prior to running the
1254 comparison. Only ASCII characters are case-folded.
1255 NOCASE
1256 does not implement a general purpose unicode caseless comparison.
1257 </td></tr><tr><td valign="top">RTRIM
1258 </td><td> RTRIM is like BINARY except that extra spaces at the end of either
1259 string do not change the result. In other words, strings will
1260 compare equal to one another as long as they
1261 differ only in the number of spaces at the end.
1262 </td></tr></table></blockquote>
1263
1264 <p>Additional application-specific collating functions can be added to
1265 SQLite using the <a href="c3ref/create_collation.html">sqlite3_create_collation()</a> interface.</p>
1266
1267 <p>The default collating function for all strings is BINARY.
1268 Alternative collating functions for table columns can be specified in the
1269 <a href="lang_createtable.html">CREATE TABLE</a> statement using the COLLATE clause on the <a href="lang_createtable.html#tablecoldef">column definition</a>.
1270 When a column is indexed, the same collating function specified in the
1271 <a href="lang_createtable.html">CREATE TABLE</a> statement is used for the column in the index, by default,
1272 though this can be overridden using a COLLATE clause in the
1273 <a href="lang_createindex.html">CREATE INDEX</a> statement.
1274
1275 <a name="#sqltab"></a>
1276
1277 </p><h2 id="representation_of_sql_tables"><span>2.3. </span>Representation Of SQL Tables</h2>
1278
1279 <p> Each ordinary SQL table in the database schema is represented on-disk
1280 by a table b-tree. Each entry in the table b-tree corresponds to a row
1281 of the SQL table. The <a href="lang_createtable.html#rowid">rowid</a> of the SQL table is the 64-bit signed
1282 integer key for each entry in the table b-tree.</p>
1283
1284 <p> The content of each SQL table row is stored in the database file by
1285 first combining the values in the various columns into a byte array
1286 in the record format, then storing that byte array as the payload in
1287 an entry in the table b-tree. The order of values in the record is
1288 the same as the order of columns in the SQL table definition.
1289 When an SQL table includes an
1290 <a href="lang_createtable.html#rowid">INTEGER PRIMARY KEY</a> column (which aliases the <a href="lang_createtable.html#rowid">rowid</a>) then that
1291 column appears in the record as a NULL value. SQLite will always use
1292 the table b-tree key rather than the NULL value when referencing the
1293 <a href="lang_createtable.html#rowid">INTEGER PRIMARY KEY</a> column.</p>
1294
1295 <p> If the <a href="datatype3.html#affinity">affinity</a> of a column is REAL and that column contains a
1296 value that can be converted to an integer without loss of information
1297 (if the value contains no fractional part and is not too large to be
1298 represented as an integer) then the column may be stored in the record
1299 as an integer. SQLite will convert the value back to floating
1300 point when extracting it from the record.</p>
1301
1302 <h2 id="representation_of_without_rowid_tables"><span>2.4. </span>Representation of WITHOUT ROWID Tables</h2>
1303
1304 <p>If an SQL table is created using the "WITHOUT ROWID" clause at the
1305 end of its CREATE TABLE statement, then that table is a <a href="withoutrowid.html">WITHOUT ROWID</a>
1306 table and uses a different on-disk representation. A WITHOUT ROWID
1307 table uses an index b-tree rather than a table b-tree for storage.
1308 The key for each entry in the WITHOUT ROWID b-tree is a record composed
1309 of the columns of the PRIMARY KEY followed by all remaining columns of
1310 the table. The primary key columns appear in the order that they were
1311 declared in the PRIMARY KEY clause and the remaining columns appear in
1312 the order they occur in the CREATE TABLE statement.
1313
1314 </p><p>Hence, the content encoding for a WITHOUT ROWID table is the same
1315 as the content encoding for an ordinary rowid table, except that the
1316 order of the columns is rearranged so that PRIMARY KEY columns come
1317 first, and the content is used as the key in an index b-tree rather
1318 than as the data in a table b-tree.
1319 The special encoding rules for columns with REAL affinity
1320 apply to WITHOUT ROWID tables the same as they do with rowid tables.
1321
1322 </p><h3 id="suppression_of_redundant_columns_in_the_primary_key_of_without_rowid_tables"><span>2.4.1. </span>Suppression of redundant columns in the PRIMARY KEY
1323 of WITHOUT ROWID tables</h3>
1324
1325 <p>If the PRIMARY KEY of a WITHOUT ROWID tables uses the same columns
1326 with the same collating sequence more than once, then the second and
1327 subsequent occurrences of that column in the PRIMARY KEY definition are
1328 ignored. For example, the following CREATE TABLE statements all specify
1329 the same table, which will have the exact same representation on disk:
1330
1331 </p><blockquote><pre>
1332 CREATE TABLE t1(a,b,c,d,PRIMARY KEY(a,c)) WITHOUT ROWID;
1333 CREATE TABLE t1(a,b,c,d,PRIMARY KEY(a,c,a,c)) WITHOUT ROWID;
1334 CREATE TABLE t1(a,b,c,d,PRIMARY KEY(a,A,a,C)) WITHOUT ROWID;
1335 CREATE TABLE t1(a,b,c,d,PRIMARY KEY(a,a,a,a,c)) WITHOUT ROWID;
1336 </pre></blockquote>
1337
1338 <p>The first example above is the preferred definition of the table,
1339 of course. All of the examples create a WITHOUT ROWID table with
1340 two PRIMARY KEY columns, "a" and "c", in that order, followed by
1341 two data columns "b" and "d", also in that order.
1342
1343 </p><h2 id="representation_of_sql_indices"><span>2.5. </span>Representation Of SQL Indices</h2>
1344
1345 <p>Each SQL index, whether explicitly declared via a <a href="lang_createindex.html">CREATE INDEX</a> statement
1346 or implied by a UNIQUE or PRIMARY KEY constraint, corresponds to an
1347 index b-tree in the database file.
1348 Each entry in the index b-tree corresponds to a single row in the
1349 associated SQL table.
1350 The key to an index b-tree is
1351 a record composed of the columns that are being indexed followed by the
1352 key of the corresponding table row. For ordinary tables, the row key is
1353 the <a href="lang_createtable.html#rowid">rowid</a>, and for <a href="withoutrowid.html">WITHOUT ROWID</a> tables the row key is the PRIMARY KEY.
1354 Because every row in the table has a unique row key,
1355 all keys in an index are unique.</p>
1356
1357 <p>In a normal index, there is a one-to-one mapping between rows in a
1358 table and entries in each index associated with that table.
1359 However, in a <a href="partialindex.html">partial index</a>, the index b-tree only contains entries
1360 corresponding to table rows for which the WHERE clause expression on the
1361 CREATE INDEX statement is true.
1362 Corresponding rows in the index and table b-trees share the same rowid
1363 or primary key values and contain the same value for all indexed columns.</p>
1364
1365 <h3 id="suppression_of_redundant_columns_in_without_rowid_secondary_indexes_"><span>2.5.1. </span>Suppression of redundant columns in WITHOUT ROWID secondary indexes
1366 </h3>
1367
1368 <p> In an index on a WITHOUT ROWID table, if a column of the PRIMARY KEY
1369 is also a column in the index and has a matching collating sequence, then the
1370 indexed column is not repeated in the table-key suffix on the
1371 end of the index record. As an example, consider the following SQL:
1372
1373 </p><blockquote><pre>
1374 CREATE TABLE ex25(a,b,c,d,e,PRIMARY KEY(d,c,a)) WITHOUT rowid;
1375 CREATE INDEX ex25ce ON ex25(c,e);
1376 CREATE INDEX ex25acde ON ex25(a,c,d,e);
1377 CREATE INDEX ex25ae ON ex25(a COLLATE nocase,e);
1378 </pre></blockquote>
1379
1380 <p>Each row in the ex25ce index is a record
1381 with these columns: c, e, d, a. The first two columns are
1382 the columns being indexed, c and e. The remaining columns are the primary
1383 key of the corresponding table row. Normally, the primary key would be
1384 columns d, c, and a, but because column c already appears earlier in the
1385 index, it is omitted from the key suffix.</p>
1386
1387 <p>In the extreme case where the columns being indexed cover all columns
1388 of the PRIMARY KEY, the index will consist of only the columns being
1389 indexed. The ex25acde example above demonstrates this. Each entry in
1390 the ex25acde index consists of only the columns a, c, d, and e, in that
1391 order.</p>
1392
1393 <p>Each row in ex25ae contains five columns: a, e, d, c, a. The "a"
1394 column is repeated since the first occurrence of "a" has a collating
1395 function of "nocase" and the second has a collating sequence of "binary".
1396 If the "a" column is not repeated and if the table contains two or more
1397 entries with the same "e" value and where "a" differs only in case, then
1398 all of those table entries would correspond to a single entry in the
1399 index, which would break the one-to-one correspondence between the table
1400 and the index.
1401
1402 </p><p> The suppression of redundant columns in the key suffix of an index
1403 entry only occurs in WITHOUT ROWID tables. In an ordinary rowid table,
1404 the index entry always ends with the rowid even if the <a href="lang_createtable.html#rowid">INTEGER PRIMARY KEY</a>
1405 column is one of the columns being indexed.</p>
1406
1407 <a name="ffschema"></a>
1408
1409 <h2 id="storage_of_the_sql_database_schema"><span>2.6. </span>Storage Of The SQL Database Schema</h2>
1410
1411 <p>Page 1 of a database file is the root page of a table b-tree that
1412 holds a special table named "<a href="schematab.html">sqlite_schema</a>". This b-tree is known
1413 as the "schema table" since it stores the complete
1414 database schema. The structure of the sqlite_schema table is as
1415 if it had been created using the following SQL:</p>
1416
1417 <blockquote><pre>
1418 CREATE TABLE sqlite_schema(
1419 type text,
1420 name text,
1421 tbl_name text,
1422 rootpage integer,
1423 sql text
1424 );
1425 </pre></blockquote>
1426
1427 <p>The sqlite_schema table contains one row for each table, index, view,
1428 and trigger (collectively "objects") in the database schema, except there
1429 is no entry for the sqlite_schema table itself. The sqlite_schema table
1430 contains entries for <a href="fileformat2.html#intschema">internal schema objects</a> in addition to application-
1431 and programmer-defined objects.
1432
1433
1434 </p><p>The sqlite_schema.type column will be one
1435 of the following text strings: 'table', 'index', 'view', or 'trigger'
1436 according to the type of object defined. The 'table' string is used
1437 for both ordinary and <a href="vtab.html">virtual tables</a>.</p>
1438
1439 <p>The sqlite_schema.name column will hold the name of the object.
1440 <a href="lang_createtable.html#uniqueconst">UNIQUE</a> and <a href="lang_createtable.html#primkeyconst">PRIMARY KEY</a> constraints on tables cause SQLite to create
1441 <a href="fileformat2.html#intschema">internal indexes</a> with names of the form "sqlite_autoindex_TABLE_N"
1442 where TABLE is replaced by the name of the table that contains the
1443 constraint and N is an integer beginning with 1 and increasing by one
1444 with each constraint seen in the table definition.
1445 In a <a href="withoutrowid.html">WITHOUT ROWID</a> table, there is no sqlite_schema entry for the
1446 PRIMARY KEY, but the "sqlite_autoindex_TABLE_N" name is set aside
1447 for the PRIMARY KEY as if the sqlite_schema entry did exist. This
1448 will affect the numbering of subsequent UNIQUE constraints.
1449 The "sqlite_autoindex_TABLE_N" name is never allocated for an
1450 <a href="lang_createtable.html#rowid">INTEGER PRIMARY KEY</a>, either in rowid tables or WITHOUT ROWID tables.
1451 </p>
1452
1453 <p>The sqlite_schema.tbl_name column holds the name of a table or view
1454 that the object is associated with. For a table or view, the
1455 tbl_name column is a copy of the name column. For an index, the tbl_name
1456 is the name of the table that is indexed. For a trigger, the tbl_name
1457 column stores the name of the table or view that causes the trigger
1458 to fire.</p>
1459
1460 <p>The sqlite_schema.rootpage column stores the page number of the root
1461 b-tree page for tables and indexes. For rows that define views, triggers,
1462 and virtual tables, the rootpage column is 0 or NULL.</p>
1463
1464 <p>The sqlite_schema.sql column stores SQL text that describes the
1465 object. This SQL text is a <a href="lang_createtable.html">CREATE TABLE</a>, <a href="lang_createvtab.html">CREATE VIRTUAL TABLE</a>,
1466 <a href="lang_createindex.html">CREATE INDEX</a>,
1467 <a href="lang_createview.html">CREATE VIEW</a>, or <a href="lang_createtrigger.html">CREATE TRIGGER</a> statement that if evaluated against
1468 the database file when it is the main database of a <a href="c3ref/sqlite3.html">database connection</a>
1469 would recreate the object. The text is usually a copy of the original
1470 statement used to create the object but with normalizations applied so
1471 that the text conforms to the following rules:
1472
1473 </p><ul>
1474 <li>The CREATE, TABLE, VIEW, TRIGGER, and INDEX keywords at the beginning
1475 of the statement are converted to all upper case letters.
1476 </li><li>The TEMP or TEMPORARY keyword is removed if it occurs after the
1477 initial CREATE keyword.
1478 </li><li>Any database name qualifier that occurs prior to the name of the
1479 object being created is removed.
1480 </li><li>Leading spaces are removed.
1481 </li><li>All spaces following the first two keywords are converted into a single
1482 space.
1483 </li></ul>
1484
1485 <p>The text in the sqlite_schema.sql column is a copy of the original
1486 CREATE statement text that created the object, except normalized as
1487 described above and as modified by subsequent <a href="lang_altertable.html">ALTER TABLE</a> statements.
1488 The sqlite_schema.sql is NULL for the <a href="fileformat2.html#intschema">internal indexes</a> that are
1489 automatically created by <a href="lang_createtable.html#uniqueconst">UNIQUE</a> or <a href="lang_createtable.html#primkeyconst">PRIMARY KEY</a> constraints.</p>
1490
1491 <h3 id="alternative_names_for_the_schema_table"><span>2.6.1. </span>Alternative Names For The Schema Table</h3>
1492
1493 <p>The name "sqlite_schema" does not appear anywhere in the file format.
1494 That name is just a convention used by the database implementation.
1495 Due to historical and operational considerations, the
1496 "sqlite_schema" table can also sometimes be called by one of the
1497 following aliases:
1498
1499 </p><ol>
1500 <li> sqlite_master
1501 </li><li> sqlite_temp_schema
1502 </li><li> sqlite_temp_master
1503 </li></ol>
1504
1505 <p>Because the name of the schema table does not appear anywhere in
1506 the file format, the meaning of the database file is not changed if
1507 the application chooses to refer to the schema table by one of
1508 these alternative names.
1509
1510 <a name="intschema"></a>
1511
1512 </p><h3 id="internal_schema_objects"><span>2.6.2. </span>Internal Schema Objects</h3>
1513
1514 <p>In addition to the tables, indexes, views, and triggers created by
1515 the application and/or the developer using CREATE statements SQL, the
1516 sqlite_schema table may contain zero or more entries for
1517 <i>internal schema objects</i> that are created by SQLite for its
1518 own internal use. The names of internal schema objects
1519 always begin with "sqlite_" and any table, index, view, or trigger
1520 whose name begins with "sqlite_" is an internal schema object.
1521 SQLite prohibits applications from creating objects whose names begin
1522 with "sqlite_".
1523
1524 </p><p>Internal schema objects used by SQLite may include the following:
1525
1526 </p><ul>
1527 <li><p>Indices with names of the form "sqlite_autoindex_TABLE_N" that
1528 are used to implement <a href="lang_createtable.html#uniqueconst">UNIQUE</a> and <a href="lang_createtable.html#primkeyconst">PRIMARY KEY</a> constraints on
1529 ordinary tables.
1530
1531 </p></li><li><p>A table with the name "sqlite_sequence" that is used to keep track
1532 of the maximum historical <a href="lang_createtable.html#rowid">INTEGER PRIMARY KEY</a> for a table
1533 using <a href="autoinc.html">AUTOINCREMENT</a>.
1534
1535 </p></li><li><p>Tables with names of the form "sqlite_statN" where N is an integer.
1536 Such tables store database statistics gathered by the <a href="lang_analyze.html">ANALYZE</a>
1537 command and used by the query planner to help determine the best
1538 algorithm to use for each query.
1539 </p></li></ul>
1540
1541 <p>New internal schema objects names, always beginning with "sqlite_",
1542 may be added to the SQLite file format in future releases.
1543
1544 <a name="seqtab"></a>
1545
1546 </p><h3 id="the_sqlite_sequence_table"><span>2.6.3. </span>The sqlite_sequence table</h3>
1547
1548 <p>The sqlite_sequence table is an internal table used to help implement
1549 <a href="autoinc.html">AUTOINCREMENT</a>. The sqlite_sequence table is created automatically
1550 whenever any ordinary table with an AUTOINCREMENT integer primary
1551 key is created. Once created, the sqlite_sequence table exists in the
1552 sqlite_schema table forever; it cannot be dropped.
1553 The schema for the sqlite_sequence table is:
1554
1555 </p><blockquote><pre>
1556 CREATE TABLE sqlite_sequence(name,seq);
1557 </pre></blockquote>
1558
1559 <p>There is a single row in the sqlite_sequence table for each ordinary
1560 table that uses AUTOINCREMENT. The name of the table (as it appears in
1561 sqlite_schema.name) is in the sqlite_sequence.name field and the largest
1562 <a href="lang_createtable.html#rowid">INTEGER PRIMARY KEY</a> ever inserted into that table is
1563 in the sqlite_sequence.seq field.
1564 New automatically generated integer primary keys for AUTOINCREMENT
1565 tables are guaranteed to be larger than the sqlite_sequence.seq field for
1566 that table.
1567 If the sqlite_sequence.seq field of an AUTOINCREMENT table is already at
1568 the largest integer value (9223372036854775807) then attempts to add new
1569 rows to that table with an automatically generated integer primary will fail
1570 with an <a href="rescode.html#full">SQLITE_FULL</a> error.
1571 The sqlite_sequence.seq field is automatically updated if required when
1572 new entries are inserted to an AUTOINCREMENT table.
1573 The sqlite_sequence row for an AUTOINCREMENT table is automatically deleted
1574 when the table is dropped.
1575 If the sqlite_sequence row for an AUTOINCREMENT table does not exist when
1576 the AUTOINCREMENT table is updated, then a new sqlite_sequence row is created.
1577 If the sqlite_sequence.seq value for an AUTOINCREMENT table is manually
1578 set to something other than an integer and there is a subsequent attempt to
1579 insert the or update the AUTOINCREMENT table, then the behavior is undefined.
1580
1581 </p><p>Application code is allowed to modify the sqlite_sequence table, to add
1582 new rows, to delete rows, or to modify existing rows. However, application
1583 code cannot create the sqlite_sequence table if it does not already exist.
1584 Application code can delete all entries from the sqlite_sequence table,
1585 but application code cannot drop the sqlite_sequence table.
1586
1587 <a name="stat1tab"></a>
1588
1589 </p><h3 id="the_sqlite_stat1_table"><span>2.6.4. </span>The sqlite_stat1 table</h3>
1590
1591 <p>The sqlite_stat1 is an internal table created by the <a href="lang_analyze.html">ANALYZE</a> command
1592 and used to hold supplemental information about tables and indexes that the
1593 query planner can use to help it find better ways of performing queries.
1594 Applications can update, delete from, insert into or drop the sqlite_stat1
1595 table, but may not create or alter the sqlite_stat1 table.
1596 The schema of the sqlite_stat1 table is as follows:
1597
1598 </p><blockquote><pre>
1599 CREATE TABLE sqlite_stat1(tbl,idx,stat);
1600 </pre></blockquote>
1601
1602 <p> There is normally one row per index, with the index identified by the
1603 name in the sqlite_stat1.idx column. The sqlite_stat1.tbl column is
1604 the name of the table to which the index belongs. In each such row,
1605 the sqlite_stat.stat column will be
1606 a string consisting of a list of integers followed by zero or more
1607 arguments. The first integer in this
1608 list is the approximate number of rows in the index. (The number of
1609 rows in the index is the same as the number of rows in the table,
1610 except for <a href="partialindex.html">partial indexes</a>.)
1611 The second integer is the approximate number of rows in the index
1612 that have the same value in the first column of the index. The third
1613 integer is the number of rows in the index that have
1614 the same value for the first two columns. The N-th integer (for N>1)
1615 is the estimated average number of rows in
1616 the index which have the same value for the first N-1 columns. For
1617 a K-column index, there will be K+1 integers in the stat column. If
1618 the index is unique, then the last integer will be 1.
1619
1620 </p><p>The list of integers in the stat column can optionally be followed
1621 by arguments, each of which is a sequence of non-space characters.
1622 All arguments are preceded by a single space.
1623 Unrecognized arguments are silently ignored.
1624
1625 </p><p>If the "unordered" argument is present, then the query planner assumes
1626 that the index is unordered and will not use the index for a range query
1627 or for sorting.
1628
1629 </p><p>The "sz=NNN" argument (where NNN represents a sequence of 1 or more digits)
1630 means that the average row size over all records of the table or
1631 index is NNN bytes per row. The SQLite query planner might use the
1632 estimated row size information provided by the "sz=NNN" token
1633 to help it choose smaller tables and indexes that require less disk I/O.
1634
1635 </p><p>The presence of the "noskipscan" token on the sqlite_stat1.stat field
1636 of an index prevents that index from being used with the
1637 <a href="optoverview.html#skipscan">skip-scan optimization</a>.
1638
1639 </p><p>New text tokens may be added to the end of the stat column in future
1640 enhancements to SQLite. For compatibility, unrecognized tokens at the end
1641 of the stat column are silently ignored.
1642
1643 </p><p>If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
1644 column contains a single integer which is the approximate number of
1645 rows in the table identified by sqlite_stat1.tbl.
1646 If the sqlite_stat1.idx column is the same as the sqlite_stat1.tbl
1647 column, then the table is a <a href="withoutrowid.html">WITHOUT ROWID</a> table and the sqlite_stat1.stat
1648 field contains information about the index btree that implements the
1649 WITHOUT ROWID table.
1650
1651 <a name="stat2tab"></a>
1652
1653 </p><h3 id="the_sqlite_stat2_table"><span>2.6.5. </span>The sqlite_stat2 table</h3>
1654
1655 <p>The sqlite_stat2 is only created and is only used if SQLite is compiled
1656 with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
1657 3.6.18 (2009-09-11) and 3.7.8 (2011-09-19).
1658 The sqlite_stat2 table is neither read nor written by any
1659 version of SQLite before 3.6.18 nor after 3.7.8.
1660 The sqlite_stat2 table contains additional information
1661 about the distribution of keys within an index.
1662 The schema of the sqlite_stat2 table is as follows:
1663
1664 </p><blockquote><pre>
1665 CREATE TABLE sqlite_stat2(tbl,idx,sampleno,sample);
1666 </pre></blockquote>
1667
1668 <p>The sqlite_stat2.idx column and the sqlite_stat2.tbl column in each
1669 row of the sqlite_stat2 table identify an index described by that row.
1670 There are usually 10 rows in the sqlite_stat2
1671 table for each index.
1672
1673 </p><p>The sqlite_stat2 entries for an index that have sqlite_stat2.sampleno
1674 between 0 and 9 inclusive are samples of the left-most key value in the
1675 index taken at evenly spaced points along the index.
1676 Let C be the number of rows in the index.
1677 Then the sampled rows are given by
1678
1679 </p><blockquote>
1680 rownumber = (i*C*2 + C)/20
1681 </blockquote>
1682
1683 <p>The variable i in the previous expression varies between 0 and 9.
1684 Conceptually, the index space is divided into
1685 10 uniform buckets and the samples are the middle row from each bucket.
1686
1687 </p><p>The format for sqlite_stat2 is recorded here for legacy reference.
1688 Recent versions of SQLite no longer support sqlite_stat2 and the
1689 sqlite_stat2 table, if is exists, is simply ignored.
1690
1691 <a name="stat3tab"></a>
1692
1693 </p><h3 id="the_sqlite_stat3_table"><span>2.6.6. </span>The sqlite_stat3 table</h3>
1694
1695 <p>The sqlite_stat3 is only used if SQLite is compiled
1696 with <a href="compile.html#enable_stat3">SQLITE_ENABLE_STAT3</a> or <a href="compile.html#enable_stat4">SQLITE_ENABLE_STAT4</a>
1697 and if the SQLite version number is 3.7.9 (2011-11-01) or greater.
1698 The sqlite_stat3 table is neither read nor written by any
1699 version of SQLite before 3.7.9.
1700 If the <a href="compile.html#enable_stat4">SQLITE_ENABLE_STAT4</a> compile-time option is used and the
1701 SQLite version number is 3.8.1 (2013-10-17) or greater,
1702 then sqlite_stat3 might be read but not written.
1703 The sqlite_stat3 table contains additional information
1704 about the distribution of keys within an index, information that the
1705 query planner can use to devise better and faster query algorithms.
1706 The schema of the sqlite_stat3 table is as follows:
1707
1708 </p><blockquote><pre>
1709 CREATE TABLE sqlite_stat3(tbl,idx,nEq,nLt,nDLt,sample);
1710 </pre></blockquote>
1711
1712 <p>There are usually multiple entries in the sqlite_stat3 table for each index.
1713 The sqlite_stat3.sample column holds the value of the left-most field of an
1714 index identified by sqlite_stat3.idx and sqlite_stat3.tbl.
1715 The sqlite_stat3.nEq column holds the approximate
1716 number of entries in the index whose left-most column exactly matches
1717 the sample.
1718 The sqlite_stat3.nLt holds the approximate number of entries in the
1719 index whose left-most column is less than the sample.
1720 The sqlite_stat3.nDLt column holds the approximate
1721 number of distinct left-most entries in the index that are less than
1722 the sample.
1723
1724 </p><p>There can be an arbitrary number of sqlite_stat3 entries per index.
1725 The <a href="lang_analyze.html">ANALYZE</a> command will typically generate sqlite_stat3 tables
1726 that contain between 10 and 40 samples that are distributed across
1727 the key space and with large nEq values.
1728
1729 </p><p>In a well-formed sqlite_stat3 table, the samples for any single
1730 index must appear in the same order that they occur in the index.
1731 In other words, if the entry with left-most column S1 is earlier in
1732 the index b-tree than the
1733 entry with left-most column S2, then in the sqlite_stat3 table,
1734 sample S1 must have a smaller rowid than sample S2.
1735
1736 <a name="stat4tab"></a>
1737
1738 </p><h3 id="the_sqlite_stat4_table"><span>2.6.7. </span>The sqlite_stat4 table</h3>
1739
1740 <p>The sqlite_stat4 is only created and is only used if SQLite is compiled
1741 with <a href="compile.html#enable_stat4">SQLITE_ENABLE_STAT4</a> and if the SQLite version number is
1742 3.8.1 (2013-10-17) or greater.
1743 The sqlite_stat4 table is neither read nor written by any
1744 version of SQLite before 3.8.1.
1745 The sqlite_stat4 table contains additional information
1746 about the distribution of keys within an index or the distribution of
1747 keys in the primary key of a <a href="withoutrowid.html">WITHOUT ROWID</a> table.
1748 The query planner can sometimes use the additional information in
1749 the sqlite_stat4 table to devise better and faster query algorithms.
1750 The schema of the sqlite_stat4 table is as follows:
1751
1752 </p><blockquote><pre>
1753 CREATE TABLE sqlite_stat4(tbl,idx,nEq,nLt,nDLt,sample);
1754 </pre></blockquote>
1755
1756 <p>There are typically between 10 to 40 entries in the sqlite_stat4 table for
1757 each index for which statistics are available, however these limits are
1758 not hard bounds.
1759 The meanings of the columns in the sqlite_stat4 table are as follows:
1760
1761 </p><center>
1762 <table border="0" width="100%" cellpadding="10">
1763 <tr><td valign="top" align="right">tbl:</td>
1764 <td>The sqlite_stat4.tbl column holds name of the table that owns
1765 the index that the row describes
1766
1767 </td></tr><tr><td valign="top" align="right">idx:</td>
1768 <td>The sqlite_stat4.idx column holds name of the index that the
1769 row describes, or in the case of
1770 an sqlite_stat4 entry for a <a href="withoutrowid.html">WITHOUT ROWID</a> table, the
1771 name of the table itself.
1772
1773 </td></tr><tr><td valign="top" align="right">sample:</td>
1774 <td>The sqlite_stat4.sample column holds a BLOB
1775 in the <a href="fileformat2.html#record_format">record format</a> that encodes the indexed columns followed by
1776 the rowid for a rowid table or by the columns of the primary key
1777 for a WITHOUT ROWID table.
1778 The sqlite_stat4.sample BLOB for the WITHOUT ROWID table itself
1779 contains just the columns of the primary key.
1780 Let the number of columns encoded by the sqlite_stat4.sample blob be N.
1781 For indexes on an ordinary rowid table, N will be one more than the number
1782 of columns indexed.
1783 For indexes on WITHOUT ROWID tables, N will be the number of columns
1784 indexed plus the number of columns in the primary key.
1785 For a WITHOUT ROWID table, N will be the number of columns in the
1786 primary key.
1787
1788 </td></tr><tr><td valign="top" align="right">nEq:</td>
1789 <td>The sqlite_stat4.nEq column holds a list of N integers where
1790 the K-th integer is the approximate number of entries in the index
1791 whose left-most K columns exactly match the K left-most columns
1792 of the sample.
1793
1794 </td></tr><tr><td valign="top" align="right">nLt:</td>
1795 <td>The sqlite_stat4.nLt column holds a list of N integers where
1796 the K-th integer is the approximate number of entries in the
1797 index whose K left-most columns are collectively less than the
1798 K left-most columns of the sample.
1799
1800 </td></tr><tr><td valign="top" align="right">nDLt:</td>
1801 <td>The sqlite_stat4.nDLt column holds a list of N integers where
1802 the K-th integer is the approximate
1803 number of entries in the index that are distinct in the first K columns and
1804 where the left-most K columns are collectively less than the left-most
1805 K columns of the sample.
1806 </td></tr></table>
1807 </center>
1808
1809 <p>The sqlite_stat4 is a generalization of the sqlite_stat3 table. The
1810 sqlite_stat3 table provides information about the left-most column of an
1811 index whereas the sqlite_stat4 table provides information about all columns
1812 of the index.
1813
1814 </p><p>There can be an arbitrary number of sqlite_stat4 entries per index.
1815 The <a href="lang_analyze.html">ANALYZE</a> command will typically generate sqlite_stat4 tables
1816 that contain between 10 and 40 samples that are distributed across
1817 the key space and with large nEq values.
1818
1819 </p><p>In a well-formed sqlite_stat4 table, the samples for any single
1820 index must appear in the same order that they occur in the index.
1821 In other words, if entry S1 is earlier in the index b-tree than
1822 entry S2, then in the sqlite_stat4 table, sample S1 must have a
1823 smaller rowid than sample S2.
1824
1825 <a name="rollbackjournal"></a>
1826
1827 </p><h1 id="the_rollback_journal"><span>3. </span>The Rollback Journal</h1>
1828
1829 <p>The rollback journal is a file associated with each SQLite database
1830 file that holds information used to restore the database file to its initial
1831 state during the course of a transaction.
1832 The rollback journal file is always located in the same
1833 directory as the database
1834 file and has the same name as the database file but with the string
1835 "<tt>-journal</tt>" appended. There can only be a single rollback journal
1836 associated with a give database and hence there can only be one write
1837 transaction open against a single database at one time.</p>
1838
1839 <p>Before any information-bearing page of the database is modified,
1840 the original unmodified content of that page is written into the
1841 rollback journal. If a transaction is interrupted and needs to be
1842 rolled back, the rollback journal can then be used to restore the
1843 database to its original state. Freelist leaf pages bear no
1844 information that would need to be restored on a rollback and so they
1845 are not written to the journal prior to modification, in order to
1846 reduce disk I/O.</p>
1847
1848 <p>If a transaction is aborted due to an application crash, or a single,
1849 or an operating system crash, or a hardware power failure or crash, then
1850 the main database file might be left in an inconsistent state.
1851 The next time SQLite attempts to open
1852 the database file, the presence of the rollback journal file will be
1853 detected and the journal will be automatically played back to restore the
1854 database to its state at the start of the incomplete transaction.</p>
1855
1856 <p>A rollback journal is only considered to be valid if it exists and
1857 contains a valid header. Hence a transaction can be committed in one
1858 of three ways:
1859 </p><ol>
1860 <li>The rollback journal file can be deleted,
1861 </li><li>The rollback journal file can be truncated to zero length, or
1862 </li><li>The header of the rollback journal can be overwritten with
1863 invalid header text (for example, all zeros).
1864 </li></ol>
1865 <p>
1866 These three ways of committing a transaction correspond to the DELETE,
1867 TRUNCATE, and PERSIST settings, respectively, of the <a href="pragma.html#pragma_journal_mode">journal_mode pragma</a>.
1868 </p>
1869
1870
1871 <p>A valid rollback journal begins with a header in the following format:</p>
1872
1873 <center>
1874 <i>Rollback Journal Header Format</i><br>
1875 <table width="80%" border="1">
1876 <tr><th>Offset</th><th>Size</th><th>Description
1877 </th></tr><tr><td valign="top" align="center">0
1878 </td><td valign="top" align="center">8
1879 </td><td>Header string: 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7
1880 </td></tr><tr><td valign="top" align="center">8
1881 </td><td valign="top" align="center">4
1882 </td><td>The "Page Count" - The number of pages in the next segment of the
1883 journal, or -1 to
1884 mean all content to the end of the file
1885 </td></tr><tr><td valign="top" align="center">12
1886 </td><td valign="top" align="center">4
1887 </td><td>A random nonce for the checksum
1888 </td></tr><tr><td valign="top" align="center">16
1889 </td><td valign="top" align="center">4
1890 </td><td>Initial size of the database in pages
1891 </td></tr><tr><td valign="top" align="center">20
1892 </td><td valign="top" align="center">4
1893 </td><td>Size of a disk sector assumed by the process that wrote this
1894 journal.
1895 </td></tr><tr><td valign="top" align="center">24
1896 </td><td valign="top" align="center">4
1897 </td><td>Size of pages in this journal.
1898 </td></tr></table>
1899 </center>
1900
1901 <p>A rollback journal header is padded with zeros out to the size of a
1902 single sector (as defined by the sector size integer at offset 20).
1903 The header is in a sector by itself so that if a power loss occurs while
1904 writing the sector, information that follows the header will be
1905 (hopefully) undamaged.</p>
1906
1907 <p>After the header and zero padding are zero or more page records. Each
1908 page record stores a copy of the content of a page from the database file
1909 before it was changed. The same page may not appear more than once
1910 within a single rollback journal.
1911 To rollback an incomplete transaction, a process
1912 has merely to read the rollback journal from beginning to end and
1913 write pages found in the journal back into the database file at the
1914 appropriate location.</p>
1915
1916 <p>Let the database page size (the value of the integer at offset 24
1917 in the journal header) be N.
1918 Then the format of a page record is as follows:</p>
1919
1920 <center>
1921 <i>Rollback Journal Page Record Format</i><br>
1922 <table width="80%" border="1">
1923 <tr><th>Offset</th><th>Size</th><th>Description
1924 </th></tr><tr><td valign="top" align="center">0
1925 </td><td valign="top" align="center">4
1926 </td><td>The page number in the database file
1927 </td></tr><tr><td valign="top" align="center">4
1928 </td><td valign="top" align="center">N
1929 </td><td>Original content of the page prior to the start of the transaction
1930 </td></tr><tr><td valign="top" align="center">N+4
1931 </td><td valign="top" align="center">4
1932 </td><td>Checksum
1933 </td></tr></table>
1934 </center>
1935
1936
1937 <p>The checksum is an unsigned 32-bit integer computed as follows:</p>
1938
1939 <ol>
1940 <li>Initialize the checksum to the checksum nonce value found in the
1941 journal header at offset 12.
1942 </li><li>Initialize index X to be N-200 (where N is the size of a database page
1943 in bytes.
1944 </li><li>Interpret the byte at offset X into the page as an 8-bit unsigned integer
1945 and add the value of that integer to the checksum.
1946 </li><li>Subtract 200 from X.
1947 </li><li>If X is greater than or equal to zero, go back to step 3.
1948 </li></ol>
1949
1950 <p>The checksum value is used to guard against incomplete writes of
1951 a journal page record following a power failure. A different random nonce
1952 is used each time a transaction is started in order to minimize the risk
1953 that unwritten sectors might by chance contain data from the same page
1954 that was a part of prior journals. By changing the nonce for each
1955 transaction, stale data on disk will still generate an incorrect checksum
1956 and be detected with high probability. The checksum only uses a sparse sample
1957 of 32-bit words from the data record for performance reasons - design studies
1958 during the planning phases of SQLite 3.0.0 showed
1959 a significant performance hit in checksumming the entire page.</p>
1960
1961 <p>Let the page count value at offset 8 in the journal header be M.
1962 If M is greater than zero then after M page records the journal file
1963 may be zero padded out to the next multiple of the sector size and another
1964 journal header may be inserted. All journal headers within the same
1965 journal must contain the same database page size and sector size.</p>
1966
1967 <p>If M is -1 in the initial journal header, then the number of page records
1968 that follow is computed by computing how many page records will fit in
1969 the available space of the remainder of the journal file.</p>
1970
1971 <a name="walformat"></a>
1972
1973 <h1 id="the_write_ahead_log"><span>4. </span>The Write-Ahead Log</h1>
1974
1975 <p>Beginning with <a href="releaselog/3_7_0.html">version 3.7.0</a> (2010-07-21),
1976 SQLite supports a new transaction
1977 control mechanism called "<a href="wal.html">write-ahead log</a>" or "<a href="wal.html">WAL</a>".
1978 When a database is in WAL mode, all connections to that database must
1979 use the WAL. A particular database will use either a rollback journal
1980 or a WAL, but not both at the same time.
1981 The WAL is always located in the same directory as the database
1982 file and has the same name as the database file but with the string
1983 "<tt>-wal</tt>" appended.</p>
1984
1985 <h2 id="wal_file_format"><span>4.1. </span>WAL File Format</h2>
1986
1987 <p>A <a href="wal.html#walfile">WAL file</a> consists of a header followed by zero or more "frames".
1988 Each frame records the revised content of a single page from the
1989 database file. All changes to the database are recorded by writing
1990 frames into the WAL. Transactions commit when a frame is written that
1991 contains a commit marker. A single WAL can and usually does record
1992 multiple transactions. Periodically, the content of the WAL is
1993 transferred back into the database file in an operation called a
1994 "checkpoint".</p>
1995
1996 <p>A single WAL file can be reused multiple times. In other words, the
1997 WAL can fill up with frames and then be checkpointed and then new
1998 frames can overwrite the old ones. A WAL always grows from beginning
1999 toward the end. Checksums and counters attached to each frame are
2000 used to determine which frames within the WAL are valid and which
2001 are leftovers from prior checkpoints.</p>
2002
2003 <p>The WAL header is 32 bytes in size and consists of the following eight
2004 big-endian 32-bit unsigned integer values:</p>
2005
2006 <center>
2007 <i>WAL Header Format</i><br>
2008 <table width="80%" border="1">
2009 <tr><th>Offset</th><th>Size</th><th>Description
2010 </th></tr><tr><td valign="top" align="center">0</td><td valign="top" align="center">4
2011 </td><td>Magic number. 0x377f0682 or 0x377f0683
2012 </td></tr><tr><td valign="top" align="center">4</td><td valign="top" align="center">4
2013 </td><td>File format version. Currently 3007000.
2014 </td></tr><tr><td valign="top" align="center">8</td><td valign="top" align="center">4
2015 </td><td>Database page size. Example: 1024
2016 </td></tr><tr><td valign="top" align="center">12</td><td valign="top" align="center">4
2017 </td><td>Checkpoint sequence number
2018 </td></tr><tr><td valign="top" align="center">16</td><td valign="top" align="center">4
2019 </td><td>Salt-1: random integer incremented with each checkpoint
2020 </td></tr><tr><td valign="top" align="center">20</td><td valign="top" align="center">4
2021 </td><td>Salt-2: a different random number for each checkpoint
2022 </td></tr><tr><td valign="top" align="center">24</td><td valign="top" align="center">4
2023 </td><td>Checksum-1: First part of a checksum on the first 24 bytes of header
2024 </td></tr><tr><td valign="top" align="center">28</td><td valign="top" align="center">4
2025 </td><td>Checksum-2: Second part of the checksum on the first 24 bytes of header
2026 </td></tr></table>
2027 </center>
2028
2029 <p>Immediately following the wal-header are zero or more frames. Each
2030 frame consists of a 24-byte frame-header followed by a <i>page-size</i> bytes
2031 of page data. The frame-header is six big-endian 32-bit unsigned
2032 integer values, as follows:
2033
2034 </p><center>
2035 <i>WAL Frame Header Format</i><br>
2036 <table width="80%" border="1">
2037 <tr><th>Offset</th><th>Size</th><th>Description
2038 </th></tr><tr><td valign="top" align="center">0</td><td valign="top" align="center">4
2039 </td><td>Page number
2040 </td></tr><tr><td valign="top" align="center">4</td><td valign="top" align="center">4
2041 </td><td>For commit records, the size of the database file in pages
2042 after the commit. For all other records, zero.
2043 </td></tr><tr><td valign="top" align="center">8</td><td valign="top" align="center">4
2044 </td><td>Salt-1 copied from the WAL header
2045 </td></tr><tr><td valign="top" align="center">12</td><td valign="top" align="center">4
2046 </td><td>Salt-2 copied from the WAL header
2047 </td></tr><tr><td valign="top" align="center">16</td><td valign="top" align="center">4
2048 </td><td>Checksum-1: Cumulative checksum up through and including this page
2049 </td></tr><tr><td valign="top" align="center">20</td><td valign="top" align="center">4
2050 </td><td>Checksum-2: Second half of the cumulative checksum.
2051 </td></tr></table>
2052 </center>
2053
2054 <p>A frame is considered valid if and only if the following conditions are
2055 true:</p>
2056
2057 <ol>
2058 <li><p>The salt-1 and salt-2 values in the frame-header match
2059 salt values in the wal-header</p></li>
2060
2061 <li><p>The checksum values in the final 8 bytes of the frame-header
2062 exactly match the checksum computed consecutively on the
2063 first 24 bytes of the WAL header and the first 8 bytes and
2064 the content of all frames
2065 up to and including the current frame.</p></li>
2066 </ol>
2067
2068 <a name="walcksm"></a>
2069
2070 <h2 id="checksum_algorithm"><span>4.2. </span>Checksum Algorithm</h2>
2071
2072 <p>The checksum is computed by interpreting the input as
2073 an even number of unsigned 32-bit integers: x(0) through x(N).
2074 The 32-bit integers are big-endian if the
2075 magic number in the first 4 bytes of the WAL header is 0x377f0683 and
2076 the integers are little-endian if the magic number is 0x377f0682.
2077 The checksum values are always stored in the frame header in a
2078 big-endian format regardless of which byte order is used to compute
2079 the checksum.</p>
2080
2081 <p>The checksum algorithm only works for content which is a multiple of
2082 8 bytes in length. In other words, if the inputs are x(0) through x(N)
2083 then N must be odd.
2084 The checksum algorithm is as follows:
2085
2086 </p><blockquote><pre>
2087 s0 = s1 = 0
2088 for i from 0 to n-1 step 2:
2089 s0 += x(i) + s1;
2090 s1 += x(i+1) + s0;
2091 endfor
2092 # result in s0 and s1
2093 </pre></blockquote>
2094
2095 <p>The outputs s0 and s1 are both weighted checksums using Fibonacci weights
2096 in reverse order. (The largest Fibonacci weight occurs on the first element
2097 of the sequence being summed.) The s1 value spans all 32-bit integer
2098 terms of the sequence whereas s0 omits the final term.</p>
2099
2100 <h2 id="checkpoint_algorithm"><span>4.3. </span>Checkpoint Algorithm</h2>
2101
2102 <p>On a <a href="wal.html#ckpt">checkpoint</a>, the WAL is first flushed to persistent storage using
2103 the xSync method of the <a href="c3ref/io_methods.html">VFS</a>.
2104 Then valid content of the WAL is transferred into the database file.
2105 Finally, the database is flushed to persistent storage using another
2106 xSync method call.
2107 The xSync operations serve as write barriers - all writes launched
2108 before the xSync must complete before any write that launches after the
2109 xSync begins.</p>
2110
2111 <p>A checkpoint need not run to completion. It might be that some
2112 readers are still using older transactions with data that is contained
2113 in the database file. In that case, transferring content for newer
2114 transactions from the WAL file into the database would delete the content
2115 out from under readers still using the older transactions. To avoid that,
2116 checkpoints only run to completion if all reader are using the
2117 last transaction in the WAL.
2118
2119 <a name="walreset"></a>
2120
2121 </p><h2 id="wal_reset"><span>4.4. </span>WAL Reset</h2>
2122
2123 <p>After a complete checkpoint, if no other connections are in transactions
2124 that use the WAL, then subsequent write transactions can
2125 overwrite the WAL file from the beginning. This is called "resetting the
2126 WAL". At the start of the first new
2127 write transaction, the WAL header salt-1 value is incremented
2128 and the salt-2 value is randomized. These changes to the salts invalidate
2129 old frames in the WAL that have already been checkpointed but not yet
2130 overwritten, and prevent them from being checkpointed again.</p>
2131
2132 <p>The WAL file can optionally be truncated on a reset, but it need not be.
2133 Performance is usually a little better if the WAL is not truncated, since
2134 filesystems generally will overwrite an existing file faster than they
2135 will grow a file.
2136
2137 <a name="walread"></a>
2138
2139 </p><h2 id="reader_algorithm"><span>4.5. </span>Reader Algorithm</h2>
2140
2141 <p>To read a page from the database (call it page number P), a reader
2142 first checks the WAL to see if it contains page P. If so, then the
2143 last valid instance of page P that is followed by a commit frame
2144 or is a commit frame itself becomes the value read. If the WAL
2145 contains no copies of page P that are valid and which are a commit
2146 frame or are followed by a commit frame, then page P is read from
2147 the database file.</p>
2148
2149 <p>To start a read transaction, the reader records the number of value
2150 frames in the WAL as "mxFrame". (<a href="walformat.html#mxframe">More detail</a>)
2151 The reader uses this recorded mxFrame value
2152 for all subsequent read operations. New transactions can be appended
2153 to the WAL, but as long as the reader uses its original mxFrame value
2154 and ignores subsequently appended content, the reader will see a
2155 consistent snapshot of the database from a single point in time.
2156 This technique allows multiple concurrent readers to view different
2157 versions of the database content simultaneously.</p>
2158
2159 <p>The reader algorithm in the previous paragraphs works correctly, but
2160 because frames for page P can appear anywhere within the WAL, the
2161 reader has to scan the entire WAL looking for page P frames. If the
2162 WAL is large (multiple megabytes is typical) that scan can be slow,
2163 and read performance suffers. To overcome this problem, a separate
2164 data structure called the wal-index is maintained to expedite the
2165 search for frames of a particular page.</p>
2166
2167 <a name="walindexformat"></a>
2168
2169 <h2 id="wal_index_format"><span>4.6. </span>WAL-Index Format</h2>
2170
2171 <p>Conceptually, the wal-index is shared memory, though the current
2172 VFS implementations use a memory-mapped file for operating-system
2173 portability. The memory-mapped
2174 file is in the same directory as the database and has the same name
2175 as the database with a "<tt>-shm</tt>" suffix appended. Because
2176 the wal-index is shared memory, SQLite does not support
2177 <a href="pragma.html#pragma_journal_mode">journal_mode=WAL</a>
2178 on a network filesystem when clients are on different machines, as
2179 all clients of the database must be able to share the same memory.</p>
2180
2181 <p>The purpose of the wal-index is to answer this question quickly:</p>
2182
2183 <blockquote><i>
2184 Given a page number P and a maximum WAL frame index M,
2185 return the largest WAL frame index for page P that does not exceed M,
2186 or return NULL if there are no frames for page P that do not exceed M.
2187 </i></blockquote>
2188
2189 <p>The <i>M</i> value in the previous paragraph is the "mxFrame" value
2190 defined in <a href="fileformat2.html#walread">section 4.4</a> that is read at the start
2191 of a transaction and which defines the maximum frame from the WAL that
2192 the reader will use.</p>
2193
2194 <p>The wal-index is transient. After a crash, the wal-index is
2195 reconstructed from the original WAL file. The VFS is required
2196 to either truncate or zero the header of the wal-index when the last
2197 connection to it closes. Because the wal-index is transient, it can
2198 use an architecture-specific format; it does not have to be cross-platform.
2199 Hence, unlike the database and WAL file formats which store all values
2200 as big endian, the wal-index stores multi-byte values in the native
2201 byte order of the host computer.</p>
2202
2203 <p>This document is concerned with the persistent state of the database
2204 file, and since the wal-index is a transient structure, no further
2205 information about the format of the wal-index will be provided here.
2206 Additional details on the format of the wal-index are contained in
2207 the separate <a href="walformat.html#walidxfmt">WAL-index File Format</a> document.</p>
2208 <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/fileformat2.in?m=745ac9d6ba">2024-07-24 10:03:34</a> UTC </small></i></p>
2209