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