xref: /sqlite-3.40.0/src/vdbeaux.c (revision 8a29dfde)
1 /*
2 ** 2003 September 6
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains code used for creating, destroying, and populating
13 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
14 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
15 ** But that file was getting too big so this subroutines were split out.
16 */
17 #include "sqliteInt.h"
18 #include <ctype.h>
19 #include "vdbeInt.h"
20 
21 
22 
23 /*
24 ** When debugging the code generator in a symbolic debugger, one can
25 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
26 ** as they are added to the instruction stream.
27 */
28 #ifdef SQLITE_DEBUG
29 int sqlite3VdbeAddopTrace = 0;
30 #endif
31 
32 
33 /*
34 ** Create a new virtual database engine.
35 */
36 Vdbe *sqlite3VdbeCreate(sqlite3 *db){
37   Vdbe *p;
38   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
39   if( p==0 ) return 0;
40   p->db = db;
41   if( db->pVdbe ){
42     db->pVdbe->pPrev = p;
43   }
44   p->pNext = db->pVdbe;
45   p->pPrev = 0;
46   db->pVdbe = p;
47   p->magic = VDBE_MAGIC_INIT;
48   return p;
49 }
50 
51 /*
52 ** Remember the SQL string for a prepared statement.
53 */
54 void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
55   if( p==0 ) return;
56   assert( p->zSql==0 );
57   p->zSql = sqlite3DbStrNDup(p->db, z, n);
58 }
59 
60 /*
61 ** Return the SQL associated with a prepared statement
62 */
63 const char *sqlite3_sql(sqlite3_stmt *pStmt){
64   return ((Vdbe *)pStmt)->zSql;
65 }
66 
67 /*
68 ** Swap all content between two VDBE structures.
69 */
70 void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
71   Vdbe tmp, *pTmp;
72   char *zTmp;
73   int nTmp;
74   tmp = *pA;
75   *pA = *pB;
76   *pB = tmp;
77   pTmp = pA->pNext;
78   pA->pNext = pB->pNext;
79   pB->pNext = pTmp;
80   pTmp = pA->pPrev;
81   pA->pPrev = pB->pPrev;
82   pB->pPrev = pTmp;
83   zTmp = pA->zSql;
84   pA->zSql = pB->zSql;
85   pB->zSql = zTmp;
86   nTmp = pA->nSql;
87   pA->nSql = pB->nSql;
88   pB->nSql = nTmp;
89 }
90 
91 #ifdef SQLITE_DEBUG
92 /*
93 ** Turn tracing on or off
94 */
95 void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
96   p->trace = trace;
97 }
98 #endif
99 
100 /*
101 ** Resize the Vdbe.aOp array so that it contains at least N
102 ** elements.
103 **
104 ** If an out-of-memory error occurs while resizing the array,
105 ** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
106 ** any opcodes already allocated can be correctly deallocated
107 ** along with the rest of the Vdbe).
108 */
109 static void resizeOpArray(Vdbe *p, int N){
110   VdbeOp *pNew;
111   pNew = sqlite3DbRealloc(p->db, p->aOp, N*sizeof(Op));
112   if( pNew ){
113     p->nOpAlloc = N;
114     p->aOp = pNew;
115   }
116 }
117 
118 /*
119 ** Add a new instruction to the list of instructions current in the
120 ** VDBE.  Return the address of the new instruction.
121 **
122 ** Parameters:
123 **
124 **    p               Pointer to the VDBE
125 **
126 **    op              The opcode for this instruction
127 **
128 **    p1, p2, p3      Operands
129 **
130 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
131 ** the sqlite3VdbeChangeP4() function to change the value of the P4
132 ** operand.
133 */
134 int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
135   int i;
136   VdbeOp *pOp;
137 
138   i = p->nOp;
139   assert( p->magic==VDBE_MAGIC_INIT );
140   if( p->nOpAlloc<=i ){
141     resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
142     if( p->db->mallocFailed ){
143       return 0;
144     }
145   }
146   p->nOp++;
147   pOp = &p->aOp[i];
148   pOp->opcode = op;
149   pOp->p5 = 0;
150   pOp->p1 = p1;
151   pOp->p2 = p2;
152   pOp->p3 = p3;
153   pOp->p4.p = 0;
154   pOp->p4type = P4_NOTUSED;
155   p->expired = 0;
156 #ifdef SQLITE_DEBUG
157   pOp->zComment = 0;
158   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
159 #endif
160 #ifdef VDBE_PROFILE
161   pOp->cycles = 0;
162   pOp->cnt = 0;
163 #endif
164   return i;
165 }
166 int sqlite3VdbeAddOp0(Vdbe *p, int op){
167   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
168 }
169 int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
170   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
171 }
172 int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
173   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
174 }
175 
176 
177 /*
178 ** Add an opcode that includes the p4 value as a pointer.
179 */
180 int sqlite3VdbeAddOp4(
181   Vdbe *p,            /* Add the opcode to this VM */
182   int op,             /* The new opcode */
183   int p1,             /* The P1 operand */
184   int p2,             /* The P2 operand */
185   int p3,             /* The P3 operand */
186   const char *zP4,    /* The P4 operand */
187   int p4type          /* P4 operand type */
188 ){
189   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
190   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
191   return addr;
192 }
193 
194 /*
195 ** Create a new symbolic label for an instruction that has yet to be
196 ** coded.  The symbolic label is really just a negative number.  The
197 ** label can be used as the P2 value of an operation.  Later, when
198 ** the label is resolved to a specific address, the VDBE will scan
199 ** through its operation list and change all values of P2 which match
200 ** the label into the resolved address.
201 **
202 ** The VDBE knows that a P2 value is a label because labels are
203 ** always negative and P2 values are suppose to be non-negative.
204 ** Hence, a negative P2 value is a label that has yet to be resolved.
205 **
206 ** Zero is returned if a malloc() fails.
207 */
208 int sqlite3VdbeMakeLabel(Vdbe *p){
209   int i;
210   i = p->nLabel++;
211   assert( p->magic==VDBE_MAGIC_INIT );
212   if( i>=p->nLabelAlloc ){
213     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
214     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
215                                     p->nLabelAlloc*sizeof(p->aLabel[0]));
216   }
217   if( p->aLabel ){
218     p->aLabel[i] = -1;
219   }
220   return -1-i;
221 }
222 
223 /*
224 ** Resolve label "x" to be the address of the next instruction to
225 ** be inserted.  The parameter "x" must have been obtained from
226 ** a prior call to sqlite3VdbeMakeLabel().
227 */
228 void sqlite3VdbeResolveLabel(Vdbe *p, int x){
229   int j = -1-x;
230   assert( p->magic==VDBE_MAGIC_INIT );
231   assert( j>=0 && j<p->nLabel );
232   if( p->aLabel ){
233     p->aLabel[j] = p->nOp;
234   }
235 }
236 
237 /*
238 ** Loop through the program looking for P2 values that are negative
239 ** on jump instructions.  Each such value is a label.  Resolve the
240 ** label by setting the P2 value to its correct non-zero value.
241 **
242 ** This routine is called once after all opcodes have been inserted.
243 **
244 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
245 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
246 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
247 **
248 ** This routine also does the following optimization:  It scans for
249 ** instructions that might cause a statement rollback.  Such instructions
250 ** are:
251 **
252 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
253 **   *  OP_Destroy
254 **   *  OP_VUpdate
255 **   *  OP_VRename
256 **
257 ** If no such instruction is found, then every Statement instruction
258 ** is changed to a Noop.  In this way, we avoid creating the statement
259 ** journal file unnecessarily.
260 */
261 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
262   int i;
263   int nMaxArgs = 0;
264   Op *pOp;
265   int *aLabel = p->aLabel;
266   int doesStatementRollback = 0;
267   int hasStatementBegin = 0;
268   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
269     u8 opcode = pOp->opcode;
270 
271     if( opcode==OP_Function ){
272       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
273     }else if( opcode==OP_AggStep
274 #ifndef SQLITE_OMIT_VIRTUALTABLE
275         || opcode==OP_VUpdate
276 #endif
277     ){
278       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
279     }
280     if( opcode==OP_Halt ){
281       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
282         doesStatementRollback = 1;
283       }
284     }else if( opcode==OP_Statement ){
285       hasStatementBegin = 1;
286     }else if( opcode==OP_Destroy ){
287       doesStatementRollback = 1;
288 #ifndef SQLITE_OMIT_VIRTUALTABLE
289     }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
290       doesStatementRollback = 1;
291     }else if( opcode==OP_VFilter ){
292       int n;
293       assert( p->nOp - i >= 3 );
294       assert( pOp[-1].opcode==OP_Integer );
295       n = pOp[-1].p1;
296       if( n>nMaxArgs ) nMaxArgs = n;
297 #endif
298     }
299 
300     if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){
301       assert( -1-pOp->p2<p->nLabel );
302       pOp->p2 = aLabel[-1-pOp->p2];
303     }
304   }
305   sqlite3_free(p->aLabel);
306   p->aLabel = 0;
307 
308   *pMaxFuncArgs = nMaxArgs;
309 
310   /* If we never rollback a statement transaction, then statement
311   ** transactions are not needed.  So change every OP_Statement
312   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
313   ** which can be expensive on some platforms.
314   */
315   if( hasStatementBegin && !doesStatementRollback ){
316     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
317       if( pOp->opcode==OP_Statement ){
318         pOp->opcode = OP_Noop;
319       }
320     }
321   }
322 }
323 
324 /*
325 ** Return the address of the next instruction to be inserted.
326 */
327 int sqlite3VdbeCurrentAddr(Vdbe *p){
328   assert( p->magic==VDBE_MAGIC_INIT );
329   return p->nOp;
330 }
331 
332 /*
333 ** Add a whole list of operations to the operation stack.  Return the
334 ** address of the first operation added.
335 */
336 int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
337   int addr;
338   assert( p->magic==VDBE_MAGIC_INIT );
339   if( p->nOp + nOp > p->nOpAlloc ){
340     resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
341     assert( p->nOp+nOp<=p->nOpAlloc || p->db->mallocFailed );
342   }
343   if( p->db->mallocFailed ){
344     return 0;
345   }
346   addr = p->nOp;
347   if( nOp>0 ){
348     int i;
349     VdbeOpList const *pIn = aOp;
350     for(i=0; i<nOp; i++, pIn++){
351       int p2 = pIn->p2;
352       VdbeOp *pOut = &p->aOp[i+addr];
353       pOut->opcode = pIn->opcode;
354       pOut->p1 = pIn->p1;
355       if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){
356         pOut->p2 = addr + ADDR(p2);
357       }else{
358         pOut->p2 = p2;
359       }
360       pOut->p3 = pIn->p3;
361       pOut->p4type = P4_NOTUSED;
362       pOut->p4.p = 0;
363       pOut->p5 = 0;
364 #ifdef SQLITE_DEBUG
365       pOut->zComment = 0;
366       if( sqlite3VdbeAddopTrace ){
367         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
368       }
369 #endif
370     }
371     p->nOp += nOp;
372   }
373   return addr;
374 }
375 
376 /*
377 ** Change the value of the P1 operand for a specific instruction.
378 ** This routine is useful when a large program is loaded from a
379 ** static array using sqlite3VdbeAddOpList but we want to make a
380 ** few minor changes to the program.
381 */
382 void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
383   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
384   if( p && addr>=0 && p->nOp>addr && p->aOp ){
385     p->aOp[addr].p1 = val;
386   }
387 }
388 
389 /*
390 ** Change the value of the P2 operand for a specific instruction.
391 ** This routine is useful for setting a jump destination.
392 */
393 void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
394   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
395   if( p && addr>=0 && p->nOp>addr && p->aOp ){
396     p->aOp[addr].p2 = val;
397   }
398 }
399 
400 /*
401 ** Change the value of the P3 operand for a specific instruction.
402 */
403 void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
404   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
405   if( p && addr>=0 && p->nOp>addr && p->aOp ){
406     p->aOp[addr].p3 = val;
407   }
408 }
409 
410 /*
411 ** Change the value of the P5 operand for the most recently
412 ** added operation.
413 */
414 void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
415   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
416   if( p && p->aOp ){
417     assert( p->nOp>0 );
418     p->aOp[p->nOp-1].p5 = val;
419   }
420 }
421 
422 /*
423 ** Change the P2 operand of instruction addr so that it points to
424 ** the address of the next instruction to be coded.
425 */
426 void sqlite3VdbeJumpHere(Vdbe *p, int addr){
427   sqlite3VdbeChangeP2(p, addr, p->nOp);
428 }
429 
430 
431 /*
432 ** If the input FuncDef structure is ephemeral, then free it.  If
433 ** the FuncDef is not ephermal, then do nothing.
434 */
435 static void freeEphemeralFunction(FuncDef *pDef){
436   if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
437     sqlite3_free(pDef);
438   }
439 }
440 
441 /*
442 ** Delete a P4 value if necessary.
443 */
444 static void freeP4(int p4type, void *p3){
445   if( p3 ){
446     switch( p4type ){
447       case P4_REAL:
448       case P4_INT64:
449       case P4_MPRINTF:
450       case P4_DYNAMIC:
451       case P4_KEYINFO:
452       case P4_KEYINFO_HANDOFF: {
453         sqlite3_free(p3);
454         break;
455       }
456       case P4_VDBEFUNC: {
457         VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
458         freeEphemeralFunction(pVdbeFunc->pFunc);
459         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
460         sqlite3_free(pVdbeFunc);
461         break;
462       }
463       case P4_FUNCDEF: {
464         freeEphemeralFunction((FuncDef*)p3);
465         break;
466       }
467       case P4_MEM: {
468         sqlite3ValueFree((sqlite3_value*)p3);
469         break;
470       }
471     }
472   }
473 }
474 
475 
476 /*
477 ** Change N opcodes starting at addr to No-ops.
478 */
479 void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
480   if( p && p->aOp ){
481     VdbeOp *pOp = &p->aOp[addr];
482     while( N-- ){
483       freeP4(pOp->p4type, pOp->p4.p);
484       memset(pOp, 0, sizeof(pOp[0]));
485       pOp->opcode = OP_Noop;
486       pOp++;
487     }
488   }
489 }
490 
491 /*
492 ** Change the value of the P4 operand for a specific instruction.
493 ** This routine is useful when a large program is loaded from a
494 ** static array using sqlite3VdbeAddOpList but we want to make a
495 ** few minor changes to the program.
496 **
497 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
498 ** the string is made into memory obtained from sqlite3_malloc().
499 ** A value of n==0 means copy bytes of zP4 up to and including the
500 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
501 **
502 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
503 ** A copy is made of the KeyInfo structure into memory obtained from
504 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
505 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
506 ** stored in memory that the caller has obtained from sqlite3_malloc. The
507 ** caller should not free the allocation, it will be freed when the Vdbe is
508 ** finalized.
509 **
510 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
511 ** to a string or structure that is guaranteed to exist for the lifetime of
512 ** the Vdbe. In these cases we can just copy the pointer.
513 **
514 ** If addr<0 then change P4 on the most recently inserted instruction.
515 */
516 void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
517   Op *pOp;
518   assert( p!=0 );
519   assert( p->magic==VDBE_MAGIC_INIT );
520   if( p->aOp==0 || p->db->mallocFailed ){
521     if (n != P4_KEYINFO) {
522       freeP4(n, (void*)*(char**)&zP4);
523     }
524     return;
525   }
526   assert( addr<p->nOp );
527   if( addr<0 ){
528     addr = p->nOp - 1;
529     if( addr<0 ) return;
530   }
531   pOp = &p->aOp[addr];
532   freeP4(pOp->p4type, pOp->p4.p);
533   pOp->p4.p = 0;
534   if( n==P4_INT32 ){
535     /* Note: this cast is safe, because the origin data point was an int
536     ** that was cast to a (const char *). */
537     pOp->p4.i = (int)(sqlite3_intptr_t)zP4;
538     pOp->p4type = n;
539   }else if( zP4==0 ){
540     pOp->p4.p = 0;
541     pOp->p4type = P4_NOTUSED;
542   }else if( n==P4_KEYINFO ){
543     KeyInfo *pKeyInfo;
544     int nField, nByte;
545 
546     nField = ((KeyInfo*)zP4)->nField;
547     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
548     pKeyInfo = sqlite3_malloc( nByte );
549     pOp->p4.pKeyInfo = pKeyInfo;
550     if( pKeyInfo ){
551       memcpy(pKeyInfo, zP4, nByte);
552       /* In the current implementation, P4_KEYINFO is only ever used on
553       ** KeyInfo structures that have no aSortOrder component.  Elements
554       ** with an aSortOrder always use P4_KEYINFO_HANDOFF.  So we do not
555       ** need to bother with duplicating the aSortOrder. */
556       assert( pKeyInfo->aSortOrder==0 );
557 #if 0
558       aSortOrder = pKeyInfo->aSortOrder;
559       if( aSortOrder ){
560         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
561         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
562       }
563 #endif
564       pOp->p4type = P4_KEYINFO;
565     }else{
566       p->db->mallocFailed = 1;
567       pOp->p4type = P4_NOTUSED;
568     }
569   }else if( n==P4_KEYINFO_HANDOFF ){
570     pOp->p4.p = (void*)zP4;
571     pOp->p4type = P4_KEYINFO;
572   }else if( n<0 ){
573     pOp->p4.p = (void*)zP4;
574     pOp->p4type = n;
575   }else{
576     if( n==0 ) n = strlen(zP4);
577     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
578     pOp->p4type = P4_DYNAMIC;
579   }
580 }
581 
582 #ifndef NDEBUG
583 /*
584 ** Change the comment on the the most recently coded instruction.
585 */
586 void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
587   va_list ap;
588   assert( p->nOp>0 || p->aOp==0 );
589   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
590   if( p->nOp ){
591     char **pz = &p->aOp[p->nOp-1].zComment;
592     va_start(ap, zFormat);
593     sqlite3_free(*pz);
594     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
595     va_end(ap);
596   }
597 }
598 #endif
599 
600 /*
601 ** Return the opcode for a given address.
602 */
603 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
604   assert( p->magic==VDBE_MAGIC_INIT );
605   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
606   return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
607 }
608 
609 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
610      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
611 /*
612 ** Compute a string that describes the P4 parameter for an opcode.
613 ** Use zTemp for any required temporary buffer space.
614 */
615 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
616   char *zP4 = zTemp;
617   assert( nTemp>=20 );
618   switch( pOp->p4type ){
619     case P4_KEYINFO: {
620       int i, j;
621       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
622       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
623       i = strlen(zTemp);
624       for(j=0; j<pKeyInfo->nField; j++){
625         CollSeq *pColl = pKeyInfo->aColl[j];
626         if( pColl ){
627           int n = strlen(pColl->zName);
628           if( i+n>nTemp-6 ){
629             memcpy(&zTemp[i],",...",4);
630             break;
631           }
632           zTemp[i++] = ',';
633           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
634             zTemp[i++] = '-';
635           }
636           memcpy(&zTemp[i], pColl->zName,n+1);
637           i += n;
638         }else if( i+4<nTemp-6 ){
639           memcpy(&zTemp[i],",nil",4);
640           i += 4;
641         }
642       }
643       zTemp[i++] = ')';
644       zTemp[i] = 0;
645       assert( i<nTemp );
646       break;
647     }
648     case P4_COLLSEQ: {
649       CollSeq *pColl = pOp->p4.pColl;
650       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
651       break;
652     }
653     case P4_FUNCDEF: {
654       FuncDef *pDef = pOp->p4.pFunc;
655       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
656       break;
657     }
658     case P4_INT64: {
659       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
660       break;
661     }
662     case P4_INT32: {
663       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
664       break;
665     }
666     case P4_REAL: {
667       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
668       break;
669     }
670     case P4_MEM: {
671       Mem *pMem = pOp->p4.pMem;
672       assert( (pMem->flags & MEM_Null)==0 );
673       if( pMem->flags & MEM_Str ){
674         zP4 = pMem->z;
675       }else if( pMem->flags & MEM_Int ){
676         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
677       }else if( pMem->flags & MEM_Real ){
678         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
679       }
680       break;
681     }
682 #ifndef SQLITE_OMIT_VIRTUALTABLE
683     case P4_VTAB: {
684       sqlite3_vtab *pVtab = pOp->p4.pVtab;
685       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
686       break;
687     }
688 #endif
689     default: {
690       zP4 = pOp->p4.z;
691       if( zP4==0 ){
692         zP4 = zTemp;
693         zTemp[0] = 0;
694       }
695     }
696   }
697   assert( zP4!=0 );
698   return zP4;
699 }
700 #endif
701 
702 /*
703 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
704 **
705 */
706 void sqlite3VdbeUsesBtree(Vdbe *p, int i){
707   int mask;
708   assert( i>=0 && i<p->db->nDb );
709   assert( i<sizeof(p->btreeMask)*8 );
710   mask = 1<<i;
711   if( (p->btreeMask & mask)==0 ){
712     p->btreeMask |= mask;
713     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
714   }
715 }
716 
717 
718 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
719 /*
720 ** Print a single opcode.  This routine is used for debugging only.
721 */
722 void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
723   char *zP4;
724   char zPtr[50];
725   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
726   if( pOut==0 ) pOut = stdout;
727   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
728   fprintf(pOut, zFormat1, pc,
729       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
730 #ifdef SQLITE_DEBUG
731       pOp->zComment ? pOp->zComment : ""
732 #else
733       ""
734 #endif
735   );
736   fflush(pOut);
737 }
738 #endif
739 
740 /*
741 ** Release an array of N Mem elements
742 */
743 static void releaseMemArray(Mem *p, int N, int freebuffers){
744   if( p && N ){
745     sqlite3 *db = p->db;
746     int malloc_failed = db->mallocFailed;
747     while( N-->0 ){
748       assert( N<2 || p[0].db==p[1].db );
749       if( freebuffers ){
750         sqlite3VdbeMemRelease(p);
751       }else{
752         sqlite3VdbeMemReleaseExternal(p);
753       }
754       p->flags = MEM_Null;
755       p++;
756     }
757     db->mallocFailed = malloc_failed;
758   }
759 }
760 
761 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
762 int sqlite3VdbeReleaseBuffers(Vdbe *p){
763   int ii;
764   int nFree = 0;
765   assert( sqlite3_mutex_held(p->db->mutex) );
766   for(ii=1; ii<=p->nMem; ii++){
767     Mem *pMem = &p->aMem[ii];
768     if( pMem->z && pMem->flags&MEM_Dyn ){
769       assert( !pMem->xDel );
770       nFree += sqlite3MallocSize(pMem->z);
771       sqlite3VdbeMemRelease(pMem);
772     }
773   }
774   return nFree;
775 }
776 #endif
777 
778 #ifndef SQLITE_OMIT_EXPLAIN
779 /*
780 ** Give a listing of the program in the virtual machine.
781 **
782 ** The interface is the same as sqlite3VdbeExec().  But instead of
783 ** running the code, it invokes the callback once for each instruction.
784 ** This feature is used to implement "EXPLAIN".
785 **
786 ** When p->explain==1, each instruction is listed.  When
787 ** p->explain==2, only OP_Explain instructions are listed and these
788 ** are shown in a different format.  p->explain==2 is used to implement
789 ** EXPLAIN QUERY PLAN.
790 */
791 int sqlite3VdbeList(
792   Vdbe *p                   /* The VDBE */
793 ){
794   sqlite3 *db = p->db;
795   int i;
796   int rc = SQLITE_OK;
797   Mem *pMem = p->pResultSet = &p->aMem[1];
798 
799   assert( p->explain );
800   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
801   assert( db->magic==SQLITE_MAGIC_BUSY );
802   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
803 
804   /* Even though this opcode does not use dynamic strings for
805   ** the result, result columns may become dynamic if the user calls
806   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
807   */
808   releaseMemArray(pMem, p->nMem, 1);
809 
810   do{
811     i = p->pc++;
812   }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
813   if( i>=p->nOp ){
814     p->rc = SQLITE_OK;
815     rc = SQLITE_DONE;
816   }else if( db->u1.isInterrupted ){
817     p->rc = SQLITE_INTERRUPT;
818     rc = SQLITE_ERROR;
819     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
820   }else{
821     char *z;
822     Op *pOp = &p->aOp[i];
823     if( p->explain==1 ){
824       pMem->flags = MEM_Int;
825       pMem->type = SQLITE_INTEGER;
826       pMem->u.i = i;                                /* Program counter */
827       pMem++;
828 
829       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
830       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
831       assert( pMem->z!=0 );
832       pMem->n = strlen(pMem->z);
833       pMem->type = SQLITE_TEXT;
834       pMem->enc = SQLITE_UTF8;
835       pMem++;
836     }
837 
838     pMem->flags = MEM_Int;
839     pMem->u.i = pOp->p1;                          /* P1 */
840     pMem->type = SQLITE_INTEGER;
841     pMem++;
842 
843     pMem->flags = MEM_Int;
844     pMem->u.i = pOp->p2;                          /* P2 */
845     pMem->type = SQLITE_INTEGER;
846     pMem++;
847 
848     if( p->explain==1 ){
849       pMem->flags = MEM_Int;
850       pMem->u.i = pOp->p3;                          /* P3 */
851       pMem->type = SQLITE_INTEGER;
852       pMem++;
853     }
854 
855     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
856       p->db->mallocFailed = 1;
857       return SQLITE_NOMEM;
858     }
859     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
860     z = displayP4(pOp, pMem->z, 32);
861     if( z!=pMem->z ){
862       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
863     }else{
864       assert( pMem->z!=0 );
865       pMem->n = strlen(pMem->z);
866       pMem->enc = SQLITE_UTF8;
867     }
868     pMem->type = SQLITE_TEXT;
869     pMem++;
870 
871     if( p->explain==1 ){
872       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
873         p->db->mallocFailed = 1;
874         return SQLITE_NOMEM;
875       }
876       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
877       pMem->n = 2;
878       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
879       pMem->type = SQLITE_TEXT;
880       pMem->enc = SQLITE_UTF8;
881       pMem++;
882 
883 #ifdef SQLITE_DEBUG
884       if( pOp->zComment ){
885         pMem->flags = MEM_Str|MEM_Term;
886         pMem->z = pOp->zComment;
887         pMem->n = strlen(pMem->z);
888         pMem->enc = SQLITE_UTF8;
889       }else
890 #endif
891       {
892         pMem->flags = MEM_Null;                       /* Comment */
893         pMem->type = SQLITE_NULL;
894       }
895     }
896 
897     p->nResColumn = 8 - 5*(p->explain-1);
898     p->rc = SQLITE_OK;
899     rc = SQLITE_ROW;
900   }
901   return rc;
902 }
903 #endif /* SQLITE_OMIT_EXPLAIN */
904 
905 #ifdef SQLITE_DEBUG
906 /*
907 ** Print the SQL that was used to generate a VDBE program.
908 */
909 void sqlite3VdbePrintSql(Vdbe *p){
910   int nOp = p->nOp;
911   VdbeOp *pOp;
912   if( nOp<1 ) return;
913   pOp = &p->aOp[0];
914   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
915     const char *z = pOp->p4.z;
916     while( isspace(*(u8*)z) ) z++;
917     printf("SQL: [%s]\n", z);
918   }
919 }
920 #endif
921 
922 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
923 /*
924 ** Print an IOTRACE message showing SQL content.
925 */
926 void sqlite3VdbeIOTraceSql(Vdbe *p){
927   int nOp = p->nOp;
928   VdbeOp *pOp;
929   if( sqlite3IoTrace==0 ) return;
930   if( nOp<1 ) return;
931   pOp = &p->aOp[0];
932   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
933     int i, j;
934     char z[1000];
935     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
936     for(i=0; isspace((unsigned char)z[i]); i++){}
937     for(j=0; z[i]; i++){
938       if( isspace((unsigned char)z[i]) ){
939         if( z[i-1]!=' ' ){
940           z[j++] = ' ';
941         }
942       }else{
943         z[j++] = z[i];
944       }
945     }
946     z[j] = 0;
947     sqlite3IoTrace("SQL %s\n", z);
948   }
949 }
950 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
951 
952 
953 /*
954 ** Prepare a virtual machine for execution.  This involves things such
955 ** as allocating stack space and initializing the program counter.
956 ** After the VDBE has be prepped, it can be executed by one or more
957 ** calls to sqlite3VdbeExec().
958 **
959 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
960 ** VDBE_MAGIC_RUN.
961 */
962 void sqlite3VdbeMakeReady(
963   Vdbe *p,                       /* The VDBE */
964   int nVar,                      /* Number of '?' see in the SQL statement */
965   int nMem,                      /* Number of memory cells to allocate */
966   int nCursor,                   /* Number of cursors to allocate */
967   int isExplain                  /* True if the EXPLAIN keywords is present */
968 ){
969   int n;
970   sqlite3 *db = p->db;
971 
972   assert( p!=0 );
973   assert( p->magic==VDBE_MAGIC_INIT );
974 
975   /* There should be at least one opcode.
976   */
977   assert( p->nOp>0 );
978 
979   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
980    * is because the call to resizeOpArray() below may shrink the
981    * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN
982    * state.
983    */
984   p->magic = VDBE_MAGIC_RUN;
985 
986   /* For each cursor required, also allocate a memory cell. Memory
987   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
988   ** the vdbe program. Instead they are used to allocate space for
989   ** Cursor/BtCursor structures. The blob of memory associated with
990   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
991   ** stores the blob of memory associated with cursor 1, etc.
992   **
993   ** See also: allocateCursor().
994   */
995   nMem += nCursor;
996 
997   /*
998   ** Allocation space for registers.
999   */
1000   if( p->aMem==0 ){
1001     int nArg;       /* Maximum number of args passed to a user function. */
1002     resolveP2Values(p, &nArg);
1003     /*resizeOpArray(p, p->nOp);*/
1004     assert( nVar>=0 );
1005     if( isExplain && nMem<10 ){
1006       p->nMem = nMem = 10;
1007     }
1008     p->aMem = sqlite3DbMallocZero(db,
1009         nMem*sizeof(Mem)               /* aMem */
1010       + nVar*sizeof(Mem)               /* aVar */
1011       + nArg*sizeof(Mem*)              /* apArg */
1012       + nVar*sizeof(char*)             /* azVar */
1013       + nCursor*sizeof(Cursor*) + 1    /* apCsr */
1014     );
1015     if( !db->mallocFailed ){
1016       p->aMem--;             /* aMem[] goes from 1..nMem */
1017       p->nMem = nMem;        /*       not from 0..nMem-1 */
1018       p->aVar = &p->aMem[nMem+1];
1019       p->nVar = nVar;
1020       p->okVar = 0;
1021       p->apArg = (Mem**)&p->aVar[nVar];
1022       p->azVar = (char**)&p->apArg[nArg];
1023       p->apCsr = (Cursor**)&p->azVar[nVar];
1024       p->nCursor = nCursor;
1025       for(n=0; n<nVar; n++){
1026         p->aVar[n].flags = MEM_Null;
1027         p->aVar[n].db = db;
1028       }
1029       for(n=1; n<=nMem; n++){
1030         p->aMem[n].flags = MEM_Null;
1031         p->aMem[n].db = db;
1032       }
1033     }
1034   }
1035 #ifdef SQLITE_DEBUG
1036   for(n=1; n<p->nMem; n++){
1037     assert( p->aMem[n].db==db );
1038   }
1039 #endif
1040 
1041   p->pc = -1;
1042   p->rc = SQLITE_OK;
1043   p->uniqueCnt = 0;
1044   p->returnDepth = 0;
1045   p->errorAction = OE_Abort;
1046   p->explain |= isExplain;
1047   p->magic = VDBE_MAGIC_RUN;
1048   p->nChange = 0;
1049   p->cacheCtr = 1;
1050   p->minWriteFileFormat = 255;
1051   p->openedStatement = 0;
1052 #ifdef VDBE_PROFILE
1053   {
1054     int i;
1055     for(i=0; i<p->nOp; i++){
1056       p->aOp[i].cnt = 0;
1057       p->aOp[i].cycles = 0;
1058     }
1059   }
1060 #endif
1061 }
1062 
1063 /*
1064 ** Close a VDBE cursor and release all the resources that cursor
1065 ** happens to hold.
1066 */
1067 void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
1068   if( pCx==0 ){
1069     return;
1070   }
1071   if( pCx->pCursor ){
1072     sqlite3BtreeCloseCursor(pCx->pCursor);
1073   }
1074   if( pCx->pBt ){
1075     sqlite3BtreeClose(pCx->pBt);
1076   }
1077 #ifndef SQLITE_OMIT_VIRTUALTABLE
1078   if( pCx->pVtabCursor ){
1079     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
1080     const sqlite3_module *pModule = pCx->pModule;
1081     p->inVtabMethod = 1;
1082     (void)sqlite3SafetyOff(p->db);
1083     pModule->xClose(pVtabCursor);
1084     (void)sqlite3SafetyOn(p->db);
1085     p->inVtabMethod = 0;
1086   }
1087 #endif
1088   if( !pCx->ephemPseudoTable ){
1089     sqlite3_free(pCx->pData);
1090   }
1091   /* memset(pCx, 0, sizeof(Cursor)); */
1092   /* sqlite3_free(pCx->aType); */
1093   /* sqlite3_free(pCx); */
1094 }
1095 
1096 /*
1097 ** Close all cursors except for VTab cursors that are currently
1098 ** in use.
1099 */
1100 static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
1101   int i;
1102   if( p->apCsr==0 ) return;
1103   for(i=0; i<p->nCursor; i++){
1104     Cursor *pC = p->apCsr[i];
1105     if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
1106       sqlite3VdbeFreeCursor(p, pC);
1107       p->apCsr[i] = 0;
1108     }
1109   }
1110 }
1111 
1112 /*
1113 ** Clean up the VM after execution.
1114 **
1115 ** This routine will automatically close any cursors, lists, and/or
1116 ** sorters that were left open.  It also deletes the values of
1117 ** variables in the aVar[] array.
1118 */
1119 static void Cleanup(Vdbe *p, int freebuffers){
1120   int i;
1121   closeAllCursorsExceptActiveVtabs(p);
1122   for(i=1; i<=p->nMem; i++){
1123     MemSetTypeFlag(&p->aMem[i], MEM_Null);
1124   }
1125   releaseMemArray(&p->aMem[1], p->nMem, freebuffers);
1126   sqlite3VdbeFifoClear(&p->sFifo);
1127   if( p->contextStack ){
1128     for(i=0; i<p->contextStackTop; i++){
1129       sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
1130     }
1131     sqlite3_free(p->contextStack);
1132   }
1133   p->contextStack = 0;
1134   p->contextStackDepth = 0;
1135   p->contextStackTop = 0;
1136   sqlite3_free(p->zErrMsg);
1137   p->zErrMsg = 0;
1138   p->pResultSet = 0;
1139 }
1140 
1141 /*
1142 ** Set the number of result columns that will be returned by this SQL
1143 ** statement. This is now set at compile time, rather than during
1144 ** execution of the vdbe program so that sqlite3_column_count() can
1145 ** be called on an SQL statement before sqlite3_step().
1146 */
1147 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
1148   Mem *pColName;
1149   int n;
1150 
1151   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N, 1);
1152   sqlite3_free(p->aColName);
1153   n = nResColumn*COLNAME_N;
1154   p->nResColumn = nResColumn;
1155   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(p->db, sizeof(Mem)*n );
1156   if( p->aColName==0 ) return;
1157   while( n-- > 0 ){
1158     pColName->flags = MEM_Null;
1159     pColName->db = p->db;
1160     pColName++;
1161   }
1162 }
1163 
1164 /*
1165 ** Set the name of the idx'th column to be returned by the SQL statement.
1166 ** zName must be a pointer to a nul terminated string.
1167 **
1168 ** This call must be made after a call to sqlite3VdbeSetNumCols().
1169 **
1170 ** If N==P4_STATIC  it means that zName is a pointer to a constant static
1171 ** string and we can just copy the pointer. If it is P4_DYNAMIC, then
1172 ** the string is freed using sqlite3_free() when the vdbe is finished with
1173 ** it. Otherwise, N bytes of zName are copied.
1174 */
1175 int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
1176   int rc;
1177   Mem *pColName;
1178   assert( idx<p->nResColumn );
1179   assert( var<COLNAME_N );
1180   if( p->db->mallocFailed ) return SQLITE_NOMEM;
1181   assert( p->aColName!=0 );
1182   pColName = &(p->aColName[idx+var*p->nResColumn]);
1183   if( N==P4_DYNAMIC || N==P4_STATIC ){
1184     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
1185   }else{
1186     rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
1187   }
1188   if( rc==SQLITE_OK && N==P4_DYNAMIC ){
1189     pColName->flags &= (~MEM_Static);
1190     pColName->zMalloc = pColName->z;
1191   }
1192   return rc;
1193 }
1194 
1195 /*
1196 ** A read or write transaction may or may not be active on database handle
1197 ** db. If a transaction is active, commit it. If there is a
1198 ** write-transaction spanning more than one database file, this routine
1199 ** takes care of the master journal trickery.
1200 */
1201 static int vdbeCommit(sqlite3 *db){
1202   int i;
1203   int nTrans = 0;  /* Number of databases with an active write-transaction */
1204   int rc = SQLITE_OK;
1205   int needXcommit = 0;
1206 
1207   /* Before doing anything else, call the xSync() callback for any
1208   ** virtual module tables written in this transaction. This has to
1209   ** be done before determining whether a master journal file is
1210   ** required, as an xSync() callback may add an attached database
1211   ** to the transaction.
1212   */
1213   rc = sqlite3VtabSync(db, rc);
1214   if( rc!=SQLITE_OK ){
1215     return rc;
1216   }
1217 
1218   /* This loop determines (a) if the commit hook should be invoked and
1219   ** (b) how many database files have open write transactions, not
1220   ** including the temp database. (b) is important because if more than
1221   ** one database file has an open write transaction, a master journal
1222   ** file is required for an atomic commit.
1223   */
1224   for(i=0; i<db->nDb; i++){
1225     Btree *pBt = db->aDb[i].pBt;
1226     if( sqlite3BtreeIsInTrans(pBt) ){
1227       needXcommit = 1;
1228       if( i!=1 ) nTrans++;
1229     }
1230   }
1231 
1232   /* If there are any write-transactions at all, invoke the commit hook */
1233   if( needXcommit && db->xCommitCallback ){
1234     (void)sqlite3SafetyOff(db);
1235     rc = db->xCommitCallback(db->pCommitArg);
1236     (void)sqlite3SafetyOn(db);
1237     if( rc ){
1238       return SQLITE_CONSTRAINT;
1239     }
1240   }
1241 
1242   /* The simple case - no more than one database file (not counting the
1243   ** TEMP database) has a transaction active.   There is no need for the
1244   ** master-journal.
1245   **
1246   ** If the return value of sqlite3BtreeGetFilename() is a zero length
1247   ** string, it means the main database is :memory:.  In that case we do
1248   ** not support atomic multi-file commits, so use the simple case then
1249   ** too.
1250   */
1251   if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
1252     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1253       Btree *pBt = db->aDb[i].pBt;
1254       if( pBt ){
1255         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
1256       }
1257     }
1258 
1259     /* Do the commit only if all databases successfully complete phase 1.
1260     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
1261     ** IO error while deleting or truncating a journal file. It is unlikely,
1262     ** but could happen. In this case abandon processing and return the error.
1263     */
1264     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1265       Btree *pBt = db->aDb[i].pBt;
1266       if( pBt ){
1267         rc = sqlite3BtreeCommitPhaseTwo(pBt);
1268       }
1269     }
1270     if( rc==SQLITE_OK ){
1271       sqlite3VtabCommit(db);
1272     }
1273   }
1274 
1275   /* The complex case - There is a multi-file write-transaction active.
1276   ** This requires a master journal file to ensure the transaction is
1277   ** committed atomicly.
1278   */
1279 #ifndef SQLITE_OMIT_DISKIO
1280   else{
1281     sqlite3_vfs *pVfs = db->pVfs;
1282     int needSync = 0;
1283     char *zMaster = 0;   /* File-name for the master journal */
1284     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
1285     sqlite3_file *pMaster = 0;
1286     i64 offset = 0;
1287 
1288     /* Select a master journal file name */
1289     do {
1290       u32 random;
1291       sqlite3_free(zMaster);
1292       sqlite3_randomness(sizeof(random), &random);
1293       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, random&0x7fffffff);
1294       if( !zMaster ){
1295         return SQLITE_NOMEM;
1296       }
1297       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS);
1298     }while( rc==1 );
1299     if( rc!=0 ){
1300       rc = SQLITE_IOERR_NOMEM;
1301     }else{
1302       /* Open the master journal. */
1303       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
1304           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
1305           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
1306       );
1307     }
1308     if( rc!=SQLITE_OK ){
1309       sqlite3_free(zMaster);
1310       return rc;
1311     }
1312 
1313     /* Write the name of each database file in the transaction into the new
1314     ** master journal file. If an error occurs at this point close
1315     ** and delete the master journal file. All the individual journal files
1316     ** still have 'null' as the master journal pointer, so they will roll
1317     ** back independently if a failure occurs.
1318     */
1319     for(i=0; i<db->nDb; i++){
1320       Btree *pBt = db->aDb[i].pBt;
1321       if( i==1 ) continue;   /* Ignore the TEMP database */
1322       if( sqlite3BtreeIsInTrans(pBt) ){
1323         char const *zFile = sqlite3BtreeGetJournalname(pBt);
1324         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
1325         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
1326           needSync = 1;
1327         }
1328         rc = sqlite3OsWrite(pMaster, zFile, strlen(zFile)+1, offset);
1329         offset += strlen(zFile)+1;
1330         if( rc!=SQLITE_OK ){
1331           sqlite3OsCloseFree(pMaster);
1332           sqlite3OsDelete(pVfs, zMaster, 0);
1333           sqlite3_free(zMaster);
1334           return rc;
1335         }
1336       }
1337     }
1338 
1339     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
1340     ** flag is set this is not required.
1341     */
1342     zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
1343     if( (needSync
1344      && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
1345      && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
1346       sqlite3OsCloseFree(pMaster);
1347       sqlite3OsDelete(pVfs, zMaster, 0);
1348       sqlite3_free(zMaster);
1349       return rc;
1350     }
1351 
1352     /* Sync all the db files involved in the transaction. The same call
1353     ** sets the master journal pointer in each individual journal. If
1354     ** an error occurs here, do not delete the master journal file.
1355     **
1356     ** If the error occurs during the first call to
1357     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
1358     ** master journal file will be orphaned. But we cannot delete it,
1359     ** in case the master journal file name was written into the journal
1360     ** file before the failure occured.
1361     */
1362     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1363       Btree *pBt = db->aDb[i].pBt;
1364       if( pBt ){
1365         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
1366       }
1367     }
1368     sqlite3OsCloseFree(pMaster);
1369     if( rc!=SQLITE_OK ){
1370       sqlite3_free(zMaster);
1371       return rc;
1372     }
1373 
1374     /* Delete the master journal file. This commits the transaction. After
1375     ** doing this the directory is synced again before any individual
1376     ** transaction files are deleted.
1377     */
1378     rc = sqlite3OsDelete(pVfs, zMaster, 1);
1379     sqlite3_free(zMaster);
1380     zMaster = 0;
1381     if( rc ){
1382       return rc;
1383     }
1384 
1385     /* All files and directories have already been synced, so the following
1386     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
1387     ** deleting or truncating journals. If something goes wrong while
1388     ** this is happening we don't really care. The integrity of the
1389     ** transaction is already guaranteed, but some stray 'cold' journals
1390     ** may be lying around. Returning an error code won't help matters.
1391     */
1392     disable_simulated_io_errors();
1393     for(i=0; i<db->nDb; i++){
1394       Btree *pBt = db->aDb[i].pBt;
1395       if( pBt ){
1396         sqlite3BtreeCommitPhaseTwo(pBt);
1397       }
1398     }
1399     enable_simulated_io_errors();
1400 
1401     sqlite3VtabCommit(db);
1402   }
1403 #endif
1404 
1405   return rc;
1406 }
1407 
1408 /*
1409 ** This routine checks that the sqlite3.activeVdbeCnt count variable
1410 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
1411 ** currently active. An assertion fails if the two counts do not match.
1412 ** This is an internal self-check only - it is not an essential processing
1413 ** step.
1414 **
1415 ** This is a no-op if NDEBUG is defined.
1416 */
1417 #ifndef NDEBUG
1418 static void checkActiveVdbeCnt(sqlite3 *db){
1419   Vdbe *p;
1420   int cnt = 0;
1421   p = db->pVdbe;
1422   while( p ){
1423     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
1424       cnt++;
1425     }
1426     p = p->pNext;
1427   }
1428   assert( cnt==db->activeVdbeCnt );
1429 }
1430 #else
1431 #define checkActiveVdbeCnt(x)
1432 #endif
1433 
1434 /*
1435 ** For every Btree that in database connection db which
1436 ** has been modified, "trip" or invalidate each cursor in
1437 ** that Btree might have been modified so that the cursor
1438 ** can never be used again.  This happens when a rollback
1439 *** occurs.  We have to trip all the other cursors, even
1440 ** cursor from other VMs in different database connections,
1441 ** so that none of them try to use the data at which they
1442 ** were pointing and which now may have been changed due
1443 ** to the rollback.
1444 **
1445 ** Remember that a rollback can delete tables complete and
1446 ** reorder rootpages.  So it is not sufficient just to save
1447 ** the state of the cursor.  We have to invalidate the cursor
1448 ** so that it is never used again.
1449 */
1450 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
1451   int i;
1452   for(i=0; i<db->nDb; i++){
1453     Btree *p = db->aDb[i].pBt;
1454     if( p && sqlite3BtreeIsInTrans(p) ){
1455       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
1456     }
1457   }
1458 }
1459 
1460 /*
1461 ** This routine is called the when a VDBE tries to halt.  If the VDBE
1462 ** has made changes and is in autocommit mode, then commit those
1463 ** changes.  If a rollback is needed, then do the rollback.
1464 **
1465 ** This routine is the only way to move the state of a VM from
1466 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
1467 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
1468 **
1469 ** Return an error code.  If the commit could not complete because of
1470 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
1471 ** means the close did not happen and needs to be repeated.
1472 */
1473 int sqlite3VdbeHalt(Vdbe *p){
1474   sqlite3 *db = p->db;
1475   int i;
1476   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
1477   int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
1478 
1479   /* This function contains the logic that determines if a statement or
1480   ** transaction will be committed or rolled back as a result of the
1481   ** execution of this virtual machine.
1482   **
1483   ** If any of the following errors occur:
1484   **
1485   **     SQLITE_NOMEM
1486   **     SQLITE_IOERR
1487   **     SQLITE_FULL
1488   **     SQLITE_INTERRUPT
1489   **
1490   ** Then the internal cache might have been left in an inconsistent
1491   ** state.  We need to rollback the statement transaction, if there is
1492   ** one, or the complete transaction if there is no statement transaction.
1493   */
1494 
1495   if( p->db->mallocFailed ){
1496     p->rc = SQLITE_NOMEM;
1497   }
1498   closeAllCursorsExceptActiveVtabs(p);
1499   if( p->magic!=VDBE_MAGIC_RUN ){
1500     return SQLITE_OK;
1501   }
1502   checkActiveVdbeCnt(db);
1503 
1504   /* No commit or rollback needed if the program never started */
1505   if( p->pc>=0 ){
1506     int mrc;   /* Primary error code from p->rc */
1507 
1508     /* Lock all btrees used by the statement */
1509     sqlite3BtreeMutexArrayEnter(&p->aMutex);
1510 
1511     /* Check for one of the special errors */
1512     mrc = p->rc & 0xff;
1513     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
1514                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
1515     if( isSpecialError ){
1516       /* This loop does static analysis of the query to see which of the
1517       ** following three categories it falls into:
1518       **
1519       **     Read-only
1520       **     Query with statement journal
1521       **     Query without statement journal
1522       **
1523       ** We could do something more elegant than this static analysis (i.e.
1524       ** store the type of query as part of the compliation phase), but
1525       ** handling malloc() or IO failure is a fairly obscure edge case so
1526       ** this is probably easier. Todo: Might be an opportunity to reduce
1527       ** code size a very small amount though...
1528       */
1529       int notReadOnly = 0;
1530       int isStatement = 0;
1531       assert(p->aOp || p->nOp==0);
1532       for(i=0; i<p->nOp; i++){
1533         switch( p->aOp[i].opcode ){
1534           case OP_Transaction:
1535             notReadOnly |= p->aOp[i].p2;
1536             break;
1537           case OP_Statement:
1538             isStatement = 1;
1539             break;
1540         }
1541       }
1542 
1543 
1544       /* If the query was read-only, we need do no rollback at all. Otherwise,
1545       ** proceed with the special handling.
1546       */
1547       if( notReadOnly || mrc!=SQLITE_INTERRUPT ){
1548         if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
1549           xFunc = sqlite3BtreeRollbackStmt;
1550           p->rc = SQLITE_BUSY;
1551         } else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && isStatement ){
1552           xFunc = sqlite3BtreeRollbackStmt;
1553         }else{
1554           /* We are forced to roll back the active transaction. Before doing
1555           ** so, abort any other statements this handle currently has active.
1556           */
1557           invalidateCursorsOnModifiedBtrees(db);
1558           sqlite3RollbackAll(db);
1559           db->autoCommit = 1;
1560         }
1561       }
1562     }
1563 
1564     /* If the auto-commit flag is set and this is the only active vdbe, then
1565     ** we do either a commit or rollback of the current transaction.
1566     **
1567     ** Note: This block also runs if one of the special errors handled
1568     ** above has occured.
1569     */
1570     if( db->autoCommit && db->activeVdbeCnt==1 ){
1571       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
1572         /* The auto-commit flag is true, and the vdbe program was
1573         ** successful or hit an 'OR FAIL' constraint. This means a commit
1574         ** is required.
1575         */
1576         int rc = vdbeCommit(db);
1577         if( rc==SQLITE_BUSY ){
1578           sqlite3BtreeMutexArrayLeave(&p->aMutex);
1579           return SQLITE_BUSY;
1580         }else if( rc!=SQLITE_OK ){
1581           p->rc = rc;
1582           sqlite3RollbackAll(db);
1583         }else{
1584           sqlite3CommitInternalChanges(db);
1585         }
1586       }else{
1587         sqlite3RollbackAll(db);
1588       }
1589     }else if( !xFunc ){
1590       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
1591         if( p->openedStatement ){
1592           xFunc = sqlite3BtreeCommitStmt;
1593         }
1594       }else if( p->errorAction==OE_Abort ){
1595         xFunc = sqlite3BtreeRollbackStmt;
1596       }else{
1597         invalidateCursorsOnModifiedBtrees(db);
1598         sqlite3RollbackAll(db);
1599         db->autoCommit = 1;
1600       }
1601     }
1602 
1603     /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
1604     ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
1605     ** and the return code is still SQLITE_OK, set the return code to the new
1606     ** error value.
1607     */
1608     assert(!xFunc ||
1609       xFunc==sqlite3BtreeCommitStmt ||
1610       xFunc==sqlite3BtreeRollbackStmt
1611     );
1612     for(i=0; xFunc && i<db->nDb; i++){
1613       int rc;
1614       Btree *pBt = db->aDb[i].pBt;
1615       if( pBt ){
1616         rc = xFunc(pBt);
1617         if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
1618           p->rc = rc;
1619           sqlite3SetString(&p->zErrMsg, 0);
1620         }
1621       }
1622     }
1623 
1624     /* If this was an INSERT, UPDATE or DELETE and the statement was committed,
1625     ** set the change counter.
1626     */
1627     if( p->changeCntOn && p->pc>=0 ){
1628       if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
1629         sqlite3VdbeSetChanges(db, p->nChange);
1630       }else{
1631         sqlite3VdbeSetChanges(db, 0);
1632       }
1633       p->nChange = 0;
1634     }
1635 
1636     /* Rollback or commit any schema changes that occurred. */
1637     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
1638       sqlite3ResetInternalSchema(db, 0);
1639       db->flags = (db->flags | SQLITE_InternChanges);
1640     }
1641 
1642     /* Release the locks */
1643     sqlite3BtreeMutexArrayLeave(&p->aMutex);
1644   }
1645 
1646   /* We have successfully halted and closed the VM.  Record this fact. */
1647   if( p->pc>=0 ){
1648     db->activeVdbeCnt--;
1649   }
1650   p->magic = VDBE_MAGIC_HALT;
1651   checkActiveVdbeCnt(db);
1652   if( p->db->mallocFailed ){
1653     p->rc = SQLITE_NOMEM;
1654   }
1655   checkActiveVdbeCnt(db);
1656 
1657   return SQLITE_OK;
1658 }
1659 
1660 
1661 /*
1662 ** Each VDBE holds the result of the most recent sqlite3_step() call
1663 ** in p->rc.  This routine sets that result back to SQLITE_OK.
1664 */
1665 void sqlite3VdbeResetStepResult(Vdbe *p){
1666   p->rc = SQLITE_OK;
1667 }
1668 
1669 /*
1670 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
1671 ** Write any error messages into *pzErrMsg.  Return the result code.
1672 **
1673 ** After this routine is run, the VDBE should be ready to be executed
1674 ** again.
1675 **
1676 ** To look at it another way, this routine resets the state of the
1677 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
1678 ** VDBE_MAGIC_INIT.
1679 */
1680 int sqlite3VdbeReset(Vdbe *p, int freebuffers){
1681   sqlite3 *db;
1682   db = p->db;
1683 
1684   /* If the VM did not run to completion or if it encountered an
1685   ** error, then it might not have been halted properly.  So halt
1686   ** it now.
1687   */
1688   (void)sqlite3SafetyOn(db);
1689   sqlite3VdbeHalt(p);
1690   (void)sqlite3SafetyOff(db);
1691 
1692   /* If the VDBE has be run even partially, then transfer the error code
1693   ** and error message from the VDBE into the main database structure.  But
1694   ** if the VDBE has just been set to run but has not actually executed any
1695   ** instructions yet, leave the main database error information unchanged.
1696   */
1697   if( p->pc>=0 ){
1698     if( p->zErrMsg ){
1699       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,sqlite3_free);
1700       db->errCode = p->rc;
1701       p->zErrMsg = 0;
1702     }else if( p->rc ){
1703       sqlite3Error(db, p->rc, 0);
1704     }else{
1705       sqlite3Error(db, SQLITE_OK, 0);
1706     }
1707   }else if( p->rc && p->expired ){
1708     /* The expired flag was set on the VDBE before the first call
1709     ** to sqlite3_step(). For consistency (since sqlite3_step() was
1710     ** called), set the database error in this case as well.
1711     */
1712     sqlite3Error(db, p->rc, 0);
1713     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, sqlite3_free);
1714     p->zErrMsg = 0;
1715   }
1716 
1717   /* Reclaim all memory used by the VDBE
1718   */
1719   Cleanup(p, freebuffers);
1720 
1721   /* Save profiling information from this VDBE run.
1722   */
1723 #ifdef VDBE_PROFILE
1724   {
1725     FILE *out = fopen("vdbe_profile.out", "a");
1726     if( out ){
1727       int i;
1728       fprintf(out, "---- ");
1729       for(i=0; i<p->nOp; i++){
1730         fprintf(out, "%02x", p->aOp[i].opcode);
1731       }
1732       fprintf(out, "\n");
1733       for(i=0; i<p->nOp; i++){
1734         fprintf(out, "%6d %10lld %8lld ",
1735            p->aOp[i].cnt,
1736            p->aOp[i].cycles,
1737            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
1738         );
1739         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
1740       }
1741       fclose(out);
1742     }
1743   }
1744 #endif
1745   p->magic = VDBE_MAGIC_INIT;
1746   p->aborted = 0;
1747   return p->rc & db->errMask;
1748 }
1749 
1750 /*
1751 ** Clean up and delete a VDBE after execution.  Return an integer which is
1752 ** the result code.  Write any error message text into *pzErrMsg.
1753 */
1754 int sqlite3VdbeFinalize(Vdbe *p){
1755   int rc = SQLITE_OK;
1756   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
1757     rc = sqlite3VdbeReset(p, 1);
1758     assert( (rc & p->db->errMask)==rc );
1759   }else if( p->magic!=VDBE_MAGIC_INIT ){
1760     return SQLITE_MISUSE;
1761   }
1762   releaseMemArray(&p->aMem[1], p->nMem, 1);
1763   sqlite3VdbeDelete(p);
1764   return rc;
1765 }
1766 
1767 /*
1768 ** Call the destructor for each auxdata entry in pVdbeFunc for which
1769 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
1770 ** are always destroyed.  To destroy all auxdata entries, call this
1771 ** routine with mask==0.
1772 */
1773 void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
1774   int i;
1775   for(i=0; i<pVdbeFunc->nAux; i++){
1776     struct AuxData *pAux = &pVdbeFunc->apAux[i];
1777     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
1778       if( pAux->xDelete ){
1779         pAux->xDelete(pAux->pAux);
1780       }
1781       pAux->pAux = 0;
1782     }
1783   }
1784 }
1785 
1786 /*
1787 ** Delete an entire VDBE.
1788 */
1789 void sqlite3VdbeDelete(Vdbe *p){
1790   int i;
1791   if( p==0 ) return;
1792   Cleanup(p, 1);
1793   if( p->pPrev ){
1794     p->pPrev->pNext = p->pNext;
1795   }else{
1796     assert( p->db->pVdbe==p );
1797     p->db->pVdbe = p->pNext;
1798   }
1799   if( p->pNext ){
1800     p->pNext->pPrev = p->pPrev;
1801   }
1802   if( p->aOp ){
1803     Op *pOp = p->aOp;
1804     for(i=0; i<p->nOp; i++, pOp++){
1805       freeP4(pOp->p4type, pOp->p4.p);
1806 #ifdef SQLITE_DEBUG
1807       sqlite3_free(pOp->zComment);
1808 #endif
1809     }
1810     sqlite3_free(p->aOp);
1811   }
1812   releaseMemArray(p->aVar, p->nVar, 1);
1813   sqlite3_free(p->aLabel);
1814   if( p->aMem ){
1815     sqlite3_free(&p->aMem[1]);
1816   }
1817   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N, 1);
1818   sqlite3_free(p->aColName);
1819   sqlite3_free(p->zSql);
1820   p->magic = VDBE_MAGIC_DEAD;
1821   sqlite3_free(p);
1822 }
1823 
1824 /*
1825 ** If a MoveTo operation is pending on the given cursor, then do that
1826 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
1827 ** routine does nothing and returns SQLITE_OK.
1828 */
1829 int sqlite3VdbeCursorMoveto(Cursor *p){
1830   if( p->deferredMoveto ){
1831     int res, rc;
1832 #ifdef SQLITE_TEST
1833     extern int sqlite3_search_count;
1834 #endif
1835     assert( p->isTable );
1836     rc = sqlite3BtreeMoveto(p->pCursor, 0, 0, p->movetoTarget, 0, &res);
1837     if( rc ) return rc;
1838     *p->pIncrKey = 0;
1839     p->lastRowid = keyToInt(p->movetoTarget);
1840     p->rowidIsValid = res==0;
1841     if( res<0 ){
1842       rc = sqlite3BtreeNext(p->pCursor, &res);
1843       if( rc ) return rc;
1844     }
1845 #ifdef SQLITE_TEST
1846     sqlite3_search_count++;
1847 #endif
1848     p->deferredMoveto = 0;
1849     p->cacheStatus = CACHE_STALE;
1850   }
1851   return SQLITE_OK;
1852 }
1853 
1854 /*
1855 ** The following functions:
1856 **
1857 ** sqlite3VdbeSerialType()
1858 ** sqlite3VdbeSerialTypeLen()
1859 ** sqlite3VdbeSerialRead()
1860 ** sqlite3VdbeSerialLen()
1861 ** sqlite3VdbeSerialWrite()
1862 **
1863 ** encapsulate the code that serializes values for storage in SQLite
1864 ** data and index records. Each serialized value consists of a
1865 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
1866 ** integer, stored as a varint.
1867 **
1868 ** In an SQLite index record, the serial type is stored directly before
1869 ** the blob of data that it corresponds to. In a table record, all serial
1870 ** types are stored at the start of the record, and the blobs of data at
1871 ** the end. Hence these functions allow the caller to handle the
1872 ** serial-type and data blob seperately.
1873 **
1874 ** The following table describes the various storage classes for data:
1875 **
1876 **   serial type        bytes of data      type
1877 **   --------------     ---------------    ---------------
1878 **      0                     0            NULL
1879 **      1                     1            signed integer
1880 **      2                     2            signed integer
1881 **      3                     3            signed integer
1882 **      4                     4            signed integer
1883 **      5                     6            signed integer
1884 **      6                     8            signed integer
1885 **      7                     8            IEEE float
1886 **      8                     0            Integer constant 0
1887 **      9                     0            Integer constant 1
1888 **     10,11                               reserved for expansion
1889 **    N>=12 and even       (N-12)/2        BLOB
1890 **    N>=13 and odd        (N-13)/2        text
1891 **
1892 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
1893 ** of SQLite will not understand those serial types.
1894 */
1895 
1896 /*
1897 ** Return the serial-type for the value stored in pMem.
1898 */
1899 u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
1900   int flags = pMem->flags;
1901   int n;
1902 
1903   if( flags&MEM_Null ){
1904     return 0;
1905   }
1906   if( flags&MEM_Int ){
1907     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
1908 #   define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
1909     i64 i = pMem->u.i;
1910     u64 u;
1911     if( file_format>=4 && (i&1)==i ){
1912       return 8+i;
1913     }
1914     u = i<0 ? -i : i;
1915     if( u<=127 ) return 1;
1916     if( u<=32767 ) return 2;
1917     if( u<=8388607 ) return 3;
1918     if( u<=2147483647 ) return 4;
1919     if( u<=MAX_6BYTE ) return 5;
1920     return 6;
1921   }
1922   if( flags&MEM_Real ){
1923     return 7;
1924   }
1925   assert( flags&(MEM_Str|MEM_Blob) );
1926   n = pMem->n;
1927   if( flags & MEM_Zero ){
1928     n += pMem->u.i;
1929   }
1930   assert( n>=0 );
1931   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
1932 }
1933 
1934 /*
1935 ** Return the length of the data corresponding to the supplied serial-type.
1936 */
1937 int sqlite3VdbeSerialTypeLen(u32 serial_type){
1938   if( serial_type>=12 ){
1939     return (serial_type-12)/2;
1940   }else{
1941     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
1942     return aSize[serial_type];
1943   }
1944 }
1945 
1946 /*
1947 ** If we are on an architecture with mixed-endian floating
1948 ** points (ex: ARM7) then swap the lower 4 bytes with the
1949 ** upper 4 bytes.  Return the result.
1950 **
1951 ** For most architectures, this is a no-op.
1952 **
1953 ** (later):  It is reported to me that the mixed-endian problem
1954 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
1955 ** that early versions of GCC stored the two words of a 64-bit
1956 ** float in the wrong order.  And that error has been propagated
1957 ** ever since.  The blame is not necessarily with GCC, though.
1958 ** GCC might have just copying the problem from a prior compiler.
1959 ** I am also told that newer versions of GCC that follow a different
1960 ** ABI get the byte order right.
1961 **
1962 ** Developers using SQLite on an ARM7 should compile and run their
1963 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
1964 ** enabled, some asserts below will ensure that the byte order of
1965 ** floating point values is correct.
1966 **
1967 ** (2007-08-30)  Frank van Vugt has studied this problem closely
1968 ** and has send his findings to the SQLite developers.  Frank
1969 ** writes that some Linux kernels offer floating point hardware
1970 ** emulation that uses only 32-bit mantissas instead of a full
1971 ** 48-bits as required by the IEEE standard.  (This is the
1972 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
1973 ** byte swapping becomes very complicated.  To avoid problems,
1974 ** the necessary byte swapping is carried out using a 64-bit integer
1975 ** rather than a 64-bit float.  Frank assures us that the code here
1976 ** works for him.  We, the developers, have no way to independently
1977 ** verify this, but Frank seems to know what he is talking about
1978 ** so we trust him.
1979 */
1980 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
1981 static u64 floatSwap(u64 in){
1982   union {
1983     u64 r;
1984     u32 i[2];
1985   } u;
1986   u32 t;
1987 
1988   u.r = in;
1989   t = u.i[0];
1990   u.i[0] = u.i[1];
1991   u.i[1] = t;
1992   return u.r;
1993 }
1994 # define swapMixedEndianFloat(X)  X = floatSwap(X)
1995 #else
1996 # define swapMixedEndianFloat(X)
1997 #endif
1998 
1999 /*
2000 ** Write the serialized data blob for the value stored in pMem into
2001 ** buf. It is assumed that the caller has allocated sufficient space.
2002 ** Return the number of bytes written.
2003 **
2004 ** nBuf is the amount of space left in buf[].  nBuf must always be
2005 ** large enough to hold the entire field.  Except, if the field is
2006 ** a blob with a zero-filled tail, then buf[] might be just the right
2007 ** size to hold everything except for the zero-filled tail.  If buf[]
2008 ** is only big enough to hold the non-zero prefix, then only write that
2009 ** prefix into buf[].  But if buf[] is large enough to hold both the
2010 ** prefix and the tail then write the prefix and set the tail to all
2011 ** zeros.
2012 **
2013 ** Return the number of bytes actually written into buf[].  The number
2014 ** of bytes in the zero-filled tail is included in the return value only
2015 ** if those bytes were zeroed in buf[].
2016 */
2017 int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
2018   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
2019   int len;
2020 
2021   /* Integer and Real */
2022   if( serial_type<=7 && serial_type>0 ){
2023     u64 v;
2024     int i;
2025     if( serial_type==7 ){
2026       assert( sizeof(v)==sizeof(pMem->r) );
2027       memcpy(&v, &pMem->r, sizeof(v));
2028       swapMixedEndianFloat(v);
2029     }else{
2030       v = pMem->u.i;
2031     }
2032     len = i = sqlite3VdbeSerialTypeLen(serial_type);
2033     assert( len<=nBuf );
2034     while( i-- ){
2035       buf[i] = (v&0xFF);
2036       v >>= 8;
2037     }
2038     return len;
2039   }
2040 
2041   /* String or blob */
2042   if( serial_type>=12 ){
2043     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
2044              == sqlite3VdbeSerialTypeLen(serial_type) );
2045     assert( pMem->n<=nBuf );
2046     len = pMem->n;
2047     memcpy(buf, pMem->z, len);
2048     if( pMem->flags & MEM_Zero ){
2049       len += pMem->u.i;
2050       if( len>nBuf ){
2051         len = nBuf;
2052       }
2053       memset(&buf[pMem->n], 0, len-pMem->n);
2054     }
2055     return len;
2056   }
2057 
2058   /* NULL or constants 0 or 1 */
2059   return 0;
2060 }
2061 
2062 /*
2063 ** Deserialize the data blob pointed to by buf as serial type serial_type
2064 ** and store the result in pMem.  Return the number of bytes read.
2065 */
2066 int sqlite3VdbeSerialGet(
2067   const unsigned char *buf,     /* Buffer to deserialize from */
2068   u32 serial_type,              /* Serial type to deserialize */
2069   Mem *pMem                     /* Memory cell to write value into */
2070 ){
2071   switch( serial_type ){
2072     case 10:   /* Reserved for future use */
2073     case 11:   /* Reserved for future use */
2074     case 0: {  /* NULL */
2075       pMem->flags = MEM_Null;
2076       break;
2077     }
2078     case 1: { /* 1-byte signed integer */
2079       pMem->u.i = (signed char)buf[0];
2080       pMem->flags = MEM_Int;
2081       return 1;
2082     }
2083     case 2: { /* 2-byte signed integer */
2084       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
2085       pMem->flags = MEM_Int;
2086       return 2;
2087     }
2088     case 3: { /* 3-byte signed integer */
2089       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
2090       pMem->flags = MEM_Int;
2091       return 3;
2092     }
2093     case 4: { /* 4-byte signed integer */
2094       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
2095       pMem->flags = MEM_Int;
2096       return 4;
2097     }
2098     case 5: { /* 6-byte signed integer */
2099       u64 x = (((signed char)buf[0])<<8) | buf[1];
2100       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
2101       x = (x<<32) | y;
2102       pMem->u.i = *(i64*)&x;
2103       pMem->flags = MEM_Int;
2104       return 6;
2105     }
2106     case 6:   /* 8-byte signed integer */
2107     case 7: { /* IEEE floating point */
2108       u64 x;
2109       u32 y;
2110 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
2111       /* Verify that integers and floating point values use the same
2112       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
2113       ** defined that 64-bit floating point values really are mixed
2114       ** endian.
2115       */
2116       static const u64 t1 = ((u64)0x3ff00000)<<32;
2117       static const double r1 = 1.0;
2118       u64 t2 = t1;
2119       swapMixedEndianFloat(t2);
2120       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
2121 #endif
2122 
2123       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
2124       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
2125       x = (x<<32) | y;
2126       if( serial_type==6 ){
2127         pMem->u.i = *(i64*)&x;
2128         pMem->flags = MEM_Int;
2129       }else{
2130         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
2131         swapMixedEndianFloat(x);
2132         memcpy(&pMem->r, &x, sizeof(x));
2133         pMem->flags = MEM_Real;
2134       }
2135       return 8;
2136     }
2137     case 8:    /* Integer 0 */
2138     case 9: {  /* Integer 1 */
2139       pMem->u.i = serial_type-8;
2140       pMem->flags = MEM_Int;
2141       return 0;
2142     }
2143     default: {
2144       int len = (serial_type-12)/2;
2145       pMem->z = (char *)buf;
2146       pMem->n = len;
2147       pMem->xDel = 0;
2148       if( serial_type&0x01 ){
2149         pMem->flags = MEM_Str | MEM_Ephem;
2150       }else{
2151         pMem->flags = MEM_Blob | MEM_Ephem;
2152       }
2153       return len;
2154     }
2155   }
2156   return 0;
2157 }
2158 
2159 /*
2160 ** The header of a record consists of a sequence variable-length integers.
2161 ** These integers are almost always small and are encoded as a single byte.
2162 ** The following macro takes advantage this fact to provide a fast decode
2163 ** of the integers in a record header.  It is faster for the common case
2164 ** where the integer is a single byte.  It is a little slower when the
2165 ** integer is two or more bytes.  But overall it is faster.
2166 **
2167 ** The following expressions are equivalent:
2168 **
2169 **     x = sqlite3GetVarint32( A, &B );
2170 **
2171 **     x = GetVarint( A, B );
2172 **
2173 */
2174 #define GetVarint(A,B)  ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
2175 
2176 /*
2177 ** Given the nKey-byte encoding of a record in pKey[], parse the
2178 ** record into a UnpackedRecord structure.  Return a pointer to
2179 ** that structure.
2180 **
2181 ** The calling function might provide szSpace bytes of memory
2182 ** space at pSpace.  This space can be used to hold the returned
2183 ** VDbeParsedRecord structure if it is large enough.  If it is
2184 ** not big enough, space is obtained from sqlite3_malloc().
2185 **
2186 ** The returned structure should be closed by a call to
2187 ** sqlite3VdbeDeleteUnpackedRecord().
2188 */
2189 UnpackedRecord *sqlite3VdbeRecordUnpack(
2190   KeyInfo *pKeyInfo,     /* Information about the record format */
2191   int nKey,              /* Size of the binary record */
2192   const void *pKey,      /* The binary record */
2193   void *pSpace,          /* Space available to hold resulting object */
2194   int szSpace            /* Size of pSpace[] in bytes */
2195 ){
2196   const unsigned char *aKey = (const unsigned char *)pKey;
2197   UnpackedRecord *p;
2198   int nByte;
2199   int i, idx, d;
2200   u32 szHdr;
2201   Mem *pMem;
2202 
2203   assert( sizeof(Mem)>sizeof(*p) );
2204   nByte = sizeof(Mem)*(pKeyInfo->nField+2);
2205   if( nByte>szSpace ){
2206     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
2207     if( p==0 ) return 0;
2208     p->needFree = 1;
2209   }else{
2210     p = pSpace;
2211     p->needFree = 0;
2212   }
2213   p->pKeyInfo = pKeyInfo;
2214   p->nField = pKeyInfo->nField + 1;
2215   p->needDestroy = 1;
2216   p->aMem = pMem = &((Mem*)p)[1];
2217   idx = GetVarint(aKey, szHdr);
2218   d = szHdr;
2219   i = 0;
2220   while( idx<szHdr && i<p->nField ){
2221     u32 serial_type;
2222 
2223     idx += GetVarint( aKey+idx, serial_type);
2224     if( d>=nKey && sqlite3VdbeSerialTypeLen(serial_type)>0 ) break;
2225     pMem->enc = pKeyInfo->enc;
2226     pMem->db = pKeyInfo->db;
2227     pMem->flags = 0;
2228     pMem->zMalloc = 0;
2229     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
2230     pMem++;
2231     i++;
2232   }
2233   p->nField = i;
2234   return (void*)p;
2235 }
2236 
2237 /*
2238 ** This routine destroys a UnpackedRecord object
2239 */
2240 void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
2241   if( p ){
2242     if( p->needDestroy ){
2243       int i;
2244       Mem *pMem;
2245       for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
2246         if( pMem->zMalloc ){
2247           sqlite3VdbeMemRelease(pMem);
2248         }
2249       }
2250     }
2251     if( p->needFree ){
2252       sqlite3_free(p);
2253     }
2254   }
2255 }
2256 
2257 /*
2258 ** This function compares the two table rows or index records
2259 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
2260 ** or positive integer if {nKey1, pKey1} is less than, equal to or
2261 ** greater than pPKey2.  The {nKey1, pKey1} key must be a blob
2262 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
2263 ** key must be a parsed key such as obtained from
2264 ** sqlite3VdbeParseRecord.
2265 **
2266 ** Key1 and Key2 do not have to contain the same number of fields.
2267 ** But if the lengths differ, Key2 must be the shorter of the two.
2268 **
2269 ** Historical note: In earlier versions of this routine both Key1
2270 ** and Key2 were blobs obtained from OP_MakeRecord.  But we found
2271 ** that in typical use the same Key2 would be submitted multiple times
2272 ** in a row.  So an optimization was added to parse the Key2 key
2273 ** separately and submit the parsed version.  In this way, we avoid
2274 ** parsing the same Key2 multiple times in a row.
2275 */
2276 int sqlite3VdbeRecordCompare(
2277   int nKey1, const void *pKey1,
2278   UnpackedRecord *pPKey2
2279 ){
2280   u32 d1;            /* Offset into aKey[] of next data element */
2281   u32 idx1;          /* Offset into aKey[] of next header element */
2282   u32 szHdr1;        /* Number of bytes in header */
2283   int i = 0;
2284   int nField;
2285   int rc = 0;
2286   const unsigned char *aKey1 = (const unsigned char *)pKey1;
2287   KeyInfo *pKeyInfo;
2288   Mem mem1;
2289 
2290   pKeyInfo = pPKey2->pKeyInfo;
2291   mem1.enc = pKeyInfo->enc;
2292   mem1.db = pKeyInfo->db;
2293   mem1.flags = 0;
2294   mem1.zMalloc = 0;
2295 
2296   idx1 = GetVarint(aKey1, szHdr1);
2297   d1 = szHdr1;
2298   nField = pKeyInfo->nField;
2299   while( idx1<szHdr1 && i<pPKey2->nField ){
2300     u32 serial_type1;
2301 
2302     /* Read the serial types for the next element in each key. */
2303     idx1 += GetVarint( aKey1+idx1, serial_type1 );
2304     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
2305 
2306     /* Extract the values to be compared.
2307     */
2308     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
2309 
2310     /* Do the comparison
2311     */
2312     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
2313                            i<nField ? pKeyInfo->aColl[i] : 0);
2314     if( rc!=0 ){
2315       break;
2316     }
2317     i++;
2318   }
2319   if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
2320 
2321   /* One of the keys ran out of fields, but all the fields up to that point
2322   ** were equal. If the incrKey flag is true, then the second key is
2323   ** treated as larger.
2324   */
2325   if( rc==0 ){
2326     if( pKeyInfo->incrKey ){
2327       rc = -1;
2328     }else if( !pKeyInfo->prefixIsEqual ){
2329       if( d1<nKey1 ){
2330         rc = 1;
2331       }
2332     }
2333   }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
2334                && pKeyInfo->aSortOrder[i] ){
2335     rc = -rc;
2336   }
2337 
2338   return rc;
2339 }
2340 
2341 /*
2342 ** The argument is an index entry composed using the OP_MakeRecord opcode.
2343 ** The last entry in this record should be an integer (specifically
2344 ** an integer rowid).  This routine returns the number of bytes in
2345 ** that integer.
2346 */
2347 int sqlite3VdbeIdxRowidLen(const u8 *aKey){
2348   u32 szHdr;        /* Size of the header */
2349   u32 typeRowid;    /* Serial type of the rowid */
2350 
2351   sqlite3GetVarint32(aKey, &szHdr);
2352   sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
2353   return sqlite3VdbeSerialTypeLen(typeRowid);
2354 }
2355 
2356 
2357 /*
2358 ** pCur points at an index entry created using the OP_MakeRecord opcode.
2359 ** Read the rowid (the last field in the record) and store it in *rowid.
2360 ** Return SQLITE_OK if everything works, or an error code otherwise.
2361 */
2362 int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
2363   i64 nCellKey = 0;
2364   int rc;
2365   u32 szHdr;        /* Size of the header */
2366   u32 typeRowid;    /* Serial type of the rowid */
2367   u32 lenRowid;     /* Size of the rowid */
2368   Mem m, v;
2369 
2370   sqlite3BtreeKeySize(pCur, &nCellKey);
2371   if( nCellKey<=0 ){
2372     return SQLITE_CORRUPT_BKPT;
2373   }
2374   m.flags = 0;
2375   m.db = 0;
2376   m.zMalloc = 0;
2377   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
2378   if( rc ){
2379     return rc;
2380   }
2381   sqlite3GetVarint32((u8*)m.z, &szHdr);
2382   sqlite3GetVarint32((u8*)&m.z[szHdr-1], &typeRowid);
2383   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
2384   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
2385   *rowid = v.u.i;
2386   sqlite3VdbeMemRelease(&m);
2387   return SQLITE_OK;
2388 }
2389 
2390 /*
2391 ** Compare the key of the index entry that cursor pC is point to against
2392 ** the key string in pKey (of length nKey).  Write into *pRes a number
2393 ** that is negative, zero, or positive if pC is less than, equal to,
2394 ** or greater than pKey.  Return SQLITE_OK on success.
2395 **
2396 ** pKey is either created without a rowid or is truncated so that it
2397 ** omits the rowid at the end.  The rowid at the end of the index entry
2398 ** is ignored as well.
2399 */
2400 int sqlite3VdbeIdxKeyCompare(
2401   Cursor *pC,                 /* The cursor to compare against */
2402   int nKey, const u8 *pKey,   /* The key to compare */
2403   int *res                    /* Write the comparison result here */
2404 ){
2405   i64 nCellKey = 0;
2406   int rc;
2407   BtCursor *pCur = pC->pCursor;
2408   int lenRowid;
2409   Mem m;
2410   UnpackedRecord *pRec;
2411   char zSpace[200];
2412 
2413   sqlite3BtreeKeySize(pCur, &nCellKey);
2414   if( nCellKey<=0 ){
2415     *res = 0;
2416     return SQLITE_OK;
2417   }
2418   m.db = 0;
2419   m.flags = 0;
2420   m.zMalloc = 0;
2421   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
2422   if( rc ){
2423     return rc;
2424   }
2425   lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
2426   pRec = sqlite3VdbeRecordUnpack(pC->pKeyInfo, nKey, pKey,
2427                                 zSpace, sizeof(zSpace));
2428   if( pRec==0 ){
2429     return SQLITE_NOMEM;
2430   }
2431   *res = sqlite3VdbeRecordCompare(m.n-lenRowid, m.z, pRec);
2432   sqlite3VdbeDeleteUnpackedRecord(pRec);
2433   sqlite3VdbeMemRelease(&m);
2434   return SQLITE_OK;
2435 }
2436 
2437 /*
2438 ** This routine sets the value to be returned by subsequent calls to
2439 ** sqlite3_changes() on the database handle 'db'.
2440 */
2441 void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
2442   assert( sqlite3_mutex_held(db->mutex) );
2443   db->nChange = nChange;
2444   db->nTotalChange += nChange;
2445 }
2446 
2447 /*
2448 ** Set a flag in the vdbe to update the change counter when it is finalised
2449 ** or reset.
2450 */
2451 void sqlite3VdbeCountChanges(Vdbe *v){
2452   v->changeCntOn = 1;
2453 }
2454 
2455 /*
2456 ** Mark every prepared statement associated with a database connection
2457 ** as expired.
2458 **
2459 ** An expired statement means that recompilation of the statement is
2460 ** recommend.  Statements expire when things happen that make their
2461 ** programs obsolete.  Removing user-defined functions or collating
2462 ** sequences, or changing an authorization function are the types of
2463 ** things that make prepared statements obsolete.
2464 */
2465 void sqlite3ExpirePreparedStatements(sqlite3 *db){
2466   Vdbe *p;
2467   for(p = db->pVdbe; p; p=p->pNext){
2468     p->expired = 1;
2469   }
2470 }
2471 
2472 /*
2473 ** Return the database associated with the Vdbe.
2474 */
2475 sqlite3 *sqlite3VdbeDb(Vdbe *v){
2476   return v->db;
2477 }
2478