Debian Codegraph @

www/appfileformat.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>SQLite As An Application 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
119
120
121 <h1 align="center">
122 SQLite As An Application File Format
123 </h1>
124
125 <h2>Executive Summary</h2>
126
127 <p>An SQLite database file with a defined schema
128 often makes an excellent application file format.
129 Here are a dozen reasons why this is so:
130
131 <ol>
132 <li> Simplified Application Development
133 <li> Single-File Documents
134 <li> High-Level Query Language
135 <li> Accessible Content
136 <li> Cross-Platform
137 <li> Atomic Transactions
138 <li> Incremental And Continuous Updates
139 <li> Easily Extensible
140 <li> Performance
141 <li> Concurrent Use By Multiple Processes
142 <li> Multiple Programming Languages
143 <li> Better Applications
144 </ol>
145
146 <p>Each of these points will be described in more detail below,
147 after first considering more closely the meaning of
148 "application file format". See also the <a href="aff_short.html">short version</a> of this
149 whitepaper.
150
151 <h2>What Is An Application File Format?</h2>
152
153 <p>
154 An "application file format" is the file format
155 used to persist application state to disk or to exchange
156 information between programs.
157 There are thousands of application file formats in use today.
158 Here are just a few examples:
159
160 <ul>
161 <li>DOC - Word Perfect and Microsoft Office documents
162 <li>DWG - AutoCAD drawings
163 <li>PDF - Portable Document Format from Adobe
164 <li>XLS - Microsoft Excel Spreadsheet
165 <li>GIT - Git source code repository
166 <li>EPUB - The Electronic Publication format used by non-Kindle eBooks
167 <li>ODT - The Open Document format used by OpenOffice and others
168 <li>PPT - Microsoft PowerPoint presentations
169 <li>ODP - The Open Document presentation format used by OpenOffice and others
170 </ul>
171
172 <p>We make a distinction between a "file format" and an "application format".
173 A file format is used to store a single object. So, for example, a GIF or
174 JPEG file stores a single image, and an XHTML file stores text,
175 so those are "file formats" and not "application formats". An EPUB file,
176 in contrast, stores both text and images (as contained XHTML and GIF/JPEG
177 files) and so it is considered an "application format". This article is
178 about "application formats".
179
180 <p>The boundary between a file format and an application format is fuzzy.
181 This article calls JPEG a file format, but for an image editor, JPEG
182 might be considered the application format. Much depends on context.
183 For this article, let us say that a file format stores a single object
184 and an application format stores many different objects and their relationships
185 to one another.
186
187 <p>Most application formats fit into one of these three categories:
188
189 <ol>
190 <li><p><b>Fully Custom Formats.</b>
191 Custom formats are specifically designed for a single application.
192 DOC, DWG, PDF, XLS, and PPT are examples of custom formats. Custom
193 formats are usually contained within a single file, for ease of transport.
194 They are also usually binary, though the DWG format is a notable exception.
195 Custom file formats require specialized application code
196 to read and write and are not normally accessible from commonly
197 available tools such as unix command-line programs and text editors.
198 In other words, custom formats are usually "opaque blobs".
199 To access the content of a custom application file format, one needs
200 a tool specifically engineered to read and/or write that format.
201
202 <li><p><b>Pile-of-Files Formats.</b>
203 Sometimes the application state is stored as a hierarchy of
204 files. Git is a prime example of this, though the phenomenon occurs
205 frequently in one-off and bespoke applications. A pile-of-files format
206 essentially uses the filesystem as a key/value database, storing small
207 chunks of information into separate files. This gives the
208 advantage of making the content more accessible to common utility
209 programs such as text editors or "awk" or "grep". But even if many
210 of the files in a pile-of-files format
211 are easily readable, there are usually some files that have their
212 own custom format (example: Git "Packfiles") and are hence
213 "opaque blobs" that are not readable
214 or writable without specialized tools. It is also much less convenient
215 to move a pile-of-files from one place or machine to another, than
216 it is to move a single file. And it is hard to make a pile-of-files
217 document into an email attachment, for example. Finally, a pile-of-files
218 format breaks the "document metaphor":
219 there is no one file that a user can point to
220 that is "the document".
221
222 <li><p><b>Wrapped Pile-of-Files Formats.</b>
223 Some applications use a Pile-of-Files that is then encapsulated into
224 some kind of single-file container, usually a ZIP archive.
225 EPUB, ODT,and ODP are examples of this approach.
226 An EPUB book is really just a ZIP archive that contains various
227 XHTML files for the text of book chapters, GIF and JPEG images for
228 the artwork, and a specialized catalog file that tells the eBook
229 reader how all the XML and image files fit together. OpenOffice
230 documents (ODT and ODP) are also ZIP archives containing XML and
231 images that represent their content as well as "catalog" files that
232 show the interrelationships between the component parts.
233
234 <p>A wrapped pile-of-files format is a compromise between a full
235 custom file format and a pure pile-of-files format.
236 A wrapped pile-of-files format is not an opaque blob in the same sense
237 as a custom format, since the component parts can still be accessed
238 using any common ZIP archiver, but the format is not quite as accessible
239 as a pure pile-of-files format because one does still need the ZIP
240 archiver, and one cannot normally use command-line tools like "find"
241 on the file hierarchy without first un-zipping it. On the other
242 hand, a wrapped pile-of-files format does preserve the document
243 metaphor by putting all content into a single disk file. And
244 because it is compressed, the wrapped pile-of-files format tends to
245 be more compact.
246
247 <p>As with custom file formats, and unlike pure pile-of-file formats,
248 a wrapped pile-of-files format is not as easy to edit, since
249 usually the entire file must be rewritten in order to change any
250 component part.
251 </ol>
252
253 <p>The purpose of this document is to argue in favor of a fourth
254 new category of application file format: An SQLite database file.
255
256 <h2>SQLite As The Application File Format</h2>
257
258 <p>
259 Any application state that can be recorded in a pile-of-files can
260 also be recorded in an SQLite database with a simple key/value schema
261 like this:
262 <blockquote><pre>
263 CREATE TABLE files(filename TEXT PRIMARY KEY, content BLOB);
264 </pre></blockquote>
265 If the content is compressed, then such an <a href="sqlar.html">SQLite Archive</a> database is
266 <a href="affcase1.html#smaller">the same size</a> (&#177;1%)
267 as an equivalent ZIP archive, and it has the advantage
268 of being able to update individual "files" without rewriting
269 the entire document.
270
271 <p>
272 But an SQLite database is not limited to a simple key/value structure
273 like a pile-of-files database. An SQLite database can have dozens
274 or hundreds or thousands of different tables, with dozens or
275 hundreds or thousands of fields per table, each with different datatypes
276 and constraints and particular meanings, all cross-referencing each other,
277 appropriately and automatically indexed for rapid retrieval,
278 and all stored efficiently and compactly in a single disk file.
279 And all of this structure is succinctly documented for humans
280 by the SQL schema.
281
282 <p>In other words, an SQLite database can do everything that a
283 pile-of-files or wrapped pile-of-files format can do, plus much more,
284 and with greater lucidity.
285 An SQLite database is a more versatile container than key/value
286 filesystem or a ZIP archive. (For a detailed example, see the
287 <a href="affcase1.html">OpenOffice case study</a> essay.)
288
289 <p>The power of an SQLite database could, in theory, be achieved using
290 a custom file format. But any custom file format that is as expressive
291 as a relational database would likely require an enormous design specification
292 and many tens or hundreds of thousands of lines of code to
293 implement. And the end result would be an "opaque blob" that is
294 inaccessible without specialized tools.
295
296 <p>
297 Hence, in comparison to other approaches, the use of
298 an SQLite database as an application file format has
299 compelling advantages. Here are a few of these advantages,
300 enumerated and expounded:
301 </p>
302
303 <ol>
304 <li><p><b>Simplified Application Development.</b>
305 No new code is needed for reading or writing the application file.
306 One has merely to link against the SQLite library, or include the
307 <a href="amalgamation.html">single "sqlite3.c" source file</a> with the rest of the
308 application C code, and SQLite will take care of all of the application
309 file I/O. This can reduce application code size by many thousands of
310 lines, with corresponding saving in development and maintenance costs.
311
312 <p>SQLite is one of the
313 <a href="mostdeployed.html">most used</a> software libraries in the world.
314 There are literally tens of billions of SQLite database files in use
315 daily, on smartphones and gadgets and in desktop applications.
316 SQLite is <a href="testing.html">carefully tested</a> and proven reliable. It is not
317 a component that needs much tuning or debugging, allowing developers
318 to stay focused on application logic.
319
320 <li><p><b>Single-File Documents.</b>
321 An SQLite database is contained in a single file, which is easily
322 copied or moved or attached. The "document" metaphor is preserved.
323
324 <p>SQLite does not have any file naming requirements
325 and so the application can use any custom file suffix that it wants
326 to help identify the file as "belonging" to the application.
327 SQLite database files contain a 4-byte <a href="fileformat2.html#appid">Application ID</a> in
328 their headers that can be set to an application-defined value
329 and then used to identify the "type" of the document for utility
330 programs such as <a href="http://linux.die.net/man/1/file">file(1)</a>, further
331 enhancing the document metaphor.
332
333
334 <li><p><b>High-Level Query Language.</b>
335 SQLite is a complete relational database engine, which means that the
336 application can access content using high-level queries. Application
337 developers need not spend time thinking about "how" to retrieve the
338 information they need from a document. Developers write SQL that
339 expresses "what" information they want and let the database engine
340 to figure out how to best retrieve that content. This helps developers
341 operate "heads up" and remain focused on solving the user's problem,
342 and avoid time spent "heads down" fiddling with low-level file
343 formatting details.
344
345 <p>A pile-of-files format can be viewed as a key/value database.
346 A key/value database is better than no database at all.
347 But without transactions or indices or a high-level query language or
348 a proper schema,
349 it is much harder and more error prone to use a key/value database than
350 a relational database.
351
352 <li><p><b>Accessible Content.</b>
353 Information held in an SQLite database file is accessible using
354 commonly available open-source command-line tools - tools that
355 are installed by default on Mac and Linux systems and that are
356 freely available as a self-contained EXE file on Windows.
357 Unlike custom file formats, application-specific programs are
358 not required to read or write content in an SQLite database.
359 An SQLite database file is not an opaque blob. It is true
360 that command-line tools such as text editors or "grep" or "awk" are
361 not useful on an SQLite database, but the SQL query language is a much
362 more powerful and convenient way for examining the content, so the
363 inability to use "grep" and "awk" and the like is not seen as a loss.
364
365 <p>An SQLite database is a <a href="fileformat2.html">well-defined and well-documented</a>
366 file format that is in widespread use by literally millions of applications
367 and is backwards compatible to its inception in 2004 and which promises
368 to continue to be compatible in decades to come. The longevity of
369 SQLite database files is particularly important to bespoke applications,
370 since it allows the document content to be accessed far in the
371 future, long after all traces of the original application have been lost.
372 Data lives longer than code.
373 SQLite databases are <a href="locrsf.html">recommended by the US Library of Congress</a>
374 as a storage format for long-term preservation of digital content.
375
376
377 <li><p><b>Cross-Platform.</b>
378 SQLite database files are portable between 32-bit and 64-bit machines and
379 between big-endian and little-endian architectures and between any of the
380 various flavors of Windows and Unix-like operating systems.
381 The application using an SQLite application file format can store
382 binary numeric data without having to worry about the byte-order of
383 integers or floating point numbers.
384 Text content can be read or written as UTF-8, UTF-16LE, or UTF-16BE and
385 SQLite will automatically perform any necessary translations on-the-fly.
386
387 <li><p><b>Atomic Transactions.</b>
388 Writes to an SQLite database are <a href="atomiccommit.html">atomic</a>.
389 They either happen completely
390 or not at all, even during system crashes or power failures. So
391 there is no danger of corrupting a document just because the power happened
392 to go out at the same instant that a change was being written to disk.
393
394 <p>SQLite is transactional, meaning that multiple changes can be grouped
395 together such that either all or none of them occur, and so that the
396 changes can be rolled back if a problem is found prior to commit.
397 This allows an application to make a change incrementally, then run
398 various sanity and consistency checks on the resulting data prior to
399 committing the changes to disk. The
400 <a href="http://www.fossil-scm.org/">Fossil</a> DVCS
401 <a href="http://www.fossil-scm.org/fossil/doc/tip/www/selfcheck.wiki">uses this technique</a>
402 to verify that no repository history has been lost prior to each change.
403
404 <li><p><b>Incremental And Continuous Updates.</b>
405 When writing to an SQLite database file, only those parts of the file that
406 actually change are written out to disk. This makes the writing happen faster
407 and saves wear on SSDs. This is an enormous advantage over custom
408 and wrapped pile-of-files formats, both of which usually require a
409 rewrite of the entire document in order to change a single byte.
410 Pure pile-of-files formats can also
411 do incremental updates to some extent, though the granularity of writes is
412 usually larger with pile-of-file formats (a single file) than with SQLite
413 (a single page).
414
415 <p>SQLite also supports continuous update.
416 Instead of collecting changes in memory and then writing
417 them to disk only on a File/Save action, changes can be written back to
418 the disk as they occur. This avoids loss of work on a system crash or
419 power failure. An <a href="undoredo.html">automated undo/redo stack</a>, managed using triggers,
420 can be kept in the on-disk database, meaning that undo/redo can occur
421 across session boundaries.
422
423 <li><p><b>Easily Extensible.</b>
424 As an application grows, new features can be added to an
425 SQLite application file format simply by adding new tables to the schema
426 or by adding new columns to existing tables. Adding columns or tables
427 does not change the meaning of prior queries, so with a
428 modicum of care to ensuring that the meaning of legacy columns and
429 tables are preserved, backwards compatibility is maintained.
430
431 <p>It is possible to extend custom or pile-of-files formats too, of course,
432 but doing is often much harder. If indices are added, then all application
433 code that changes the corresponding tables must be located and modified to
434 keep those indices up-to-date. If columns are added, then all application
435 code that accesses the corresponding table must be located and modified to
436 take into account the new columns.
437
438 <li><p><b>Performance.</b>
439 In many cases, an SQLite application file format will be
440 <a href="fasterthanfs.html">faster than a pile-of-files format</a> or
441 a custom format. In addition to being faster for raw read and
442 writes, SQLite can often dramatically improves start-up times because
443 instead of having to
444 read and parse the entire document into memory, the application can
445 do queries to extract only the information needed for the initial screen.
446 As the application progresses, it only needs to load as much material as
447 is needed to draw the next screen, and can discard information from
448 prior screens that is no longer in use. This helps keep the memory
449 footprint of the application under control.
450
451 <p>A pile-of-files format can be read incrementally just like SQLite.
452 But many developers are surprised to learn that SQLite can read and
453 write smaller BLOBs (less than about 100KB in size) from its database
454 faster than those same blobs can be read or written as separate files
455 from the filesystem. (See
456 <a href="fasterthanfs.html">35% Faster Than The Filesystem</a> and
457 <a href="intern-v-extern-blob.html">Internal Versus External BLOBs</a> for further information.)
458 There is overhead associated with operating a relational
459 database engine, however one should not assume that direct file I/O
460 is faster than SQLite database I/O, as often it is not.
461
462 <p>In either case, if performance problems do arise in an SQLite application
463 those problems can often be resolved by adding one or two <a href="lang_createindex.html">CREATE INDEX</a>
464 statements to the schema or perhaps running <a href="lang_analyze.html">ANALYZE</a> one time
465 and without having to touch a single line of
466 application code. But if a performance problem comes up in a custom or
467 pile-of-files format, the fix will often require extensive changes
468 to application code to add and maintain new indices or to extract
469 information using different algorithms.
470
471 <li><p><b>Concurrent Use By Multiple Processes.</b>
472 SQLite automatically coordinates concurrent access to the same
473 document from multiple threads and/or processes. Two or more
474 applications can connect and read from the same document at the
475 same time. Writes are serialized, but as writes normally only
476 take milliseconds, applications simply take turns writing.
477 SQLite automatically ensures that the low-level format of the
478 document is uncorrupted. Accomplishing the same with a custom
479 or pile-of-files format, in contrast, requires extensive support
480 in the application. And the application logic needed to support
481 concurrency is a notorious bug-magnet.
482
483 <li><p><b>Multiple Programming Languages.</b>
484 Though SQLite is itself written in ANSI-C, interfaces exist for
485 just about every other programming language you can think of:
486 C++, C#, Objective-C, Java, Tcl, Perl, Python, Ruby, Erlang,
487 JavaScript, and so forth. So programmers can develop in whatever
488 language they are most comfortable with and which best matches
489 the needs of the project.
490
491 <p>An SQLite application file format is a great
492 choice in cases where there is a collection or "federation" of
493 separate programs, often written in different languages and by
494 different development teams.
495 This comes up commonly in research or laboratory
496 environments where one team is responsible for data acquisition
497 and other teams are responsible for various stages of analysis.
498 Each team can use whatever hardware, operating system,
499 programming language and development methodology that they are
500 most comfortable with, and as long as all programs use an SQLite
501 database with a common schema, they can all interoperate.
502
503
504 <li><p><b>Better Applications.</b>
505 If the application file format is an SQLite database, the complete
506 documentation for that file format consists of the database schema,
507 with perhaps a few extra words about what each table and column
508 represents. The description of a custom file format,
509 on the other hand, typically runs on for hundreds of
510 pages. A pile-of-files format, while much simpler and easier to
511 describe than a fully custom format, still tends to be much larger
512 and more complex than an SQL schema dump, since the names and format
513 for the individual files must still be described.
514
515 <p>This is not a trivial point. A clear, concise, and easy to understand
516 file format is a crucial part of any application design.
517 Fred Brooks, in his all-time best-selling computer science text,
518 <i>The Mythical Man-Month</i> says:
519 <blockquote><i>Representation is the
520 essence of computer programming.<br />...<br />
521 Show me your flowcharts and conceal your tables, and I shall
522 continue to be mystified. Show me your tables, and I won't usually
523 need your flowcharts; they'll be obvious.</i></blockquote>
524 <p>Rob Pike, in his
525 <i>Rules of Programming</i> expresses the same idea this way:
526 <blockquote>
527 <i>Data dominates. If you've chosen the right data structures
528 and organized things well, the algorithms will almost always
529 be self-evident. Data structures, not algorithms, are central
530 to programming.</i></blockquote>
531 <p> Linus Torvalds used different words to say
532 much the same thing on the Git mailing list on 2006-06-27:
533 <blockquote>
534 <i>Bad programmers worry about the code. Good programmers worry
535 about data structures and their relationships.</i>
536 </blockquote>
537
538 <p>The point is this: an SQL database schema almost always does
539 a far better job of defining and organizing the tables and
540 data structures and their relationships.
541 And having clear, concise, and well-defined representation
542 almost always results in an application that performs better,
543 has fewer problems, and is easier to develop and maintain.
544 </ol>
545
546 <h2>Conclusion</h2>
547
548 <p>
549 SQLite is not the perfect application file format for every situation.
550 But in many cases, SQLite is a far better choice than either a custom
551 file format, a pile-of-files, or a wrapped pile-of-files.
552 SQLite is a high-level, stable, reliable, cross-platform, widely-deployed,
553 extensible, performant, accessible, concurrent file format. It deserves
554 your consideration as the standard file format on your next application
555 design.
556 <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/appfileformat.in?m=dcc7b088c6">2022-01-08 05:02:57</a> UTC </small></i></p>
557