Debian Codegraph @

www/howitworks.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>How SQLite Works</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 How SQLite Works
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="#background">1. Background</a></div>
129 <div class="fancy-toc2"><a href="#sqlite_is_different_from_most_other_sql_databases">1.1. SQLite Is Different From Most Other SQL Databases</a></div>
130 <div class="fancy-toc1"><a href="#sql_is_a_programming_language">2. SQL Is A Programming Language</a></div>
131 <div class="fancy-toc2"><a href="#programming_language_processing_steps">2.1. Programming Language Processing Steps</a></div>
132 <div class="fancy-toc2"><a href="#compiling_sqlite_programs">2.2. Compiling SQLite Programs</a></div>
133 <div class="fancy-toc1"><a href="#further_reading">3. Further Reading</a></div>
134 </div>
135 </div>
136 <script>
137 function toggle_toc(){
138 var sub = document.getElementById("toc_sub")
139 var mk = document.getElementById("toc_mk")
140 if( sub.style.display!="block" ){
141 sub.style.display = "block";
142 mk.innerHTML = "&#x25bc;";
143 } else {
144 sub.style.display = "none";
145 mk.innerHTML = "&#x25ba;";
146 }
147 }
148 </script>
149 </div>
150
151
152
153
154
155 <h1 id="background"><span>1. </span>Background</h1>
156
157 <p>
158 SQLite is a <a href="https://en.wikipedia.org/wiki/Library_(computing)">software library</a>
159 that translates high-level disk I/O requests generated by an application
160 into low-level I/O operations that
161 can be carried out by the operating system. The application constructs
162 high-level I/O requests using the
163 <a href="https://en.wikipedia.org/wiki/SQL">SQL language</a>.
164 SQLite translates each high-level SQL statement into a sequence of
165 many low-level I/O requests (open a file, read a few bytes from a file,
166 write a few bytes into a file, etc.) that do the work requested by
167 the SQL.
168
169
170 </p><p>
171 An application program could do all its disk I/O by direct calls to
172 operating system I/O routines
173 or by using a key/value storage engine like
174 <a href="https://en.wikipedia.org/wiki/Berkeley_DB">Berkeley DB</a> or
175 <a href="https://en.wikipedia.org/wiki/RocksDB">RocksDB</a> (to name but two).
176 But there are advantages to using a higher-level interface based
177 on the SQL language.
178
179 </p><ol>
180 <li><p>
181 SQL is a very high-level language.
182 A few lines of SQL can replace hundreds or thousands of lines of
183 procedural code. SQL thus reduces
184 the amount of work needed to develop and maintain the application,
185 and thereby helps to reduce the number of bugs in the application.
186
187 </p></li><li><p>
188 SQL and SQLite are
189 <a href="https://en.wikipedia.org/wiki/Database_transaction">transactional</a>.
190 The use of a transactional storage system makes it much easier to
191 reason about the behavior of the application, and to write applications
192 that are robust, even in the face of software bugs, hardware faults,
193 or power losses.
194
195 </p></li><li><p>
196 SQLite is often
197 <a href="fasterthanfs.html">faster than direct low-level I/O</a>.
198 This is counterintuitive. One would expect that a
199 high-level interface such as SQLite would impose a run-time penalty.
200 And, theoretically, that is correct. But in practice, SQL-based
201 systems such as SQLite do so many behind-the-scenes optimizations
202 that an application developer would never have time to create and
203 maintain, that the SQL-based systems end up providing
204 a net performance gain.
205 </p></li></ol>
206
207 <h2 id="sqlite_is_different_from_most_other_sql_databases"><span>1.1. </span>SQLite Is Different From Most Other SQL Databases</h2>
208
209 <p>
210 There are many SQL-based database management systems available, besides
211 SQLite. Common options include MySQL, PostgreSQL, and SQL-Server.
212 All these systems use the SQL langauge to communicate with the
213 application, just like SQLite. But these other systems different
214 from SQLite in important respects.
215
216 </p><ol>
217 <li><p>
218 SQLite is a <a href="serverless.html">serverless</a> software library, whereas the other
219 systems are client-server based. With MySQL, PostgreSQL, SQL-Server,
220 and others, the application sends a message containing some SQL
221 over to a separate server thread or process. That separate
222 thread or process performs the requested I/O, then send the results
223 back to the application. But there is no separate thread or
224 process with SQLite. SQLite runs in the same address space as
225 the application, using the same program counter and heap storage.
226 SQLite does no interprocess communication (IPC). When an application
227 sends an SQL statement into SQLite (by invoking a the appropriate
228 SQLite library subroutine), SQLite interprets the SQL
229 in the same thread as the caller. When an SQLite API routine
230 returns, it does not leave behind any background tasks that
231 run separately from the application.
232
233 </p></li><li><p>
234 An SQLite database is a single ordinary file on disk
235 (with a <a href="fileformat2.html">well-defined file format</a>). With other
236 systems, a "database" is usually a large number of separate
237 files hidden away in obscure directories of the filesystem, or
238 even spread across multiple machines. But with SQLite, a
239 complete database is just an ordinary disk file.
240 </p></li></ol>
241
242 <h1 id="sql_is_a_programming_language"><span>2. </span>SQL Is A Programming Language</h1>
243
244 <p>
245 The best way to understand how SQL database engines work is to
246 think of SQL as a programming language, not as a "query language".
247 Each SQL statement is a separate program. Applications construct
248 SQL program source files and send them to the database engine.
249 The database engine compiles the SQL source code into executable
250 form, runs that executable, then sends the result back to the
251 application.
252
253 </p><p>
254 While SQL is a programming language, it is different from other
255 programming languages like C, Javascript, Python, or Go in that
256 SQL is a
257 <a href="https://en.wikipedia.org/wiki/Declarative_programming">declarative language</a>
258 where the others are
259 <a href="https://en.wikipedia.org/wiki/Imperative_programming">imperative languages</a>.
260 This is an important difference that has implications for the
261 design of the compiler used to translate program source text into an
262 executable format. However, those details
263 should not detract from the fact that
264 SQL is really just another programming language.
265
266 </p><h2 id="programming_language_processing_steps"><span>2.1. </span>Programming Language Processing Steps</h2>
267
268 <p>
269 All programming languages are processed in two steps:
270
271 </p><ol>
272 <li><p>
273 Translate the program source text into an executable format.
274 </p></li><li><p>
275 Run the executable generated in the previous step in order to
276 carry out the desired action.
277 </p></li></ol>
278
279 <p>
280 All programming languages uses those two basic steps.
281 The main difference is in the executable format.
282
283 </p><p>
284 "Compiled" languages like C++ and Rust translate
285 the source text into machine code that can be directly executed
286 by the underlying hardware. There exist SQL database systems
287 that do the same with SQL - they translate each SQL statement
288 directly into machine code. But that approach is uncommon and
289 is not the approach taken by SQLite.
290
291 </p><p>
292 Other languages like Java, Perl, Python, and TCL
293 typically translate the program source text into bytecode.
294 This bytecode is then run through an interpreter that
295 reads the bytecode and carries out the desired operations.
296 SQLite uses this bytecode approach. If you preceed
297 any SQL statement with the "<a href="lang_explain.html">EXPLAIN</a>" keyword in SQLite,
298 it will show you the bytecode that is generated rather
299 than run the bytecode.
300
301 </p><p>
302 Another approach is to translate the program source text
303 into a tree of objects in memory. This tree is the "executable".
304 An interpret runs the executable by walking the tree.
305 This is the technique used by MySQL, PostgreSQL, and
306 SQL-Server.
307
308 </p><p>
309 Of course, not every language fits neatly into one of the
310 above categories. This applies to both SQL database engines
311 and more familiar imperative programming languages. Javascript
312 is famous for using a hybrid execution model, where the code
313 is initially compiled into a tree of objects, but might be
314 further translating (using just-in-time compilation) down into
315 more efficient bytecode or machine code, as a means of boosting
316 performance.
317
318 </p><p>
319 The executable format really ends up being just an implementation
320 detail. The key point is that all languages have a compiler
321 step which translates programs into an executable format and
322 a run step that executes the compiled program.
323
324
325 </p><h2 id="compiling_sqlite_programs"><span>2.2. </span>Compiling SQLite Programs</h2>
326
327 <p>
328 When an SQL program is submitted to SQLite, the first step is
329 to split the source text into "tokens". A token might be:
330
331 </p><ul>
332 <li>A language keyword like "SELECT" or "UPDATE".
333 </li><li>An identifier for a table or column or variable.
334 </li><li>Punctuation characters like "," or "==" or ";".
335 </li><li>Literal values: numeric or string constants.
336 </li><li>Whitespace or comments.
337 </li></ul>
338
339 <p>
340 Whitespace and comment tokens are discarded. All other tokens
341 are fed into an
342 <a href="https://en.wikipedia.org/wiki/LALR_parser">LALR(1) Parser</a>
343 that analyzes the structure of the input program and generates an
344 <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">Abstract Syntax Tree (AST)</a>
345 for the input program.
346
347 </p><p>
348 The parser forwards the AST on to the code generator.
349 The code generator is the heart of SQLite, and is where most of
350 the magic happens.
351 The code generator resolves symbolic names in the AST - matching
352 the names of columns and tables in the input SQL into actual
353 columns and tables of the database. The code generator also does
354 various transformations on the AST to "optimize" it. Finally
355 the code generator chooses appropriate algorithms to implement
356 the operations requested by the AST and constructs bytecode to
357 carry out those operations.
358
359 </p><p>
360 The bytecode generated by the code generator is called a
361 "<a href="c3ref/stmt.html">prepared statement</a>". Translating SQL source text into a
362 prepared statement is analogous to converting a C++ program
363 into machine code by invoking gcc or clang. Human-readable
364 source text (SQL or C++) goes in, and a machine readable executable
365 (bytecode or machine code) comes out.
366
367 </p><h1 id="further_reading"><span>3. </span>Further Reading</h1>
368
369 <ul>
370 <li><p>
371 The <a href="atomiccommit.html">Atomic Commit</a> document describes how SQLite implements
372 transactions.
373
374 </p></li><li><p>
375 The <a href="opcode.html">bytecode engine</a> document has more information
376 on the bytecode format used by SQLite, and how to view and interpret
377 an SQLite prepared statement.
378
379 </p></li><li><p>
380 The <a href="optoverview.html">SQLite query planner</a> and
381 <a href="queryplanner-ng.html">Next Generation Query Planner</a> documents have further details
382 on the algorithms SQLite uses to implement SQL statements and
383 how it goes above choosing an appropriate algorithm for each
384 individual SQL statement.
385 </p></li></ul>
386
387