Debian Codegraph @

www/whybytecode.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>Why SQLite Uses Bytecode</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 Why SQLite Uses Bytecode
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="#introduction">1. Introduction</a></div>
129 <div class="fancy-toc2"><a href="#how_to_provide_feedback">1.1. How To Provide Feedback</a></div>
130 <div class="fancy-toc2"><a href="#definition_of_bytecode_">1.2. Definition Of "Bytecode"</a></div>
131 <div class="fancy-toc2"><a href="#definition_of_abstract_syntax_tree_or_ast_">1.3. Definition Of "Abstract Syntax Tree" or "AST"</a></div>
132 <div class="fancy-toc2"><a href="#dataflow_programming">1.4. Dataflow Programming</a></div>
133 <div class="fancy-toc1"><a href="#advantages_to_compiling_into_bytecode">2. Advantages To Compiling Into Bytecode</a></div>
134 <div class="fancy-toc2"><a href="#bytecode_is_easier_to_understand">2.1. Bytecode Is Easier To Understand</a></div>
135 <div class="fancy-toc2"><a href="#bytecode_is_easier_to_debug">2.2. Bytecode Is Easier To Debug</a></div>
136 <div class="fancy-toc2"><a href="#bytecode_can_be_run_incrementally">2.3. Bytecode Can Be Run Incrementally</a></div>
137 <div class="fancy-toc2"><a href="#bytecode_is_smaller">2.4. Bytecode Is Smaller</a></div>
138 <div class="fancy-toc2"><a href="#bytecode_is_faster">2.5. Bytecode Is Faster</a></div>
139 <div class="fancy-toc1"><a href="#advantages_of_compiling_into_a_tree_of_objects">3. Advantages Of Compiling Into A Tree Of Objects</a></div>
140 <div class="fancy-toc2"><a href="#query_planning_decisions_can_be_deferred_until_runtime">3.1. Query Planning Decisions Can Be Deferred Until Runtime</a></div>
141 <div class="fancy-toc2"><a href="#dataflow_programs_are_easy_to_parallelize">3.2. Dataflow Programs Are Easy To Parallelize</a></div>
142 </div>
143 </div>
144 <script>
145 function toggle_toc(){
146 var sub = document.getElementById("toc_sub")
147 var mk = document.getElementById("toc_mk")
148 if( sub.style.display!="block" ){
149 sub.style.display = "block";
150 mk.innerHTML = "&#x25bc;";
151 } else {
152 sub.style.display = "none";
153 mk.innerHTML = "&#x25ba;";
154 }
155 }
156 </script>
157 </div>
158
159
160
161
162
163 <h1 id="introduction"><span>1. </span>Introduction</h1>
164
165 <p>Every SQL database engine works in roughly the same way: It first
166 translates the input SQL text into a "prepared statement". Then it "executes"
167 the prepared statement to generate a result.
168
169 </p><p>A prepared statement is an object that represents the steps needed
170 to accomplish the input SQL. Or, to think of it in another way,
171 the prepared statement is the SQL statement translated into a form that is
172 more easily understood by the computer.
173
174 </p><p>In SQLite, a prepared statement is an instance of the
175 <a href="c3ref/stmt.html">sqlite3_stmt object</a>. In other systems, the prepared
176 statement is usually an internal data structure that is not directly visible to
177 the application programmer. Developers of other SQL database engines
178 do not necessarily call these objects "prepared statements".
179 But such objects exists, whatever they might be called.
180 This paper will use the term "prepared statement".
181
182 </p><p>There are countless ways of implementing a prepared statement. This
183 paper will look at the two most common methods:
184
185 </p><ol>
186 <li><p>
187 <b>Bytecode</b> &rarr; The input SQL is translated into a virtual machine language
188 that is then run by a virtual machine interpreter. This is the technique
189 used by SQLite.
190
191 </p></li><li><p>
192 <b>Tree-Of-Objects</b> &rarr; The input SQL is translated in a tree of objects
193 that represent the processing to be done. The SQL is executed by walking this
194 tree. This is the technique used by MySQL and PostgreSQL.
195 </p></li></ol>
196
197 <p>
198 There are advantages and disadvantages to each of these representations of
199 a prepared statement. The purpose of this paper is to articulate some of those
200 advantages and disadvantages.
201
202 </p><h2 id="how_to_provide_feedback"><span>1.1. </span>How To Provide Feedback</h2>
203
204 <p>
205 This document is written from the perspective of the original author of SQLite.
206 If you disagree with any of the opinions offered in this document, you are
207 welcomed to offer corrections and/or contrary views on the
208 <a href="https://sqlite.org/forum">SQLite Forum</a>. Or you can email the author
209 directly.
210
211 </p><h2 id="definition_of_bytecode_"><span>1.2. </span>Definition Of "Bytecode"</h2>
212
213 <p>The <a href="opcode.html">bytecode generated by SQLite</a> might be a little different from what
214 many readers think of as bytecode. The bytecode used (for example) by the
215 <a href="https://en.wikipedia.org/wiki/Java_virtual_machine">Java virtual machine</a> or
216 by <a href="https://en.wikipedia.org/wiki/WebAssembly">WebAssembly</a> consists almost
217 entirely of low-level operations, similar to what physical CPUs implement:
218 basic math operators, comparisons, conditional jumps, and
219 instructions to move content between different memory locations. SQLite bytecode
220 has these kinds of low-level instructions, too. But SQLite bytecode also contains
221 some high-level operations that are specific to the needs of a database engine.
222 Here are just a few examples:
223
224 </p><p>
225 </p><ul>
226 <li><p><b>OP_Column</b> &rarr; Extract the value from the N-th column of the
227 database row that a particular cursor is currently pointing at.
228 </p></li><li><p><b>OP_CreateBtree</b> &rarr; Allocate space for a new B-Tree in the
229 database file.
230 </p></li><li><p><b>OP_ParseSchema</b> &rarr; Reread and reparse all or part of the
231 <a href="schematab.html">sqlite_schema table</a> and refresh internal symbol tables accordingly.
232 </p></li><li><p><b>OP_SeekGE</b> &rarr; Move a cursor on a particular B-Tree to the first
233 entry that is greater than or equal to a given key.
234 </p></li><li><p><b>OP_Next</b> &rarr; Advance a cursor on a particular B-Tree to the next
235 entry in the B-Tree and jump, or fall through if there are no more entries in that
236 B-Tree.
237 </p></li></ul>
238
239 <p>In other words, the "bytecode" used by SQLite is not so much a set of CPU
240 instructions as it is a list of database primitives that are to be run
241 in a particular order.
242
243 </p><h2 id="definition_of_abstract_syntax_tree_or_ast_"><span>1.3. </span>Definition Of "Abstract Syntax Tree" or "AST"</h2>
244
245 <p>
246 An "<a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">Abstract Syntax Tree</a>" or AST
247 is a data structure that describes a program or statement in some kind of formal
248 language. In our context, the formal language is SQL. An AST is typically
249 implemented as a tree of objects where each object represents one small part of
250 the overall SQL statement. ASTs emerge naturally from parsers for formal languages.
251 The usual technique is to use an
252 <a href="https://en.wikipedia.org/wiki/LALR_parser">LALR(1) parser</a>.
253 With such a parser, each terminal
254 symbol holds metadata that will become a leaf of the AST, and each non-terminal
255 symbol holds metadata that will become a sub-branch of the overall AST.
256 As rules of the grammar are "reduced" by the parser, new nodes of the AST are
257 allocated and connected to subnodes.
258 After the parse completes, the start-symbol of the grammar is left holding the
259 root of the AST.
260
261 </p><p>An AST is a tree of objects. But an AST is not a suitable form for
262 a prepared statement. After being generated, an AST first needs to be
263 transformed in various ways before it can executed. Symbols need to be
264 resolved. Semantic rules need to be checked. Optimizations need to be
265 applied that transform input SQL statement into different forms that
266 execute more quickly. Finally, the AST needs to be translated into an
267 alternative representation that is more amenable to execution.
268
269 </p><p>Some people refer to the tree of objects that is used as the
270 executable form for MySQL and PostgreSQL as an AST. This is probably a
271 misuse of the term "AST", because by the time the tree of objects is
272 ready to be executed, it has been changed so much that it has little
273 resemblance to the original SQL text. The confusion arises in part because
274 both the final prepared statement object and the original AST are both
275 trees of objects. The usual technique is for the original AST that comes
276 directly out of the parser to be transformed little by little, in multiple
277 passes, until at the end it is fully converted into an tree of objects
278 that is no longer strictly an AST but that can be evaluated to
279 generate a result. There is not necessarily a clear point during this
280 process when the tree-of-objects ceases to be an AST and becomes a
281 prepared statement instead. And because there is no clear boundary between an
282 AST and a prepared statement, people often refer to a prepared statement
283 that is represented as a tree of objects as an "AST", even though that
284 description is not precise.
285
286 </p><h2 id="dataflow_programming"><span>1.4. </span>Dataflow Programming</h2>
287
288 <p><a href="https://en.wikipedia.org/wiki/Dataflow_programming">Dataflow programming</a>
289 is a style of programming in which individual nodes specialize in doing
290 one small part of the overall computation. Each node receives inputs from
291 other nodes and sends its output to other nodes. Thus the nodes form a
292 directed graph that carry inputs into outputs.
293
294 </p><p>
295 A "dataflow program" is perhaps a better description than "AST" for
296 the tree of objects that an SQL database engine uses as a prepared statement.
297
298 </p><h1 id="advantages_to_compiling_into_bytecode"><span>2. </span>Advantages To Compiling Into Bytecode</h1>
299
300 <p>SQLite compiles to bytecode, and the SQLite developers are very happy
301 with this approach. Here is why:
302
303 </p><h2 id="bytecode_is_easier_to_understand"><span>2.1. </span>Bytecode Is Easier To Understand</h2>
304
305 <p>A flat list of opcodes can be easily printed to see exactly
306 how an SQL statement is being implemented. This is what happens in SQLite
307 when you preface an SQL statement with the "EXPLAIN" keyword: Instead of
308 actually running the SQL, the result is a listing of the bytecode
309 that would have been used to implement that SQL.
310
311 </p><p>Bytecode lends itself to this because a bytecode program is easily
312 represented as a table. In SQLite bytecode, each instruction
313 has one opcode and five operands. Thus a prepared statement can be
314 rendered as if it were a query against a six-column table.
315
316 </p><p>A tree-of-objects representation is more difficult to publish in
317 a human-readable form. The objects that comprise the tree tend to
318 all be very different, and thus it is tricky to come up with a
319 consistent and simple table representation with which to display
320 the objects. Any such table representation that you do come up
321 with would almost certainly have more than six columns, probably many more.
322 The problem of rendering a tree-of-objects as a table is sufficiently
323 difficult that nobody does it, as far as I know. Hence, no
324 tree-of-objects database engine provides the level
325 of detail in their "EXPLAIN" output that SQLite provides.
326
327 </p><h2 id="bytecode_is_easier_to_debug"><span>2.2. </span>Bytecode Is Easier To Debug</h2>
328
329 <p>Bytecode provides a clear separation between front-end parsing and
330 analysis and back-end evaluation of an SQL statement. When problems arise
331 (incorrect answers and/or poor performance), the developers can examine
332 the bytecode to quickly determine if the source of the trouble is either the
333 front-end analysis or the back-end data storage section of the product.
334
335 </p><p>In debugging builds of SQLite, the <a href="pragma.html#pragma_vdbe_trace">PRAGMA vdbe_trace=ON;</a> command will
336 cause a trace of the bytecode execution to appear on the console.
337
338 </p><h2 id="bytecode_can_be_run_incrementally"><span>2.3. </span>Bytecode Can Be Run Incrementally</h2>
339
340 <p>
341 SQL statements written in bytecode can be evaluated incrementally.
342 For example, a statement can be run until it generates just its first
343 row of output. The statement then pauses until it is stepped again.
344 It is not necessary to run the statement to completion before examining
345 the first row of output.
346
347 </p><p>
348 This is more difficult to achieve in a tree-of-objects design. When
349 the prepared statement is a tree-of-objects, execution is normally
350 accomplished by walking the tree. To pause the statement in the middle
351 of a computation means unwinding the stack back up to the caller, all
352 the while saving enough state to resume evaluation where it last left
353 off. This is not impossible to do, but is sufficiently difficult that
354 I have never seen it actually done.
355
356 </p><p>
357 Most SQL database engines do not really need to do incremental
358 execution of prepared statements because most SQL database engines
359 are client/server. In client/server engines, a single SQL statement is sent
360 to the server, then the complete reply comes back over the wire
361 all at once. Thus each statement runs to completion in a single go.
362 But SQLite is not client/server. SQLite is a library
363 that runs in the same address space and using the same stack as the
364 application. Being able to easily and reliably perform incremental
365 execution of an SQL statement is important to SQLite.
366
367 </p><h2 id="bytecode_is_smaller"><span>2.4. </span>Bytecode Is Smaller</h2>
368
369 <p>
370 The bytecode generated by SQLite is usually smaller than the corresponding
371 AST coming out of the parser. During initial processing of SQL text
372 (during the call to <a href="c3ref/prepare.html">sqlite3_prepare()</a> and similar) both the AST and the
373 bytecode exist in memory at the same time, so more memory is used then.
374 But that is a transient state. The AST
375 is quickly discarded and its memory recycled, even before the call to
376 <a href="c3ref/prepare.html">sqlite3_prepare()</a> returns, so the resulting <a href="c3ref/stmt.html">prepared statement</a> ends
377 up consuming less memory in its bytecode representation than it did as an AST.
378 This is important because calls to <a href="c3ref/prepare.html">sqlite3_prepare()</a> are transient, but
379 prepared statements are often cached for possible reuse and persist in memory
380 for a long time.
381
382 </p><h2 id="bytecode_is_faster"><span>2.5. </span>Bytecode Is Faster</h2>
383
384 <p>
385 I <i>believe</i> that a bytecode representation of a prepared statement
386 runs faster, because fewer decisions need to be made for each step of
387 the computation. Emphasis on "believe" in the previous sentence
388 &rarr; it is difficult to verify
389 this claim experimentally since nobody has ever put in the multiple years
390 of effort necessary to generate equivalent bytecode and tree-of-object
391 representations of a prepared statement to see which one actually runs faster.
392 We do know that <a href="fasterthanfs.html">SQLite is very fast</a>, but we
393 do not have good side-by-side comparisons with other SQL databases since
394 the other databases spend a lot of time doing client/server message processing,
395 and it is difficult to untangle the message round-trip overhead from the
396 actual processing time.
397
398 </p><h1 id="advantages_of_compiling_into_a_tree_of_objects"><span>3. </span>Advantages Of Compiling Into A Tree Of Objects</h1>
399
400 <p>The SQLite developers think that the bytecode approach is
401 best, at least for the use cases the SQLite tries to fill, but the
402 tree-of-objects approach to processing SQL does have some advantages over
403 bytecode. There are always tradeoffs.
404
405 </p><h2 id="query_planning_decisions_can_be_deferred_until_runtime"><span>3.1. </span>Query Planning Decisions Can Be Deferred Until Runtime</h2>
406
407 <p>
408 When a prepared statement is bytecode, once the bytecode has been generated,
409 the algorithm is fixed and cannot be subsequently changed without completely
410 rewriting the bytecode.
411 This is not the case with a tree-of-objects prepared
412 statement. A tree-of-objects is easier to modify on-the-fly. The query
413 plan is mutable and can be tweaked as it is running, based on the progress
414 of the query. Thus a query can be dynamically self-tuning.
415
416 </p><h2 id="dataflow_programs_are_easy_to_parallelize"><span>3.2. </span>Dataflow Programs Are Easy To Parallelize</h2>
417
418 <p>In a dataflow program, each processing node can be assigned to a
419 different thread. There needs to be some kind of threadsafe queuing
420 mechanism for transferring intermediate results from one node to the
421 next. But no synchronization primitives are typically needed within
422 each node of the program. Node schedule is trivial: A node becomes
423 eligible to run when it has data available and there is space in its
424 output queue.
425
426 </p><p>This is an important consideration for database engines that are
427 designed to run large analytic queries
428 (<a href="https://en.wikipedia.org/wiki/Online_analytical_processing">OLAP</a>)
429 on large multi-core servers.
430 The primary focus of SQLite is transaction processing
431 (<a href="https://en.wikipedia.org/wiki/Online_transaction_processing">OLTP</a>)
432 on the internet-of-things, so there is less need to
433 represent prepared statements as dataflow programs in SQLite.
434 </p><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/whybytecode.in?m=d62430c8d6">2024-05-09 17:38:03</a> UTC </small></i></p>
435