vdbe.tcl 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  1. #
  2. # Run this Tcl script to generate the vdbe.html file.
  3. #
  4. set rcsid {$Id: vdbe.tcl,v 1.9 2001/11/24 13:23:05 drh Exp $}
  5. puts {<html>
  6. <head>
  7. <title>The Virtual Database Engine of SQLite</title>
  8. </head>
  9. <body bgcolor=white>
  10. <h1 align=center>
  11. The Virtual Database Engine of SQLite
  12. </h1>}
  13. puts "<p align=center>
  14. (This page was last modified on [lrange $rcsid 3 4] UTC)
  15. </p>"
  16. puts {
  17. <blockquote><font color="red"><b>
  18. This document describes the
  19. virtual machine used in SQLite version 1.0. It has not been
  20. updated to reflect important changes that have occurred for
  21. version 2.0. Some of the information presented below is
  22. obsolete and/or incorrect. Use it accordingly.
  23. </b></font></blockquote>
  24. }
  25. puts {
  26. <p>If you want to know how the SQLite library works internally,
  27. you need to begin with a solid understanding of the Virtual Database
  28. Engine or VDBE. The VDBE occurs right in the middle of the
  29. processing stream (see the <a href="arch.html">architecture diagram</a>)
  30. and so it seems to touch most parts of the library. Even
  31. parts of the code that do not directly interact with the VDBE
  32. are usually in a supporting role. The VDBE really is the heart of
  33. SQLite.</p>
  34. <p>This article is a brief introduction to how the VDBE
  35. works and in particular how the various VDBE instructions
  36. (documented <a href="opcode.html">here</a>) work together
  37. to do useful things with the database. The style is tutorial,
  38. beginning with simple tasks and working toward solving more
  39. complex problems. Along the way we will visit most
  40. submodules in the SQLite library. After completeing this tutorial,
  41. you should have a pretty good understanding of how SQLite works
  42. and will be ready to begin studying the actual source code.</p>
  43. <h2>Preliminaries</h2>
  44. <p>The VDBE implements a virtual computer that runs a program in
  45. its virtual machine language. The goal of each program is to
  46. interrogate or change the database. Toward this end, the machine
  47. language that the VDBE implements is specifically designed to
  48. search, read, and modify databases.</p>
  49. <p>Each instruction of the VDBE language contains an opcode and
  50. three operands labeled P1, P2, and P3. Operand P1 is an arbitrary
  51. integer. P2 is a non-negative integer. P3 is a null-terminated
  52. string, or possibly just a null pointer. Only a few VDBE
  53. instructions use all three operands. Many instructions use only
  54. one or two operands. A significant number of instructions use
  55. no operands at all but instead take their data and storing their results
  56. on the execution stack. The details of what each instruction
  57. does and which operands it uses are described in the separate
  58. <a href="opcode.html">opcode description</a> document.</p>
  59. <p>A VDBE program begins
  60. execution on instruction 0 and continues with successive instructions
  61. until it either (1) encounters a fatal error, (2) executes a
  62. Halt instruction, or (3) advances the program counter past the
  63. last instruction of the program. When the VDBE completes execution,
  64. all open database cursors are closed, all memory is freed, and
  65. everything is popped from the stack.
  66. So there are never any worries about memory leaks or
  67. undeallocated resources.</p>
  68. <p>If you have done any assembly language programming or have
  69. worked with any kind of abstract machine before, all of these
  70. details should be familiar to you. So let's jump right in and
  71. start looking as some code.</p>
  72. <a name="insert1">
  73. <h2>Inserting Records Into The Database</h2>
  74. <p>We begin with a problem that can be solved using a VDBE program
  75. that is only a few instructions long. Suppose we have an SQL
  76. table that was created like this:</p>
  77. <blockquote><pre>
  78. CREATE TABLE examp(one text, two int);
  79. </pre></blockquote>
  80. <p>In words, we have a database table named "examp" that has two
  81. columns of data named "one" and "two". Now suppose we want to insert a single
  82. record into this table. Like this:</p>
  83. <blockquote><pre>
  84. INSERT INTO examp VALUES('Hello, World!',99);
  85. </pre></blockquote>
  86. <p>We can see the VDBE program that SQLite uses to implement this
  87. INSERT using the <b>sqlite</b> command-line utility. First start
  88. up <b>sqlite</b> on a new, empty database, then create the table.
  89. Next change the output format of <b>sqlite</b> to a form that
  90. is designed to work with VDBE program dumps by entering the
  91. ".explain" command.
  92. Finally, enter the INSERT statement shown above, but precede the
  93. INSERT with the special keyword "EXPLAIN". The EXPLAIN keyword
  94. will cause <b>sqlite</b> to print the VDBE program rather than
  95. execute it. We have:</p>
  96. }
  97. proc Code {body} {
  98. puts {<blockquote><pre>}
  99. regsub -all {&} [string trim $body] {\&amp;} body
  100. regsub -all {>} $body {\&gt;} body
  101. regsub -all {<} $body {\&lt;} body
  102. regsub -all {\(\(\(} $body {<font color="#00671f"><u>} body
  103. regsub -all {\)\)\)} $body {</u></font>} body
  104. puts $body
  105. puts {</pre></blockquote>}
  106. }
  107. Code {
  108. $ (((sqlite test_database_1)))
  109. sqlite> (((CREATE TABLE examp(one text, two int);)))
  110. sqlite> (((.explain)))
  111. sqlite> (((EXPLAIN INSERT INTO examp VALUES('Hello, World!',99);)))
  112. addr opcode p1 p2 p3
  113. ---- ------------ ----- ----- ----------------------------------------
  114. 0 Open 0 1 examp
  115. 1 New 0 0
  116. 2 String 0 0 Hello, World!
  117. 3 Integer 99 0
  118. 4 MakeRecord 2 0
  119. 5 Put 0 0
  120. }
  121. puts {<p>As you can see above, our simple insert statement is
  122. implemented in just 6 instructions. There are no jumps, so the
  123. program executes once through from top to bottom. Let's now
  124. look at each instruction in detail.</p>
  125. <p>The first instruction opens a cursor that points into the
  126. "examp" table. The P1 operand is a handle for the cursor: zero
  127. in this case. Cursor handles can be any non-negative integer.
  128. But the VDBE allocates cursors in an array with the size of the
  129. array being one more than the largest cursor. So to conserve
  130. memory, it is best to use handles beginning with zero and
  131. working upward consecutively.</p>
  132. <p>The P2 operand to the open instruction is 1 which means
  133. that the cursor is opened for writing. 0 would have been used
  134. for P2 if we wanted to open the cursor for reading only.
  135. It is acceptable to open more than one cursor to the same
  136. database file at the same time. But all simultaneously
  137. opened cursors must be opened with the same P2 value. It is
  138. not allowed to have one cursor open for reading a file and
  139. another cursor open for writing that same file.</p>
  140. <p>The second instruction, New, generates an integer key that
  141. has not been previously used in the file "examp". The New instruction
  142. uses its P1 operand as the handle of a cursor for the file
  143. for which the new key will be generated. The generated key is
  144. pushed onto the stack. The P2 and P3 operands are not used
  145. by the New instruction.</p>
  146. <p>The third instruction, String, simply pushes its P3
  147. operand onto the stack. After the string instruction executes,
  148. the stack will contain two elements, as follows:</p>
  149. }
  150. proc stack args {
  151. puts "<blockquote><table border=2>"
  152. foreach elem $args {
  153. puts "<tr><td align=center>$elem</td></tr>"
  154. }
  155. puts "</table></blockquote>"
  156. }
  157. stack {The string "Hello, World!"} {A random integer key}
  158. puts {<p>The 4th instruction pushes an integer value 99 onto the
  159. stack. After the 4th instruction executes, the stack looks like this:</p>
  160. }
  161. stack {Integer value 99} {The string "Hello, World!"} {A random integer key}
  162. puts {<p>The 5th instructionn, MakeRecord, pops the top P1
  163. elements off the stack (2 elements in this case) and converts them
  164. all into the binary format used for storing records in a
  165. database file. (See the <a href="fileformat.html">file format</a>
  166. description for details.) The record format consists of
  167. a header with one integer for each column giving the offset
  168. into the record for the beginning of data for that column.
  169. Following the header is the data for each column, Each column
  170. is stored as a null-terminated ASCII text string. The new
  171. record generated by the MakeRecord instruction is pushed back
  172. onto the stack, so that after the 5th instruction executes,
  173. the stack looks like this:</p>
  174. }
  175. stack {A data record holding "Hello, World!" and 99} \
  176. {A random integer key}
  177. puts {<p>The last instruction pops the top two elements from the stack
  178. and uses them as data and key to make a new entry in the
  179. database file pointed to by cursor P1. This instruction is where
  180. the insert actually occurs.</p>
  181. <p>After the last instruction executes, the program counter
  182. advances to one past the last instruction, which causes the
  183. VDBE to halt. When the VDBE halts, it automatically closes
  184. all open cursors, frees any elements left on the stack,
  185. and releases any other resources we may have allocated.
  186. In this case, the only cleanup necessary is to close the
  187. cursor to the "examp" file.</p>
  188. <a name="trace">
  189. <h2>Tracing VDBE Program Execution</h2>
  190. <p>If the SQLite library is compiled without the NDEBUG
  191. preprocessor macro, then
  192. there is a special SQL comment that will cause the
  193. the VDBE to traces the execution of programs.
  194. Though this feature was originally intended for testing
  195. and debugging, it might also be useful in learning about
  196. how the VDBE operates.
  197. Use the "<tt>--vdbe-trace-on--</tt>" comment to
  198. turn tracing on and "<tt>--vdbe-trace-off--</tt>" to turn tracing
  199. back off. Like this:</p>
  200. }
  201. Code {
  202. sqlite> (((--vdbe-trace-on--)))
  203. ...> (((INSERT INTO examp VALUES('Hello, World!',99);)))
  204. 0 Open 0 1 examp
  205. 1 New 0 0
  206. Stack: i:1053779177
  207. 2 String 0 0 Hello, World!
  208. Stack: s:[Hello, Worl] i:1053779177
  209. 3 Integer 99 0
  210. Stack: i:99 s:[Hello, Worl] i:1053779177
  211. 4 MakeRecord 2 0
  212. Stack: z:] i:1053779177
  213. 5 Put 0 0
  214. }
  215. puts {
  216. <p>With tracing mode on, the VDBE prints each instruction prior
  217. to executing it. After the instruction is executed, the top few
  218. entries in the stack are displayed. The stack display is omitted
  219. if the stack is empty.</p>
  220. <p>On the stack display, most entries are shown with a prefix
  221. that tells the datatype of that stack entry. Integers begin
  222. with "<tt>i:</tt>". Floating point values begin with "<tt>r:</tt>".
  223. (The "r" stands for "real-number".) Strings begin with either
  224. "<tt>s:</tt>" or "<tt>z:</tt>". The difference between s: and
  225. z: strings is that z: strings are stored in memory obtained
  226. from <b>malloc()</b>. This doesn't make any difference to you,
  227. the observer, but it is vitally important to the VDBE since the
  228. z: strings need to be passed to <b>free()</b> when they are
  229. popped to avoid a memory leak. Note that only the first 10
  230. characters of string values are displayed and that binary
  231. values (such as the result of the MakeRecord instruction) are
  232. treated as strings. The only other datatype that can be stored
  233. on the VDBE stack is a NULL, which is display without prefix
  234. as simply "<tt>NULL</tt>".
  235. <a name="query1">
  236. <h2>Simple Queries</h2>
  237. <p>At this point, you should understand the basics of how the VDBE
  238. writes to a database. Now let's look at how it does queries.
  239. We will use the follow simple SELECT statement as our example:</p>
  240. <blockquote><pre>
  241. SELECT * FROM examp;
  242. </pre></blockquote>
  243. <p>The VDBE program generated for this SQL statement is as follows:</p>
  244. }
  245. Code {
  246. sqlite> (((EXPLAIN SELECT * FROM examp;)))
  247. 0 ColumnCount 2 0
  248. 1 ColumnName 0 0 one
  249. 2 ColumnName 1 0 two
  250. 3 Open 0 0 examp
  251. 4 Next 0 9
  252. 5 Field 0 0
  253. 6 Field 0 1
  254. 7 Callback 2 0
  255. 8 Goto 0 4
  256. 9 Close 0 0
  257. }
  258. puts {
  259. <p>Before we begin looking at this problem, let's briefly review
  260. how queries work in SQLite so that we will know what we are trying
  261. to accomplish. For each row in the result of a query,
  262. SQLite will invoke a callback function with the following
  263. prototype:</p>
  264. <blockquote><pre>
  265. int Callback(void *pUserData, int nColumn, char *azData[], char *azColumnName[]);
  266. </pre></blockquote>
  267. <p>The SQLite library supplies the VDBE with a pointer to the callback function
  268. and the <b>pUserData</b> pointer. (Both the callback and the user data were
  269. originally passed in as arguments to the <b>sqlite_exec()</b> API function.)
  270. The job of the VDBE is to
  271. come up with values for <b>nColumn</b>, <b>azData[]</b>,
  272. and <b>azColumnName[]</b>.
  273. <b>nColumn</b> is the number of columns in the results, of course.
  274. <b>azColumnName[]</b> is an array of strings where each string is the name
  275. of one of the result column. <b>azData[]</b> is an array of strings holding
  276. the actual data.</p>
  277. <p>The first three instructions in the VDBE program for our query are
  278. concerned with setting up values for <b>azColumn</b>.
  279. The ColumnCount instruction tells the VDBE how much space to allocate
  280. for the <b>azColumnName[]</b> array. The ColumnName instructions
  281. tell the VDBE what values to fill in for each element of the
  282. <b>azColumnName[]</b> array. Every query will begin with one
  283. ColumnCount instruction and one ColumnName instruction for each
  284. column in the result.</p>
  285. <p>The 4th instruction opens a cursor into the database file
  286. that is to be queried. This works the same as the Open instruction
  287. in the INSERT example except that the
  288. cursor is opened for reading this time instead of for writing.</p>
  289. <p>The instructions at address 4 and 8 form a loop that will execute
  290. once for each record in the database file. This is a key concept that
  291. you should pay close attention to. The Next instruction at
  292. address 4 tells the VDBE to advance the cursor (identified by P1)
  293. to the next record. The first time this Next instruction is executed,
  294. the cursor is set to the first record of the file. If there are
  295. no more records in the database file when Next is executed, then
  296. the VDBE makes an immediate jump over the body of the loop to
  297. instruction 9 (specified by operand P2). The body of the loop
  298. is formed by instructions at addresses 5, 6, and 7. After the loop
  299. body is an unconditional jump at instruction 8 which takes us
  300. back to the Next instruction at the beginning of the loop.
  301. </p>
  302. <p>The body of the loop consists of instructions at addresses 5 through
  303. 7. The Field instructions at addresses 5 and 6 each
  304. take the P2-th column from
  305. the P1-th cursor and pushes it onto the stack.
  306. (The "Field" instruction probably should be renamed as the "Column"
  307. instruction.) In this example, the first Field instruction is pushing the
  308. value for the "one" data column onto the stack and the second Field
  309. instruction is pushing the data for "two".</p>
  310. <p>The Callback instruction at address 7 invokes the callback function.
  311. The P1 operand to callback becomes the value for <b>nColumn</b>.
  312. The Callback instruction also pops P1 values from the stack and
  313. uses them to form the <b>azData[]</b> for the callback.</p>
  314. <p>The Close instruction at the end of the program closes the
  315. cursor that points into the database file. It is not really necessary
  316. to call Close here since all cursors will be automatically closed
  317. by the VDBE when the program halts. But we needed an instruction
  318. for the Next to jump to so we might as well go ahead and have that
  319. instruction do something useful.</p>
  320. <a name="query2">
  321. <h2>A Slightly More Complex Query</h2>
  322. <p>The key points of the previous example where the use of the Callback
  323. instruction to invoke the callback function, and the use of the Next
  324. instruction to implement a loop over all records of the database file.
  325. This example attempts to drive home those ideas by demonstrating a
  326. slightly more complex query that involves more columns of
  327. output, some of which are computed values, and a WHERE clause that
  328. limits which records actually make it to the callback function.
  329. Consider this query:</p>
  330. <blockquote><pre>
  331. SELECT one, two, one || two AS 'both'
  332. FROM examp
  333. WHERE one LIKE 'H%'
  334. </pre></blockquote>
  335. <p>This query is perhaps a bit contrived, but it does serve to
  336. illustrate our points. The result will have three column with
  337. names "one", "two", and "both". The first two columns are direct
  338. copies of the two columns in the table and the third result
  339. column is a string formed by concatenating the first and
  340. second columns of the table.
  341. Finally, the
  342. WHERE clause says that we will only chose rows for the
  343. results where the "one" column begins with an "H".
  344. Here is what the VDBE program looks like for this query:</p>
  345. }
  346. Code {
  347. addr opcode p1 p2 p3
  348. ---- ------------ ----- ----- ----------------------------------------
  349. 0 ColumnCount 3 0
  350. 1 ColumnName 0 0 one
  351. 2 ColumnName 1 0 two
  352. 3 ColumnName 2 0 both
  353. 4 Open 0 0 examp
  354. 5 Next 0 16
  355. 6 Field 0 0
  356. 7 String 0 0 H%
  357. 8 Like 1 5
  358. 9 Field 0 0
  359. 10 Field 0 1
  360. 11 Field 0 0
  361. 12 Field 0 1
  362. 13 Concat 2 0
  363. 14 Callback 3 0
  364. 15 Goto 0 5
  365. 16 Close 0 0
  366. }
  367. puts {
  368. <p>Except for the WHERE clause, the structure of the program for
  369. this example is very much like the prior example, just with an
  370. extra column. The ColumnCount is 3 now, instead of 2 as before,
  371. and there are three ColumnName instructions.
  372. A cursor is opened using the Open instruction, just like in the
  373. prior example. The Next instruction at address 5 and the
  374. Goto at address 15 form a loop over all records of the database
  375. file. The Close instruction at the end is there to give the
  376. Next instruction something to jump to when it is done. All of
  377. this is just like in the first query demonstration.</p>
  378. <p>The Callback instruction in this example has to generate
  379. data for three result columns instead of two, but is otherwise
  380. the same as in the first query. When the Callback instruction
  381. is invoked, the left-most column of the result should be
  382. the lowest in the stack and the right-most result column should
  383. be the top of the stack. We can see the stack being set up
  384. this way at addresses 9 through 13. The Field instructions at
  385. 9 and 10 push the values for the first two columns in the result.
  386. The two Field instructions at 11 and 12 pull in the values needed
  387. to compute the third result column and the Concat instruction at
  388. 13 joins them together into a single entry on the stack.</p>
  389. <p>The only thing that is really new about the current example
  390. is the WHERE clause which is implemented by instructions at
  391. addresses 6, 7, and 8. Instructions at address 6 and 7 push
  392. onto the stack the value of the "one" column from the table
  393. and the literal string "H%". The Like instruction at address 8 pops these
  394. two values from the stack and causes an
  395. immediate jump back to the Next instruction if the "one" value
  396. is <em>not</em> like the literal string "H%". Taking this
  397. jump effectively skips the callback, which is the whole point
  398. of the WHERE clause. If the result
  399. of the comparison is true, the jump is not taken and control
  400. falls through to the Callback instruction below.</p>
  401. <p>Notice how the Like instruction works. It uses the top of
  402. the stack as its pattern and the next on stack as the data
  403. to compare. Because P1 is 1, a jump is made to P2 if the
  404. comparison fails. So with P1 equal to one, a more precise
  405. name for this instruction might be "Jump If NOS Is Not Like TOS".
  406. The sense of the test in inverted if P1 is 0. So when P1
  407. is zero, the instruction is "Jump If NOS Is Like TOS".
  408. </p>
  409. <a name="pattern1">
  410. <h2>A Template For SELECT Programs</h2>
  411. <p>The first two query examples illustrate a kind of template that
  412. every SELECT program will follow. Basically, we have:</p>
  413. <p>
  414. <ol>
  415. <li>Initialize the <b>azColumnName[]</b> array for the callback.</li>
  416. <li>Open a cursor into the table to be queried.</li>
  417. <li>For each record in the table, do:
  418. <ol type="a">
  419. <li>If the WHERE clause evaluates to FALSE, then skip the steps that
  420. follow and continue to the next record.</li>
  421. <li>Compute all columns for the current row of the result.</li>
  422. <li>Invoke the callback function for the current row of the result.</li>
  423. </ol>
  424. <li>Close the cursor.</li>
  425. </ol>
  426. </p>
  427. <p>This template will be expanded considerably as we consider
  428. additional complications such as joins, compound selects, using
  429. indices to speed the search, sorting, and aggregate functions
  430. with and without GROUP BY and HAVING clauses.
  431. But the same basic ideas will continue to apply.</p>
  432. <h2>UPDATE And DELETE Statements</h2>
  433. <p>The UPDATE and DELETE statements are coded using a template
  434. that is very similar to the SELECT statement template. The main
  435. difference, of course, is that the end action is to modify the
  436. database rather than invoke a callback function. Let's begin
  437. by looking at a DELETE statement:</p>
  438. <blockquote><pre>
  439. DELETE FROM examp WHERE two<50;
  440. </pre></blockquote>
  441. <p>This DELETE statement will remove every record from the "examp"
  442. table where the "two" column is less than 50.
  443. The code generated to do this is as follows:</p>
  444. }
  445. Code {
  446. addr opcode p1 p2 p3
  447. ---- ------------ ----- ----- ----------------------------------------
  448. 0 ListOpen 0 0
  449. 1 Open 0 0 examp
  450. 2 Next 0 9
  451. 3 Field 0 1
  452. 4 Integer 50 0
  453. 5 Ge 0 2
  454. 6 Key 0 0
  455. 7 ListWrite 0 0
  456. 8 Goto 0 2
  457. 9 Close 0 0
  458. 10 ListRewind 0 0
  459. 11 Open 0 1 examp
  460. 12 ListRead 0 15
  461. 13 Delete 0 0
  462. 14 Goto 0 12
  463. 15 ListClose 0 0
  464. }
  465. puts {
  466. <p>Here is what the program must do. First it has to locate all of
  467. the records in the "examp" database that are to be deleted. This is
  468. done using a loop very much like the loop used in the SELECT examples
  469. above. Once all records have been located, then we can go back through
  470. and delete them one by one. Note that we cannot delete each record
  471. as soon as we find it. We have to locate all records first, then
  472. go back and delete them. This is because the GDBM database
  473. backend might change the scan order after a delete operation.
  474. And if the scan
  475. order changes in the middle of the scan, some records might be
  476. visited more than once and other records might not be visited at all.</p>
  477. <p>So the implemention of DELETE is really in two loops. The
  478. first loop (instructions 2 through 8 in the example) locates the records that
  479. are to be deleted and the second loop (instructions 12 through 14)
  480. does the actual deleting.</p>
  481. <p>The very first instruction in the program, the ListOpen instruction,
  482. creates a new List object in which we can store the keys of the records
  483. that are to be deleted. The P1 operand serves as a handle to the
  484. list. As with cursors, you can open as many lists as you like
  485. (though in practice we never need more than one at a time.) Each list
  486. has a handle specified by P1 which is a non-negative integer. The
  487. VDBE allocates an array of handles, so it is best to use only small
  488. handles. As currently implemented, SQLite never uses more than one
  489. list at a time and so it always uses the handle of 0 for every list.</p>
  490. <p>Lists are implemented using temporary files.
  491. The program will work like this:
  492. the first loop will locate records that need to
  493. be deleted and write their keys onto the list. Then the second
  494. loop will playback the list and delete the records one by one.</p>
  495. <p>The second instruction opens a cursor to the database file "examp".
  496. Notice that the cursor is opened for reading, not writing. At this
  497. stage of the program we are going to be scanning the file not changing
  498. it. We will reopen the same file for writing it later, at instruction 11.
  499. </p>
  500. <p>Following the Open, there is a loop composed of the Next instruction
  501. at address 2 and continuing down to the Goto at 8. This loop works
  502. the same way as the query loops worked in the prior examples. But
  503. instead of invoking a callback at the end of each loop iteration, this
  504. program calls ListWrite at instruction 7. The ListWrite instruction
  505. pops an integer from the stack and appends it to the List identified
  506. by P1. The integer is a key to a record that should be deleted and
  507. was placed on the stack by the preceding Key instruction.
  508. The WHERE clause is implemented by instructions 3, 4, and 5.
  509. The job of the where clause is to skip the ListWrite if the WHERE
  510. condition is false. To this end, it jumps back to the Next instruction
  511. if the "two" column (extracted by the Field instruction at 3) is
  512. greater than or equal to 50.</p>
  513. <p>At the end of the first loop, the cursor is closed at instruction 9,
  514. and the list is rewound back to the beginning at instruction 10.
  515. The Open instruction at 11 reopens the same database file, but for
  516. writing this time. The loop that does the actual deleting of records
  517. is on instructions 12, 13, and 14.</p>
  518. <p>The ListRead instruction at 12 reads a single integer key from
  519. the list and pushes that key onto the stack. If there are no
  520. more keys, nothing gets pushed onto the stack but instead a jump
  521. is made to instruction 15. Notice the similarity
  522. between the ListRead and Next instructions. Both operations work
  523. according to this rule:</p>
  524. <blockquote>
  525. Push the next "thing" onto the stack and fall through.
  526. Or if there is no next "thing" to push, jump immediately to P2.
  527. </blockquote>
  528. <p>The only difference between Next and ListRead is their idea
  529. of a "thing". The "things" for the Next instruction are records
  530. in a database file. "Things" for ListRead are integer keys in a list.
  531. Later on,
  532. we will see other looping instructions (NextIdx and SortNext) that
  533. operate using the same principle.</p>
  534. <p>The Delete instruction at address 13 pops an integer key from
  535. the stack (the key was put there by the preceding ListRead
  536. instruction) and deletes the record of cursor P1 that has that key.
  537. If there is no record in the database with the given key, then
  538. Delete is a no-op.</p>
  539. <p>There is a Goto instruction at 14 to complete the second loop.
  540. Then at instruction 15 is as ListClose operation. The ListClose
  541. closes the list and deletes the temporary file that held it.
  542. Calling ListClose is optional. The VDBE will automatically close
  543. the list when it halts. But we need an instruction for the
  544. ListRead to jump to when it reaches the end of the list and
  545. ListClose seemed like a natural candidate.</p>
  546. <p>UPDATE statements work very much like DELETE statements except
  547. that instead of deleting the record they replace it with a new one.
  548. Consider this example:
  549. </p>
  550. <blockquote><pre>
  551. UPDATE examp SET one= '(' || one || ')' WHERE two < 50;
  552. </pre></blockquote>
  553. <p>Instead of deleting records where the "two" column is less than
  554. 50, this statement just puts the "one" column in parentheses
  555. The VDBE program to implement this statement follows:</p>
  556. }
  557. Code {
  558. addr opcode p1 p2 p3
  559. ---- ------------ ----- ----- ----------------------------------------
  560. 0 ListOpen 0 0
  561. 1 Open 0 0 examp
  562. 2 Next 0 9
  563. 3 Field 0 1
  564. 4 Integer 50 0
  565. 5 Ge 0 2
  566. 6 Key 0 0
  567. 7 ListWrite 0 0
  568. 8 Goto 0 2
  569. 9 Close 0 0
  570. 10 ListRewind 0 0
  571. 11 Open 0 1 examp
  572. 12 ListRead 0 24
  573. 13 Dup 0 0
  574. 14 Fetch 0 0
  575. 15 String 0 0 (
  576. 16 Field 0 0
  577. 17 Concat 2 0
  578. 18 String 0 0 )
  579. 19 Concat 2 0
  580. 20 Field 0 1
  581. 21 MakeRecord 2 0
  582. 22 Put 0 0
  583. 23 Goto 0 12
  584. 24 ListClose 0 0
  585. }
  586. puts {
  587. <p>This program is exactly the same as the DELETE program
  588. except that the single Delete instruction in the second loop
  589. has been replace by a sequence of instructions (at addresses
  590. 13 through 22) that update the record rather than delete it.
  591. Most of this instruction sequence should already be familiar to
  592. you, but there are a couple of minor twists so we will go
  593. over it briefly.</p>
  594. <p>As we enter the interior of the second loop (at instruction 13)
  595. the stack contains a single integer which is the key of the
  596. record we want to modify. We are going to need to use this
  597. key twice: once to fetch the old value of the record and
  598. a second time to write back the revised record. So the first instruction
  599. is a Dup to make a duplicate of the key on the top of the stack. The
  600. Dup instruction will duplicate any element of the stack, not just the top
  601. element. You specify which element to duplication using the
  602. P1 operand. When P1 is 0, the top of the stack is duplicated.
  603. When P1 is 1, the next element down on the stack duplication.
  604. And so forth.</p>
  605. <p>After duplicating the key, the next instruction, Fetch,
  606. pops the stack once and uses the value popped as a key to
  607. load a record from the database file. In this way, we obtain
  608. the old column values for the record that is about to be
  609. updated.</p>
  610. <p>Instructions 15 through 21 construct a new database record
  611. that will be used to replace the existing record. This is
  612. the same kind of code that we saw
  613. in the description of INSERT and will not be described further.
  614. After instruction 21 executes, the stack looks like this:</p>
  615. }
  616. stack {New data record} {Integer key}
  617. puts {
  618. <p>The Put instruction (also described
  619. during the discussion about INSERT) writes an entry into the
  620. database file whose data is the top of the stack and whose key
  621. is the next on the stack, and then pops the stack twice. The
  622. Put instruction will overwrite the data of an existing record
  623. with the same key, which is what we want here. Overwriting was not
  624. an issue with INSERT because with INSERT the key was generated
  625. by the Key instruction which is guaranteed to provide a key
  626. that has not been used before.</p>
  627. }
  628. if 0 {(By the way, since keys must
  629. all be unique and each key is a 32-bit integer, a single
  630. SQLite database table can have no more than 2<sup>32</sup>
  631. rows. Actually, the Key instruction starts to become
  632. very inefficient as you approach this upper bound, so it
  633. is best to keep the number of entries below 2<sup>31</sup>
  634. or so. Surely a couple billion records will be enough for
  635. most applications!)</p>
  636. }
  637. puts {
  638. <h2>CREATE and DROP</h2>
  639. <p>Using CREATE or DROP to create or destroy a table or index is
  640. really the same as doing an INSERT or DELETE from the special
  641. "sqlite_master" table, at least from the point of view of the VDBE.
  642. The sqlite_master table is a special table that is automatically
  643. created for every SQLite database. It looks like this:</p>
  644. <blockquote><pre>
  645. CREATE TABLE sqlite_master (
  646. type TEXT, -- either "table" or "index"
  647. name TEXT, -- name of this table or index
  648. tbl_name TEXT, -- for indices: name of associated table
  649. sql TEXT -- SQL text of the original CREATE statement
  650. )
  651. </pre></blockquote>
  652. <p>Every table (except the "sqlite_master" table itself)
  653. and every named index in an SQLite database has an entry
  654. in the sqlite_master table. You can query this table using
  655. a SELECT statement just like any other table. But you are
  656. not allowed to directly change the table using UPDATE, INSERT,
  657. or DELETE. Changes to sqlite_master have to occur using
  658. the CREATE and DROP commands because SQLite also has to update
  659. some of its internal data structures when tables and indices
  660. are added or destroyed.</p>
  661. <p>But from the point of view of the VDBE, a CREATE works
  662. pretty much like an INSERT and a DROP works like a DELETE.
  663. When the SQLite library opens to an existing database,
  664. the first thing it does is a SELECT to read the "sql"
  665. columns from all entries of the sqlite_master table.
  666. The "sql" column contains the complete SQL text of the
  667. CREATE statement that originally generated the index or
  668. table. This text is fed back into the SQLite parser
  669. and used to reconstruct the
  670. internal data structures describing the index or table.</p>
  671. <h2>Using Indexes To Speed Searching</h2>
  672. <p>In the example queries above, every row of the table being
  673. queried must be loaded off of the disk and examined, even if only
  674. a small percentage of the rows end up in the result. This can
  675. take a long time on a big table. To speed things up, SQLite
  676. can use an index.</p>
  677. <p>A GDBM file associates a key with some data. For a SQLite
  678. table, the GDBM file is set up so that the key is a integer
  679. and the data is the information for one row of the table.
  680. Indices in SQLite reverse this arrangement. The GDBM key
  681. is (some of) the information being stored and the GDBM data
  682. is an integer.
  683. To access a table row that has some particular
  684. content, we first look up the content in the GDBM index file to find
  685. its integer index, then we use that integer to look up the
  686. complete record in the GDBM table file.</p>
  687. <p>Note that because GDBM uses hashing instead of b-trees, indices
  688. are only helpful when the WHERE clause of the SELECT statement
  689. contains tests for equality. Inequalities will not work since there
  690. is no way to ask GDBM to fetch records that do not match a key.
  691. So, in other words, queries like the following will use an index
  692. if it is available:</p>
  693. <blockquote><pre>
  694. SELECT * FROM examp WHERE two==50;
  695. </pre></blockquote>
  696. <p>If there exists an index that maps the "two" column of the "examp"
  697. table into integers, then SQLite will use that index to find the integer
  698. keys of all rows in examp that have a value of 50 for column two.
  699. But the following query will not use an index:</p>
  700. <blockquote><pre>
  701. SELECT * FROM examp WHERE two<50;
  702. </pre></blockquote>
  703. <p>GDBM does not have the ability to select records based on
  704. a magnitude comparison, and so there is no way to use an index
  705. to speed the search in this case.</p>
  706. <p>To understand better how indices work, lets first look at how
  707. they are created. Let's go ahead and put an index on the two
  708. column of the examp table. We have:</p>
  709. <blockquote><pre>
  710. CREATE INDEX examp_idx1 ON examp(two);
  711. </pre></blockquote>
  712. <p>The VDBE code generated by the above statement looks like the
  713. following:</p>
  714. }
  715. Code {
  716. addr opcode p1 p2 p3
  717. ---- ------------ ----- ----- ----------------------------------------
  718. 0 Open 0 0 examp
  719. 1 Open 1 1 examp_idx1
  720. 2 Open 2 1 sqlite_master
  721. 3 New 2 0
  722. 4 String 0 0 index
  723. 5 String 0 0 examp_idx1
  724. 6 String 0 0 examp
  725. 7 String 0 0 CREATE INDEX examp_idx1 ON examp(two)
  726. 8 MakeRecord 4 0
  727. 9 Put 2 0
  728. 10 Close 2 0
  729. 11 Next 0 17
  730. 12 Key 0 0
  731. 13 Field 0 1
  732. 14 MakeKey 1 0
  733. 15 PutIdx 1 0
  734. 16 Goto 0 11
  735. 17 Noop 0 0
  736. 18 Close 1 0
  737. 19 Close 0 0
  738. }
  739. puts {
  740. <p>Remember that every table (except sqlite_master) and every named
  741. index has an entry in the sqlite_master table. Since we are creating
  742. a new index, we have to add a new entry to sqlite_master. This is
  743. handled by instructions 2 through 10. Adding an entry to sqlite_master
  744. works just like any other INSERT statement so we will not say anymore
  745. about it here. In this example, we want to focus on populating the
  746. new index with valid data, which happens on instructions 0 and 1 and
  747. on instructions 11 through 19.</p>
  748. <p>The first thing that happens is that we open the table being
  749. indexed for reading. In order to construct an index for a table,
  750. we have to know what is in that table. The second instruction
  751. opens the index file for writing.</p>
  752. <p>Instructions 11 through 16 implement a loop over every row
  753. of the table being indexed. For each table row, we first extract
  754. the integer key for that row in instruction 12, then get the
  755. value of the two column in instruction 13. The MakeKey instruction
  756. at 14 converts data from the two column (which is on the top of
  757. the stack) into a valid index key. For an index on a single column,
  758. this is basically a no-op. But if the P1 operand to MakeKey had
  759. been greater than one multiple entries would have been popped from
  760. the stack and converted into a single index key. The PutIdx
  761. instruction at 15 is what actually creates the index entry. PutIdx
  762. pops two elements from the stack. The top of the stack is used as
  763. a key to fetch an entry from the GDBM index file. Then the integer
  764. which was second on stack is added to the set of integers for that
  765. index and the new record is written back to the GDBM file. Note
  766. that the same index entry can store multiple integers if there
  767. are two or more table entries with the same value for the two
  768. column.
  769. </p>
  770. <p>Now let's look at how this index will be used. Consider the
  771. following query:</p>
  772. <blockquote><pre>
  773. SELECT * FROM examp WHERE two==50;
  774. </pre></blockquote>
  775. <p>SQLite generates the following VDBE code to handle this query:</p>
  776. }
  777. Code {
  778. addr opcode p1 p2 p3
  779. ---- ------------ ----- ----- ----------------------------------------
  780. 0 ColumnCount 2 0
  781. 1 ColumnName 0 0 one
  782. 2 ColumnName 1 0 two
  783. 3 Open 0 0 examp
  784. 4 Open 1 0 examp_idx1
  785. 5 Integer 50 0
  786. 6 MakeKey 1 0
  787. 7 Fetch 1 0
  788. 8 NextIdx 1 14
  789. 9 Fetch 0 0
  790. 10 Field 0 0
  791. 11 Field 0 1
  792. 12 Callback 2 0
  793. 13 Goto 0 8
  794. 14 Close 0 0
  795. 15 Close 1 0
  796. }
  797. puts {
  798. <p>The SELECT begins in a familiar fashion. First the column
  799. names are initialized and the table being queried is opened.
  800. Things become different beginning with instruction 4 where
  801. the index file is also opened. Instructions 5 and 6 make
  802. a key with the value of 50 and instruction 7 fetches the
  803. record of the GDBM index file that has this key. This will
  804. be the only fetch from the index file.</p>
  805. <p>Instructions 8 through 13 implement a loop over all
  806. integers in the payload of the index record that was fetched
  807. by instruction 7. The NextIdx operation works much like
  808. the Next and ListRead operations that are discussed above.
  809. Each NextIdx instruction reads a single integer from the
  810. payload of the index record and falls through, except that
  811. if there are no more records it jumps immediately to 14.</p>
  812. <p>The Fetch instruction at 9 loads a single record from
  813. the GDBM file that holds the table. Then there are two
  814. Field instructions to construct the result and the callback
  815. is invoked. All this is the same as we have seen before.
  816. The only difference is that the loop is now constructed using
  817. NextIdx instead of Next.</p>
  818. <p>Since the index is used to look up values in the table,
  819. it is important that the index and table be kept consistent.
  820. Now that there is an index on the examp table, we will have
  821. to update that index whenever data is inserted, deleted, or
  822. changed in the examp table. Remember the first example above
  823. how we were able to insert a new row into the examp table using
  824. only 6 VDBE instructions. Now that this table is indexed, 10
  825. instructions are required. The SQL statement is this:</p>
  826. <blockquote><pre>
  827. INSERT INTO examp VALUES('Hello, World!',99);
  828. </pre></blockquote>
  829. <p>And the generated code looks like this:</p>
  830. }
  831. Code {
  832. addr opcode p1 p2 p3
  833. ---- ------------ ----- ----- ----------------------------------------
  834. 0 Open 0 1 examp
  835. 1 Open 1 1 examp_idx1
  836. 2 New 0 0
  837. 3 Dup 0 0
  838. 4 String 0 0 Hello, World!
  839. 5 Integer 99 0
  840. 6 MakeRecord 2 0
  841. 7 Put 0 0
  842. 8 Integer 99 0
  843. 9 MakeKey 1 0
  844. 10 PutIdx 1 0
  845. }
  846. puts {
  847. <p>At this point, you should understand the VDBE well enough to
  848. figure out on your own how the above program works. So we will
  849. not discuss it further in this text.</p>
  850. <h2>Joins</h2>
  851. <p>In a join, two or more tables are combined to generate a single
  852. result. The result table consists of every possible combination
  853. of rows from the tables being joined. The easiest and most natural
  854. way to implement this is with nested loops.</p>
  855. <p>Recall the query template discussed above where there was a
  856. single loop that searched through every record of the table.
  857. In a join we have basically the same thing except that there
  858. are nested loops. For example, to join two tables, the query
  859. template might look something like this:</p>
  860. <p>
  861. <ol>
  862. <li>Initialize the <b>azColumnName[]</b> array for the callback.</li>
  863. <li>Open two cursors, one to each of the two tables being queried.</li>
  864. <li>For each record in the first table, do:
  865. <ol type="a">
  866. <li>For each record in the second table do:
  867. <ol type="i">
  868. <li>If the WHERE clause evaluates to FALSE, then skip the steps that
  869. follow and continue to the next record.</li>
  870. <li>Compute all columns for the current row of the result.</li>
  871. <li>Invoke the callback function for the current row of the result.</li>
  872. </ol></li>
  873. </ol>
  874. <li>Close both cursors.</li>
  875. </ol>
  876. </p>
  877. <p>This template will work, but it is likely to be slow since we
  878. are now dealing with an O(N<sup>2</sup>) loop. But it often works
  879. out that the WHERE clause can be factored into terms and that one or
  880. more of those terms will involve only columns in the first table.
  881. When this happens, we can factor part of the WHERE clause test out of
  882. the inner loop and gain a lot of efficiency. So a better template
  883. would be something like this:</p>
  884. <p>
  885. <ol>
  886. <li>Initialize the <b>azColumnName[]</b> array for the callback.</li>
  887. <li>Open two cursors, one to each of the two tables being queried.</li>
  888. <li>For each record in the first table, do:
  889. <ol type="a">
  890. <li>Evaluate terms of the WHERE clause that only involve columns from
  891. the first table. If any term is false (meaning that the whole
  892. WHERE clause must be false) then skip the rest of this loop and
  893. continue to the next record.</li>
  894. <li>For each record in the second table do:
  895. <ol type="i">
  896. <li>If the WHERE clause evaluates to FALSE, then skip the steps that
  897. follow and continue to the next record.</li>
  898. <li>Compute all columns for the current row of the result.</li>
  899. <li>Invoke the callback function for the current row of the result.</li>
  900. </ol></li>
  901. </ol>
  902. <li>Close both cursors.</li>
  903. </ol>
  904. </p>
  905. <p>Additional speed-up can occur if an index can be used to speed
  906. the search of either or the two loops.</p>
  907. <p>SQLite always constructs the loops in the same order as the
  908. tables appear in the FROM clause of the SELECT statement. The
  909. left-most table becomes the outer loop and the right-most table
  910. becomes the inner loop. It is possible, in theory, to reorder
  911. the loops in some circumstances to speed the evaluation of the
  912. join. But SQLite does not attempt this optimization.</p>
  913. <p>You can see how SQLite constructs nested loops in the following
  914. example:</p>
  915. <blockquote><pre>
  916. CREATE TABLE examp2(three int, four int);
  917. SELECT * FROM examp, examp2 WHERE two<50 AND four==two;
  918. </pre></blockquote>
  919. }
  920. Code {
  921. addr opcode p1 p2 p3
  922. ---- ------------ ----- ----- ----------------------------------------
  923. 0 ColumnCount 4 0
  924. 1 ColumnName 0 0 examp.one
  925. 2 ColumnName 1 0 examp.two
  926. 3 ColumnName 2 0 examp2.three
  927. 4 ColumnName 3 0 examp2.four
  928. 5 Open 0 0 examp
  929. 6 Open 1 0 examp2
  930. 7 Next 0 21
  931. 8 Field 0 1
  932. 9 Integer 50 0
  933. 10 Ge 0 7
  934. 11 Next 1 7
  935. 12 Field 1 1
  936. 13 Field 0 1
  937. 14 Ne 0 11
  938. 15 Field 0 0
  939. 16 Field 0 1
  940. 17 Field 1 0
  941. 18 Field 1 1
  942. 19 Callback 4 0
  943. 20 Goto 0 11
  944. 21 Close 0 0
  945. 22 Close 1 0
  946. }
  947. puts {
  948. <p>The outer loop over table examp is implement by instructions
  949. 7 through 20. The inner loop is instructions 11 through 20.
  950. Notice that the "two<50" term of the WHERE expression involves
  951. only columns from the first table and can be factored out of
  952. the inner loop. SQLite does this and implements the "two<50"
  953. test in instructions 8 through 10. The "four==two" test is
  954. implement by instructions 12 through 14 in the inner loop.</p>
  955. <p>SQLite does not impose any arbitrary limits on the tables in
  956. a join. It also allows a table to be joined with itself.</p>
  957. <h2>The ORDER BY clause</h2>
  958. <p>As noted previously, GDBM does not have any facility for
  959. handling inequalities. A consequence of this is that we cannot
  960. sort on disk using GDBM. All sorted must be done in memory.</p>
  961. <p>SQLite implements the ORDER BY clause using a special
  962. set of instruction control an object called a sorter. In the
  963. inner-most loop of the query, where there would normally be
  964. a Callback instruction, instead a record is constructed that
  965. contains both callback parameters and a key. This record
  966. is added to a linked list. After the query loop finishes,
  967. the list of records is sort and this walked. For each record
  968. on the list, the callback is invoked. Finally, the sorter
  969. is closed and memory is deallocated.</p>
  970. <p>We can see the process in action in the following query:</p>
  971. <blockquote><pre>
  972. SELECT * FROM examp ORDER BY one DESC, two;
  973. </pre></blockquote>
  974. }
  975. Code {
  976. addr opcode p1 p2 p3
  977. ---- ------------ ----- ----- ----------------------------------------
  978. 0 SortOpen 0 0
  979. 1 ColumnCount 2 0
  980. 2 ColumnName 0 0 one
  981. 3 ColumnName 1 0 two
  982. 4 Open 0 0 examp
  983. 5 Next 0 14
  984. 6 Field 0 0
  985. 7 Field 0 1
  986. 8 SortMakeRec 2 0
  987. 9 Field 0 0
  988. 10 Field 0 1
  989. 11 SortMakeKey 2 0 -+
  990. 12 SortPut 0 0
  991. 13 Goto 0 5
  992. 14 Close 0 0
  993. 15 Sort 0 0
  994. 16 SortNext 0 19
  995. 17 SortCallback 2 0
  996. 18 Goto 0 16
  997. 19 SortClose 0 0
  998. }
  999. puts {
  1000. <p>The sorter is opened on the first instruction. The VDBE allows
  1001. any number of sorters, but in practice no more than one is every used.</p>
  1002. <p>The query loop is built from instructions 5 through 13. Instructions
  1003. 6 through 8 build a record that contains the azData[] values for a single
  1004. invocation of the callback. A sort key is generated by instructions
  1005. 9 through 11. Instruction 12 combines the invocation record and the
  1006. sort key into a single entry and puts that entry on the sort list.<p>
  1007. <p>The P3 argument of instruction 11 is of particular interest. The
  1008. sort key is formed by prepending one character from P3 to each string
  1009. and concatenating all the strings. The sort comparison function will
  1010. look at this character to determine whether the sort order is
  1011. ascending or descending. In this example, the first column should be
  1012. sorted in descending order so its prefix is "-" and the second column
  1013. should sort in ascending order so its prefix is "+".</p>
  1014. <p>After the query loop ends, the table being queried is closed at
  1015. instruction 14. This is done early in order to allow other processes
  1016. or threads to access that table, if desired. The list of records
  1017. that was built up inside the query loop is sorted by the instruction
  1018. at 15. Instructions 16 through 18 walk through the record list
  1019. (which is now in sorted order) and invoke the callback once for
  1020. each record. Finally, the sorter is closed at instruction 19.</p>
  1021. <h2>Aggregate Functions And The GROUP BY and HAVING Clauses</h2>
  1022. <p>To compute aggregate functions, the VDBE implements a special
  1023. data structure and instructions for controlling that data structure.
  1024. The data structure is an unordered set of buckets, where each bucket
  1025. has a key and one or more memory locations. Within the query
  1026. loop, the GROUP BY clause is used to construct a key and the bucket
  1027. with that key is brought into focus. A new bucket is created with
  1028. the key if one did not previously exist. Once the bucket is in
  1029. focus, the memory locations of the bucket are used to accumulate
  1030. the values of the various aggregate functions. After the query
  1031. loop terminates, each bucket is visited once to generate a
  1032. single row of the results.</p>
  1033. <p>An example will help to clarify this concept. Consider the
  1034. following query:</p>
  1035. <blockquote><pre>
  1036. SELECT three, min(three+four)+avg(four)
  1037. FROM examp2
  1038. GROUP BY three;
  1039. </pre></blockquote>
  1040. }
  1041. puts {
  1042. <p>The VDBE code generated for this query is as follows:</p>
  1043. }
  1044. Code {
  1045. addr opcode p1 p2 p3
  1046. ---- ------------ ----- ----- ----------------------------------------
  1047. 0 ColumnCount 2 0
  1048. 1 ColumnName 0 0 three
  1049. 2 ColumnName 1 0 min(three+four)+avg(four)
  1050. 3 AggReset 0 4
  1051. 4 Open 0 0 examp2
  1052. 5 Next 0 23
  1053. 6 Field 0 0
  1054. 7 MakeKey 1 0
  1055. 8 AggFocus 0 11
  1056. 9 Field 0 0
  1057. 10 AggSet 0 0
  1058. 11 Field 0 0
  1059. 12 Field 0 1
  1060. 13 Add 0 0
  1061. 14 AggGet 0 1
  1062. 15 Min 0 0
  1063. 16 AggSet 0 1
  1064. 17 AggIncr 1 2
  1065. 18 Field 0 1
  1066. 19 AggGet 0 3
  1067. 20 Add 0 0
  1068. 21 AggSet 0 3
  1069. 22 Goto 0 5
  1070. 23 Close 0 0
  1071. 24 AggNext 0 33
  1072. 25 AggGet 0 0
  1073. 26 AggGet 0 1
  1074. 27 AggGet 0 3
  1075. 28 AggGet 0 2
  1076. 29 Divide 0 0
  1077. 30 Add 0 0
  1078. 31 Callback 2 0
  1079. 32 Goto 0 24
  1080. 33 Noop 0 0
  1081. }
  1082. puts {
  1083. <p>The first instruction of interest is the AggReset at 3.
  1084. The AggReset instruction initializes the set of buckets to be the
  1085. empty set and specifies the number of memory slots available in each
  1086. bucket. In this example, each bucket will hold four memory slots.
  1087. It is not obvious, but if you look closely at the rest of the program
  1088. you can figure out what each of these four slots is intended for.</p>
  1089. <blockquote><table border="2" cellpadding="5">
  1090. <tr><th>Memory Slot</th><th>Intended Use Of This Memory Slot</th></tr>
  1091. <tr><td>0</td><td>The "three" column -- the key to the bucket</td></tr>
  1092. <tr><td>1</td><td>The minimum "three+four" value</td></tr>
  1093. <tr><td>2</td><td>The number of records with the same key. This value
  1094. divides the value in slot 3 to compute "avg(four)".</td></tr>
  1095. <tr><td>3</td><td>The sum of all "four" values. This is used to compute
  1096. "avg(four)".</td></tr>
  1097. </table></blockquote>
  1098. <p>The query loop is implement by instructions 5 through 22.
  1099. The aggregate key specified by the GROUP BY clause is computed
  1100. by instructions 6 and 7. Instruction 8 causes the appropriate
  1101. bucket to come into focus. If a bucket with the given key does
  1102. not already exists, a new bucket is created and control falls
  1103. through to instructions 9 and 10 which initialize the bucket.
  1104. If the bucket does already exist, then a jump is made to instruction
  1105. 11. The values of aggregate functions are updated by the instructions
  1106. between 11 and 21. Instructions 11 through 16 update memory
  1107. slot 1 to hold the next value "min(three+four)". The counter in
  1108. slot 2 is incremented by instruction 17. Finally the sum of
  1109. the "four" column is updated by instructions 18 through 21.</p>
  1110. <p>After the query loop is finished, the GDBM table is closed at
  1111. instruction 23 so that its lock will be released and it can be
  1112. used by other threads or processes. The next step is to loop
  1113. over all aggregate buckets and output one row of the result for
  1114. each bucket. This is done by the loop at instructions 24
  1115. through 32. The AggNext instruction at 24 brings the next bucket
  1116. into focus, or jumps to the end of the loop if all buckets have
  1117. been examined already. The first column of the result ("three")
  1118. is computed by instruction 25. The second result column
  1119. ("min(three+four)+avg(four)") is computed by instructions
  1120. 26 through 30. Notice how the avg() function is computed
  1121. as if it where sum()/count(). Finally, the callback is invoked
  1122. at instruction 31.</p>
  1123. <p>In summary then, any query with aggregate functions is implemented
  1124. by two loops. The first loop scans the input table and computes
  1125. aggregate information into buckets and the second loop scans through
  1126. all the buckets to compute the final result.</p>
  1127. <p>The realization that an aggregate query is really two consequtive
  1128. loops makes it much easier to understand the difference between
  1129. a WHERE clause and a HAVING clause in SQL query statement. The
  1130. WHERE clause is a restriction on the first loop and the HAVING
  1131. clause is a restriction on the second loop. You can see this
  1132. by adding both a WHERE and a HAVING clause to our example query:</p>
  1133. <blockquote><pre>
  1134. SELECT three, min(three+four)+avg(four)
  1135. FROM examp2
  1136. WHERE three>four
  1137. GROUP BY three
  1138. HAVING avg(four)<10;
  1139. </pre></blockquote>
  1140. }
  1141. Code {
  1142. addr opcode p1 p2 p3
  1143. ---- ------------ ----- ----- ----------------------------------------
  1144. 0 ColumnCount 2 0
  1145. 1 ColumnName 0 0 three
  1146. 2 ColumnName 1 0 min(three+four)+avg(four)
  1147. 3 AggReset 0 4
  1148. 4 Open 0 0 examp2
  1149. 5 Next 0 26
  1150. 6 Field 0 0
  1151. 7 Field 0 1
  1152. 8 Le 0 5
  1153. 9 Field 0 0
  1154. 10 MakeKey 1 0
  1155. 11 AggFocus 0 14
  1156. 12 Field 0 0
  1157. 13 AggSet 0 0
  1158. 14 Field 0 0
  1159. 15 Field 0 1
  1160. 16 Add 0 0
  1161. 17 AggGet 0 1
  1162. 18 Min 0 0
  1163. 19 AggSet 0 1
  1164. 20 AggIncr 1 2
  1165. 21 Field 0 1
  1166. 22 AggGet 0 3
  1167. 23 Add 0 0
  1168. 24 AggSet 0 3
  1169. 25 Goto 0 5
  1170. 26 Close 0 0
  1171. 27 AggNext 0 41
  1172. 28 AggGet 0 3
  1173. 29 AggGet 0 2
  1174. 30 Divide 0 0
  1175. 31 Integer 10 0
  1176. 32 Ge 0 27
  1177. 33 AggGet 0 0
  1178. 34 AggGet 0 1
  1179. 35 AggGet 0 3
  1180. 36 AggGet 0 2
  1181. 37 Divide 0 0
  1182. 38 Add 0 0
  1183. 39 Callback 2 0
  1184. 40 Goto 0 27
  1185. 41 Noop 0 0
  1186. }
  1187. puts {
  1188. <p>The code generated in this last example is the same as the
  1189. previous except for the addition of two conditional jumps used
  1190. to implement the extra WHERE and HAVING clauses. The WHERE
  1191. clause is implemented by instructions 6 through 8 in the query
  1192. loop. The HAVING clause is implemented by instruction 28 through
  1193. 32 in the output loop.</p>
  1194. <h2>Using SELECT Statements As Terms In An Expression</h2>
  1195. <p>The very name "Structured Query Language" tells us that SQL should
  1196. support nested queries. And, in fact, two different kinds of nesting
  1197. are supported. Any SELECT statement that returns a single-row, single-column
  1198. result can be used as a term in an expression of another SELECT statement.
  1199. And, a SELECT statement that returns a single-column, multi-row result
  1200. can be used as the right-hand operand of the IN and NOT IN operators.
  1201. We will begin this section with an example of the first kind of nesting,
  1202. where a single-row, single-column SELECT is used as a term in an expression
  1203. of another SELECT. Here is our example:</p>
  1204. <blockquote><pre>
  1205. SELECT * FROM examp
  1206. WHERE two!=(SELECT three FROM examp2
  1207. WHERE four=5);
  1208. </pre></blockquote>
  1209. <p>The way SQLite deals with this is to first run the inner SELECT
  1210. (the one against examp2) and store its result in a private memory
  1211. cell. SQLite then substitutes the value of this private memory
  1212. cell for the inner SELECT when it evaluations the outer SELECT.
  1213. The code looks like this:</p>
  1214. }
  1215. Code {
  1216. addr opcode p1 p2 p3
  1217. ---- ------------ ----- ----- ----------------------------------------
  1218. 0 Null 0 0
  1219. 1 MemStore 0 0
  1220. 2 Open 0 0 examp2
  1221. 3 Next 0 11
  1222. 4 Field 0 1
  1223. 5 Integer 5 0
  1224. 6 Ne 0 3
  1225. 7 Field 0 0
  1226. 8 MemStore 0 0
  1227. 9 Goto 0 11
  1228. 10 Goto 0 3
  1229. 11 Close 0 0
  1230. 12 ColumnCount 2 0
  1231. 13 ColumnName 0 0 one
  1232. 14 ColumnName 1 0 two
  1233. 15 Open 0 0 examp
  1234. 16 Next 0 24
  1235. 17 Field 0 1
  1236. 18 MemLoad 0 0
  1237. 19 Eq 0 16
  1238. 20 Field 0 0
  1239. 21 Field 0 1
  1240. 22 Callback 2 0
  1241. 23 Goto 0 16
  1242. 24 Close 0 0
  1243. }
  1244. puts {
  1245. <p>The private memory cell is initialized to NULL by the first
  1246. two instructions. Instructions 2 through 11 implement the inner
  1247. SELECT statement against the examp2 table. Notice that instead of
  1248. sending the result to a callback or storing the result on a sorter,
  1249. the result of the query is pushed into the memory cell by instruction
  1250. 8 and the loop is abandoned by the jump at instruction 9.
  1251. The jump at instruction at 10 is vestigial and
  1252. never executes.</p>
  1253. <p>The outer SELECT is implemented by instructions 12 through 24.
  1254. In particular, the WHERE clause that contains the nested select
  1255. is implemented by instructions 17 through 19. You can see that
  1256. the result of the inner select is loaded onto the stack by instruction
  1257. 18 and used by the conditional jump at 19.</p>
  1258. <p>When the result of a sub-select is a scalar, a single private memory
  1259. cell can be used, as shown in the previous
  1260. example. But when the result of a sub-select is a vector, such
  1261. as when the sub-select is the right-hand operand of IN or NOT IN,
  1262. a different approach is needed. In this case,
  1263. the result of the sub-select is
  1264. stored in a temporary GDBM table and the contents of that table
  1265. are tested using the Found or NotFound operators. Consider this
  1266. example:</p>
  1267. <blockquote><pre>
  1268. SELECT * FROM examp
  1269. WHERE two IN (SELECT three FROM examp2);
  1270. </pre></blockquote>
  1271. <p>The code generated to implement this last query is as follows:</p>
  1272. }
  1273. Code {
  1274. addr opcode p1 p2 p3
  1275. ---- ------------ ----- ----- ----------------------------------------
  1276. 0 Open 0 1
  1277. 1 Open 1 0 examp2
  1278. 2 Next 1 7
  1279. 3 Field 1 0
  1280. 4 String 0 0
  1281. 5 Put 0 0
  1282. 6 Goto 0 2
  1283. 7 Close 1 0
  1284. 8 ColumnCount 2 0
  1285. 9 ColumnName 0 0 one
  1286. 10 ColumnName 1 0 two
  1287. 11 Open 1 0 examp
  1288. 12 Next 1 19
  1289. 13 Field 1 1
  1290. 14 NotFound 0 12
  1291. 15 Field 1 0
  1292. 16 Field 1 1
  1293. 17 Callback 2 0
  1294. 18 Goto 0 12
  1295. 19 Close 1 0
  1296. }
  1297. puts {
  1298. <p>The temporary table in which the results of the inner SELECT are
  1299. stored is created by instruction 0. Notice that the P3 field of
  1300. this Open instruction is empty. An empty P3 field on an Open
  1301. instruction tells the VDBE to create a temporary table. This temporary
  1302. table will be automatically deleted from the disk when the
  1303. VDBE halts.</p>
  1304. <p>The inner SELECT statement is implemented by instructions 1 through 7.
  1305. All this code does is make an entry in the temporary table for each
  1306. row of the examp2 table. The key for each temporary table entry
  1307. is the "three" column of examp2 and the data
  1308. is an empty string since it is never used.</p>
  1309. <p>The outer SELECT is implemented by instructions 8 through 19. In
  1310. particular, the WHERE clause containing the IN operator is implemented
  1311. by two instructions at 13 and 14. Instruction 13 pushes the value of
  1312. the "two" column for the current row onto the stack and instruction 14
  1313. tests to see if top of the stack matches any key in the temporary table.
  1314. All the rest of the code is the same as what has been shown before.</p>
  1315. <h2>Compound SELECT Statements</h2>
  1316. <p>SQLite also allows two or more SELECT statements to be joined as
  1317. peers using operators UNION, UNION ALL, INTERSECT, and EXCEPT. These
  1318. compound select statements are implemented using temporary tables.
  1319. The implementation is slightly different for each operator, but the
  1320. basic ideas are the same. For an example we will use the EXCEPT
  1321. operator.</p>
  1322. <blockquote><pre>
  1323. SELECT two FROM examp
  1324. EXCEPT
  1325. SELECT four FROM examp2;
  1326. </pre></blockquote>
  1327. <p>The result of this last example should be every unique value
  1328. of the two column in the examp table except any value that is
  1329. in the four column of examp2 is removed. The code to implement
  1330. this query is as follows:</p>
  1331. }
  1332. Code {
  1333. addr opcode p1 p2 p3
  1334. ---- ------------ ----- ----- ----------------------------------------
  1335. 0 Open 0 1
  1336. 1 KeyAsData 0 1
  1337. 2 Open 1 0 examp
  1338. 3 Next 1 9
  1339. 4 Field 1 1
  1340. 5 MakeRecord 1 0
  1341. 6 String 0 0
  1342. 7 Put 0 0
  1343. 8 Goto 0 3
  1344. 9 Close 1 0
  1345. 10 Open 1 0 examp2
  1346. 11 Next 1 16
  1347. 12 Field 1 1
  1348. 13 MakeRecord 1 0
  1349. 14 Delete 0 0
  1350. 15 Goto 0 11
  1351. 16 Close 1 0
  1352. 17 ColumnCount 1 0
  1353. 18 ColumnName 0 0 four
  1354. 19 Next 0 23
  1355. 20 Field 0 0
  1356. 21 Callback 1 0
  1357. 22 Goto 0 19
  1358. 23 Close 0 0
  1359. }
  1360. puts {
  1361. <p>The temporary table in which the result is built is created by
  1362. instruction 0. Three loops then follow. The loop at instructions
  1363. 3 through 8 implements the first SELECT statement. The second
  1364. SELECT statement is implemented by the loop at instructions 11 through
  1365. 15. Finally, a loop at instructions 19 through 22 reads the temporary
  1366. table and invokes the callback once for each row in the result.</p>
  1367. <p>Instruction 1 is of particular importance in this example. Normally,
  1368. the Field opcode extracts the value of a column from a larger
  1369. record in the data of a GDBM file entry. Instructions 1 sets a flag on
  1370. the temporary table so that Field will instead treat the key of the
  1371. GDBM file entry as if it were data and extract column information from
  1372. the key.</p>
  1373. <p>Here is what is going to happen: The first SELECT statement
  1374. will construct rows of the result and save each row as the key of
  1375. an entry in the temporary table. The data for each entry in the
  1376. temporary table is a never used so we fill it in with an empty string.
  1377. The second SELECT statement also constructs rows, but the rows
  1378. constructed by the second SELECT are removed from the temporary table.
  1379. That is why we want the rows to be stored in the key of the GDBM file
  1380. instead of in the data -- so they can be easily located and deleted.</p>
  1381. <p>Let's look more closely at what is happening here. The first
  1382. SELECT is implemented by the loop at instructions 3 through 8.
  1383. Instruction 4 extracts the value of the "two" column from "examp"
  1384. and instruction 5 converts this into a row. Instruction 6 pushes
  1385. an empty string onto the stack. Finally, instruction 7 writes the
  1386. row into the temporary table. But remember, the Put opcode uses
  1387. the top of the stack as the GDBM data and the next on stack as the
  1388. GDBM key. For an INSERT statement, the row generated by the
  1389. MakeRecord opcode is the GDBM data and the GDBM key is an integer
  1390. created by the New opcode. But here the roles are reversed and
  1391. the row created by MakeRecord is the GDBM key and the GDBM data is
  1392. just an empty string.</p>
  1393. <p>The second SELECT is implemented by instructions 11 through 15.
  1394. A new result row is created from the "four" column of table "examp2"
  1395. by instructions 12 and 13. But instead of using Put to write this
  1396. new row into the temporary table, we instead call Delete to remove
  1397. it from the temporary table if it exists.</p>
  1398. <p>The result of the compound select is sent to the callback routine
  1399. by the loop at instructions 19 through 22. There is nothing new
  1400. or remarkable about this loop, except for the fact that the Field
  1401. instruction at 20 will be extracting a column out of the GDBM key
  1402. rather than the GDBM data.</p>
  1403. <h2>Summary</h2>
  1404. <p>This article has reviewed all of the major techniques used by
  1405. SQLite's VDBE to implement SQL statements. What has not been shown
  1406. is that most of these techniques can be used in combination to
  1407. generate code for an appropriately complex query statement. For
  1408. example, we have shown how sorting is accomplished on a simple query
  1409. and we have shown how to implement a compound query. But we did
  1410. not give an example of sorting in a compound query. This is because
  1411. sorting a compound query does not introduce any new concepts: it
  1412. merely combines two previous ideas (sorting and compounding)
  1413. in the same VDBE program.</p>
  1414. <p>For additional information on how the SQLite library
  1415. functions, the reader is directed to look at the SQLite source
  1416. code directly. If you understand the material in this article,
  1417. you should not have much difficulty in following the sources.
  1418. Serious students of the internals of SQLite will probably
  1419. also what to make a careful study of the VDBE opcodes
  1420. as documented <a href="opcode.html">here</a>. Most of the
  1421. opcode documentation is extracted from comments in the source
  1422. code using a script so you can also get information about the
  1423. various opcodes directly from the <b>vdbe.c</b> source file.
  1424. If you have successfully read this far, you should have little
  1425. difficulty understanding the rest.</p>
  1426. <p>If you find errors in either the documentation or the code,
  1427. feel free to fix them and/or contact the author at
  1428. <a href="mailto:drh@hwaci.com">drh@hwaci.com</a>. Your bug fixes or
  1429. suggestions are always welcomed.</p>
  1430. }
  1431. puts {
  1432. <p><hr /></p>
  1433. <p><a href="index.html"><img src="/goback.jpg" border=0 />
  1434. Back to the SQLite Home Page</a>
  1435. </p>
  1436. </body></html>}