xref: /sqlite-3.40.0/src/vdbe.c (revision e21733ba)
1 /*
2 ** 2001 September 15
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 ** The code in this file implements execution method of the
13 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
14 ** handles housekeeping details such as creating and deleting
15 ** VDBE instances.  This file is solely interested in executing
16 ** the VDBE program.
17 **
18 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
19 ** to a VDBE.
20 **
21 ** The SQL parser generates a program which is then executed by
22 ** the VDBE to do the work of the SQL statement.  VDBE programs are
23 ** similar in form to assembly language.  The program consists of
24 ** a linear sequence of operations.  Each operation has an opcode
25 ** and 3 operands.  Operands P1 and P2 are integers.  Operand P3
26 ** is a null-terminated string.   The P2 operand must be non-negative.
27 ** Opcodes will typically ignore one or more operands.  Many opcodes
28 ** ignore all three operands.
29 **
30 ** Computation results are stored on a stack.  Each entry on the
31 ** stack is either an integer, a null-terminated string, a floating point
32 ** number, or the SQL "NULL" value.  An inplicit conversion from one
33 ** type to the other occurs as necessary.
34 **
35 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
36 ** function which does the work of interpreting a VDBE program.
37 ** But other routines are also provided to help in building up
38 ** a program instruction by instruction.
39 **
40 ** Various scripts scan this source file in order to generate HTML
41 ** documentation, headers files, or other derived files.  The formatting
42 ** of the code in this file is, therefore, important.  See other comments
43 ** in this file for details.  If in doubt, do not deviate from existing
44 ** commenting and indentation practices when changing or adding code.
45 **
46 ** $Id: vdbe.c,v 1.639 2007/07/26 06:50:06 danielk1977 Exp $
47 */
48 #include "sqliteInt.h"
49 #include "os.h"
50 #include <ctype.h>
51 #include <math.h>
52 #include "vdbeInt.h"
53 
54 /*
55 ** The following global variable is incremented every time a cursor
56 ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes.  The test
57 ** procedures use this information to make sure that indices are
58 ** working correctly.  This variable has no function other than to
59 ** help verify the correct operation of the library.
60 */
61 #ifdef SQLITE_TEST
62 int sqlite3_search_count = 0;
63 #endif
64 
65 /*
66 ** When this global variable is positive, it gets decremented once before
67 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
68 ** field of the sqlite3 structure is set in order to simulate and interrupt.
69 **
70 ** This facility is used for testing purposes only.  It does not function
71 ** in an ordinary build.
72 */
73 #ifdef SQLITE_TEST
74 int sqlite3_interrupt_count = 0;
75 #endif
76 
77 /*
78 ** The next global variable is incremented each type the OP_Sort opcode
79 ** is executed.  The test procedures use this information to make sure that
80 ** sorting is occurring or not occuring at appropriate times.   This variable
81 ** has no function other than to help verify the correct operation of the
82 ** library.
83 */
84 #ifdef SQLITE_TEST
85 int sqlite3_sort_count = 0;
86 #endif
87 
88 /*
89 ** The next global variable records the size of the largest MEM_Blob
90 ** or MEM_Str that has appeared on the VDBE stack.  The test procedures
91 ** use this information to make sure that the zero-blob functionality
92 ** is working correctly.   This variable has no function other than to
93 ** help verify the correct operation of the library.
94 */
95 #ifdef SQLITE_TEST
96 int sqlite3_max_blobsize = 0;
97 #endif
98 
99 /*
100 ** Release the memory associated with the given stack level.  This
101 ** leaves the Mem.flags field in an inconsistent state.
102 */
103 #define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
104 
105 /*
106 ** Convert the given stack entity into a string if it isn't one
107 ** already. Return non-zero if a malloc() fails.
108 */
109 #define Stringify(P, enc) \
110    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
111      { goto no_mem; }
112 
113 /*
114 ** Convert the given stack entity into a string that has been obtained
115 ** from sqliteMalloc().  This is different from Stringify() above in that
116 ** Stringify() will use the NBFS bytes of static string space if the string
117 ** will fit but this routine always mallocs for space.
118 ** Return non-zero if we run out of memory.
119 */
120 #define Dynamicify(P,enc) sqlite3VdbeMemDynamicify(P)
121 
122 /*
123 ** The header of a record consists of a sequence variable-length integers.
124 ** These integers are almost always small and are encoded as a single byte.
125 ** The following macro takes advantage this fact to provide a fast decode
126 ** of the integers in a record header.  It is faster for the common case
127 ** where the integer is a single byte.  It is a little slower when the
128 ** integer is two or more bytes.  But overall it is faster.
129 **
130 ** The following expressions are equivalent:
131 **
132 **     x = sqlite3GetVarint32( A, &B );
133 **
134 **     x = GetVarint( A, B );
135 **
136 */
137 #define GetVarint(A,B)  ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
138 
139 /*
140 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
141 ** a pointer to a dynamically allocated string where some other entity
142 ** is responsible for deallocating that string.  Because the stack entry
143 ** does not control the string, it might be deleted without the stack
144 ** entry knowing it.
145 **
146 ** This routine converts an ephemeral string into a dynamically allocated
147 ** string that the stack entry itself controls.  In other words, it
148 ** converts an MEM_Ephem string into an MEM_Dyn string.
149 */
150 #define Deephemeralize(P) \
151    if( ((P)->flags&MEM_Ephem)!=0 \
152        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
153 
154 /*
155 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
156 ** P if required.
157 */
158 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
159 
160 /*
161 ** Argument pMem points at a memory cell that will be passed to a
162 ** user-defined function or returned to the user as the result of a query.
163 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
164 ** stack variables.  This routine sets the pMem->enc and pMem->type
165 ** variables used by the sqlite3_value_*() routines.
166 */
167 #define storeTypeInfo(A,B) _storeTypeInfo(A)
168 static void _storeTypeInfo(Mem *pMem){
169   int flags = pMem->flags;
170   if( flags & MEM_Null ){
171     pMem->type = SQLITE_NULL;
172   }
173   else if( flags & MEM_Int ){
174     pMem->type = SQLITE_INTEGER;
175   }
176   else if( flags & MEM_Real ){
177     pMem->type = SQLITE_FLOAT;
178   }
179   else if( flags & MEM_Str ){
180     pMem->type = SQLITE_TEXT;
181   }else{
182     pMem->type = SQLITE_BLOB;
183   }
184 }
185 
186 /*
187 ** Pop the stack N times.
188 */
189 static void popStack(Mem **ppTos, int N){
190   Mem *pTos = *ppTos;
191   while( N>0 ){
192     N--;
193     Release(pTos);
194     pTos--;
195   }
196   *ppTos = pTos;
197 }
198 
199 /*
200 ** Allocate cursor number iCur.  Return a pointer to it.  Return NULL
201 ** if we run out of memory.
202 */
203 static Cursor *allocateCursor(Vdbe *p, int iCur, int iDb){
204   Cursor *pCx;
205   assert( iCur<p->nCursor );
206   if( p->apCsr[iCur] ){
207     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
208   }
209   p->apCsr[iCur] = pCx = sqliteMalloc( sizeof(Cursor) );
210   if( pCx ){
211     pCx->iDb = iDb;
212   }
213   return pCx;
214 }
215 
216 /*
217 ** Try to convert a value into a numeric representation if we can
218 ** do so without loss of information.  In other words, if the string
219 ** looks like a number, convert it into a number.  If it does not
220 ** look like a number, leave it alone.
221 */
222 static void applyNumericAffinity(Mem *pRec){
223   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
224     int realnum;
225     sqlite3VdbeMemNulTerminate(pRec);
226     if( (pRec->flags&MEM_Str)
227          && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
228       i64 value;
229       sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
230       if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
231         sqlite3VdbeMemRelease(pRec);
232         pRec->u.i = value;
233         pRec->flags = MEM_Int;
234       }else{
235         sqlite3VdbeMemRealify(pRec);
236       }
237     }
238   }
239 }
240 
241 /*
242 ** Processing is determine by the affinity parameter:
243 **
244 ** SQLITE_AFF_INTEGER:
245 ** SQLITE_AFF_REAL:
246 ** SQLITE_AFF_NUMERIC:
247 **    Try to convert pRec to an integer representation or a
248 **    floating-point representation if an integer representation
249 **    is not possible.  Note that the integer representation is
250 **    always preferred, even if the affinity is REAL, because
251 **    an integer representation is more space efficient on disk.
252 **
253 ** SQLITE_AFF_TEXT:
254 **    Convert pRec to a text representation.
255 **
256 ** SQLITE_AFF_NONE:
257 **    No-op.  pRec is unchanged.
258 */
259 static void applyAffinity(Mem *pRec, char affinity, u8 enc){
260   if( affinity==SQLITE_AFF_TEXT ){
261     /* Only attempt the conversion to TEXT if there is an integer or real
262     ** representation (blob and NULL do not get converted) but no string
263     ** representation.
264     */
265     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
266       sqlite3VdbeMemStringify(pRec, enc);
267     }
268     pRec->flags &= ~(MEM_Real|MEM_Int);
269   }else if( affinity!=SQLITE_AFF_NONE ){
270     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
271              || affinity==SQLITE_AFF_NUMERIC );
272     applyNumericAffinity(pRec);
273     if( pRec->flags & MEM_Real ){
274       sqlite3VdbeIntegerAffinity(pRec);
275     }
276   }
277 }
278 
279 /*
280 ** Try to convert the type of a function argument or a result column
281 ** into a numeric representation.  Use either INTEGER or REAL whichever
282 ** is appropriate.  But only do the conversion if it is possible without
283 ** loss of information and return the revised type of the argument.
284 **
285 ** This is an EXPERIMENTAL api and is subject to change or removal.
286 */
287 int sqlite3_value_numeric_type(sqlite3_value *pVal){
288   Mem *pMem = (Mem*)pVal;
289   applyNumericAffinity(pMem);
290   storeTypeInfo(pMem, 0);
291   return pMem->type;
292 }
293 
294 /*
295 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
296 ** not the internal Mem* type.
297 */
298 void sqlite3ValueApplyAffinity(sqlite3_value *pVal, u8 affinity, u8 enc){
299   applyAffinity((Mem *)pVal, affinity, enc);
300 }
301 
302 #ifdef SQLITE_DEBUG
303 /*
304 ** Write a nice string representation of the contents of cell pMem
305 ** into buffer zBuf, length nBuf.
306 */
307 void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
308   char *zCsr = zBuf;
309   int f = pMem->flags;
310 
311   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
312 
313   if( f&MEM_Blob ){
314     int i;
315     char c;
316     if( f & MEM_Dyn ){
317       c = 'z';
318       assert( (f & (MEM_Static|MEM_Ephem))==0 );
319     }else if( f & MEM_Static ){
320       c = 't';
321       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
322     }else if( f & MEM_Ephem ){
323       c = 'e';
324       assert( (f & (MEM_Static|MEM_Dyn))==0 );
325     }else{
326       c = 's';
327     }
328 
329     sqlite3_snprintf(100, zCsr, "%c", c);
330     zCsr += strlen(zCsr);
331     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
332     zCsr += strlen(zCsr);
333     for(i=0; i<16 && i<pMem->n; i++){
334       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
335       zCsr += strlen(zCsr);
336     }
337     for(i=0; i<16 && i<pMem->n; i++){
338       char z = pMem->z[i];
339       if( z<32 || z>126 ) *zCsr++ = '.';
340       else *zCsr++ = z;
341     }
342 
343     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
344     zCsr += strlen(zCsr);
345     if( f & MEM_Zero ){
346       sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
347       zCsr += strlen(zCsr);
348     }
349     *zCsr = '\0';
350   }else if( f & MEM_Str ){
351     int j, k;
352     zBuf[0] = ' ';
353     if( f & MEM_Dyn ){
354       zBuf[1] = 'z';
355       assert( (f & (MEM_Static|MEM_Ephem))==0 );
356     }else if( f & MEM_Static ){
357       zBuf[1] = 't';
358       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
359     }else if( f & MEM_Ephem ){
360       zBuf[1] = 'e';
361       assert( (f & (MEM_Static|MEM_Dyn))==0 );
362     }else{
363       zBuf[1] = 's';
364     }
365     k = 2;
366     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
367     k += strlen(&zBuf[k]);
368     zBuf[k++] = '[';
369     for(j=0; j<15 && j<pMem->n; j++){
370       u8 c = pMem->z[j];
371       if( c>=0x20 && c<0x7f ){
372         zBuf[k++] = c;
373       }else{
374         zBuf[k++] = '.';
375       }
376     }
377     zBuf[k++] = ']';
378     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
379     k += strlen(&zBuf[k]);
380     zBuf[k++] = 0;
381   }
382 }
383 #endif
384 
385 
386 #ifdef VDBE_PROFILE
387 /*
388 ** The following routine only works on pentium-class processors.
389 ** It uses the RDTSC opcode to read the cycle count value out of the
390 ** processor and returns that value.  This can be used for high-res
391 ** profiling.
392 */
393 __inline__ unsigned long long int hwtime(void){
394   unsigned long long int x;
395   __asm__("rdtsc\n\t"
396           "mov %%edx, %%ecx\n\t"
397           :"=A" (x));
398   return x;
399 }
400 #endif
401 
402 /*
403 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
404 ** sqlite3_interrupt() routine has been called.  If it has been, then
405 ** processing of the VDBE program is interrupted.
406 **
407 ** This macro added to every instruction that does a jump in order to
408 ** implement a loop.  This test used to be on every single instruction,
409 ** but that meant we more testing that we needed.  By only testing the
410 ** flag on jump instructions, we get a (small) speed improvement.
411 */
412 #define CHECK_FOR_INTERRUPT \
413    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
414 
415 
416 /*
417 ** Execute as much of a VDBE program as we can then return.
418 **
419 ** sqlite3VdbeMakeReady() must be called before this routine in order to
420 ** close the program with a final OP_Halt and to set up the callbacks
421 ** and the error message pointer.
422 **
423 ** Whenever a row or result data is available, this routine will either
424 ** invoke the result callback (if there is one) or return with
425 ** SQLITE_ROW.
426 **
427 ** If an attempt is made to open a locked database, then this routine
428 ** will either invoke the busy callback (if there is one) or it will
429 ** return SQLITE_BUSY.
430 **
431 ** If an error occurs, an error message is written to memory obtained
432 ** from sqliteMalloc() and p->zErrMsg is made to point to that memory.
433 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
434 **
435 ** If the callback ever returns non-zero, then the program exits
436 ** immediately.  There will be no error message but the p->rc field is
437 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
438 **
439 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
440 ** routine to return SQLITE_ERROR.
441 **
442 ** Other fatal errors return SQLITE_ERROR.
443 **
444 ** After this routine has finished, sqlite3VdbeFinalize() should be
445 ** used to clean up the mess that was left behind.
446 */
447 int sqlite3VdbeExec(
448   Vdbe *p                    /* The VDBE */
449 ){
450   int pc;                    /* The program counter */
451   Op *pOp;                   /* Current operation */
452   int rc = SQLITE_OK;        /* Value to return */
453   sqlite3 *db = p->db;       /* The database */
454   u8 encoding = ENC(db);     /* The database encoding */
455   Mem *pTos;                 /* Top entry in the operand stack */
456 #ifdef VDBE_PROFILE
457   unsigned long long start;  /* CPU clock count at start of opcode */
458   int origPc;                /* Program counter at start of opcode */
459 #endif
460 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
461   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
462 #endif
463 #ifndef NDEBUG
464   Mem *pStackLimit;
465 #endif
466 
467   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
468   assert( db->magic==SQLITE_MAGIC_BUSY );
469   pTos = p->pTos;
470   if( p->rc==SQLITE_NOMEM ){
471     /* This happens if a malloc() inside a call to sqlite3_column_text() or
472     ** sqlite3_column_text16() failed.  */
473     goto no_mem;
474   }
475   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
476   p->rc = SQLITE_OK;
477   assert( p->explain==0 );
478   if( p->popStack ){
479     popStack(&pTos, p->popStack);
480     p->popStack = 0;
481   }
482   p->resOnStack = 0;
483   db->busyHandler.nBusy = 0;
484   CHECK_FOR_INTERRUPT;
485   sqlite3VdbeIOTraceSql(p);
486 #ifdef SQLITE_DEBUG
487   if( (p->db->flags & SQLITE_VdbeListing)!=0
488     || sqlite3OsFileExists("vdbe_explain")
489   ){
490     int i;
491     printf("VDBE Program Listing:\n");
492     sqlite3VdbePrintSql(p);
493     for(i=0; i<p->nOp; i++){
494       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
495     }
496   }
497   if( sqlite3OsFileExists("vdbe_trace") ){
498     p->trace = stdout;
499   }
500 #endif
501   for(pc=p->pc; rc==SQLITE_OK; pc++){
502     assert( pc>=0 && pc<p->nOp );
503     assert( pTos<=&p->aStack[pc] );
504     if( sqlite3MallocFailed() ) goto no_mem;
505 #ifdef VDBE_PROFILE
506     origPc = pc;
507     start = hwtime();
508 #endif
509     pOp = &p->aOp[pc];
510 
511     /* Only allow tracing if SQLITE_DEBUG is defined.
512     */
513 #ifdef SQLITE_DEBUG
514     if( p->trace ){
515       if( pc==0 ){
516         printf("VDBE Execution Trace:\n");
517         sqlite3VdbePrintSql(p);
518       }
519       sqlite3VdbePrintOp(p->trace, pc, pOp);
520     }
521     if( p->trace==0 && pc==0 && sqlite3OsFileExists("vdbe_sqltrace") ){
522       sqlite3VdbePrintSql(p);
523     }
524 #endif
525 
526 
527     /* Check to see if we need to simulate an interrupt.  This only happens
528     ** if we have a special test build.
529     */
530 #ifdef SQLITE_TEST
531     if( sqlite3_interrupt_count>0 ){
532       sqlite3_interrupt_count--;
533       if( sqlite3_interrupt_count==0 ){
534         sqlite3_interrupt(db);
535       }
536     }
537 #endif
538 
539 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
540     /* Call the progress callback if it is configured and the required number
541     ** of VDBE ops have been executed (either since this invocation of
542     ** sqlite3VdbeExec() or since last time the progress callback was called).
543     ** If the progress callback returns non-zero, exit the virtual machine with
544     ** a return code SQLITE_ABORT.
545     */
546     if( db->xProgress ){
547       if( db->nProgressOps==nProgressOps ){
548         int prc;
549         if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
550         prc =db->xProgress(db->pProgressArg);
551         if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
552         if( prc!=0 ){
553           rc = SQLITE_INTERRUPT;
554           goto vdbe_halt;
555         }
556         nProgressOps = 0;
557       }
558       nProgressOps++;
559     }
560 #endif
561 
562 #ifndef NDEBUG
563     /* This is to check that the return value of static function
564     ** opcodeNoPush() (see vdbeaux.c) returns values that match the
565     ** implementation of the virtual machine in this file. If
566     ** opcodeNoPush() returns non-zero, then the stack is guarenteed
567     ** not to grow when the opcode is executed. If it returns zero, then
568     ** the stack may grow by at most 1.
569     **
570     ** The global wrapper function sqlite3VdbeOpcodeUsesStack() is not
571     ** available if NDEBUG is defined at build time.
572     */
573     pStackLimit = pTos;
574     if( !sqlite3VdbeOpcodeNoPush(pOp->opcode) ){
575       pStackLimit++;
576     }
577 #endif
578 
579     switch( pOp->opcode ){
580 
581 /*****************************************************************************
582 ** What follows is a massive switch statement where each case implements a
583 ** separate instruction in the virtual machine.  If we follow the usual
584 ** indentation conventions, each case should be indented by 6 spaces.  But
585 ** that is a lot of wasted space on the left margin.  So the code within
586 ** the switch statement will break with convention and be flush-left. Another
587 ** big comment (similar to this one) will mark the point in the code where
588 ** we transition back to normal indentation.
589 **
590 ** The formatting of each case is important.  The makefile for SQLite
591 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
592 ** file looking for lines that begin with "case OP_".  The opcodes.h files
593 ** will be filled with #defines that give unique integer values to each
594 ** opcode and the opcodes.c file is filled with an array of strings where
595 ** each string is the symbolic name for the corresponding opcode.  If the
596 ** case statement is followed by a comment of the form "/# same as ... #/"
597 ** that comment is used to determine the particular value of the opcode.
598 **
599 ** If a comment on the same line as the "case OP_" construction contains
600 ** the word "no-push", then the opcode is guarenteed not to grow the
601 ** vdbe stack when it is executed. See function opcode() in
602 ** vdbeaux.c for details.
603 **
604 ** Documentation about VDBE opcodes is generated by scanning this file
605 ** for lines of that contain "Opcode:".  That line and all subsequent
606 ** comment lines are used in the generation of the opcode.html documentation
607 ** file.
608 **
609 ** SUMMARY:
610 **
611 **     Formatting is important to scripts that scan this file.
612 **     Do not deviate from the formatting style currently in use.
613 **
614 *****************************************************************************/
615 
616 /* Opcode:  Goto * P2 *
617 **
618 ** An unconditional jump to address P2.
619 ** The next instruction executed will be
620 ** the one at index P2 from the beginning of
621 ** the program.
622 */
623 case OP_Goto: {             /* no-push */
624   CHECK_FOR_INTERRUPT;
625   pc = pOp->p2 - 1;
626   break;
627 }
628 
629 /* Opcode:  Gosub * P2 *
630 **
631 ** Push the current address plus 1 onto the return address stack
632 ** and then jump to address P2.
633 **
634 ** The return address stack is of limited depth.  If too many
635 ** OP_Gosub operations occur without intervening OP_Returns, then
636 ** the return address stack will fill up and processing will abort
637 ** with a fatal error.
638 */
639 case OP_Gosub: {            /* no-push */
640   assert( p->returnDepth<sizeof(p->returnStack)/sizeof(p->returnStack[0]) );
641   p->returnStack[p->returnDepth++] = pc+1;
642   pc = pOp->p2 - 1;
643   break;
644 }
645 
646 /* Opcode:  Return * * *
647 **
648 ** Jump immediately to the next instruction after the last unreturned
649 ** OP_Gosub.  If an OP_Return has occurred for all OP_Gosubs, then
650 ** processing aborts with a fatal error.
651 */
652 case OP_Return: {           /* no-push */
653   assert( p->returnDepth>0 );
654   p->returnDepth--;
655   pc = p->returnStack[p->returnDepth] - 1;
656   break;
657 }
658 
659 /* Opcode:  Halt P1 P2 P3
660 **
661 ** Exit immediately.  All open cursors, Fifos, etc are closed
662 ** automatically.
663 **
664 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
665 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
666 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
667 ** whether or not to rollback the current transaction.  Do not rollback
668 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
669 ** then back out all changes that have occurred during this execution of the
670 ** VDBE, but do not rollback the transaction.
671 **
672 ** If P3 is not null then it is an error message string.
673 **
674 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
675 ** every program.  So a jump past the last instruction of the program
676 ** is the same as executing Halt.
677 */
678 case OP_Halt: {            /* no-push */
679   p->pTos = pTos;
680   p->rc = pOp->p1;
681   p->pc = pc;
682   p->errorAction = pOp->p2;
683   if( pOp->p3 ){
684     sqlite3SetString(&p->zErrMsg, pOp->p3, (char*)0);
685   }
686   rc = sqlite3VdbeHalt(p);
687   assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
688   if( rc==SQLITE_BUSY ){
689     p->rc = SQLITE_BUSY;
690     return SQLITE_BUSY;
691   }
692   return p->rc ? SQLITE_ERROR : SQLITE_DONE;
693 }
694 
695 /* Opcode: Integer P1 * *
696 **
697 ** The 32-bit integer value P1 is pushed onto the stack.
698 */
699 case OP_Integer: {
700   pTos++;
701   pTos->flags = MEM_Int;
702   pTos->u.i = pOp->p1;
703   break;
704 }
705 
706 /* Opcode: Int64 * * P3
707 **
708 ** P3 is a string representation of an integer.  Convert that integer
709 ** to a 64-bit value and push it onto the stack.
710 */
711 case OP_Int64: {
712   pTos++;
713   assert( pOp->p3!=0 );
714   pTos->flags = MEM_Str|MEM_Static|MEM_Term;
715   pTos->z = pOp->p3;
716   pTos->n = strlen(pTos->z);
717   pTos->enc = SQLITE_UTF8;
718   pTos->u.i = sqlite3VdbeIntValue(pTos);
719   pTos->flags |= MEM_Int;
720   break;
721 }
722 
723 /* Opcode: Real * * P3
724 **
725 ** The string value P3 is converted to a real and pushed on to the stack.
726 */
727 case OP_Real: {            /* same as TK_FLOAT, */
728   pTos++;
729   pTos->flags = MEM_Str|MEM_Static|MEM_Term;
730   pTos->z = pOp->p3;
731   pTos->n = strlen(pTos->z);
732   pTos->enc = SQLITE_UTF8;
733   pTos->r = sqlite3VdbeRealValue(pTos);
734   pTos->flags |= MEM_Real;
735   sqlite3VdbeChangeEncoding(pTos, encoding);
736   break;
737 }
738 
739 /* Opcode: String8 * * P3
740 **
741 ** P3 points to a nul terminated UTF-8 string. This opcode is transformed
742 ** into an OP_String before it is executed for the first time.
743 */
744 case OP_String8: {         /* same as TK_STRING */
745   assert( pOp->p3!=0 );
746   pOp->opcode = OP_String;
747   pOp->p1 = strlen(pOp->p3);
748   assert( SQLITE_MAX_SQL_LENGTH < SQLITE_MAX_LENGTH );
749   assert( pOp->p1 < SQLITE_MAX_LENGTH );
750 
751 #ifndef SQLITE_OMIT_UTF16
752   if( encoding!=SQLITE_UTF8 ){
753     pTos++;
754     sqlite3VdbeMemSetStr(pTos, pOp->p3, -1, SQLITE_UTF8, SQLITE_STATIC);
755     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pTos, encoding) ) goto no_mem;
756     if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pTos) ) goto no_mem;
757     pTos->flags &= ~(MEM_Dyn);
758     pTos->flags |= MEM_Static;
759     if( pOp->p3type==P3_DYNAMIC ){
760       sqliteFree(pOp->p3);
761     }
762     pOp->p3type = P3_DYNAMIC;
763     pOp->p3 = pTos->z;
764     pOp->p1 = pTos->n;
765     assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
766     break;
767   }
768 #endif
769   /* Otherwise fall through to the next case, OP_String */
770 }
771 
772 /* Opcode: String P1 * P3
773 **
774 ** The string value P3 of length P1 (bytes) is pushed onto the stack.
775 */
776 case OP_String: {
777   assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
778   pTos++;
779   assert( pOp->p3!=0 );
780   pTos->flags = MEM_Str|MEM_Static|MEM_Term;
781   pTos->z = pOp->p3;
782   pTos->n = pOp->p1;
783   pTos->enc = encoding;
784   break;
785 }
786 
787 /* Opcode: Null * * *
788 **
789 ** Push a NULL onto the stack.
790 */
791 case OP_Null: {
792   pTos++;
793   pTos->flags = MEM_Null;
794   pTos->n = 0;
795   break;
796 }
797 
798 
799 #ifndef SQLITE_OMIT_BLOB_LITERAL
800 /* Opcode: HexBlob * * P3
801 **
802 ** P3 is an UTF-8 SQL hex encoding of a blob. The blob is pushed onto the
803 ** vdbe stack.
804 **
805 ** The first time this instruction executes, in transforms itself into a
806 ** 'Blob' opcode with a binary blob as P3.
807 */
808 case OP_HexBlob: {            /* same as TK_BLOB */
809   pOp->opcode = OP_Blob;
810   pOp->p1 = strlen(pOp->p3)/2;
811   assert( SQLITE_MAX_SQL_LENGTH < SQLITE_MAX_LENGTH );
812   assert( pOp->p1 < SQLITE_MAX_LENGTH );
813   if( pOp->p1 ){
814     char *zBlob = sqlite3HexToBlob(pOp->p3);
815     if( !zBlob ) goto no_mem;
816     if( pOp->p3type==P3_DYNAMIC ){
817       sqliteFree(pOp->p3);
818     }
819     pOp->p3 = zBlob;
820     pOp->p3type = P3_DYNAMIC;
821   }else{
822     if( pOp->p3type==P3_DYNAMIC ){
823       sqliteFree(pOp->p3);
824     }
825     pOp->p3type = P3_STATIC;
826     pOp->p3 = "";
827   }
828 
829   /* Fall through to the next case, OP_Blob. */
830 }
831 
832 /* Opcode: Blob P1 * P3
833 **
834 ** P3 points to a blob of data P1 bytes long. Push this
835 ** value onto the stack. This instruction is not coded directly
836 ** by the compiler. Instead, the compiler layer specifies
837 ** an OP_HexBlob opcode, with the hex string representation of
838 ** the blob as P3. This opcode is transformed to an OP_Blob
839 ** the first time it is executed.
840 */
841 case OP_Blob: {
842   pTos++;
843   assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
844   sqlite3VdbeMemSetStr(pTos, pOp->p3, pOp->p1, 0, 0);
845   pTos->enc = encoding;
846   break;
847 }
848 #endif /* SQLITE_OMIT_BLOB_LITERAL */
849 
850 /* Opcode: Variable P1 * *
851 **
852 ** Push the value of variable P1 onto the stack.  A variable is
853 ** an unknown in the original SQL string as handed to sqlite3_compile().
854 ** Any occurance of the '?' character in the original SQL is considered
855 ** a variable.  Variables in the SQL string are number from left to
856 ** right beginning with 1.  The values of variables are set using the
857 ** sqlite3_bind() API.
858 */
859 case OP_Variable: {
860   int j = pOp->p1 - 1;
861   Mem *pVar;
862   assert( j>=0 && j<p->nVar );
863 
864   pVar = &p->aVar[j];
865   if( sqlite3VdbeMemTooBig(pVar) ){
866     goto too_big;
867   }
868   pTos++;
869   sqlite3VdbeMemShallowCopy(pTos, &p->aVar[j], MEM_Static);
870   break;
871 }
872 
873 /* Opcode: Pop P1 * *
874 **
875 ** P1 elements are popped off of the top of stack and discarded.
876 */
877 case OP_Pop: {            /* no-push */
878   assert( pOp->p1>=0 );
879   popStack(&pTos, pOp->p1);
880   assert( pTos>=&p->aStack[-1] );
881   break;
882 }
883 
884 /* Opcode: Dup P1 P2 *
885 **
886 ** A copy of the P1-th element of the stack
887 ** is made and pushed onto the top of the stack.
888 ** The top of the stack is element 0.  So the
889 ** instruction "Dup 0 0 0" will make a copy of the
890 ** top of the stack.
891 **
892 ** If the content of the P1-th element is a dynamically
893 ** allocated string, then a new copy of that string
894 ** is made if P2==0.  If P2!=0, then just a pointer
895 ** to the string is copied.
896 **
897 ** Also see the Pull instruction.
898 */
899 case OP_Dup: {
900   Mem *pFrom = &pTos[-pOp->p1];
901   assert( pFrom<=pTos && pFrom>=p->aStack );
902   pTos++;
903   sqlite3VdbeMemShallowCopy(pTos, pFrom, MEM_Ephem);
904   if( pOp->p2 ){
905     Deephemeralize(pTos);
906   }
907   break;
908 }
909 
910 /* Opcode: Pull P1 * *
911 **
912 ** The P1-th element is removed from its current location on
913 ** the stack and pushed back on top of the stack.  The
914 ** top of the stack is element 0, so "Pull 0 0 0" is
915 ** a no-op.  "Pull 1 0 0" swaps the top two elements of
916 ** the stack.
917 **
918 ** See also the Dup instruction.
919 */
920 case OP_Pull: {            /* no-push */
921   Mem *pFrom = &pTos[-pOp->p1];
922   int i;
923   Mem ts;
924 
925   ts = *pFrom;
926   Deephemeralize(pTos);
927   for(i=0; i<pOp->p1; i++, pFrom++){
928     Deephemeralize(&pFrom[1]);
929     assert( (pFrom[1].flags & MEM_Ephem)==0 );
930     *pFrom = pFrom[1];
931     if( pFrom->flags & MEM_Short ){
932       assert( pFrom->flags & (MEM_Str|MEM_Blob) );
933       assert( pFrom->z==pFrom[1].zShort );
934       pFrom->z = pFrom->zShort;
935     }
936   }
937   *pTos = ts;
938   if( pTos->flags & MEM_Short ){
939     assert( pTos->flags & (MEM_Str|MEM_Blob) );
940     assert( pTos->z==pTos[-pOp->p1].zShort );
941     pTos->z = pTos->zShort;
942   }
943   break;
944 }
945 
946 /* Opcode: Push P1 * *
947 **
948 ** Overwrite the value of the P1-th element down on the
949 ** stack (P1==0 is the top of the stack) with the value
950 ** of the top of the stack.  Then pop the top of the stack.
951 */
952 case OP_Push: {            /* no-push */
953   Mem *pTo = &pTos[-pOp->p1];
954 
955   assert( pTo>=p->aStack );
956   sqlite3VdbeMemMove(pTo, pTos);
957   pTos--;
958   break;
959 }
960 
961 /* Opcode: Callback P1 * *
962 **
963 ** The top P1 values on the stack represent a single result row from
964 ** a query.  This opcode causes the sqlite3_step() call to terminate
965 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
966 ** structure to provide access to the top P1 values as the result
967 ** row.  When the sqlite3_step() function is run again, the top P1
968 ** values will be automatically popped from the stack before the next
969 ** instruction executes.
970 */
971 case OP_Callback: {            /* no-push */
972   Mem *pMem;
973   Mem *pFirstColumn;
974   assert( p->nResColumn==pOp->p1 );
975 
976   /* Data in the pager might be moved or changed out from under us
977   ** in between the return from this sqlite3_step() call and the
978   ** next call to sqlite3_step().  So deephermeralize everything on
979   ** the stack.  Note that ephemeral data is never stored in memory
980   ** cells so we do not have to worry about them.
981   */
982   pFirstColumn = &pTos[0-pOp->p1];
983   for(pMem = p->aStack; pMem<pFirstColumn; pMem++){
984     Deephemeralize(pMem);
985   }
986 
987   /* Invalidate all ephemeral cursor row caches */
988   p->cacheCtr = (p->cacheCtr + 2)|1;
989 
990   /* Make sure the results of the current row are \000 terminated
991   ** and have an assigned type.  The results are deephemeralized as
992   ** as side effect.
993   */
994   for(; pMem<=pTos; pMem++ ){
995     sqlite3VdbeMemNulTerminate(pMem);
996     storeTypeInfo(pMem, encoding);
997   }
998 
999   /* Set up the statement structure so that it will pop the current
1000   ** results from the stack when the statement returns.
1001   */
1002   p->resOnStack = 1;
1003   p->nCallback++;
1004   p->popStack = pOp->p1;
1005   p->pc = pc + 1;
1006   p->pTos = pTos;
1007   return SQLITE_ROW;
1008 }
1009 
1010 /* Opcode: Concat P1 P2 *
1011 **
1012 ** Look at the first P1+2 elements of the stack.  Append them all
1013 ** together with the lowest element first.  The original P1+2 elements
1014 ** are popped from the stack if P2==0 and retained if P2==1.  If
1015 ** any element of the stack is NULL, then the result is NULL.
1016 **
1017 ** When P1==1, this routine makes a copy of the top stack element
1018 ** into memory obtained from sqliteMalloc().
1019 */
1020 case OP_Concat: {           /* same as TK_CONCAT */
1021   char *zNew;
1022   i64 nByte;
1023   int nField;
1024   int i, j;
1025   Mem *pTerm;
1026 
1027   /* Loop through the stack elements to see how long the result will be. */
1028   nField = pOp->p1 + 2;
1029   pTerm = &pTos[1-nField];
1030   nByte = 0;
1031   for(i=0; i<nField; i++, pTerm++){
1032     assert( pOp->p2==0 || (pTerm->flags&MEM_Str) );
1033     if( pTerm->flags&MEM_Null ){
1034       nByte = -1;
1035       break;
1036     }
1037     ExpandBlob(pTerm);
1038     Stringify(pTerm, encoding);
1039     nByte += pTerm->n;
1040   }
1041 
1042   if( nByte<0 ){
1043     /* If nByte is less than zero, then there is a NULL value on the stack.
1044     ** In this case just pop the values off the stack (if required) and
1045     ** push on a NULL.
1046     */
1047     if( pOp->p2==0 ){
1048       popStack(&pTos, nField);
1049     }
1050     pTos++;
1051     pTos->flags = MEM_Null;
1052   }else{
1053     /* Otherwise malloc() space for the result and concatenate all the
1054     ** stack values.
1055     */
1056     if( nByte+2>SQLITE_MAX_LENGTH ){
1057       goto too_big;
1058     }
1059     zNew = sqliteMallocRaw( nByte+2 );
1060     if( zNew==0 ) goto no_mem;
1061     j = 0;
1062     pTerm = &pTos[1-nField];
1063     for(i=j=0; i<nField; i++, pTerm++){
1064       int n = pTerm->n;
1065       assert( pTerm->flags & (MEM_Str|MEM_Blob) );
1066       memcpy(&zNew[j], pTerm->z, n);
1067       j += n;
1068     }
1069     zNew[j] = 0;
1070     zNew[j+1] = 0;
1071     assert( j==nByte );
1072 
1073     if( pOp->p2==0 ){
1074       popStack(&pTos, nField);
1075     }
1076     pTos++;
1077     pTos->n = j;
1078     pTos->flags = MEM_Str|MEM_Dyn|MEM_Term;
1079     pTos->xDel = 0;
1080     pTos->enc = encoding;
1081     pTos->z = zNew;
1082   }
1083   break;
1084 }
1085 
1086 /* Opcode: Add * * *
1087 **
1088 ** Pop the top two elements from the stack, add them together,
1089 ** and push the result back onto the stack.  If either element
1090 ** is a string then it is converted to a double using the atof()
1091 ** function before the addition.
1092 ** If either operand is NULL, the result is NULL.
1093 */
1094 /* Opcode: Multiply * * *
1095 **
1096 ** Pop the top two elements from the stack, multiply them together,
1097 ** and push the result back onto the stack.  If either element
1098 ** is a string then it is converted to a double using the atof()
1099 ** function before the multiplication.
1100 ** If either operand is NULL, the result is NULL.
1101 */
1102 /* Opcode: Subtract * * *
1103 **
1104 ** Pop the top two elements from the stack, subtract the
1105 ** first (what was on top of the stack) from the second (the
1106 ** next on stack)
1107 ** and push the result back onto the stack.  If either element
1108 ** is a string then it is converted to a double using the atof()
1109 ** function before the subtraction.
1110 ** If either operand is NULL, the result is NULL.
1111 */
1112 /* Opcode: Divide * * *
1113 **
1114 ** Pop the top two elements from the stack, divide the
1115 ** first (what was on top of the stack) from the second (the
1116 ** next on stack)
1117 ** and push the result back onto the stack.  If either element
1118 ** is a string then it is converted to a double using the atof()
1119 ** function before the division.  Division by zero returns NULL.
1120 ** If either operand is NULL, the result is NULL.
1121 */
1122 /* Opcode: Remainder * * *
1123 **
1124 ** Pop the top two elements from the stack, divide the
1125 ** first (what was on top of the stack) from the second (the
1126 ** next on stack)
1127 ** and push the remainder after division onto the stack.  If either element
1128 ** is a string then it is converted to a double using the atof()
1129 ** function before the division.  Division by zero returns NULL.
1130 ** If either operand is NULL, the result is NULL.
1131 */
1132 case OP_Add:                   /* same as TK_PLUS, no-push */
1133 case OP_Subtract:              /* same as TK_MINUS, no-push */
1134 case OP_Multiply:              /* same as TK_STAR, no-push */
1135 case OP_Divide:                /* same as TK_SLASH, no-push */
1136 case OP_Remainder: {           /* same as TK_REM, no-push */
1137   Mem *pNos = &pTos[-1];
1138   int flags;
1139   assert( pNos>=p->aStack );
1140   flags = pTos->flags | pNos->flags;
1141   if( (flags & MEM_Null)!=0 ){
1142     Release(pTos);
1143     pTos--;
1144     Release(pTos);
1145     pTos->flags = MEM_Null;
1146   }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){
1147     i64 a, b;
1148     a = pTos->u.i;
1149     b = pNos->u.i;
1150     switch( pOp->opcode ){
1151       case OP_Add:         b += a;       break;
1152       case OP_Subtract:    b -= a;       break;
1153       case OP_Multiply:    b *= a;       break;
1154       case OP_Divide: {
1155         if( a==0 ) goto divide_by_zero;
1156         /* Dividing the largest possible negative 64-bit integer (1<<63) by
1157         ** -1 returns an integer to large to store in a 64-bit data-type. On
1158         ** some architectures, the value overflows to (1<<63). On others,
1159         ** a SIGFPE is issued. The following statement normalizes this
1160         ** behaviour so that all architectures behave as if integer
1161         ** overflow occured.
1162         */
1163         if( a==-1 && b==(((i64)1)<<63) ) a = 1;
1164         b /= a;
1165         break;
1166       }
1167       default: {
1168         if( a==0 ) goto divide_by_zero;
1169         if( a==-1 ) a = 1;
1170         b %= a;
1171         break;
1172       }
1173     }
1174     Release(pTos);
1175     pTos--;
1176     Release(pTos);
1177     pTos->u.i = b;
1178     pTos->flags = MEM_Int;
1179   }else{
1180     double a, b;
1181     a = sqlite3VdbeRealValue(pTos);
1182     b = sqlite3VdbeRealValue(pNos);
1183     switch( pOp->opcode ){
1184       case OP_Add:         b += a;       break;
1185       case OP_Subtract:    b -= a;       break;
1186       case OP_Multiply:    b *= a;       break;
1187       case OP_Divide: {
1188         if( a==0.0 ) goto divide_by_zero;
1189         b /= a;
1190         break;
1191       }
1192       default: {
1193         i64 ia = (i64)a;
1194         i64 ib = (i64)b;
1195         if( ia==0 ) goto divide_by_zero;
1196         if( ia==-1 ) ia = 1;
1197         b = ib % ia;
1198         break;
1199       }
1200     }
1201     if( sqlite3_isnan(b) ){
1202       goto divide_by_zero;
1203     }
1204     Release(pTos);
1205     pTos--;
1206     Release(pTos);
1207     pTos->r = b;
1208     pTos->flags = MEM_Real;
1209     if( (flags & MEM_Real)==0 ){
1210       sqlite3VdbeIntegerAffinity(pTos);
1211     }
1212   }
1213   break;
1214 
1215 divide_by_zero:
1216   Release(pTos);
1217   pTos--;
1218   Release(pTos);
1219   pTos->flags = MEM_Null;
1220   break;
1221 }
1222 
1223 /* Opcode: CollSeq * * P3
1224 **
1225 ** P3 is a pointer to a CollSeq struct. If the next call to a user function
1226 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1227 ** be returned. This is used by the built-in min(), max() and nullif()
1228 ** functions.
1229 **
1230 ** The interface used by the implementation of the aforementioned functions
1231 ** to retrieve the collation sequence set by this opcode is not available
1232 ** publicly, only to user functions defined in func.c.
1233 */
1234 case OP_CollSeq: {             /* no-push */
1235   assert( pOp->p3type==P3_COLLSEQ );
1236   break;
1237 }
1238 
1239 /* Opcode: Function P1 P2 P3
1240 **
1241 ** Invoke a user function (P3 is a pointer to a Function structure that
1242 ** defines the function) with P2 arguments taken from the stack.  Pop all
1243 ** arguments from the stack and push back the result.
1244 **
1245 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
1246 ** function was determined to be constant at compile time. If the first
1247 ** argument was constant then bit 0 of P1 is set. This is used to determine
1248 ** whether meta data associated with a user function argument using the
1249 ** sqlite3_set_auxdata() API may be safely retained until the next
1250 ** invocation of this opcode.
1251 **
1252 ** See also: AggStep and AggFinal
1253 */
1254 case OP_Function: {
1255   int i;
1256   Mem *pArg;
1257   sqlite3_context ctx;
1258   sqlite3_value **apVal;
1259   int n = pOp->p2;
1260 
1261   apVal = p->apArg;
1262   assert( apVal || n==0 );
1263 
1264   pArg = &pTos[1-n];
1265   for(i=0; i<n; i++, pArg++){
1266     apVal[i] = pArg;
1267     storeTypeInfo(pArg, encoding);
1268   }
1269 
1270   assert( pOp->p3type==P3_FUNCDEF || pOp->p3type==P3_VDBEFUNC );
1271   if( pOp->p3type==P3_FUNCDEF ){
1272     ctx.pFunc = (FuncDef*)pOp->p3;
1273     ctx.pVdbeFunc = 0;
1274   }else{
1275     ctx.pVdbeFunc = (VdbeFunc*)pOp->p3;
1276     ctx.pFunc = ctx.pVdbeFunc->pFunc;
1277   }
1278 
1279   ctx.s.flags = MEM_Null;
1280   ctx.s.z = 0;
1281   ctx.s.xDel = 0;
1282   ctx.isError = 0;
1283   if( ctx.pFunc->needCollSeq ){
1284     assert( pOp>p->aOp );
1285     assert( pOp[-1].p3type==P3_COLLSEQ );
1286     assert( pOp[-1].opcode==OP_CollSeq );
1287     ctx.pColl = (CollSeq *)pOp[-1].p3;
1288   }
1289   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
1290   (*ctx.pFunc->xFunc)(&ctx, n, apVal);
1291   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
1292   if( sqlite3MallocFailed() ){
1293     /* Even though a malloc() has failed, the implementation of the
1294     ** user function may have called an sqlite3_result_XXX() function
1295     ** to return a value. The following call releases any resources
1296     ** associated with such a value.
1297     **
1298     ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
1299     ** fails also (the if(...) statement above). But if people are
1300     ** misusing sqlite, they have bigger problems than a leaked value.
1301     */
1302     sqlite3VdbeMemRelease(&ctx.s);
1303     goto no_mem;
1304   }
1305   popStack(&pTos, n);
1306 
1307   /* If any auxilary data functions have been called by this user function,
1308   ** immediately call the destructor for any non-static values.
1309   */
1310   if( ctx.pVdbeFunc ){
1311     sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
1312     pOp->p3 = (char *)ctx.pVdbeFunc;
1313     pOp->p3type = P3_VDBEFUNC;
1314   }
1315 
1316   /* If the function returned an error, throw an exception */
1317   if( ctx.isError ){
1318     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
1319     rc = SQLITE_ERROR;
1320   }
1321 
1322   /* Copy the result of the function to the top of the stack */
1323   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
1324   pTos++;
1325   pTos->flags = 0;
1326   sqlite3VdbeMemMove(pTos, &ctx.s);
1327   if( sqlite3VdbeMemTooBig(pTos) ){
1328     goto too_big;
1329   }
1330   break;
1331 }
1332 
1333 /* Opcode: BitAnd * * *
1334 **
1335 ** Pop the top two elements from the stack.  Convert both elements
1336 ** to integers.  Push back onto the stack the bit-wise AND of the
1337 ** two elements.
1338 ** If either operand is NULL, the result is NULL.
1339 */
1340 /* Opcode: BitOr * * *
1341 **
1342 ** Pop the top two elements from the stack.  Convert both elements
1343 ** to integers.  Push back onto the stack the bit-wise OR of the
1344 ** two elements.
1345 ** If either operand is NULL, the result is NULL.
1346 */
1347 /* Opcode: ShiftLeft * * *
1348 **
1349 ** Pop the top two elements from the stack.  Convert both elements
1350 ** to integers.  Push back onto the stack the second element shifted
1351 ** left by N bits where N is the top element on the stack.
1352 ** If either operand is NULL, the result is NULL.
1353 */
1354 /* Opcode: ShiftRight * * *
1355 **
1356 ** Pop the top two elements from the stack.  Convert both elements
1357 ** to integers.  Push back onto the stack the second element shifted
1358 ** right by N bits where N is the top element on the stack.
1359 ** If either operand is NULL, the result is NULL.
1360 */
1361 case OP_BitAnd:                 /* same as TK_BITAND, no-push */
1362 case OP_BitOr:                  /* same as TK_BITOR, no-push */
1363 case OP_ShiftLeft:              /* same as TK_LSHIFT, no-push */
1364 case OP_ShiftRight: {           /* same as TK_RSHIFT, no-push */
1365   Mem *pNos = &pTos[-1];
1366   i64 a, b;
1367 
1368   assert( pNos>=p->aStack );
1369   if( (pTos->flags | pNos->flags) & MEM_Null ){
1370     popStack(&pTos, 2);
1371     pTos++;
1372     pTos->flags = MEM_Null;
1373     break;
1374   }
1375   a = sqlite3VdbeIntValue(pNos);
1376   b = sqlite3VdbeIntValue(pTos);
1377   switch( pOp->opcode ){
1378     case OP_BitAnd:      a &= b;     break;
1379     case OP_BitOr:       a |= b;     break;
1380     case OP_ShiftLeft:   a <<= b;    break;
1381     case OP_ShiftRight:  a >>= b;    break;
1382     default:   /* CANT HAPPEN */     break;
1383   }
1384   Release(pTos);
1385   pTos--;
1386   Release(pTos);
1387   pTos->u.i = a;
1388   pTos->flags = MEM_Int;
1389   break;
1390 }
1391 
1392 /* Opcode: AddImm  P1 * *
1393 **
1394 ** Add the value P1 to whatever is on top of the stack.  The result
1395 ** is always an integer.
1396 **
1397 ** To force the top of the stack to be an integer, just add 0.
1398 */
1399 case OP_AddImm: {            /* no-push */
1400   assert( pTos>=p->aStack );
1401   sqlite3VdbeMemIntegerify(pTos);
1402   pTos->u.i += pOp->p1;
1403   break;
1404 }
1405 
1406 /* Opcode: ForceInt P1 P2 *
1407 **
1408 ** Convert the top of the stack into an integer.  If the current top of
1409 ** the stack is not numeric (meaning that is is a NULL or a string that
1410 ** does not look like an integer or floating point number) then pop the
1411 ** stack and jump to P2.  If the top of the stack is numeric then
1412 ** convert it into the least integer that is greater than or equal to its
1413 ** current value if P1==0, or to the least integer that is strictly
1414 ** greater than its current value if P1==1.
1415 */
1416 case OP_ForceInt: {            /* no-push */
1417   i64 v;
1418   assert( pTos>=p->aStack );
1419   applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
1420   if( (pTos->flags & (MEM_Int|MEM_Real))==0 ){
1421     Release(pTos);
1422     pTos--;
1423     pc = pOp->p2 - 1;
1424     break;
1425   }
1426   if( pTos->flags & MEM_Int ){
1427     v = pTos->u.i + (pOp->p1!=0);
1428   }else{
1429     /* FIX ME:  should this not be assert( pTos->flags & MEM_Real ) ??? */
1430     sqlite3VdbeMemRealify(pTos);
1431     v = (int)pTos->r;
1432     if( pTos->r>(double)v ) v++;
1433     if( pOp->p1 && pTos->r==(double)v ) v++;
1434   }
1435   Release(pTos);
1436   pTos->u.i = v;
1437   pTos->flags = MEM_Int;
1438   break;
1439 }
1440 
1441 /* Opcode: MustBeInt P1 P2 *
1442 **
1443 ** Force the top of the stack to be an integer.  If the top of the
1444 ** stack is not an integer and cannot be converted into an integer
1445 ** with out data loss, then jump immediately to P2, or if P2==0
1446 ** raise an SQLITE_MISMATCH exception.
1447 **
1448 ** If the top of the stack is not an integer and P2 is not zero and
1449 ** P1 is 1, then the stack is popped.  In all other cases, the depth
1450 ** of the stack is unchanged.
1451 */
1452 case OP_MustBeInt: {            /* no-push */
1453   assert( pTos>=p->aStack );
1454   applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
1455   if( (pTos->flags & MEM_Int)==0 ){
1456     if( pOp->p2==0 ){
1457       rc = SQLITE_MISMATCH;
1458       goto abort_due_to_error;
1459     }else{
1460       if( pOp->p1 ) popStack(&pTos, 1);
1461       pc = pOp->p2 - 1;
1462     }
1463   }else{
1464     Release(pTos);
1465     pTos->flags = MEM_Int;
1466   }
1467   break;
1468 }
1469 
1470 /* Opcode: RealAffinity * * *
1471 **
1472 ** If the top of the stack is an integer, convert it to a real value.
1473 **
1474 ** This opcode is used when extracting information from a column that
1475 ** has REAL affinity.  Such column values may still be stored as
1476 ** integers, for space efficiency, but after extraction we want them
1477 ** to have only a real value.
1478 */
1479 case OP_RealAffinity: {                  /* no-push */
1480   assert( pTos>=p->aStack );
1481   if( pTos->flags & MEM_Int ){
1482     sqlite3VdbeMemRealify(pTos);
1483   }
1484   break;
1485 }
1486 
1487 #ifndef SQLITE_OMIT_CAST
1488 /* Opcode: ToText * * *
1489 **
1490 ** Force the value on the top of the stack to be text.
1491 ** If the value is numeric, convert it to a string using the
1492 ** equivalent of printf().  Blob values are unchanged and
1493 ** are afterwards simply interpreted as text.
1494 **
1495 ** A NULL value is not changed by this routine.  It remains NULL.
1496 */
1497 case OP_ToText: {                  /* same as TK_TO_TEXT, no-push */
1498   assert( pTos>=p->aStack );
1499   if( pTos->flags & MEM_Null ) break;
1500   assert( MEM_Str==(MEM_Blob>>3) );
1501   pTos->flags |= (pTos->flags&MEM_Blob)>>3;
1502   applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
1503   rc = ExpandBlob(pTos);
1504   assert( pTos->flags & MEM_Str );
1505   pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
1506   break;
1507 }
1508 
1509 /* Opcode: ToBlob * * *
1510 **
1511 ** Force the value on the top of the stack to be a BLOB.
1512 ** If the value is numeric, convert it to a string first.
1513 ** Strings are simply reinterpreted as blobs with no change
1514 ** to the underlying data.
1515 **
1516 ** A NULL value is not changed by this routine.  It remains NULL.
1517 */
1518 case OP_ToBlob: {                  /* same as TK_TO_BLOB, no-push */
1519   assert( pTos>=p->aStack );
1520   if( pTos->flags & MEM_Null ) break;
1521   if( (pTos->flags & MEM_Blob)==0 ){
1522     applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
1523     assert( pTos->flags & MEM_Str );
1524     pTos->flags |= MEM_Blob;
1525   }
1526   pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Str);
1527   break;
1528 }
1529 
1530 /* Opcode: ToNumeric * * *
1531 **
1532 ** Force the value on the top of the stack to be numeric (either an
1533 ** integer or a floating-point number.)
1534 ** If the value is text or blob, try to convert it to an using the
1535 ** equivalent of atoi() or atof() and store 0 if no such conversion
1536 ** is possible.
1537 **
1538 ** A NULL value is not changed by this routine.  It remains NULL.
1539 */
1540 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, no-push */
1541   assert( pTos>=p->aStack );
1542   if( (pTos->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
1543     sqlite3VdbeMemNumerify(pTos);
1544   }
1545   break;
1546 }
1547 #endif /* SQLITE_OMIT_CAST */
1548 
1549 /* Opcode: ToInt * * *
1550 **
1551 ** Force the value on the top of the stack to be an integer.  If
1552 ** The value is currently a real number, drop its fractional part.
1553 ** If the value is text or blob, try to convert it to an integer using the
1554 ** equivalent of atoi() and store 0 if no such conversion is possible.
1555 **
1556 ** A NULL value is not changed by this routine.  It remains NULL.
1557 */
1558 case OP_ToInt: {                  /* same as TK_TO_INT, no-push */
1559   assert( pTos>=p->aStack );
1560   if( (pTos->flags & MEM_Null)==0 ){
1561     sqlite3VdbeMemIntegerify(pTos);
1562   }
1563   break;
1564 }
1565 
1566 #ifndef SQLITE_OMIT_CAST
1567 /* Opcode: ToReal * * *
1568 **
1569 ** Force the value on the top of the stack to be a floating point number.
1570 ** If The value is currently an integer, convert it.
1571 ** If the value is text or blob, try to convert it to an integer using the
1572 ** equivalent of atoi() and store 0 if no such conversion is possible.
1573 **
1574 ** A NULL value is not changed by this routine.  It remains NULL.
1575 */
1576 case OP_ToReal: {                  /* same as TK_TO_REAL, no-push */
1577   assert( pTos>=p->aStack );
1578   if( (pTos->flags & MEM_Null)==0 ){
1579     sqlite3VdbeMemRealify(pTos);
1580   }
1581   break;
1582 }
1583 #endif /* SQLITE_OMIT_CAST */
1584 
1585 /* Opcode: Eq P1 P2 P3
1586 **
1587 ** Pop the top two elements from the stack.  If they are equal, then
1588 ** jump to instruction P2.  Otherwise, continue to the next instruction.
1589 **
1590 ** If the 0x100 bit of P1 is true and either operand is NULL then take the
1591 ** jump.  If the 0x100 bit of P1 is clear then fall thru if either operand
1592 ** is NULL.
1593 **
1594 ** If the 0x200 bit of P1 is set and either operand is NULL then
1595 ** both operands are converted to integers prior to comparison.
1596 ** NULL operands are converted to zero and non-NULL operands are
1597 ** converted to 1.  Thus, for example, with 0x200 set,  NULL==NULL is true
1598 ** whereas it would normally be NULL.  Similarly,  NULL==123 is false when
1599 ** 0x200 is set but is NULL when the 0x200 bit of P1 is clear.
1600 **
1601 ** The least significant byte of P1 (mask 0xff) must be an affinity character -
1602 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1603 ** to coerce both values
1604 ** according to the affinity before the comparison is made. If the byte is
1605 ** 0x00, then numeric affinity is used.
1606 **
1607 ** Once any conversions have taken place, and neither value is NULL,
1608 ** the values are compared. If both values are blobs, or both are text,
1609 ** then memcmp() is used to determine the results of the comparison. If
1610 ** both values are numeric, then a numeric comparison is used. If the
1611 ** two values are of different types, then they are inequal.
1612 **
1613 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
1614 ** stack if the jump would have been taken, or a 0 if not.  Push a
1615 ** NULL if either operand was NULL.
1616 **
1617 ** If P3 is not NULL it is a pointer to a collating sequence (a CollSeq
1618 ** structure) that defines how to compare text.
1619 */
1620 /* Opcode: Ne P1 P2 P3
1621 **
1622 ** This works just like the Eq opcode except that the jump is taken if
1623 ** the operands from the stack are not equal.  See the Eq opcode for
1624 ** additional information.
1625 */
1626 /* Opcode: Lt P1 P2 P3
1627 **
1628 ** This works just like the Eq opcode except that the jump is taken if
1629 ** the 2nd element down on the stack is less than the top of the stack.
1630 ** See the Eq opcode for additional information.
1631 */
1632 /* Opcode: Le P1 P2 P3
1633 **
1634 ** This works just like the Eq opcode except that the jump is taken if
1635 ** the 2nd element down on the stack is less than or equal to the
1636 ** top of the stack.  See the Eq opcode for additional information.
1637 */
1638 /* Opcode: Gt P1 P2 P3
1639 **
1640 ** This works just like the Eq opcode except that the jump is taken if
1641 ** the 2nd element down on the stack is greater than the top of the stack.
1642 ** See the Eq opcode for additional information.
1643 */
1644 /* Opcode: Ge P1 P2 P3
1645 **
1646 ** This works just like the Eq opcode except that the jump is taken if
1647 ** the 2nd element down on the stack is greater than or equal to the
1648 ** top of the stack.  See the Eq opcode for additional information.
1649 */
1650 case OP_Eq:               /* same as TK_EQ, no-push */
1651 case OP_Ne:               /* same as TK_NE, no-push */
1652 case OP_Lt:               /* same as TK_LT, no-push */
1653 case OP_Le:               /* same as TK_LE, no-push */
1654 case OP_Gt:               /* same as TK_GT, no-push */
1655 case OP_Ge: {             /* same as TK_GE, no-push */
1656   Mem *pNos;
1657   int flags;
1658   int res;
1659   char affinity;
1660 
1661   pNos = &pTos[-1];
1662   flags = pTos->flags|pNos->flags;
1663 
1664   /* If either value is a NULL P2 is not zero, take the jump if the least
1665   ** significant byte of P1 is true. If P2 is zero, then push a NULL onto
1666   ** the stack.
1667   */
1668   if( flags&MEM_Null ){
1669     if( (pOp->p1 & 0x200)!=0 ){
1670       /* The 0x200 bit of P1 means, roughly "do not treat NULL as the
1671       ** magic SQL value it normally is - treat it as if it were another
1672       ** integer".
1673       **
1674       ** With 0x200 set, if either operand is NULL then both operands
1675       ** are converted to integers prior to being passed down into the
1676       ** normal comparison logic below.  NULL operands are converted to
1677       ** zero and non-NULL operands are converted to 1.  Thus, for example,
1678       ** with 0x200 set,  NULL==NULL is true whereas it would normally
1679       ** be NULL.  Similarly,  NULL!=123 is true.
1680       */
1681       sqlite3VdbeMemSetInt64(pTos, (pTos->flags & MEM_Null)==0);
1682       sqlite3VdbeMemSetInt64(pNos, (pNos->flags & MEM_Null)==0);
1683     }else{
1684       /* If the 0x200 bit of P1 is clear and either operand is NULL then
1685       ** the result is always NULL.  The jump is taken if the 0x100 bit
1686       ** of P1 is set.
1687       */
1688       popStack(&pTos, 2);
1689       if( pOp->p2 ){
1690         if( pOp->p1 & 0x100 ){
1691           pc = pOp->p2-1;
1692         }
1693       }else{
1694         pTos++;
1695         pTos->flags = MEM_Null;
1696       }
1697       break;
1698     }
1699   }
1700 
1701   affinity = pOp->p1 & 0xFF;
1702   if( affinity ){
1703     applyAffinity(pNos, affinity, encoding);
1704     applyAffinity(pTos, affinity, encoding);
1705   }
1706 
1707   assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 );
1708   ExpandBlob(pNos);
1709   ExpandBlob(pTos);
1710   res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3);
1711   switch( pOp->opcode ){
1712     case OP_Eq:    res = res==0;     break;
1713     case OP_Ne:    res = res!=0;     break;
1714     case OP_Lt:    res = res<0;      break;
1715     case OP_Le:    res = res<=0;     break;
1716     case OP_Gt:    res = res>0;      break;
1717     default:       res = res>=0;     break;
1718   }
1719 
1720   popStack(&pTos, 2);
1721   if( pOp->p2 ){
1722     if( res ){
1723       pc = pOp->p2-1;
1724     }
1725   }else{
1726     pTos++;
1727     pTos->flags = MEM_Int;
1728     pTos->u.i = res;
1729   }
1730   break;
1731 }
1732 
1733 /* Opcode: And * * *
1734 **
1735 ** Pop two values off the stack.  Take the logical AND of the
1736 ** two values and push the resulting boolean value back onto the
1737 ** stack.
1738 */
1739 /* Opcode: Or * * *
1740 **
1741 ** Pop two values off the stack.  Take the logical OR of the
1742 ** two values and push the resulting boolean value back onto the
1743 ** stack.
1744 */
1745 case OP_And:              /* same as TK_AND, no-push */
1746 case OP_Or: {             /* same as TK_OR, no-push */
1747   Mem *pNos = &pTos[-1];
1748   int v1, v2;    /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
1749 
1750   assert( pNos>=p->aStack );
1751   if( pTos->flags & MEM_Null ){
1752     v1 = 2;
1753   }else{
1754     sqlite3VdbeMemIntegerify(pTos);
1755     v1 = pTos->u.i==0;
1756   }
1757   if( pNos->flags & MEM_Null ){
1758     v2 = 2;
1759   }else{
1760     sqlite3VdbeMemIntegerify(pNos);
1761     v2 = pNos->u.i==0;
1762   }
1763   if( pOp->opcode==OP_And ){
1764     static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
1765     v1 = and_logic[v1*3+v2];
1766   }else{
1767     static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
1768     v1 = or_logic[v1*3+v2];
1769   }
1770   popStack(&pTos, 2);
1771   pTos++;
1772   if( v1==2 ){
1773     pTos->flags = MEM_Null;
1774   }else{
1775     pTos->u.i = v1==0;
1776     pTos->flags = MEM_Int;
1777   }
1778   break;
1779 }
1780 
1781 /* Opcode: Negative * * *
1782 **
1783 ** Treat the top of the stack as a numeric quantity.  Replace it
1784 ** with its additive inverse.  If the top of the stack is NULL
1785 ** its value is unchanged.
1786 */
1787 /* Opcode: AbsValue * * *
1788 **
1789 ** Treat the top of the stack as a numeric quantity.  Replace it
1790 ** with its absolute value. If the top of the stack is NULL
1791 ** its value is unchanged.
1792 */
1793 case OP_Negative:              /* same as TK_UMINUS, no-push */
1794 case OP_AbsValue: {
1795   assert( pTos>=p->aStack );
1796   if( (pTos->flags & (MEM_Real|MEM_Int|MEM_Null))==0 ){
1797     sqlite3VdbeMemNumerify(pTos);
1798   }
1799   if( pTos->flags & MEM_Real ){
1800     Release(pTos);
1801     if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
1802       pTos->r = -pTos->r;
1803     }
1804     pTos->flags = MEM_Real;
1805   }else if( pTos->flags & MEM_Int ){
1806     Release(pTos);
1807     if( pOp->opcode==OP_Negative || pTos->u.i<0 ){
1808       pTos->u.i = -pTos->u.i;
1809     }
1810     pTos->flags = MEM_Int;
1811   }
1812   break;
1813 }
1814 
1815 /* Opcode: Not * * *
1816 **
1817 ** Interpret the top of the stack as a boolean value.  Replace it
1818 ** with its complement.  If the top of the stack is NULL its value
1819 ** is unchanged.
1820 */
1821 case OP_Not: {                /* same as TK_NOT, no-push */
1822   assert( pTos>=p->aStack );
1823   if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
1824   sqlite3VdbeMemIntegerify(pTos);
1825   assert( (pTos->flags & MEM_Dyn)==0 );
1826   pTos->u.i = !pTos->u.i;
1827   pTos->flags = MEM_Int;
1828   break;
1829 }
1830 
1831 /* Opcode: BitNot * * *
1832 **
1833 ** Interpret the top of the stack as an value.  Replace it
1834 ** with its ones-complement.  If the top of the stack is NULL its
1835 ** value is unchanged.
1836 */
1837 case OP_BitNot: {             /* same as TK_BITNOT, no-push */
1838   assert( pTos>=p->aStack );
1839   if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
1840   sqlite3VdbeMemIntegerify(pTos);
1841   assert( (pTos->flags & MEM_Dyn)==0 );
1842   pTos->u.i = ~pTos->u.i;
1843   pTos->flags = MEM_Int;
1844   break;
1845 }
1846 
1847 /* Opcode: Noop * * *
1848 **
1849 ** Do nothing.  This instruction is often useful as a jump
1850 ** destination.
1851 */
1852 /*
1853 ** The magic Explain opcode are only inserted when explain==2 (which
1854 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
1855 ** This opcode records information from the optimizer.  It is the
1856 ** the same as a no-op.  This opcodesnever appears in a real VM program.
1857 */
1858 case OP_Explain:
1859 case OP_Noop: {            /* no-push */
1860   break;
1861 }
1862 
1863 /* Opcode: If P1 P2 *
1864 **
1865 ** Pop a single boolean from the stack.  If the boolean popped is
1866 ** true, then jump to p2.  Otherwise continue to the next instruction.
1867 ** An integer is false if zero and true otherwise.  A string is
1868 ** false if it has zero length and true otherwise.
1869 **
1870 ** If the value popped of the stack is NULL, then take the jump if P1
1871 ** is true and fall through if P1 is false.
1872 */
1873 /* Opcode: IfNot P1 P2 *
1874 **
1875 ** Pop a single boolean from the stack.  If the boolean popped is
1876 ** false, then jump to p2.  Otherwise continue to the next instruction.
1877 ** An integer is false if zero and true otherwise.  A string is
1878 ** false if it has zero length and true otherwise.
1879 **
1880 ** If the value popped of the stack is NULL, then take the jump if P1
1881 ** is true and fall through if P1 is false.
1882 */
1883 case OP_If:                 /* no-push */
1884 case OP_IfNot: {            /* no-push */
1885   int c;
1886   assert( pTos>=p->aStack );
1887   if( pTos->flags & MEM_Null ){
1888     c = pOp->p1;
1889   }else{
1890 #ifdef SQLITE_OMIT_FLOATING_POINT
1891     c = sqlite3VdbeIntValue(pTos);
1892 #else
1893     c = sqlite3VdbeRealValue(pTos)!=0.0;
1894 #endif
1895     if( pOp->opcode==OP_IfNot ) c = !c;
1896   }
1897   Release(pTos);
1898   pTos--;
1899   if( c ) pc = pOp->p2-1;
1900   break;
1901 }
1902 
1903 /* Opcode: IsNull P1 P2 *
1904 **
1905 ** Check the top of the stack and jump to P2 if the top of the stack
1906 ** is NULL.  If P1 is positive, then pop P1 elements from the stack
1907 ** regardless of whether or not the jump is taken.  If P1 is negative,
1908 ** pop -P1 elements from the stack only if the jump is taken and leave
1909 ** the stack unchanged if the jump is not taken.
1910 */
1911 case OP_IsNull: {            /* same as TK_ISNULL, no-push */
1912   if( pTos->flags & MEM_Null ){
1913     pc = pOp->p2-1;
1914     if( pOp->p1<0 ){
1915       popStack(&pTos, -pOp->p1);
1916     }
1917   }
1918   if( pOp->p1>0 ){
1919     popStack(&pTos, pOp->p1);
1920   }
1921   break;
1922 }
1923 
1924 /* Opcode: NotNull P1 P2 *
1925 **
1926 ** Jump to P2 if the top abs(P1) values on the stack are all not NULL.
1927 ** Regardless of whether or not the jump is taken, pop the stack
1928 ** P1 times if P1 is greater than zero.  But if P1 is negative,
1929 ** leave the stack unchanged.
1930 */
1931 case OP_NotNull: {            /* same as TK_NOTNULL, no-push */
1932   int i, cnt;
1933   cnt = pOp->p1;
1934   if( cnt<0 ) cnt = -cnt;
1935   assert( &pTos[1-cnt] >= p->aStack );
1936   for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
1937   if( i>=cnt ) pc = pOp->p2-1;
1938   if( pOp->p1>0 ) popStack(&pTos, cnt);
1939   break;
1940 }
1941 
1942 /* Opcode: SetNumColumns P1 P2 *
1943 **
1944 ** Before the OP_Column opcode can be executed on a cursor, this
1945 ** opcode must be called to set the number of fields in the table.
1946 **
1947 ** This opcode sets the number of columns for cursor P1 to P2.
1948 **
1949 ** If OP_KeyAsData is to be applied to cursor P1, it must be executed
1950 ** before this op-code.
1951 */
1952 case OP_SetNumColumns: {       /* no-push */
1953   Cursor *pC;
1954   assert( (pOp->p1)<p->nCursor );
1955   assert( p->apCsr[pOp->p1]!=0 );
1956   pC = p->apCsr[pOp->p1];
1957   pC->nField = pOp->p2;
1958   break;
1959 }
1960 
1961 /* Opcode: Column P1 P2 P3
1962 **
1963 ** Interpret the data that cursor P1 points to as a structure built using
1964 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
1965 ** information about the format of the data.) Push onto the stack the value
1966 ** of the P2-th column contained in the data. If there are less that (P2+1)
1967 ** values in the record, push a NULL onto the stack.
1968 **
1969 ** If the KeyAsData opcode has previously executed on this cursor, then the
1970 ** field might be extracted from the key rather than the data.
1971 **
1972 ** If the column contains fewer than P2 fields, then push a NULL.  Or
1973 ** if P3 is of type P3_MEM, then push the P3 value.  The P3 value will
1974 ** be default value for a column that has been added using the ALTER TABLE
1975 ** ADD COLUMN command.  If P3 is an ordinary string, just push a NULL.
1976 ** When P3 is a string it is really just a comment describing the value
1977 ** to be pushed, not a default value.
1978 */
1979 case OP_Column: {
1980   u32 payloadSize;   /* Number of bytes in the record */
1981   int p1 = pOp->p1;  /* P1 value of the opcode */
1982   int p2 = pOp->p2;  /* column number to retrieve */
1983   Cursor *pC = 0;    /* The VDBE cursor */
1984   char *zRec;        /* Pointer to complete record-data */
1985   BtCursor *pCrsr;   /* The BTree cursor */
1986   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
1987   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
1988   u32 nField;        /* number of fields in the record */
1989   int len;           /* The length of the serialized data for the column */
1990   int i;             /* Loop counter */
1991   char *zData;       /* Part of the record being decoded */
1992   Mem sMem;          /* For storing the record being decoded */
1993 
1994   sMem.flags = 0;
1995   assert( p1<p->nCursor );
1996   pTos++;
1997   pTos->flags = MEM_Null;
1998 
1999   /* This block sets the variable payloadSize to be the total number of
2000   ** bytes in the record.
2001   **
2002   ** zRec is set to be the complete text of the record if it is available.
2003   ** The complete record text is always available for pseudo-tables
2004   ** If the record is stored in a cursor, the complete record text
2005   ** might be available in the  pC->aRow cache.  Or it might not be.
2006   ** If the data is unavailable,  zRec is set to NULL.
2007   **
2008   ** We also compute the number of columns in the record.  For cursors,
2009   ** the number of columns is stored in the Cursor.nField element.  For
2010   ** records on the stack, the next entry down on the stack is an integer
2011   ** which is the number of records.
2012   */
2013   pC = p->apCsr[p1];
2014 #ifndef SQLITE_OMIT_VIRTUALTABLE
2015   assert( pC->pVtabCursor==0 );
2016 #endif
2017   assert( pC!=0 );
2018   if( pC->pCursor!=0 ){
2019     /* The record is stored in a B-Tree */
2020     rc = sqlite3VdbeCursorMoveto(pC);
2021     if( rc ) goto abort_due_to_error;
2022     zRec = 0;
2023     pCrsr = pC->pCursor;
2024     if( pC->nullRow ){
2025       payloadSize = 0;
2026     }else if( pC->cacheStatus==p->cacheCtr ){
2027       payloadSize = pC->payloadSize;
2028       zRec = (char*)pC->aRow;
2029     }else if( pC->isIndex ){
2030       i64 payloadSize64;
2031       sqlite3BtreeKeySize(pCrsr, &payloadSize64);
2032       payloadSize = payloadSize64;
2033     }else{
2034       sqlite3BtreeDataSize(pCrsr, &payloadSize);
2035     }
2036     nField = pC->nField;
2037   }else if( pC->pseudoTable ){
2038     /* The record is the sole entry of a pseudo-table */
2039     payloadSize = pC->nData;
2040     zRec = pC->pData;
2041     pC->cacheStatus = CACHE_STALE;
2042     assert( payloadSize==0 || zRec!=0 );
2043     nField = pC->nField;
2044     pCrsr = 0;
2045   }else{
2046     zRec = 0;
2047     payloadSize = 0;
2048     pCrsr = 0;
2049     nField = 0;
2050   }
2051 
2052   /* If payloadSize is 0, then just push a NULL onto the stack. */
2053   if( payloadSize==0 ){
2054     assert( pTos->flags==MEM_Null );
2055     break;
2056   }
2057   if( payloadSize>SQLITE_MAX_LENGTH ){
2058     goto too_big;
2059   }
2060 
2061   assert( p2<nField );
2062 
2063   /* Read and parse the table header.  Store the results of the parse
2064   ** into the record header cache fields of the cursor.
2065   */
2066   if( pC && pC->cacheStatus==p->cacheCtr ){
2067     aType = pC->aType;
2068     aOffset = pC->aOffset;
2069   }else{
2070     u8 *zIdx;        /* Index into header */
2071     u8 *zEndHdr;     /* Pointer to first byte after the header */
2072     u32 offset;      /* Offset into the data */
2073     int szHdrSz;     /* Size of the header size field at start of record */
2074     int avail;       /* Number of bytes of available data */
2075 
2076     aType = pC->aType;
2077     if( aType==0 ){
2078       pC->aType = aType = sqliteMallocRaw( 2*nField*sizeof(aType) );
2079     }
2080     if( aType==0 ){
2081       goto no_mem;
2082     }
2083     pC->aOffset = aOffset = &aType[nField];
2084     pC->payloadSize = payloadSize;
2085     pC->cacheStatus = p->cacheCtr;
2086 
2087     /* Figure out how many bytes are in the header */
2088     if( zRec ){
2089       zData = zRec;
2090     }else{
2091       if( pC->isIndex ){
2092         zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
2093       }else{
2094         zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
2095       }
2096       /* If KeyFetch()/DataFetch() managed to get the entire payload,
2097       ** save the payload in the pC->aRow cache.  That will save us from
2098       ** having to make additional calls to fetch the content portion of
2099       ** the record.
2100       */
2101       if( avail>=payloadSize ){
2102         zRec = zData;
2103         pC->aRow = (u8*)zData;
2104       }else{
2105         pC->aRow = 0;
2106       }
2107     }
2108     /* The following assert is true in all cases accept when
2109     ** the database file has been corrupted externally.
2110     **    assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
2111     szHdrSz = GetVarint((u8*)zData, offset);
2112 
2113     /* The KeyFetch() or DataFetch() above are fast and will get the entire
2114     ** record header in most cases.  But they will fail to get the complete
2115     ** record header if the record header does not fit on a single page
2116     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
2117     ** acquire the complete header text.
2118     */
2119     if( !zRec && avail<offset ){
2120       rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
2121       if( rc!=SQLITE_OK ){
2122         goto op_column_out;
2123       }
2124       zData = sMem.z;
2125     }
2126     zEndHdr = (u8 *)&zData[offset];
2127     zIdx = (u8 *)&zData[szHdrSz];
2128 
2129     /* Scan the header and use it to fill in the aType[] and aOffset[]
2130     ** arrays.  aType[i] will contain the type integer for the i-th
2131     ** column and aOffset[i] will contain the offset from the beginning
2132     ** of the record to the start of the data for the i-th column
2133     */
2134     for(i=0; i<nField; i++){
2135       if( zIdx<zEndHdr ){
2136         aOffset[i] = offset;
2137         zIdx += GetVarint(zIdx, aType[i]);
2138         offset += sqlite3VdbeSerialTypeLen(aType[i]);
2139       }else{
2140         /* If i is less that nField, then there are less fields in this
2141         ** record than SetNumColumns indicated there are columns in the
2142         ** table. Set the offset for any extra columns not present in
2143         ** the record to 0. This tells code below to push a NULL onto the
2144         ** stack instead of deserializing a value from the record.
2145         */
2146         aOffset[i] = 0;
2147       }
2148     }
2149     Release(&sMem);
2150     sMem.flags = MEM_Null;
2151 
2152     /* If we have read more header data than was contained in the header,
2153     ** or if the end of the last field appears to be past the end of the
2154     ** record, then we must be dealing with a corrupt database.
2155     */
2156     if( zIdx>zEndHdr || offset>payloadSize ){
2157       rc = SQLITE_CORRUPT_BKPT;
2158       goto op_column_out;
2159     }
2160   }
2161 
2162   /* Get the column information. If aOffset[p2] is non-zero, then
2163   ** deserialize the value from the record. If aOffset[p2] is zero,
2164   ** then there are not enough fields in the record to satisfy the
2165   ** request.  In this case, set the value NULL or to P3 if P3 is
2166   ** a pointer to a Mem object.
2167   */
2168   if( aOffset[p2] ){
2169     assert( rc==SQLITE_OK );
2170     if( zRec ){
2171       zData = &zRec[aOffset[p2]];
2172     }else{
2173       len = sqlite3VdbeSerialTypeLen(aType[p2]);
2174       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex,&sMem);
2175       if( rc!=SQLITE_OK ){
2176         goto op_column_out;
2177       }
2178       zData = sMem.z;
2179     }
2180     sqlite3VdbeSerialGet((u8*)zData, aType[p2], pTos);
2181     pTos->enc = encoding;
2182   }else{
2183     if( pOp->p3type==P3_MEM ){
2184       sqlite3VdbeMemShallowCopy(pTos, (Mem *)(pOp->p3), MEM_Static);
2185     }else{
2186       pTos->flags = MEM_Null;
2187     }
2188   }
2189 
2190   /* If we dynamically allocated space to hold the data (in the
2191   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
2192   ** dynamically allocated space over to the pTos structure.
2193   ** This prevents a memory copy.
2194   */
2195   if( (sMem.flags & MEM_Dyn)!=0 ){
2196     assert( pTos->flags & MEM_Ephem );
2197     assert( pTos->flags & (MEM_Str|MEM_Blob) );
2198     assert( pTos->z==sMem.z );
2199     assert( sMem.flags & MEM_Term );
2200     pTos->flags &= ~MEM_Ephem;
2201     pTos->flags |= MEM_Dyn|MEM_Term;
2202   }
2203 
2204   /* pTos->z might be pointing to sMem.zShort[].  Fix that so that we
2205   ** can abandon sMem */
2206   rc = sqlite3VdbeMemMakeWriteable(pTos);
2207 
2208 op_column_out:
2209   break;
2210 }
2211 
2212 /* Opcode: MakeRecord P1 P2 P3
2213 **
2214 ** Convert the top abs(P1) entries of the stack into a single entry
2215 ** suitable for use as a data record in a database table or as a key
2216 ** in an index.  The details of the format are irrelavant as long as
2217 ** the OP_Column opcode can decode the record later and as long as the
2218 ** sqlite3VdbeRecordCompare function will correctly compare two encoded
2219 ** records.  Refer to source code comments for the details of the record
2220 ** format.
2221 **
2222 ** The original stack entries are popped from the stack if P1>0 but
2223 ** remain on the stack if P1<0.
2224 **
2225 ** If P2 is not zero and one or more of the entries are NULL, then jump
2226 ** to the address given by P2.  This feature can be used to skip a
2227 ** uniqueness test on indices.
2228 **
2229 ** P3 may be a string that is P1 characters long.  The nth character of the
2230 ** string indicates the column affinity that should be used for the nth
2231 ** field of the index key (i.e. the first character of P3 corresponds to the
2232 ** lowest element on the stack).
2233 **
2234 ** The mapping from character to affinity is given by the SQLITE_AFF_
2235 ** macros defined in sqliteInt.h.
2236 **
2237 ** If P3 is NULL then all index fields have the affinity NONE.
2238 **
2239 ** See also OP_MakeIdxRec
2240 */
2241 /* Opcode: MakeIdxRec P1 P2 P3
2242 **
2243 ** This opcode works just OP_MakeRecord except that it reads an extra
2244 ** integer from the stack (thus reading a total of abs(P1+1) entries)
2245 ** and appends that extra integer to the end of the record as a varint.
2246 ** This results in an index key.
2247 */
2248 case OP_MakeIdxRec:
2249 case OP_MakeRecord: {
2250   /* Assuming the record contains N fields, the record format looks
2251   ** like this:
2252   **
2253   ** ------------------------------------------------------------------------
2254   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2255   ** ------------------------------------------------------------------------
2256   **
2257   ** Data(0) is taken from the lowest element of the stack and data(N-1) is
2258   ** the top of the stack.
2259   **
2260   ** Each type field is a varint representing the serial type of the
2261   ** corresponding data element (see sqlite3VdbeSerialType()). The
2262   ** hdr-size field is also a varint which is the offset from the beginning
2263   ** of the record to data0.
2264   */
2265   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
2266   Mem *pRec;             /* The new record */
2267   Mem *pRowid = 0;       /* Rowid appended to the new record */
2268   u64 nData = 0;         /* Number of bytes of data space */
2269   int nHdr = 0;          /* Number of bytes of header space */
2270   u64 nByte = 0;         /* Data space required for this record */
2271   int nZero = 0;         /* Number of zero bytes at the end of the record */
2272   int nVarint;           /* Number of bytes in a varint */
2273   u32 serial_type;       /* Type field */
2274   int containsNull = 0;  /* True if any of the data fields are NULL */
2275   Mem *pData0;           /* Bottom of the stack */
2276   int leaveOnStack;      /* If true, leave the entries on the stack */
2277   int nField;            /* Number of fields in the record */
2278   int jumpIfNull;        /* Jump here if non-zero and any entries are NULL. */
2279   int addRowid;          /* True to append a rowid column at the end */
2280   char *zAffinity;       /* The affinity string for the record */
2281   int file_format;       /* File format to use for encoding */
2282   int i;                 /* Space used in zNewRecord[] */
2283   char zTemp[NBFS];      /* Space to hold small records */
2284 
2285   leaveOnStack = ((pOp->p1<0)?1:0);
2286   nField = pOp->p1 * (leaveOnStack?-1:1);
2287   jumpIfNull = pOp->p2;
2288   addRowid = pOp->opcode==OP_MakeIdxRec;
2289   zAffinity = pOp->p3;
2290 
2291   pData0 = &pTos[1-nField];
2292   assert( pData0>=p->aStack );
2293   containsNull = 0;
2294   file_format = p->minWriteFileFormat;
2295 
2296   /* Loop through the elements that will make up the record to figure
2297   ** out how much space is required for the new record.
2298   */
2299   for(pRec=pData0; pRec<=pTos; pRec++){
2300     int len;
2301     if( zAffinity ){
2302       applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
2303     }
2304     if( pRec->flags&MEM_Null ){
2305       containsNull = 1;
2306     }
2307     if( pRec->flags&MEM_Zero && pRec->n>0 ){
2308       ExpandBlob(pRec);
2309     }
2310     serial_type = sqlite3VdbeSerialType(pRec, file_format);
2311     len = sqlite3VdbeSerialTypeLen(serial_type);
2312     nData += len;
2313     nHdr += sqlite3VarintLen(serial_type);
2314     if( pRec->flags & MEM_Zero ){
2315       /* Only pure zero-filled BLOBs can be input to this Opcode.
2316       ** We do not allow blobs with a prefix and a zero-filled tail. */
2317       nZero += pRec->u.i;
2318     }else if( len ){
2319       nZero = 0;
2320     }
2321   }
2322 
2323   /* If we have to append a varint rowid to this record, set pRowid
2324   ** to the value of the rowid and increase nByte by the amount of space
2325   ** required to store it.
2326   */
2327   if( addRowid ){
2328     pRowid = &pTos[0-nField];
2329     assert( pRowid>=p->aStack );
2330     sqlite3VdbeMemIntegerify(pRowid);
2331     serial_type = sqlite3VdbeSerialType(pRowid, 0);
2332     nData += sqlite3VdbeSerialTypeLen(serial_type);
2333     nHdr += sqlite3VarintLen(serial_type);
2334     nZero = 0;
2335   }
2336 
2337   /* Add the initial header varint and total the size */
2338   nHdr += nVarint = sqlite3VarintLen(nHdr);
2339   if( nVarint<sqlite3VarintLen(nHdr) ){
2340     nHdr++;
2341   }
2342   nByte = nHdr+nData-nZero;
2343   if( nByte>SQLITE_MAX_LENGTH ){
2344     goto too_big;
2345   }
2346 
2347   /* Allocate space for the new record. */
2348   if( nByte>sizeof(zTemp) ){
2349     zNewRecord = sqliteMallocRaw(nByte);
2350     if( !zNewRecord ){
2351       goto no_mem;
2352     }
2353   }else{
2354     zNewRecord = (u8*)zTemp;
2355   }
2356 
2357   /* Write the record */
2358   i = sqlite3PutVarint(zNewRecord, nHdr);
2359   for(pRec=pData0; pRec<=pTos; pRec++){
2360     serial_type = sqlite3VdbeSerialType(pRec, file_format);
2361     i += sqlite3PutVarint(&zNewRecord[i], serial_type);      /* serial type */
2362   }
2363   if( addRowid ){
2364     i += sqlite3PutVarint(&zNewRecord[i], sqlite3VdbeSerialType(pRowid, 0));
2365   }
2366   for(pRec=pData0; pRec<=pTos; pRec++){  /* serial data */
2367     i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
2368   }
2369   if( addRowid ){
2370     i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRowid, 0);
2371   }
2372   assert( i==nByte );
2373 
2374   /* Pop entries off the stack if required. Push the new record on. */
2375   if( !leaveOnStack ){
2376     popStack(&pTos, nField+addRowid);
2377   }
2378   pTos++;
2379   pTos->n = nByte;
2380   if( nByte<=sizeof(zTemp) ){
2381     assert( zNewRecord==(unsigned char *)zTemp );
2382     pTos->z = pTos->zShort;
2383     memcpy(pTos->zShort, zTemp, nByte);
2384     pTos->flags = MEM_Blob | MEM_Short;
2385   }else{
2386     assert( zNewRecord!=(unsigned char *)zTemp );
2387     pTos->z = (char*)zNewRecord;
2388     pTos->flags = MEM_Blob | MEM_Dyn;
2389     pTos->xDel = 0;
2390   }
2391   if( nZero ){
2392     pTos->u.i = nZero;
2393     pTos->flags |= MEM_Zero;
2394   }
2395   pTos->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
2396 
2397   /* If a NULL was encountered and jumpIfNull is non-zero, take the jump. */
2398   if( jumpIfNull && containsNull ){
2399     pc = jumpIfNull - 1;
2400   }
2401   break;
2402 }
2403 
2404 /* Opcode: Statement P1 * *
2405 **
2406 ** Begin an individual statement transaction which is part of a larger
2407 ** BEGIN..COMMIT transaction.  This is needed so that the statement
2408 ** can be rolled back after an error without having to roll back the
2409 ** entire transaction.  The statement transaction will automatically
2410 ** commit when the VDBE halts.
2411 **
2412 ** The statement is begun on the database file with index P1.  The main
2413 ** database file has an index of 0 and the file used for temporary tables
2414 ** has an index of 1.
2415 */
2416 case OP_Statement: {       /* no-push */
2417   int i = pOp->p1;
2418   Btree *pBt;
2419   if( i>=0 && i<db->nDb && (pBt = db->aDb[i].pBt)!=0 && !(db->autoCommit) ){
2420     assert( sqlite3BtreeIsInTrans(pBt) );
2421     if( !sqlite3BtreeIsInStmt(pBt) ){
2422       rc = sqlite3BtreeBeginStmt(pBt);
2423       p->openedStatement = 1;
2424     }
2425   }
2426   break;
2427 }
2428 
2429 /* Opcode: AutoCommit P1 P2 *
2430 **
2431 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
2432 ** back any currently active btree transactions. If there are any active
2433 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
2434 **
2435 ** This instruction causes the VM to halt.
2436 */
2437 case OP_AutoCommit: {       /* no-push */
2438   u8 i = pOp->p1;
2439   u8 rollback = pOp->p2;
2440 
2441   assert( i==1 || i==0 );
2442   assert( i==1 || rollback==0 );
2443 
2444   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
2445 
2446   if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
2447     /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
2448     ** still running, and a transaction is active, return an error indicating
2449     ** that the other VMs must complete first.
2450     */
2451     sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit",
2452         " transaction - SQL statements in progress", (char*)0);
2453     rc = SQLITE_ERROR;
2454   }else if( i!=db->autoCommit ){
2455     if( pOp->p2 ){
2456       assert( i==1 );
2457       sqlite3RollbackAll(db);
2458       db->autoCommit = 1;
2459     }else{
2460       db->autoCommit = i;
2461       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
2462         p->pTos = pTos;
2463         p->pc = pc;
2464         db->autoCommit = 1-i;
2465         p->rc = SQLITE_BUSY;
2466         return SQLITE_BUSY;
2467       }
2468     }
2469     if( p->rc==SQLITE_OK ){
2470       return SQLITE_DONE;
2471     }else{
2472       return SQLITE_ERROR;
2473     }
2474   }else{
2475     sqlite3SetString(&p->zErrMsg,
2476         (!i)?"cannot start a transaction within a transaction":(
2477         (rollback)?"cannot rollback - no transaction is active":
2478                    "cannot commit - no transaction is active"), (char*)0);
2479 
2480     rc = SQLITE_ERROR;
2481   }
2482   break;
2483 }
2484 
2485 /* Opcode: Transaction P1 P2 *
2486 **
2487 ** Begin a transaction.  The transaction ends when a Commit or Rollback
2488 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
2489 ** transaction might also be rolled back if an error is encountered.
2490 **
2491 ** P1 is the index of the database file on which the transaction is
2492 ** started.  Index 0 is the main database file and index 1 is the
2493 ** file used for temporary tables.
2494 **
2495 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
2496 ** obtained on the database file when a write-transaction is started.  No
2497 ** other process can start another write transaction while this transaction is
2498 ** underway.  Starting a write transaction also creates a rollback journal. A
2499 ** write transaction must be started before any changes can be made to the
2500 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
2501 ** on the file.
2502 **
2503 ** If P2 is zero, then a read-lock is obtained on the database file.
2504 */
2505 case OP_Transaction: {       /* no-push */
2506   int i = pOp->p1;
2507   Btree *pBt;
2508 
2509   assert( i>=0 && i<db->nDb );
2510   pBt = db->aDb[i].pBt;
2511 
2512   if( pBt ){
2513     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
2514     if( rc==SQLITE_BUSY ){
2515       p->pc = pc;
2516       p->rc = SQLITE_BUSY;
2517       p->pTos = pTos;
2518       return SQLITE_BUSY;
2519     }
2520     if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
2521       goto abort_due_to_error;
2522     }
2523   }
2524   break;
2525 }
2526 
2527 /* Opcode: ReadCookie P1 P2 *
2528 **
2529 ** Read cookie number P2 from database P1 and push it onto the stack.
2530 ** P2==0 is the schema version.  P2==1 is the database format.
2531 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
2532 ** the main database file and P1==1 is the database file used to store
2533 ** temporary tables.
2534 **
2535 ** If P1 is negative, then this is a request to read the size of a
2536 ** databases free-list. P2 must be set to 1 in this case. The actual
2537 ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
2538 ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
2539 **
2540 ** There must be a read-lock on the database (either a transaction
2541 ** must be started or there must be an open cursor) before
2542 ** executing this instruction.
2543 */
2544 case OP_ReadCookie: {
2545   int iMeta;
2546   int iDb = pOp->p1;
2547   int iCookie = pOp->p2;
2548 
2549   assert( pOp->p2<SQLITE_N_BTREE_META );
2550   if( iDb<0 ){
2551     iDb = (-1*(iDb+1));
2552     iCookie *= -1;
2553   }
2554   assert( iDb>=0 && iDb<db->nDb );
2555   assert( db->aDb[iDb].pBt!=0 );
2556   /* The indexing of meta values at the schema layer is off by one from
2557   ** the indexing in the btree layer.  The btree considers meta[0] to
2558   ** be the number of free pages in the database (a read-only value)
2559   ** and meta[1] to be the schema cookie.  The schema layer considers
2560   ** meta[1] to be the schema cookie.  So we have to shift the index
2561   ** by one in the following statement.
2562   */
2563   rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
2564   pTos++;
2565   pTos->u.i = iMeta;
2566   pTos->flags = MEM_Int;
2567   break;
2568 }
2569 
2570 /* Opcode: SetCookie P1 P2 *
2571 **
2572 ** Write the top of the stack into cookie number P2 of database P1.
2573 ** P2==0 is the schema version.  P2==1 is the database format.
2574 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
2575 ** the main database file and P1==1 is the database file used to store
2576 ** temporary tables.
2577 **
2578 ** A transaction must be started before executing this opcode.
2579 */
2580 case OP_SetCookie: {       /* no-push */
2581   Db *pDb;
2582   assert( pOp->p2<SQLITE_N_BTREE_META );
2583   assert( pOp->p1>=0 && pOp->p1<db->nDb );
2584   pDb = &db->aDb[pOp->p1];
2585   assert( pDb->pBt!=0 );
2586   assert( pTos>=p->aStack );
2587   sqlite3VdbeMemIntegerify(pTos);
2588   /* See note about index shifting on OP_ReadCookie */
2589   rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pTos->u.i);
2590   if( pOp->p2==0 ){
2591     /* When the schema cookie changes, record the new cookie internally */
2592     pDb->pSchema->schema_cookie = pTos->u.i;
2593     db->flags |= SQLITE_InternChanges;
2594   }else if( pOp->p2==1 ){
2595     /* Record changes in the file format */
2596     pDb->pSchema->file_format = pTos->u.i;
2597   }
2598   assert( (pTos->flags & MEM_Dyn)==0 );
2599   pTos--;
2600   if( pOp->p1==1 ){
2601     /* Invalidate all prepared statements whenever the TEMP database
2602     ** schema is changed.  Ticket #1644 */
2603     sqlite3ExpirePreparedStatements(db);
2604   }
2605   break;
2606 }
2607 
2608 /* Opcode: VerifyCookie P1 P2 *
2609 **
2610 ** Check the value of global database parameter number 0 (the
2611 ** schema version) and make sure it is equal to P2.
2612 ** P1 is the database number which is 0 for the main database file
2613 ** and 1 for the file holding temporary tables and some higher number
2614 ** for auxiliary databases.
2615 **
2616 ** The cookie changes its value whenever the database schema changes.
2617 ** This operation is used to detect when that the cookie has changed
2618 ** and that the current process needs to reread the schema.
2619 **
2620 ** Either a transaction needs to have been started or an OP_Open needs
2621 ** to be executed (to establish a read lock) before this opcode is
2622 ** invoked.
2623 */
2624 case OP_VerifyCookie: {       /* no-push */
2625   int iMeta;
2626   Btree *pBt;
2627   assert( pOp->p1>=0 && pOp->p1<db->nDb );
2628   pBt = db->aDb[pOp->p1].pBt;
2629   if( pBt ){
2630     rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
2631   }else{
2632     rc = SQLITE_OK;
2633     iMeta = 0;
2634   }
2635   if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
2636     sqlite3SetString(&p->zErrMsg, "database schema has changed", (char*)0);
2637     /* If the schema-cookie from the database file matches the cookie
2638     ** stored with the in-memory representation of the schema, do
2639     ** not reload the schema from the database file.
2640     **
2641     ** If virtual-tables are in use, this is not just an optimisation.
2642     ** Often, v-tables store their data in other SQLite tables, which
2643     ** are queried from within xNext() and other v-table methods using
2644     ** prepared queries. If such a query is out-of-date, we do not want to
2645     ** discard the database schema, as the user code implementing the
2646     ** v-table would have to be ready for the sqlite3_vtab structure itself
2647     ** to be invalidated whenever sqlite3_step() is called from within
2648     ** a v-table method.
2649     */
2650     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
2651       sqlite3ResetInternalSchema(db, pOp->p1);
2652     }
2653 
2654     sqlite3ExpirePreparedStatements(db);
2655     rc = SQLITE_SCHEMA;
2656   }
2657   break;
2658 }
2659 
2660 /* Opcode: OpenRead P1 P2 P3
2661 **
2662 ** Open a read-only cursor for the database table whose root page is
2663 ** P2 in a database file.  The database file is determined by an
2664 ** integer from the top of the stack.  0 means the main database and
2665 ** 1 means the database used for temporary tables.  Give the new
2666 ** cursor an identifier of P1.  The P1 values need not be contiguous
2667 ** but all P1 values should be small integers.  It is an error for
2668 ** P1 to be negative.
2669 **
2670 ** If P2==0 then take the root page number from the next of the stack.
2671 **
2672 ** There will be a read lock on the database whenever there is an
2673 ** open cursor.  If the database was unlocked prior to this instruction
2674 ** then a read lock is acquired as part of this instruction.  A read
2675 ** lock allows other processes to read the database but prohibits
2676 ** any other process from modifying the database.  The read lock is
2677 ** released when all cursors are closed.  If this instruction attempts
2678 ** to get a read lock but fails, the script terminates with an
2679 ** SQLITE_BUSY error code.
2680 **
2681 ** The P3 value is a pointer to a KeyInfo structure that defines the
2682 ** content and collating sequence of indices.  P3 is NULL for cursors
2683 ** that are not pointing to indices.
2684 **
2685 ** See also OpenWrite.
2686 */
2687 /* Opcode: OpenWrite P1 P2 P3
2688 **
2689 ** Open a read/write cursor named P1 on the table or index whose root
2690 ** page is P2.  If P2==0 then take the root page number from the stack.
2691 **
2692 ** The P3 value is a pointer to a KeyInfo structure that defines the
2693 ** content and collating sequence of indices.  P3 is NULL for cursors
2694 ** that are not pointing to indices.
2695 **
2696 ** This instruction works just like OpenRead except that it opens the cursor
2697 ** in read/write mode.  For a given table, there can be one or more read-only
2698 ** cursors or a single read/write cursor but not both.
2699 **
2700 ** See also OpenRead.
2701 */
2702 case OP_OpenRead:          /* no-push */
2703 case OP_OpenWrite: {       /* no-push */
2704   int i = pOp->p1;
2705   int p2 = pOp->p2;
2706   int wrFlag;
2707   Btree *pX;
2708   int iDb;
2709   Cursor *pCur;
2710   Db *pDb;
2711 
2712   assert( pTos>=p->aStack );
2713   sqlite3VdbeMemIntegerify(pTos);
2714   iDb = pTos->u.i;
2715   assert( (pTos->flags & MEM_Dyn)==0 );
2716   pTos--;
2717   assert( iDb>=0 && iDb<db->nDb );
2718   pDb = &db->aDb[iDb];
2719   pX = pDb->pBt;
2720   assert( pX!=0 );
2721   if( pOp->opcode==OP_OpenWrite ){
2722     wrFlag = 1;
2723     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
2724       p->minWriteFileFormat = pDb->pSchema->file_format;
2725     }
2726   }else{
2727     wrFlag = 0;
2728   }
2729   if( p2<=0 ){
2730     assert( pTos>=p->aStack );
2731     sqlite3VdbeMemIntegerify(pTos);
2732     p2 = pTos->u.i;
2733     assert( (pTos->flags & MEM_Dyn)==0 );
2734     pTos--;
2735     assert( p2>=2 );
2736   }
2737   assert( i>=0 );
2738   pCur = allocateCursor(p, i, iDb);
2739   if( pCur==0 ) goto no_mem;
2740   pCur->nullRow = 1;
2741   if( pX==0 ) break;
2742   /* We always provide a key comparison function.  If the table being
2743   ** opened is of type INTKEY, the comparision function will be ignored. */
2744   rc = sqlite3BtreeCursor(pX, p2, wrFlag,
2745            sqlite3VdbeRecordCompare, pOp->p3,
2746            &pCur->pCursor);
2747   if( pOp->p3type==P3_KEYINFO ){
2748     pCur->pKeyInfo = (KeyInfo*)pOp->p3;
2749     pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
2750     pCur->pKeyInfo->enc = ENC(p->db);
2751   }else{
2752     pCur->pKeyInfo = 0;
2753     pCur->pIncrKey = &pCur->bogusIncrKey;
2754   }
2755   switch( rc ){
2756     case SQLITE_BUSY: {
2757       p->pc = pc;
2758       p->rc = SQLITE_BUSY;
2759       p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
2760       return SQLITE_BUSY;
2761     }
2762     case SQLITE_OK: {
2763       int flags = sqlite3BtreeFlags(pCur->pCursor);
2764       /* Sanity checking.  Only the lower four bits of the flags byte should
2765       ** be used.  Bit 3 (mask 0x08) is unpreditable.  The lower 3 bits
2766       ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
2767       ** 2 (zerodata for indices).  If these conditions are not met it can
2768       ** only mean that we are dealing with a corrupt database file
2769       */
2770       if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
2771         rc = SQLITE_CORRUPT_BKPT;
2772         goto abort_due_to_error;
2773       }
2774       pCur->isTable = (flags & BTREE_INTKEY)!=0;
2775       pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
2776       /* If P3==0 it means we are expected to open a table.  If P3!=0 then
2777       ** we expect to be opening an index.  If this is not what happened,
2778       ** then the database is corrupt
2779       */
2780       if( (pCur->isTable && pOp->p3type==P3_KEYINFO)
2781        || (pCur->isIndex && pOp->p3type!=P3_KEYINFO) ){
2782         rc = SQLITE_CORRUPT_BKPT;
2783         goto abort_due_to_error;
2784       }
2785       break;
2786     }
2787     case SQLITE_EMPTY: {
2788       pCur->isTable = pOp->p3type!=P3_KEYINFO;
2789       pCur->isIndex = !pCur->isTable;
2790       rc = SQLITE_OK;
2791       break;
2792     }
2793     default: {
2794       goto abort_due_to_error;
2795     }
2796   }
2797   break;
2798 }
2799 
2800 /* Opcode: OpenEphemeral P1 P2 P3
2801 **
2802 ** Open a new cursor P1 to a transient table.
2803 ** The cursor is always opened read/write even if
2804 ** the main database is read-only.  The transient or virtual
2805 ** table is deleted automatically when the cursor is closed.
2806 **
2807 ** P2 is the number of columns in the virtual table.
2808 ** The cursor points to a BTree table if P3==0 and to a BTree index
2809 ** if P3 is not 0.  If P3 is not NULL, it points to a KeyInfo structure
2810 ** that defines the format of keys in the index.
2811 **
2812 ** This opcode was once called OpenTemp.  But that created
2813 ** confusion because the term "temp table", might refer either
2814 ** to a TEMP table at the SQL level, or to a table opened by
2815 ** this opcode.  Then this opcode was call OpenVirtual.  But
2816 ** that created confusion with the whole virtual-table idea.
2817 */
2818 case OP_OpenEphemeral: {       /* no-push */
2819   int i = pOp->p1;
2820   Cursor *pCx;
2821   assert( i>=0 );
2822   pCx = allocateCursor(p, i, -1);
2823   if( pCx==0 ) goto no_mem;
2824   pCx->nullRow = 1;
2825   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, &pCx->pBt);
2826   if( rc==SQLITE_OK ){
2827     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
2828   }
2829   if( rc==SQLITE_OK ){
2830     /* If a transient index is required, create it by calling
2831     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
2832     ** opening it. If a transient table is required, just use the
2833     ** automatically created table with root-page 1 (an INTKEY table).
2834     */
2835     if( pOp->p3 ){
2836       int pgno;
2837       assert( pOp->p3type==P3_KEYINFO );
2838       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA);
2839       if( rc==SQLITE_OK ){
2840         assert( pgno==MASTER_ROOT+1 );
2841         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, sqlite3VdbeRecordCompare,
2842             pOp->p3, &pCx->pCursor);
2843         pCx->pKeyInfo = (KeyInfo*)pOp->p3;
2844         pCx->pKeyInfo->enc = ENC(p->db);
2845         pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
2846       }
2847       pCx->isTable = 0;
2848     }else{
2849       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, 0, &pCx->pCursor);
2850       pCx->isTable = 1;
2851       pCx->pIncrKey = &pCx->bogusIncrKey;
2852     }
2853   }
2854   pCx->nField = pOp->p2;
2855   pCx->isIndex = !pCx->isTable;
2856   break;
2857 }
2858 
2859 /* Opcode: OpenPseudo P1 * *
2860 **
2861 ** Open a new cursor that points to a fake table that contains a single
2862 ** row of data.  Any attempt to write a second row of data causes the
2863 ** first row to be deleted.  All data is deleted when the cursor is
2864 ** closed.
2865 **
2866 ** A pseudo-table created by this opcode is useful for holding the
2867 ** NEW or OLD tables in a trigger.  Also used to hold the a single
2868 ** row output from the sorter so that the row can be decomposed into
2869 ** individual columns using the OP_Column opcode.
2870 */
2871 case OP_OpenPseudo: {       /* no-push */
2872   int i = pOp->p1;
2873   Cursor *pCx;
2874   assert( i>=0 );
2875   pCx = allocateCursor(p, i, -1);
2876   if( pCx==0 ) goto no_mem;
2877   pCx->nullRow = 1;
2878   pCx->pseudoTable = 1;
2879   pCx->pIncrKey = &pCx->bogusIncrKey;
2880   pCx->isTable = 1;
2881   pCx->isIndex = 0;
2882   break;
2883 }
2884 
2885 /* Opcode: Close P1 * *
2886 **
2887 ** Close a cursor previously opened as P1.  If P1 is not
2888 ** currently open, this instruction is a no-op.
2889 */
2890 case OP_Close: {       /* no-push */
2891   int i = pOp->p1;
2892   if( i>=0 && i<p->nCursor ){
2893     sqlite3VdbeFreeCursor(p, p->apCsr[i]);
2894     p->apCsr[i] = 0;
2895   }
2896   break;
2897 }
2898 
2899 /* Opcode: MoveGe P1 P2 *
2900 **
2901 ** Pop the top of the stack and use its value as a key.  Reposition
2902 ** cursor P1 so that it points to the smallest entry that is greater
2903 ** than or equal to the key that was popped ffrom the stack.
2904 ** If there are no records greater than or equal to the key and P2
2905 ** is not zero, then jump to P2.
2906 **
2907 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
2908 */
2909 /* Opcode: MoveGt P1 P2 *
2910 **
2911 ** Pop the top of the stack and use its value as a key.  Reposition
2912 ** cursor P1 so that it points to the smallest entry that is greater
2913 ** than the key from the stack.
2914 ** If there are no records greater than the key and P2 is not zero,
2915 ** then jump to P2.
2916 **
2917 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
2918 */
2919 /* Opcode: MoveLt P1 P2 *
2920 **
2921 ** Pop the top of the stack and use its value as a key.  Reposition
2922 ** cursor P1 so that it points to the largest entry that is less
2923 ** than the key from the stack.
2924 ** If there are no records less than the key and P2 is not zero,
2925 ** then jump to P2.
2926 **
2927 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
2928 */
2929 /* Opcode: MoveLe P1 P2 *
2930 **
2931 ** Pop the top of the stack and use its value as a key.  Reposition
2932 ** cursor P1 so that it points to the largest entry that is less than
2933 ** or equal to the key that was popped from the stack.
2934 ** If there are no records less than or eqal to the key and P2 is not zero,
2935 ** then jump to P2.
2936 **
2937 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
2938 */
2939 case OP_MoveLt:         /* no-push */
2940 case OP_MoveLe:         /* no-push */
2941 case OP_MoveGe:         /* no-push */
2942 case OP_MoveGt: {       /* no-push */
2943   int i = pOp->p1;
2944   Cursor *pC;
2945 
2946   assert( pTos>=p->aStack );
2947   assert( i>=0 && i<p->nCursor );
2948   pC = p->apCsr[i];
2949   assert( pC!=0 );
2950   if( pC->pCursor!=0 ){
2951     int res, oc;
2952     oc = pOp->opcode;
2953     pC->nullRow = 0;
2954     *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
2955     if( pC->isTable ){
2956       i64 iKey;
2957       sqlite3VdbeMemIntegerify(pTos);
2958       iKey = intToKey(pTos->u.i);
2959       if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){
2960         pC->movetoTarget = iKey;
2961         pC->deferredMoveto = 1;
2962         assert( (pTos->flags & MEM_Dyn)==0 );
2963         pTos--;
2964         break;
2965       }
2966       rc = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, 0, &res);
2967       if( rc!=SQLITE_OK ){
2968         goto abort_due_to_error;
2969       }
2970       pC->lastRowid = pTos->u.i;
2971       pC->rowidIsValid = res==0;
2972     }else{
2973       assert( pTos->flags & MEM_Blob );
2974       ExpandBlob(pTos);
2975       rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
2976       if( rc!=SQLITE_OK ){
2977         goto abort_due_to_error;
2978       }
2979       pC->rowidIsValid = 0;
2980     }
2981     pC->deferredMoveto = 0;
2982     pC->cacheStatus = CACHE_STALE;
2983     *pC->pIncrKey = 0;
2984 #ifdef SQLITE_TEST
2985     sqlite3_search_count++;
2986 #endif
2987     if( oc==OP_MoveGe || oc==OP_MoveGt ){
2988       if( res<0 ){
2989         rc = sqlite3BtreeNext(pC->pCursor, &res);
2990         if( rc!=SQLITE_OK ) goto abort_due_to_error;
2991         pC->rowidIsValid = 0;
2992       }else{
2993         res = 0;
2994       }
2995     }else{
2996       assert( oc==OP_MoveLt || oc==OP_MoveLe );
2997       if( res>=0 ){
2998         rc = sqlite3BtreePrevious(pC->pCursor, &res);
2999         if( rc!=SQLITE_OK ) goto abort_due_to_error;
3000         pC->rowidIsValid = 0;
3001       }else{
3002         /* res might be negative because the table is empty.  Check to
3003         ** see if this is the case.
3004         */
3005         res = sqlite3BtreeEof(pC->pCursor);
3006       }
3007     }
3008     if( res ){
3009       if( pOp->p2>0 ){
3010         pc = pOp->p2 - 1;
3011       }else{
3012         pC->nullRow = 1;
3013       }
3014     }
3015   }
3016   Release(pTos);
3017   pTos--;
3018   break;
3019 }
3020 
3021 /* Opcode: Distinct P1 P2 *
3022 **
3023 ** Use the top of the stack as a record created using MakeRecord.  P1 is a
3024 ** cursor on a table that declared as an index.  If that table contains an
3025 ** entry that matches the top of the stack fall thru.  If the top of the stack
3026 ** matches no entry in P1 then jump to P2.
3027 **
3028 ** The cursor is left pointing at the matching entry if it exists.  The
3029 ** record on the top of the stack is not popped.
3030 **
3031 ** This instruction is similar to NotFound except that this operation
3032 ** does not pop the key from the stack.
3033 **
3034 ** The instruction is used to implement the DISTINCT operator on SELECT
3035 ** statements.  The P1 table is not a true index but rather a record of
3036 ** all results that have produced so far.
3037 **
3038 ** See also: Found, NotFound, MoveTo, IsUnique, NotExists
3039 */
3040 /* Opcode: Found P1 P2 *
3041 **
3042 ** Top of the stack holds a blob constructed by MakeRecord.  P1 is an index.
3043 ** If an entry that matches the top of the stack exists in P1 then
3044 ** jump to P2.  If the top of the stack does not match any entry in P1
3045 ** then fall thru.  The P1 cursor is left pointing at the matching entry
3046 ** if it exists.  The blob is popped off the top of the stack.
3047 **
3048 ** This instruction is used to implement the IN operator where the
3049 ** left-hand side is a SELECT statement.  P1 is not a true index but
3050 ** is instead a temporary index that holds the results of the SELECT
3051 ** statement.  This instruction just checks to see if the left-hand side
3052 ** of the IN operator (stored on the top of the stack) exists in the
3053 ** result of the SELECT statement.
3054 **
3055 ** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
3056 */
3057 /* Opcode: NotFound P1 P2 *
3058 **
3059 ** The top of the stack holds a blob constructed by MakeRecord.  P1 is
3060 ** an index.  If no entry exists in P1 that matches the blob then jump
3061 ** to P2.  If an entry does existing, fall through.  The cursor is left
3062 ** pointing to the entry that matches.  The blob is popped from the stack.
3063 **
3064 ** The difference between this operation and Distinct is that
3065 ** Distinct does not pop the key from the stack.
3066 **
3067 ** See also: Distinct, Found, MoveTo, NotExists, IsUnique
3068 */
3069 case OP_Distinct:       /* no-push */
3070 case OP_NotFound:       /* no-push */
3071 case OP_Found: {        /* no-push */
3072   int i = pOp->p1;
3073   int alreadyExists = 0;
3074   Cursor *pC;
3075   assert( pTos>=p->aStack );
3076   assert( i>=0 && i<p->nCursor );
3077   assert( p->apCsr[i]!=0 );
3078   if( (pC = p->apCsr[i])->pCursor!=0 ){
3079     int res, rx;
3080     assert( pC->isTable==0 );
3081     assert( pTos->flags & MEM_Blob );
3082     Stringify(pTos, encoding);
3083     rx = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
3084     alreadyExists = rx==SQLITE_OK && res==0;
3085     pC->deferredMoveto = 0;
3086     pC->cacheStatus = CACHE_STALE;
3087   }
3088   if( pOp->opcode==OP_Found ){
3089     if( alreadyExists ) pc = pOp->p2 - 1;
3090   }else{
3091     if( !alreadyExists ) pc = pOp->p2 - 1;
3092   }
3093   if( pOp->opcode!=OP_Distinct ){
3094     Release(pTos);
3095     pTos--;
3096   }
3097   break;
3098 }
3099 
3100 /* Opcode: IsUnique P1 P2 *
3101 **
3102 ** The top of the stack is an integer record number.  Call this
3103 ** record number R.  The next on the stack is an index key created
3104 ** using MakeIdxRec.  Call it K.  This instruction pops R from the
3105 ** stack but it leaves K unchanged.
3106 **
3107 ** P1 is an index.  So it has no data and its key consists of a
3108 ** record generated by OP_MakeRecord where the last field is the
3109 ** rowid of the entry that the index refers to.
3110 **
3111 ** This instruction asks if there is an entry in P1 where the
3112 ** fields matches K but the rowid is different from R.
3113 ** If there is no such entry, then there is an immediate
3114 ** jump to P2.  If any entry does exist where the index string
3115 ** matches K but the record number is not R, then the record
3116 ** number for that entry is pushed onto the stack and control
3117 ** falls through to the next instruction.
3118 **
3119 ** See also: Distinct, NotFound, NotExists, Found
3120 */
3121 case OP_IsUnique: {        /* no-push */
3122   int i = pOp->p1;
3123   Mem *pNos = &pTos[-1];
3124   Cursor *pCx;
3125   BtCursor *pCrsr;
3126   i64 R;
3127 
3128   /* Pop the value R off the top of the stack
3129   */
3130   assert( pNos>=p->aStack );
3131   sqlite3VdbeMemIntegerify(pTos);
3132   R = pTos->u.i;
3133   assert( (pTos->flags & MEM_Dyn)==0 );
3134   pTos--;
3135   assert( i>=0 && i<p->nCursor );
3136   pCx = p->apCsr[i];
3137   assert( pCx!=0 );
3138   pCrsr = pCx->pCursor;
3139   if( pCrsr!=0 ){
3140     int res;
3141     i64 v;         /* The record number on the P1 entry that matches K */
3142     char *zKey;    /* The value of K */
3143     int nKey;      /* Number of bytes in K */
3144     int len;       /* Number of bytes in K without the rowid at the end */
3145     int szRowid;   /* Size of the rowid column at the end of zKey */
3146 
3147     /* Make sure K is a string and make zKey point to K
3148     */
3149     assert( pNos->flags & MEM_Blob );
3150     Stringify(pNos, encoding);
3151     zKey = pNos->z;
3152     nKey = pNos->n;
3153 
3154     szRowid = sqlite3VdbeIdxRowidLen((u8*)zKey);
3155     len = nKey-szRowid;
3156 
3157     /* Search for an entry in P1 where all but the last four bytes match K.
3158     ** If there is no such entry, jump immediately to P2.
3159     */
3160     assert( pCx->deferredMoveto==0 );
3161     pCx->cacheStatus = CACHE_STALE;
3162     rc = sqlite3BtreeMoveto(pCrsr, zKey, len, 0, &res);
3163     if( rc!=SQLITE_OK ){
3164       goto abort_due_to_error;
3165     }
3166     if( res<0 ){
3167       rc = sqlite3BtreeNext(pCrsr, &res);
3168       if( res ){
3169         pc = pOp->p2 - 1;
3170         break;
3171       }
3172     }
3173     rc = sqlite3VdbeIdxKeyCompare(pCx, len, (u8*)zKey, &res);
3174     if( rc!=SQLITE_OK ) goto abort_due_to_error;
3175     if( res>0 ){
3176       pc = pOp->p2 - 1;
3177       break;
3178     }
3179 
3180     /* At this point, pCrsr is pointing to an entry in P1 where all but
3181     ** the final entry (the rowid) matches K.  Check to see if the
3182     ** final rowid column is different from R.  If it equals R then jump
3183     ** immediately to P2.
3184     */
3185     rc = sqlite3VdbeIdxRowid(pCrsr, &v);
3186     if( rc!=SQLITE_OK ){
3187       goto abort_due_to_error;
3188     }
3189     if( v==R ){
3190       pc = pOp->p2 - 1;
3191       break;
3192     }
3193 
3194     /* The final varint of the key is different from R.  Push it onto
3195     ** the stack.  (The record number of an entry that violates a UNIQUE
3196     ** constraint.)
3197     */
3198     pTos++;
3199     pTos->u.i = v;
3200     pTos->flags = MEM_Int;
3201   }
3202   break;
3203 }
3204 
3205 /* Opcode: NotExists P1 P2 *
3206 **
3207 ** Use the top of the stack as a integer key.  If a record with that key
3208 ** does not exist in table of P1, then jump to P2.  If the record
3209 ** does exist, then fall thru.  The cursor is left pointing to the
3210 ** record if it exists.  The integer key is popped from the stack.
3211 **
3212 ** The difference between this operation and NotFound is that this
3213 ** operation assumes the key is an integer and that P1 is a table whereas
3214 ** NotFound assumes key is a blob constructed from MakeRecord and
3215 ** P1 is an index.
3216 **
3217 ** See also: Distinct, Found, MoveTo, NotFound, IsUnique
3218 */
3219 case OP_NotExists: {        /* no-push */
3220   int i = pOp->p1;
3221   Cursor *pC;
3222   BtCursor *pCrsr;
3223   assert( pTos>=p->aStack );
3224   assert( i>=0 && i<p->nCursor );
3225   assert( p->apCsr[i]!=0 );
3226   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3227     int res;
3228     u64 iKey;
3229     assert( pTos->flags & MEM_Int );
3230     assert( p->apCsr[i]->isTable );
3231     iKey = intToKey(pTos->u.i);
3232     rc = sqlite3BtreeMoveto(pCrsr, 0, iKey, 0,&res);
3233     pC->lastRowid = pTos->u.i;
3234     pC->rowidIsValid = res==0;
3235     pC->nullRow = 0;
3236     pC->cacheStatus = CACHE_STALE;
3237     /* res might be uninitialized if rc!=SQLITE_OK.  But if rc!=SQLITE_OK
3238     ** processing is about to abort so we really do not care whether or not
3239     ** the following jump is taken.  (In other words, do not stress over
3240     ** the error that valgrind sometimes shows on the next statement when
3241     ** running ioerr.test and similar failure-recovery test scripts.) */
3242     if( res!=0 ){
3243       pc = pOp->p2 - 1;
3244       pC->rowidIsValid = 0;
3245     }
3246   }
3247   Release(pTos);
3248   pTos--;
3249   break;
3250 }
3251 
3252 /* Opcode: Sequence P1 * *
3253 **
3254 ** Push an integer onto the stack which is the next available
3255 ** sequence number for cursor P1.  The sequence number on the
3256 ** cursor is incremented after the push.
3257 */
3258 case OP_Sequence: {
3259   int i = pOp->p1;
3260   assert( pTos>=p->aStack );
3261   assert( i>=0 && i<p->nCursor );
3262   assert( p->apCsr[i]!=0 );
3263   pTos++;
3264   pTos->u.i = p->apCsr[i]->seqCount++;
3265   pTos->flags = MEM_Int;
3266   break;
3267 }
3268 
3269 
3270 /* Opcode: NewRowid P1 P2 *
3271 **
3272 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
3273 ** The record number is not previously used as a key in the database
3274 ** table that cursor P1 points to.  The new record number is pushed
3275 ** onto the stack.
3276 **
3277 ** If P2>0 then P2 is a memory cell that holds the largest previously
3278 ** generated record number.  No new record numbers are allowed to be less
3279 ** than this value.  When this value reaches its maximum, a SQLITE_FULL
3280 ** error is generated.  The P2 memory cell is updated with the generated
3281 ** record number.  This P2 mechanism is used to help implement the
3282 ** AUTOINCREMENT feature.
3283 */
3284 case OP_NewRowid: {
3285   int i = pOp->p1;
3286   i64 v = 0;
3287   Cursor *pC;
3288   assert( i>=0 && i<p->nCursor );
3289   assert( p->apCsr[i]!=0 );
3290   if( (pC = p->apCsr[i])->pCursor==0 ){
3291     /* The zero initialization above is all that is needed */
3292   }else{
3293     /* The next rowid or record number (different terms for the same
3294     ** thing) is obtained in a two-step algorithm.
3295     **
3296     ** First we attempt to find the largest existing rowid and add one
3297     ** to that.  But if the largest existing rowid is already the maximum
3298     ** positive integer, we have to fall through to the second
3299     ** probabilistic algorithm
3300     **
3301     ** The second algorithm is to select a rowid at random and see if
3302     ** it already exists in the table.  If it does not exist, we have
3303     ** succeeded.  If the random rowid does exist, we select a new one
3304     ** and try again, up to 1000 times.
3305     **
3306     ** For a table with less than 2 billion entries, the probability
3307     ** of not finding a unused rowid is about 1.0e-300.  This is a
3308     ** non-zero probability, but it is still vanishingly small and should
3309     ** never cause a problem.  You are much, much more likely to have a
3310     ** hardware failure than for this algorithm to fail.
3311     **
3312     ** The analysis in the previous paragraph assumes that you have a good
3313     ** source of random numbers.  Is a library function like lrand48()
3314     ** good enough?  Maybe. Maybe not. It's hard to know whether there
3315     ** might be subtle bugs is some implementations of lrand48() that
3316     ** could cause problems. To avoid uncertainty, SQLite uses its own
3317     ** random number generator based on the RC4 algorithm.
3318     **
3319     ** To promote locality of reference for repetitive inserts, the
3320     ** first few attempts at chosing a random rowid pick values just a little
3321     ** larger than the previous rowid.  This has been shown experimentally
3322     ** to double the speed of the COPY operation.
3323     */
3324     int res, rx=SQLITE_OK, cnt;
3325     i64 x;
3326     cnt = 0;
3327     if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
3328           BTREE_INTKEY ){
3329       rc = SQLITE_CORRUPT_BKPT;
3330       goto abort_due_to_error;
3331     }
3332     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
3333     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
3334 
3335 #ifdef SQLITE_32BIT_ROWID
3336 #   define MAX_ROWID 0x7fffffff
3337 #else
3338     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
3339     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
3340     ** to provide the constant while making all compilers happy.
3341     */
3342 #   define MAX_ROWID  ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
3343 #endif
3344 
3345     if( !pC->useRandomRowid ){
3346       if( pC->nextRowidValid ){
3347         v = pC->nextRowid;
3348       }else{
3349         rc = sqlite3BtreeLast(pC->pCursor, &res);
3350         if( rc!=SQLITE_OK ){
3351           goto abort_due_to_error;
3352         }
3353         if( res ){
3354           v = 1;
3355         }else{
3356           sqlite3BtreeKeySize(pC->pCursor, &v);
3357           v = keyToInt(v);
3358           if( v==MAX_ROWID ){
3359             pC->useRandomRowid = 1;
3360           }else{
3361             v++;
3362           }
3363         }
3364       }
3365 
3366 #ifndef SQLITE_OMIT_AUTOINCREMENT
3367       if( pOp->p2 ){
3368         Mem *pMem;
3369         assert( pOp->p2>0 && pOp->p2<p->nMem );  /* P2 is a valid memory cell */
3370         pMem = &p->aMem[pOp->p2];
3371         sqlite3VdbeMemIntegerify(pMem);
3372         assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P2) holds an integer */
3373         if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
3374           rc = SQLITE_FULL;
3375           goto abort_due_to_error;
3376         }
3377         if( v<pMem->u.i+1 ){
3378           v = pMem->u.i + 1;
3379         }
3380         pMem->u.i = v;
3381       }
3382 #endif
3383 
3384       if( v<MAX_ROWID ){
3385         pC->nextRowidValid = 1;
3386         pC->nextRowid = v+1;
3387       }else{
3388         pC->nextRowidValid = 0;
3389       }
3390     }
3391     if( pC->useRandomRowid ){
3392       assert( pOp->p2==0 );  /* SQLITE_FULL must have occurred prior to this */
3393       v = db->priorNewRowid;
3394       cnt = 0;
3395       do{
3396         if( v==0 || cnt>2 ){
3397           sqlite3Randomness(sizeof(v), &v);
3398           if( cnt<5 ) v &= 0xffffff;
3399         }else{
3400           unsigned char r;
3401           sqlite3Randomness(1, &r);
3402           v += r + 1;
3403         }
3404         if( v==0 ) continue;
3405         x = intToKey(v);
3406         rx = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)x, 0, &res);
3407         cnt++;
3408       }while( cnt<1000 && rx==SQLITE_OK && res==0 );
3409       db->priorNewRowid = v;
3410       if( rx==SQLITE_OK && res==0 ){
3411         rc = SQLITE_FULL;
3412         goto abort_due_to_error;
3413       }
3414     }
3415     pC->rowidIsValid = 0;
3416     pC->deferredMoveto = 0;
3417     pC->cacheStatus = CACHE_STALE;
3418   }
3419   pTos++;
3420   pTos->u.i = v;
3421   pTos->flags = MEM_Int;
3422   break;
3423 }
3424 
3425 /* Opcode: Insert P1 P2 P3
3426 **
3427 ** Write an entry into the table of cursor P1.  A new entry is
3428 ** created if it doesn't already exist or the data for an existing
3429 ** entry is overwritten.  The data is the value on the top of the
3430 ** stack.  The key is the next value down on the stack.  The key must
3431 ** be an integer.  The stack is popped twice by this instruction.
3432 **
3433 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
3434 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P2 is set,
3435 ** then rowid is stored for subsequent return by the
3436 ** sqlite3_last_insert_rowid() function (otherwise it's unmodified).
3437 **
3438 ** Parameter P3 may point to a string containing the table-name, or
3439 ** may be NULL. If it is not NULL, then the update-hook
3440 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
3441 **
3442 ** This instruction only works on tables.  The equivalent instruction
3443 ** for indices is OP_IdxInsert.
3444 */
3445 case OP_Insert: {         /* no-push */
3446   Mem *pNos = &pTos[-1];
3447   int i = pOp->p1;
3448   Cursor *pC;
3449   assert( pNos>=p->aStack );
3450   assert( i>=0 && i<p->nCursor );
3451   assert( p->apCsr[i]!=0 );
3452   if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){
3453     i64 iKey;   /* The integer ROWID or key for the record to be inserted */
3454 
3455     assert( pNos->flags & MEM_Int );
3456     assert( pC->isTable );
3457     iKey = intToKey(pNos->u.i);
3458 
3459     if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
3460     if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->u.i;
3461     if( pC->nextRowidValid && pNos->u.i>=pC->nextRowid ){
3462       pC->nextRowidValid = 0;
3463     }
3464     if( pTos->flags & MEM_Null ){
3465       pTos->z = 0;
3466       pTos->n = 0;
3467     }else{
3468       assert( pTos->flags & (MEM_Blob|MEM_Str) );
3469     }
3470     if( pC->pseudoTable ){
3471       sqliteFree(pC->pData);
3472       pC->iKey = iKey;
3473       pC->nData = pTos->n;
3474       if( pTos->flags & MEM_Dyn ){
3475         pC->pData = pTos->z;
3476         pTos->flags = MEM_Null;
3477       }else{
3478         pC->pData = sqliteMallocRaw( pC->nData+2 );
3479         if( !pC->pData ) goto no_mem;
3480         memcpy(pC->pData, pTos->z, pC->nData);
3481         pC->pData[pC->nData] = 0;
3482         pC->pData[pC->nData+1] = 0;
3483       }
3484       pC->nullRow = 0;
3485     }else{
3486       int nZero;
3487       if( pTos->flags & MEM_Zero ){
3488         nZero = pTos->u.i;
3489       }else{
3490         nZero = 0;
3491       }
3492       rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
3493                               pTos->z, pTos->n, nZero,
3494                               pOp->p2 & OPFLAG_APPEND);
3495     }
3496 
3497     pC->rowidIsValid = 0;
3498     pC->deferredMoveto = 0;
3499     pC->cacheStatus = CACHE_STALE;
3500 
3501     /* Invoke the update-hook if required. */
3502     if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
3503       const char *zDb = db->aDb[pC->iDb].zName;
3504       const char *zTbl = pOp->p3;
3505       int op = ((pOp->p2 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
3506       assert( pC->isTable );
3507       db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
3508       assert( pC->iDb>=0 );
3509     }
3510   }
3511   popStack(&pTos, 2);
3512 
3513   break;
3514 }
3515 
3516 /* Opcode: Delete P1 P2 P3
3517 **
3518 ** Delete the record at which the P1 cursor is currently pointing.
3519 **
3520 ** The cursor will be left pointing at either the next or the previous
3521 ** record in the table. If it is left pointing at the next record, then
3522 ** the next Next instruction will be a no-op.  Hence it is OK to delete
3523 ** a record from within an Next loop.
3524 **
3525 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
3526 ** incremented (otherwise not).
3527 **
3528 ** If P1 is a pseudo-table, then this instruction is a no-op.
3529 */
3530 case OP_Delete: {        /* no-push */
3531   int i = pOp->p1;
3532   Cursor *pC;
3533   assert( i>=0 && i<p->nCursor );
3534   pC = p->apCsr[i];
3535   assert( pC!=0 );
3536   if( pC->pCursor!=0 ){
3537     i64 iKey;
3538 
3539     /* If the update-hook will be invoked, set iKey to the rowid of the
3540     ** row being deleted.
3541     */
3542     if( db->xUpdateCallback && pOp->p3 ){
3543       assert( pC->isTable );
3544       if( pC->rowidIsValid ){
3545         iKey = pC->lastRowid;
3546       }else{
3547         rc = sqlite3BtreeKeySize(pC->pCursor, &iKey);
3548         if( rc ){
3549           goto abort_due_to_error;
3550         }
3551         iKey = keyToInt(iKey);
3552       }
3553     }
3554 
3555     rc = sqlite3VdbeCursorMoveto(pC);
3556     if( rc ) goto abort_due_to_error;
3557     rc = sqlite3BtreeDelete(pC->pCursor);
3558     pC->nextRowidValid = 0;
3559     pC->cacheStatus = CACHE_STALE;
3560 
3561     /* Invoke the update-hook if required. */
3562     if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
3563       const char *zDb = db->aDb[pC->iDb].zName;
3564       const char *zTbl = pOp->p3;
3565       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
3566       assert( pC->iDb>=0 );
3567     }
3568   }
3569   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
3570   break;
3571 }
3572 
3573 /* Opcode: ResetCount P1 * *
3574 **
3575 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
3576 ** then the value of the change counter is copied to the database handle
3577 ** change counter (returned by subsequent calls to sqlite3_changes())
3578 ** before it is reset. This is used by trigger programs.
3579 */
3580 case OP_ResetCount: {        /* no-push */
3581   if( pOp->p1 ){
3582     sqlite3VdbeSetChanges(db, p->nChange);
3583   }
3584   p->nChange = 0;
3585   break;
3586 }
3587 
3588 /* Opcode: RowData P1 * *
3589 **
3590 ** Push onto the stack the complete row data for cursor P1.
3591 ** There is no interpretation of the data.  It is just copied
3592 ** onto the stack exactly as it is found in the database file.
3593 **
3594 ** If the cursor is not pointing to a valid row, a NULL is pushed
3595 ** onto the stack.
3596 */
3597 /* Opcode: RowKey P1 * *
3598 **
3599 ** Push onto the stack the complete row key for cursor P1.
3600 ** There is no interpretation of the key.  It is just copied
3601 ** onto the stack exactly as it is found in the database file.
3602 **
3603 ** If the cursor is not pointing to a valid row, a NULL is pushed
3604 ** onto the stack.
3605 */
3606 case OP_RowKey:
3607 case OP_RowData: {
3608   int i = pOp->p1;
3609   Cursor *pC;
3610   u32 n;
3611 
3612   /* Note that RowKey and RowData are really exactly the same instruction */
3613   pTos++;
3614   assert( i>=0 && i<p->nCursor );
3615   pC = p->apCsr[i];
3616   assert( pC->isTable || pOp->opcode==OP_RowKey );
3617   assert( pC->isIndex || pOp->opcode==OP_RowData );
3618   assert( pC!=0 );
3619   if( pC->nullRow ){
3620     pTos->flags = MEM_Null;
3621   }else if( pC->pCursor!=0 ){
3622     BtCursor *pCrsr = pC->pCursor;
3623     rc = sqlite3VdbeCursorMoveto(pC);
3624     if( rc ) goto abort_due_to_error;
3625     if( pC->nullRow ){
3626       pTos->flags = MEM_Null;
3627       break;
3628     }else if( pC->isIndex ){
3629       i64 n64;
3630       assert( !pC->isTable );
3631       sqlite3BtreeKeySize(pCrsr, &n64);
3632       if( n64>SQLITE_MAX_LENGTH ){
3633         goto too_big;
3634       }
3635       n = n64;
3636     }else{
3637       sqlite3BtreeDataSize(pCrsr, &n);
3638     }
3639     if( n>SQLITE_MAX_LENGTH ){
3640       goto too_big;
3641     }
3642     pTos->n = n;
3643     if( n<=NBFS ){
3644       pTos->flags = MEM_Blob | MEM_Short;
3645       pTos->z = pTos->zShort;
3646     }else{
3647       char *z = sqliteMallocRaw( n );
3648       if( z==0 ) goto no_mem;
3649       pTos->flags = MEM_Blob | MEM_Dyn;
3650       pTos->xDel = 0;
3651       pTos->z = z;
3652     }
3653     if( pC->isIndex ){
3654       rc = sqlite3BtreeKey(pCrsr, 0, n, pTos->z);
3655     }else{
3656       rc = sqlite3BtreeData(pCrsr, 0, n, pTos->z);
3657     }
3658   }else if( pC->pseudoTable ){
3659     pTos->n = pC->nData;
3660     assert( pC->nData<=SQLITE_MAX_LENGTH );
3661     pTos->z = pC->pData;
3662     pTos->flags = MEM_Blob|MEM_Ephem;
3663   }else{
3664     pTos->flags = MEM_Null;
3665   }
3666   pTos->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
3667   break;
3668 }
3669 
3670 /* Opcode: Rowid P1 * *
3671 **
3672 ** Push onto the stack an integer which is the key of the table entry that
3673 ** P1 is currently point to.
3674 */
3675 case OP_Rowid: {
3676   int i = pOp->p1;
3677   Cursor *pC;
3678   i64 v;
3679 
3680   assert( i>=0 && i<p->nCursor );
3681   pC = p->apCsr[i];
3682   assert( pC!=0 );
3683   rc = sqlite3VdbeCursorMoveto(pC);
3684   if( rc ) goto abort_due_to_error;
3685   pTos++;
3686   if( pC->rowidIsValid ){
3687     v = pC->lastRowid;
3688   }else if( pC->pseudoTable ){
3689     v = keyToInt(pC->iKey);
3690   }else if( pC->nullRow || pC->pCursor==0 ){
3691     pTos->flags = MEM_Null;
3692     break;
3693   }else{
3694     assert( pC->pCursor!=0 );
3695     sqlite3BtreeKeySize(pC->pCursor, &v);
3696     v = keyToInt(v);
3697   }
3698   pTos->u.i = v;
3699   pTos->flags = MEM_Int;
3700   break;
3701 }
3702 
3703 /* Opcode: NullRow P1 * *
3704 **
3705 ** Move the cursor P1 to a null row.  Any OP_Column operations
3706 ** that occur while the cursor is on the null row will always push
3707 ** a NULL onto the stack.
3708 */
3709 case OP_NullRow: {        /* no-push */
3710   int i = pOp->p1;
3711   Cursor *pC;
3712 
3713   assert( i>=0 && i<p->nCursor );
3714   pC = p->apCsr[i];
3715   assert( pC!=0 );
3716   pC->nullRow = 1;
3717   pC->rowidIsValid = 0;
3718   break;
3719 }
3720 
3721 /* Opcode: Last P1 P2 *
3722 **
3723 ** The next use of the Rowid or Column or Next instruction for P1
3724 ** will refer to the last entry in the database table or index.
3725 ** If the table or index is empty and P2>0, then jump immediately to P2.
3726 ** If P2 is 0 or if the table or index is not empty, fall through
3727 ** to the following instruction.
3728 */
3729 case OP_Last: {        /* no-push */
3730   int i = pOp->p1;
3731   Cursor *pC;
3732   BtCursor *pCrsr;
3733 
3734   assert( i>=0 && i<p->nCursor );
3735   pC = p->apCsr[i];
3736   assert( pC!=0 );
3737   if( (pCrsr = pC->pCursor)!=0 ){
3738     int res;
3739     rc = sqlite3BtreeLast(pCrsr, &res);
3740     pC->nullRow = res;
3741     pC->deferredMoveto = 0;
3742     pC->cacheStatus = CACHE_STALE;
3743     if( res && pOp->p2>0 ){
3744       pc = pOp->p2 - 1;
3745     }
3746   }else{
3747     pC->nullRow = 0;
3748   }
3749   break;
3750 }
3751 
3752 
3753 /* Opcode: Sort P1 P2 *
3754 **
3755 ** This opcode does exactly the same thing as OP_Rewind except that
3756 ** it increments an undocumented global variable used for testing.
3757 **
3758 ** Sorting is accomplished by writing records into a sorting index,
3759 ** then rewinding that index and playing it back from beginning to
3760 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
3761 ** rewinding so that the global variable will be incremented and
3762 ** regression tests can determine whether or not the optimizer is
3763 ** correctly optimizing out sorts.
3764 */
3765 case OP_Sort: {        /* no-push */
3766 #ifdef SQLITE_TEST
3767   sqlite3_sort_count++;
3768   sqlite3_search_count--;
3769 #endif
3770   /* Fall through into OP_Rewind */
3771 }
3772 /* Opcode: Rewind P1 P2 *
3773 **
3774 ** The next use of the Rowid or Column or Next instruction for P1
3775 ** will refer to the first entry in the database table or index.
3776 ** If the table or index is empty and P2>0, then jump immediately to P2.
3777 ** If P2 is 0 or if the table or index is not empty, fall through
3778 ** to the following instruction.
3779 */
3780 case OP_Rewind: {        /* no-push */
3781   int i = pOp->p1;
3782   Cursor *pC;
3783   BtCursor *pCrsr;
3784   int res;
3785 
3786   assert( i>=0 && i<p->nCursor );
3787   pC = p->apCsr[i];
3788   assert( pC!=0 );
3789   if( (pCrsr = pC->pCursor)!=0 ){
3790     rc = sqlite3BtreeFirst(pCrsr, &res);
3791     pC->atFirst = res==0;
3792     pC->deferredMoveto = 0;
3793     pC->cacheStatus = CACHE_STALE;
3794   }else{
3795     res = 1;
3796   }
3797   pC->nullRow = res;
3798   if( res && pOp->p2>0 ){
3799     pc = pOp->p2 - 1;
3800   }
3801   break;
3802 }
3803 
3804 /* Opcode: Next P1 P2 *
3805 **
3806 ** Advance cursor P1 so that it points to the next key/data pair in its
3807 ** table or index.  If there are no more key/value pairs then fall through
3808 ** to the following instruction.  But if the cursor advance was successful,
3809 ** jump immediately to P2.
3810 **
3811 ** See also: Prev
3812 */
3813 /* Opcode: Prev P1 P2 *
3814 **
3815 ** Back up cursor P1 so that it points to the previous key/data pair in its
3816 ** table or index.  If there is no previous key/value pairs then fall through
3817 ** to the following instruction.  But if the cursor backup was successful,
3818 ** jump immediately to P2.
3819 */
3820 case OP_Prev:          /* no-push */
3821 case OP_Next: {        /* no-push */
3822   Cursor *pC;
3823   BtCursor *pCrsr;
3824 
3825   CHECK_FOR_INTERRUPT;
3826   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3827   pC = p->apCsr[pOp->p1];
3828   if( pC==0 ){
3829     break;  /* See ticket #2273 */
3830   }
3831   if( (pCrsr = pC->pCursor)!=0 ){
3832     int res;
3833     if( pC->nullRow ){
3834       res = 1;
3835     }else{
3836       assert( pC->deferredMoveto==0 );
3837       rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
3838                                   sqlite3BtreePrevious(pCrsr, &res);
3839       pC->nullRow = res;
3840       pC->cacheStatus = CACHE_STALE;
3841     }
3842     if( res==0 ){
3843       pc = pOp->p2 - 1;
3844 #ifdef SQLITE_TEST
3845       sqlite3_search_count++;
3846 #endif
3847     }
3848   }else{
3849     pC->nullRow = 1;
3850   }
3851   pC->rowidIsValid = 0;
3852   break;
3853 }
3854 
3855 /* Opcode: IdxInsert P1 P2 *
3856 **
3857 ** The top of the stack holds a SQL index key made using either the
3858 ** MakeIdxRec or MakeRecord instructions.  This opcode writes that key
3859 ** into the index P1.  Data for the entry is nil.
3860 **
3861 ** P2 is a flag that provides a hint to the b-tree layer that this
3862 ** insert is likely to be an append.
3863 **
3864 ** This instruction only works for indices.  The equivalent instruction
3865 ** for tables is OP_Insert.
3866 */
3867 case OP_IdxInsert: {        /* no-push */
3868   int i = pOp->p1;
3869   Cursor *pC;
3870   BtCursor *pCrsr;
3871   assert( pTos>=p->aStack );
3872   assert( i>=0 && i<p->nCursor );
3873   assert( p->apCsr[i]!=0 );
3874   assert( pTos->flags & MEM_Blob );
3875   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3876     assert( pC->isTable==0 );
3877     rc = ExpandBlob(pTos);
3878     if( rc==SQLITE_OK ){
3879       int nKey = pTos->n;
3880       const char *zKey = pTos->z;
3881       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p2);
3882       assert( pC->deferredMoveto==0 );
3883       pC->cacheStatus = CACHE_STALE;
3884     }
3885   }
3886   Release(pTos);
3887   pTos--;
3888   break;
3889 }
3890 
3891 /* Opcode: IdxDelete P1 * *
3892 **
3893 ** The top of the stack is an index key built using the either the
3894 ** MakeIdxRec or MakeRecord opcodes.
3895 ** This opcode removes that entry from the index.
3896 */
3897 case OP_IdxDelete: {        /* no-push */
3898   int i = pOp->p1;
3899   Cursor *pC;
3900   BtCursor *pCrsr;
3901   assert( pTos>=p->aStack );
3902   assert( pTos->flags & MEM_Blob );
3903   assert( i>=0 && i<p->nCursor );
3904   assert( p->apCsr[i]!=0 );
3905   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3906     int res;
3907     rc = sqlite3BtreeMoveto(pCrsr, pTos->z, pTos->n, 0, &res);
3908     if( rc==SQLITE_OK && res==0 ){
3909       rc = sqlite3BtreeDelete(pCrsr);
3910     }
3911     assert( pC->deferredMoveto==0 );
3912     pC->cacheStatus = CACHE_STALE;
3913   }
3914   Release(pTos);
3915   pTos--;
3916   break;
3917 }
3918 
3919 /* Opcode: IdxRowid P1 * *
3920 **
3921 ** Push onto the stack an integer which is the last entry in the record at
3922 ** the end of the index key pointed to by cursor P1.  This integer should be
3923 ** the rowid of the table entry to which this index entry points.
3924 **
3925 ** See also: Rowid, MakeIdxRec.
3926 */
3927 case OP_IdxRowid: {
3928   int i = pOp->p1;
3929   BtCursor *pCrsr;
3930   Cursor *pC;
3931 
3932   assert( i>=0 && i<p->nCursor );
3933   assert( p->apCsr[i]!=0 );
3934   pTos++;
3935   pTos->flags = MEM_Null;
3936   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3937     i64 rowid;
3938 
3939     assert( pC->deferredMoveto==0 );
3940     assert( pC->isTable==0 );
3941     if( pC->nullRow ){
3942       pTos->flags = MEM_Null;
3943     }else{
3944       rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
3945       if( rc!=SQLITE_OK ){
3946         goto abort_due_to_error;
3947       }
3948       pTos->flags = MEM_Int;
3949       pTos->u.i = rowid;
3950     }
3951   }
3952   break;
3953 }
3954 
3955 /* Opcode: IdxGT P1 P2 *
3956 **
3957 ** The top of the stack is an index entry that omits the ROWID.  Compare
3958 ** the top of stack against the index that P1 is currently pointing to.
3959 ** Ignore the ROWID on the P1 index.
3960 **
3961 ** The top of the stack might have fewer columns that P1.
3962 **
3963 ** If the P1 index entry is greater than the top of the stack
3964 ** then jump to P2.  Otherwise fall through to the next instruction.
3965 ** In either case, the stack is popped once.
3966 */
3967 /* Opcode: IdxGE P1 P2 P3
3968 **
3969 ** The top of the stack is an index entry that omits the ROWID.  Compare
3970 ** the top of stack against the index that P1 is currently pointing to.
3971 ** Ignore the ROWID on the P1 index.
3972 **
3973 ** If the P1 index entry is greater than or equal to the top of the stack
3974 ** then jump to P2.  Otherwise fall through to the next instruction.
3975 ** In either case, the stack is popped once.
3976 **
3977 ** If P3 is the "+" string (or any other non-NULL string) then the
3978 ** index taken from the top of the stack is temporarily increased by
3979 ** an epsilon prior to the comparison.  This make the opcode work
3980 ** like IdxGT except that if the key from the stack is a prefix of
3981 ** the key in the cursor, the result is false whereas it would be
3982 ** true with IdxGT.
3983 */
3984 /* Opcode: IdxLT P1 P2 P3
3985 **
3986 ** The top of the stack is an index entry that omits the ROWID.  Compare
3987 ** the top of stack against the index that P1 is currently pointing to.
3988 ** Ignore the ROWID on the P1 index.
3989 **
3990 ** If the P1 index entry is less than  the top of the stack
3991 ** then jump to P2.  Otherwise fall through to the next instruction.
3992 ** In either case, the stack is popped once.
3993 **
3994 ** If P3 is the "+" string (or any other non-NULL string) then the
3995 ** index taken from the top of the stack is temporarily increased by
3996 ** an epsilon prior to the comparison.  This makes the opcode work
3997 ** like IdxLE.
3998 */
3999 case OP_IdxLT:          /* no-push */
4000 case OP_IdxGT:          /* no-push */
4001 case OP_IdxGE: {        /* no-push */
4002   int i= pOp->p1;
4003   Cursor *pC;
4004 
4005   assert( i>=0 && i<p->nCursor );
4006   assert( p->apCsr[i]!=0 );
4007   assert( pTos>=p->aStack );
4008   if( (pC = p->apCsr[i])->pCursor!=0 ){
4009     int res;
4010 
4011     assert( pTos->flags & MEM_Blob );  /* Created using OP_MakeRecord */
4012     assert( pC->deferredMoveto==0 );
4013     ExpandBlob(pTos);
4014     *pC->pIncrKey = pOp->p3!=0;
4015     assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT );
4016     rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, (u8*)pTos->z, &res);
4017     *pC->pIncrKey = 0;
4018     if( rc!=SQLITE_OK ){
4019       break;
4020     }
4021     if( pOp->opcode==OP_IdxLT ){
4022       res = -res;
4023     }else if( pOp->opcode==OP_IdxGE ){
4024       res++;
4025     }
4026     if( res>0 ){
4027       pc = pOp->p2 - 1 ;
4028     }
4029   }
4030   Release(pTos);
4031   pTos--;
4032   break;
4033 }
4034 
4035 /* Opcode: Destroy P1 P2 *
4036 **
4037 ** Delete an entire database table or index whose root page in the database
4038 ** file is given by P1.
4039 **
4040 ** The table being destroyed is in the main database file if P2==0.  If
4041 ** P2==1 then the table to be clear is in the auxiliary database file
4042 ** that is used to store tables create using CREATE TEMPORARY TABLE.
4043 **
4044 ** If AUTOVACUUM is enabled then it is possible that another root page
4045 ** might be moved into the newly deleted root page in order to keep all
4046 ** root pages contiguous at the beginning of the database.  The former
4047 ** value of the root page that moved - its value before the move occurred -
4048 ** is pushed onto the stack.  If no page movement was required (because
4049 ** the table being dropped was already the last one in the database) then
4050 ** a zero is pushed onto the stack.  If AUTOVACUUM is disabled
4051 ** then a zero is pushed onto the stack.
4052 **
4053 ** See also: Clear
4054 */
4055 case OP_Destroy: {
4056   int iMoved;
4057   int iCnt;
4058 #ifndef SQLITE_OMIT_VIRTUALTABLE
4059   Vdbe *pVdbe;
4060   iCnt = 0;
4061   for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
4062     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
4063       iCnt++;
4064     }
4065   }
4066 #else
4067   iCnt = db->activeVdbeCnt;
4068 #endif
4069   if( iCnt>1 ){
4070     rc = SQLITE_LOCKED;
4071   }else{
4072     assert( iCnt==1 );
4073     rc = sqlite3BtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1, &iMoved);
4074     pTos++;
4075     pTos->flags = MEM_Int;
4076     pTos->u.i = iMoved;
4077 #ifndef SQLITE_OMIT_AUTOVACUUM
4078     if( rc==SQLITE_OK && iMoved!=0 ){
4079       sqlite3RootPageMoved(&db->aDb[pOp->p2], iMoved, pOp->p1);
4080     }
4081 #endif
4082   }
4083   break;
4084 }
4085 
4086 /* Opcode: Clear P1 P2 *
4087 **
4088 ** Delete all contents of the database table or index whose root page
4089 ** in the database file is given by P1.  But, unlike Destroy, do not
4090 ** remove the table or index from the database file.
4091 **
4092 ** The table being clear is in the main database file if P2==0.  If
4093 ** P2==1 then the table to be clear is in the auxiliary database file
4094 ** that is used to store tables create using CREATE TEMPORARY TABLE.
4095 **
4096 ** See also: Destroy
4097 */
4098 case OP_Clear: {        /* no-push */
4099 
4100   /* For consistency with the way other features of SQLite operate
4101   ** with a truncate, we will also skip the update callback.
4102   */
4103 #if 0
4104   Btree *pBt = db->aDb[pOp->p2].pBt;
4105   if( db->xUpdateCallback && pOp->p3 ){
4106     const char *zDb = db->aDb[pOp->p2].zName;
4107     const char *zTbl = pOp->p3;
4108     BtCursor *pCur = 0;
4109     int fin = 0;
4110 
4111     rc = sqlite3BtreeCursor(pBt, pOp->p1, 0, 0, 0, &pCur);
4112     if( rc!=SQLITE_OK ){
4113       goto abort_due_to_error;
4114     }
4115     for(
4116       rc=sqlite3BtreeFirst(pCur, &fin);
4117       rc==SQLITE_OK && !fin;
4118       rc=sqlite3BtreeNext(pCur, &fin)
4119     ){
4120       i64 iKey;
4121       rc = sqlite3BtreeKeySize(pCur, &iKey);
4122       if( rc ){
4123         break;
4124       }
4125       iKey = keyToInt(iKey);
4126       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
4127     }
4128     sqlite3BtreeCloseCursor(pCur);
4129     if( rc!=SQLITE_OK ){
4130       goto abort_due_to_error;
4131     }
4132   }
4133 #endif
4134   rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
4135   break;
4136 }
4137 
4138 /* Opcode: CreateTable P1 * *
4139 **
4140 ** Allocate a new table in the main database file if P2==0 or in the
4141 ** auxiliary database file if P2==1.  Push the page number
4142 ** for the root page of the new table onto the stack.
4143 **
4144 ** The difference between a table and an index is this:  A table must
4145 ** have a 4-byte integer key and can have arbitrary data.  An index
4146 ** has an arbitrary key but no data.
4147 **
4148 ** See also: CreateIndex
4149 */
4150 /* Opcode: CreateIndex P1 * *
4151 **
4152 ** Allocate a new index in the main database file if P2==0 or in the
4153 ** auxiliary database file if P2==1.  Push the page number of the
4154 ** root page of the new index onto the stack.
4155 **
4156 ** See documentation on OP_CreateTable for additional information.
4157 */
4158 case OP_CreateIndex:
4159 case OP_CreateTable: {
4160   int pgno;
4161   int flags;
4162   Db *pDb;
4163   assert( pOp->p1>=0 && pOp->p1<db->nDb );
4164   pDb = &db->aDb[pOp->p1];
4165   assert( pDb->pBt!=0 );
4166   if( pOp->opcode==OP_CreateTable ){
4167     /* flags = BTREE_INTKEY; */
4168     flags = BTREE_LEAFDATA|BTREE_INTKEY;
4169   }else{
4170     flags = BTREE_ZERODATA;
4171   }
4172   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
4173   pTos++;
4174   if( rc==SQLITE_OK ){
4175     pTos->u.i = pgno;
4176     pTos->flags = MEM_Int;
4177   }else{
4178     pTos->flags = MEM_Null;
4179   }
4180   break;
4181 }
4182 
4183 /* Opcode: ParseSchema P1 P2 P3
4184 **
4185 ** Read and parse all entries from the SQLITE_MASTER table of database P1
4186 ** that match the WHERE clause P3.  P2 is the "force" flag.   Always do
4187 ** the parsing if P2 is true.  If P2 is false, then this routine is a
4188 ** no-op if the schema is not currently loaded.  In other words, if P2
4189 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
4190 ** schema is already loaded into the symbol table.
4191 **
4192 ** This opcode invokes the parser to create a new virtual machine,
4193 ** then runs the new virtual machine.  It is thus a reentrant opcode.
4194 */
4195 case OP_ParseSchema: {        /* no-push */
4196   char *zSql;
4197   int iDb = pOp->p1;
4198   const char *zMaster;
4199   InitData initData;
4200 
4201   assert( iDb>=0 && iDb<db->nDb );
4202   if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
4203     break;
4204   }
4205   zMaster = SCHEMA_TABLE(iDb);
4206   initData.db = db;
4207   initData.iDb = pOp->p1;
4208   initData.pzErrMsg = &p->zErrMsg;
4209   zSql = sqlite3MPrintf(
4210      "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
4211      db->aDb[iDb].zName, zMaster, pOp->p3);
4212   if( zSql==0 ) goto no_mem;
4213   sqlite3SafetyOff(db);
4214   assert( db->init.busy==0 );
4215   db->init.busy = 1;
4216   assert( !sqlite3MallocFailed() );
4217   rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
4218   if( rc==SQLITE_ABORT ) rc = initData.rc;
4219   sqliteFree(zSql);
4220   db->init.busy = 0;
4221   sqlite3SafetyOn(db);
4222   if( rc==SQLITE_NOMEM ){
4223     sqlite3FailedMalloc();
4224     goto no_mem;
4225   }
4226   break;
4227 }
4228 
4229 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
4230 /* Opcode: LoadAnalysis P1 * *
4231 **
4232 ** Read the sqlite_stat1 table for database P1 and load the content
4233 ** of that table into the internal index hash table.  This will cause
4234 ** the analysis to be used when preparing all subsequent queries.
4235 */
4236 case OP_LoadAnalysis: {        /* no-push */
4237   int iDb = pOp->p1;
4238   assert( iDb>=0 && iDb<db->nDb );
4239   rc = sqlite3AnalysisLoad(db, iDb);
4240   break;
4241 }
4242 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)  */
4243 
4244 /* Opcode: DropTable P1 * P3
4245 **
4246 ** Remove the internal (in-memory) data structures that describe
4247 ** the table named P3 in database P1.  This is called after a table
4248 ** is dropped in order to keep the internal representation of the
4249 ** schema consistent with what is on disk.
4250 */
4251 case OP_DropTable: {        /* no-push */
4252   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p3);
4253   break;
4254 }
4255 
4256 /* Opcode: DropIndex P1 * P3
4257 **
4258 ** Remove the internal (in-memory) data structures that describe
4259 ** the index named P3 in database P1.  This is called after an index
4260 ** is dropped in order to keep the internal representation of the
4261 ** schema consistent with what is on disk.
4262 */
4263 case OP_DropIndex: {        /* no-push */
4264   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p3);
4265   break;
4266 }
4267 
4268 /* Opcode: DropTrigger P1 * P3
4269 **
4270 ** Remove the internal (in-memory) data structures that describe
4271 ** the trigger named P3 in database P1.  This is called after a trigger
4272 ** is dropped in order to keep the internal representation of the
4273 ** schema consistent with what is on disk.
4274 */
4275 case OP_DropTrigger: {        /* no-push */
4276   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p3);
4277   break;
4278 }
4279 
4280 
4281 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
4282 /* Opcode: IntegrityCk P1 P2 *
4283 **
4284 ** Do an analysis of the currently open database.  Push onto the
4285 ** stack the text of an error message describing any problems.
4286 ** If no problems are found, push a NULL onto the stack.
4287 **
4288 ** P1 is the address of a memory cell that contains the maximum
4289 ** number of allowed errors.  At most mem[P1] errors will be reported.
4290 ** In other words, the analysis stops as soon as mem[P1] errors are
4291 ** seen.  Mem[P1] is updated with the number of errors remaining.
4292 **
4293 ** The root page numbers of all tables in the database are integer
4294 ** values on the stack.  This opcode pulls as many integers as it
4295 ** can off of the stack and uses those numbers as the root pages.
4296 **
4297 ** If P2 is not zero, the check is done on the auxiliary database
4298 ** file, not the main database file.
4299 **
4300 ** This opcode is used to implement the integrity_check pragma.
4301 */
4302 case OP_IntegrityCk: {
4303   int nRoot;
4304   int *aRoot;
4305   int j;
4306   int nErr;
4307   char *z;
4308   Mem *pnErr;
4309 
4310   for(nRoot=0; &pTos[-nRoot]>=p->aStack; nRoot++){
4311     if( (pTos[-nRoot].flags & MEM_Int)==0 ) break;
4312   }
4313   assert( nRoot>0 );
4314   aRoot = sqliteMallocRaw( sizeof(int)*(nRoot+1) );
4315   if( aRoot==0 ) goto no_mem;
4316   j = pOp->p1;
4317   assert( j>=0 && j<p->nMem );
4318   pnErr = &p->aMem[j];
4319   assert( (pnErr->flags & MEM_Int)!=0 );
4320   for(j=0; j<nRoot; j++){
4321     aRoot[j] = (pTos-j)->u.i;
4322   }
4323   aRoot[j] = 0;
4324   popStack(&pTos, nRoot);
4325   pTos++;
4326   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot,
4327                                  pnErr->u.i, &nErr);
4328   pnErr->u.i -= nErr;
4329   if( nErr==0 ){
4330     assert( z==0 );
4331     pTos->flags = MEM_Null;
4332   }else{
4333     pTos->z = z;
4334     pTos->n = strlen(z);
4335     pTos->flags = MEM_Str | MEM_Dyn | MEM_Term;
4336     pTos->xDel = 0;
4337   }
4338   pTos->enc = SQLITE_UTF8;
4339   sqlite3VdbeChangeEncoding(pTos, encoding);
4340   sqliteFree(aRoot);
4341   break;
4342 }
4343 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
4344 
4345 /* Opcode: FifoWrite * * *
4346 **
4347 ** Write the integer on the top of the stack
4348 ** into the Fifo.
4349 */
4350 case OP_FifoWrite: {        /* no-push */
4351   assert( pTos>=p->aStack );
4352   sqlite3VdbeMemIntegerify(pTos);
4353   sqlite3VdbeFifoPush(&p->sFifo, pTos->u.i);
4354   assert( (pTos->flags & MEM_Dyn)==0 );
4355   pTos--;
4356   break;
4357 }
4358 
4359 /* Opcode: FifoRead * P2 *
4360 **
4361 ** Attempt to read a single integer from the Fifo
4362 ** and push it onto the stack.  If the Fifo is empty
4363 ** push nothing but instead jump to P2.
4364 */
4365 case OP_FifoRead: {
4366   i64 v;
4367   CHECK_FOR_INTERRUPT;
4368   if( sqlite3VdbeFifoPop(&p->sFifo, &v)==SQLITE_DONE ){
4369     pc = pOp->p2 - 1;
4370   }else{
4371     pTos++;
4372     pTos->u.i = v;
4373     pTos->flags = MEM_Int;
4374   }
4375   break;
4376 }
4377 
4378 #ifndef SQLITE_OMIT_TRIGGER
4379 /* Opcode: ContextPush * * *
4380 **
4381 ** Save the current Vdbe context such that it can be restored by a ContextPop
4382 ** opcode. The context stores the last insert row id, the last statement change
4383 ** count, and the current statement change count.
4384 */
4385 case OP_ContextPush: {        /* no-push */
4386   int i = p->contextStackTop++;
4387   Context *pContext;
4388 
4389   assert( i>=0 );
4390   /* FIX ME: This should be allocated as part of the vdbe at compile-time */
4391   if( i>=p->contextStackDepth ){
4392     p->contextStackDepth = i+1;
4393     p->contextStack = sqliteReallocOrFree(p->contextStack,
4394                                           sizeof(Context)*(i+1));
4395     if( p->contextStack==0 ) goto no_mem;
4396   }
4397   pContext = &p->contextStack[i];
4398   pContext->lastRowid = db->lastRowid;
4399   pContext->nChange = p->nChange;
4400   pContext->sFifo = p->sFifo;
4401   sqlite3VdbeFifoInit(&p->sFifo);
4402   break;
4403 }
4404 
4405 /* Opcode: ContextPop * * *
4406 **
4407 ** Restore the Vdbe context to the state it was in when contextPush was last
4408 ** executed. The context stores the last insert row id, the last statement
4409 ** change count, and the current statement change count.
4410 */
4411 case OP_ContextPop: {        /* no-push */
4412   Context *pContext = &p->contextStack[--p->contextStackTop];
4413   assert( p->contextStackTop>=0 );
4414   db->lastRowid = pContext->lastRowid;
4415   p->nChange = pContext->nChange;
4416   sqlite3VdbeFifoClear(&p->sFifo);
4417   p->sFifo = pContext->sFifo;
4418   break;
4419 }
4420 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
4421 
4422 /* Opcode: MemStore P1 P2 *
4423 **
4424 ** Write the top of the stack into memory location P1.
4425 ** P1 should be a small integer since space is allocated
4426 ** for all memory locations between 0 and P1 inclusive.
4427 **
4428 ** After the data is stored in the memory location, the
4429 ** stack is popped once if P2 is 1.  If P2 is zero, then
4430 ** the original data remains on the stack.
4431 */
4432 case OP_MemStore: {        /* no-push */
4433   assert( pTos>=p->aStack );
4434   assert( pOp->p1>=0 && pOp->p1<p->nMem );
4435   rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], pTos);
4436   pTos--;
4437 
4438   /* If P2 is 0 then fall thru to the next opcode, OP_MemLoad, that will
4439   ** restore the top of the stack to its original value.
4440   */
4441   if( pOp->p2 ){
4442     break;
4443   }
4444 }
4445 /* Opcode: MemLoad P1 * *
4446 **
4447 ** Push a copy of the value in memory location P1 onto the stack.
4448 **
4449 ** If the value is a string, then the value pushed is a pointer to
4450 ** the string that is stored in the memory location.  If the memory
4451 ** location is subsequently changed (using OP_MemStore) then the
4452 ** value pushed onto the stack will change too.
4453 */
4454 case OP_MemLoad: {
4455   int i = pOp->p1;
4456   assert( i>=0 && i<p->nMem );
4457   pTos++;
4458   sqlite3VdbeMemShallowCopy(pTos, &p->aMem[i], MEM_Ephem);
4459   break;
4460 }
4461 
4462 #ifndef SQLITE_OMIT_AUTOINCREMENT
4463 /* Opcode: MemMax P1 * *
4464 **
4465 ** Set the value of memory cell P1 to the maximum of its current value
4466 ** and the value on the top of the stack.  The stack is unchanged.
4467 **
4468 ** This instruction throws an error if the memory cell is not initially
4469 ** an integer.
4470 */
4471 case OP_MemMax: {        /* no-push */
4472   int i = pOp->p1;
4473   Mem *pMem;
4474   assert( pTos>=p->aStack );
4475   assert( i>=0 && i<p->nMem );
4476   pMem = &p->aMem[i];
4477   sqlite3VdbeMemIntegerify(pMem);
4478   sqlite3VdbeMemIntegerify(pTos);
4479   if( pMem->u.i<pTos->u.i){
4480     pMem->u.i = pTos->u.i;
4481   }
4482   break;
4483 }
4484 #endif /* SQLITE_OMIT_AUTOINCREMENT */
4485 
4486 /* Opcode: MemIncr P1 P2 *
4487 **
4488 ** Increment the integer valued memory cell P2 by the value in P1.
4489 **
4490 ** It is illegal to use this instruction on a memory cell that does
4491 ** not contain an integer.  An assertion fault will result if you try.
4492 */
4493 case OP_MemIncr: {        /* no-push */
4494   int i = pOp->p2;
4495   Mem *pMem;
4496   assert( i>=0 && i<p->nMem );
4497   pMem = &p->aMem[i];
4498   assert( pMem->flags==MEM_Int );
4499   pMem->u.i += pOp->p1;
4500   break;
4501 }
4502 
4503 /* Opcode: IfMemPos P1 P2 *
4504 **
4505 ** If the value of memory cell P1 is 1 or greater, jump to P2.
4506 **
4507 ** It is illegal to use this instruction on a memory cell that does
4508 ** not contain an integer.  An assertion fault will result if you try.
4509 */
4510 case OP_IfMemPos: {        /* no-push */
4511   int i = pOp->p1;
4512   Mem *pMem;
4513   assert( i>=0 && i<p->nMem );
4514   pMem = &p->aMem[i];
4515   assert( pMem->flags==MEM_Int );
4516   if( pMem->u.i>0 ){
4517      pc = pOp->p2 - 1;
4518   }
4519   break;
4520 }
4521 
4522 /* Opcode: IfMemNeg P1 P2 *
4523 **
4524 ** If the value of memory cell P1 is less than zero, jump to P2.
4525 **
4526 ** It is illegal to use this instruction on a memory cell that does
4527 ** not contain an integer.  An assertion fault will result if you try.
4528 */
4529 case OP_IfMemNeg: {        /* no-push */
4530   int i = pOp->p1;
4531   Mem *pMem;
4532   assert( i>=0 && i<p->nMem );
4533   pMem = &p->aMem[i];
4534   assert( pMem->flags==MEM_Int );
4535   if( pMem->u.i<0 ){
4536      pc = pOp->p2 - 1;
4537   }
4538   break;
4539 }
4540 
4541 /* Opcode: IfMemZero P1 P2 *
4542 **
4543 ** If the value of memory cell P1 is exactly 0, jump to P2.
4544 **
4545 ** It is illegal to use this instruction on a memory cell that does
4546 ** not contain an integer.  An assertion fault will result if you try.
4547 */
4548 case OP_IfMemZero: {        /* no-push */
4549   int i = pOp->p1;
4550   Mem *pMem;
4551   assert( i>=0 && i<p->nMem );
4552   pMem = &p->aMem[i];
4553   assert( pMem->flags==MEM_Int );
4554   if( pMem->u.i==0 ){
4555      pc = pOp->p2 - 1;
4556   }
4557   break;
4558 }
4559 
4560 /* Opcode: MemNull P1 * *
4561 **
4562 ** Store a NULL in memory cell P1
4563 */
4564 case OP_MemNull: {
4565   assert( pOp->p1>=0 && pOp->p1<p->nMem );
4566   sqlite3VdbeMemSetNull(&p->aMem[pOp->p1]);
4567   break;
4568 }
4569 
4570 /* Opcode: MemInt P1 P2 *
4571 **
4572 ** Store the integer value P1 in memory cell P2.
4573 */
4574 case OP_MemInt: {
4575   assert( pOp->p2>=0 && pOp->p2<p->nMem );
4576   sqlite3VdbeMemSetInt64(&p->aMem[pOp->p2], pOp->p1);
4577   break;
4578 }
4579 
4580 /* Opcode: MemMove P1 P2 *
4581 **
4582 ** Move the content of memory cell P2 over to memory cell P1.
4583 ** Any prior content of P1 is erased.  Memory cell P2 is left
4584 ** containing a NULL.
4585 */
4586 case OP_MemMove: {
4587   assert( pOp->p1>=0 && pOp->p1<p->nMem );
4588   assert( pOp->p2>=0 && pOp->p2<p->nMem );
4589   rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], &p->aMem[pOp->p2]);
4590   break;
4591 }
4592 
4593 /* Opcode: AggStep P1 P2 P3
4594 **
4595 ** Execute the step function for an aggregate.  The
4596 ** function has P2 arguments.  P3 is a pointer to the FuncDef
4597 ** structure that specifies the function.  Use memory location
4598 ** P1 as the accumulator.
4599 **
4600 ** The P2 arguments are popped from the stack.
4601 */
4602 case OP_AggStep: {        /* no-push */
4603   int n = pOp->p2;
4604   int i;
4605   Mem *pMem, *pRec;
4606   sqlite3_context ctx;
4607   sqlite3_value **apVal;
4608 
4609   assert( n>=0 );
4610   pRec = &pTos[1-n];
4611   assert( pRec>=p->aStack );
4612   apVal = p->apArg;
4613   assert( apVal || n==0 );
4614   for(i=0; i<n; i++, pRec++){
4615     apVal[i] = pRec;
4616     storeTypeInfo(pRec, encoding);
4617   }
4618   ctx.pFunc = (FuncDef*)pOp->p3;
4619   assert( pOp->p1>=0 && pOp->p1<p->nMem );
4620   ctx.pMem = pMem = &p->aMem[pOp->p1];
4621   pMem->n++;
4622   ctx.s.flags = MEM_Null;
4623   ctx.s.z = 0;
4624   ctx.s.xDel = 0;
4625   ctx.isError = 0;
4626   ctx.pColl = 0;
4627   if( ctx.pFunc->needCollSeq ){
4628     assert( pOp>p->aOp );
4629     assert( pOp[-1].p3type==P3_COLLSEQ );
4630     assert( pOp[-1].opcode==OP_CollSeq );
4631     ctx.pColl = (CollSeq *)pOp[-1].p3;
4632   }
4633   (ctx.pFunc->xStep)(&ctx, n, apVal);
4634   popStack(&pTos, n);
4635   if( ctx.isError ){
4636     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
4637     rc = SQLITE_ERROR;
4638   }
4639   sqlite3VdbeMemRelease(&ctx.s);
4640   break;
4641 }
4642 
4643 /* Opcode: AggFinal P1 P2 P3
4644 **
4645 ** Execute the finalizer function for an aggregate.  P1 is
4646 ** the memory location that is the accumulator for the aggregate.
4647 **
4648 ** P2 is the number of arguments that the step function takes and
4649 ** P3 is a pointer to the FuncDef for this function.  The P2
4650 ** argument is not used by this opcode.  It is only there to disambiguate
4651 ** functions that can take varying numbers of arguments.  The
4652 ** P3 argument is only needed for the degenerate case where
4653 ** the step function was not previously called.
4654 */
4655 case OP_AggFinal: {        /* no-push */
4656   Mem *pMem;
4657   assert( pOp->p1>=0 && pOp->p1<p->nMem );
4658   pMem = &p->aMem[pOp->p1];
4659   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
4660   rc = sqlite3VdbeMemFinalize(pMem, (FuncDef*)pOp->p3);
4661   if( rc==SQLITE_ERROR ){
4662     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pMem), (char*)0);
4663   }
4664   if( sqlite3VdbeMemTooBig(pMem) ){
4665     goto too_big;
4666   }
4667   break;
4668 }
4669 
4670 
4671 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
4672 /* Opcode: Vacuum * * *
4673 **
4674 ** Vacuum the entire database.  This opcode will cause other virtual
4675 ** machines to be created and run.  It may not be called from within
4676 ** a transaction.
4677 */
4678 case OP_Vacuum: {        /* no-push */
4679   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4680   rc = sqlite3RunVacuum(&p->zErrMsg, db);
4681   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4682   break;
4683 }
4684 #endif
4685 
4686 #if !defined(SQLITE_OMIT_AUTOVACUUM)
4687 /* Opcode: IncrVacuum P1 P2 *
4688 **
4689 ** Perform a single step of the incremental vacuum procedure on
4690 ** the P1 database. If the vacuum has finished, jump to instruction
4691 ** P2. Otherwise, fall through to the next instruction.
4692 */
4693 case OP_IncrVacuum: {        /* no-push */
4694   Btree *pBt;
4695 
4696   assert( pOp->p1>=0 && pOp->p1<db->nDb );
4697   pBt = db->aDb[pOp->p1].pBt;
4698   rc = sqlite3BtreeIncrVacuum(pBt);
4699   if( rc==SQLITE_DONE ){
4700     pc = pOp->p2 - 1;
4701     rc = SQLITE_OK;
4702   }
4703   break;
4704 }
4705 #endif
4706 
4707 /* Opcode: Expire P1 * *
4708 **
4709 ** Cause precompiled statements to become expired. An expired statement
4710 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
4711 ** (via sqlite3_step()).
4712 **
4713 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
4714 ** then only the currently executing statement is affected.
4715 */
4716 case OP_Expire: {        /* no-push */
4717   if( !pOp->p1 ){
4718     sqlite3ExpirePreparedStatements(db);
4719   }else{
4720     p->expired = 1;
4721   }
4722   break;
4723 }
4724 
4725 #ifndef SQLITE_OMIT_SHARED_CACHE
4726 /* Opcode: TableLock P1 P2 P3
4727 **
4728 ** Obtain a lock on a particular table. This instruction is only used when
4729 ** the shared-cache feature is enabled.
4730 **
4731 ** If P1 is not negative, then it is the index of the database
4732 ** in sqlite3.aDb[] and a read-lock is required. If P1 is negative, a
4733 ** write-lock is required. In this case the index of the database is the
4734 ** absolute value of P1 minus one (iDb = abs(P1) - 1;) and a write-lock is
4735 ** required.
4736 **
4737 ** P2 contains the root-page of the table to lock.
4738 **
4739 ** P3 contains a pointer to the name of the table being locked. This is only
4740 ** used to generate an error message if the lock cannot be obtained.
4741 */
4742 case OP_TableLock: {        /* no-push */
4743   int p1 = pOp->p1;
4744   u8 isWriteLock = (p1<0);
4745   if( isWriteLock ){
4746     p1 = (-1*p1)-1;
4747   }
4748   rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
4749   if( rc==SQLITE_LOCKED ){
4750     const char *z = (const char *)pOp->p3;
4751     sqlite3SetString(&p->zErrMsg, "database table is locked: ", z, (char*)0);
4752   }
4753   break;
4754 }
4755 #endif /* SQLITE_OMIT_SHARED_CACHE */
4756 
4757 #ifndef SQLITE_OMIT_VIRTUALTABLE
4758 /* Opcode: VBegin * * P3
4759 **
4760 ** P3 a pointer to an sqlite3_vtab structure. Call the xBegin method
4761 ** for that table.
4762 */
4763 case OP_VBegin: {   /* no-push */
4764   rc = sqlite3VtabBegin(db, (sqlite3_vtab *)pOp->p3);
4765   break;
4766 }
4767 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4768 
4769 #ifndef SQLITE_OMIT_VIRTUALTABLE
4770 /* Opcode: VCreate P1 * P3
4771 **
4772 ** P3 is the name of a virtual table in database P1. Call the xCreate method
4773 ** for that table.
4774 */
4775 case OP_VCreate: {   /* no-push */
4776   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p3, &p->zErrMsg);
4777   break;
4778 }
4779 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4780 
4781 #ifndef SQLITE_OMIT_VIRTUALTABLE
4782 /* Opcode: VDestroy P1 * P3
4783 **
4784 ** P3 is the name of a virtual table in database P1.  Call the xDestroy method
4785 ** of that table.
4786 */
4787 case OP_VDestroy: {   /* no-push */
4788   p->inVtabMethod = 2;
4789   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p3);
4790   p->inVtabMethod = 0;
4791   break;
4792 }
4793 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4794 
4795 #ifndef SQLITE_OMIT_VIRTUALTABLE
4796 /* Opcode: VOpen P1 * P3
4797 **
4798 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
4799 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
4800 ** table and stores that cursor in P1.
4801 */
4802 case OP_VOpen: {   /* no-push */
4803   Cursor *pCur = 0;
4804   sqlite3_vtab_cursor *pVtabCursor = 0;
4805 
4806   sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
4807   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
4808 
4809   assert(pVtab && pModule);
4810   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4811   rc = pModule->xOpen(pVtab, &pVtabCursor);
4812   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4813   if( SQLITE_OK==rc ){
4814     /* Initialise sqlite3_vtab_cursor base class */
4815     pVtabCursor->pVtab = pVtab;
4816 
4817     /* Initialise vdbe cursor object */
4818     pCur = allocateCursor(p, pOp->p1, -1);
4819     if( pCur ){
4820       pCur->pVtabCursor = pVtabCursor;
4821       pCur->pModule = pVtabCursor->pVtab->pModule;
4822     }else{
4823       pModule->xClose(pVtabCursor);
4824     }
4825   }
4826   break;
4827 }
4828 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4829 
4830 #ifndef SQLITE_OMIT_VIRTUALTABLE
4831 /* Opcode: VFilter P1 P2 P3
4832 **
4833 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
4834 ** the filtered result set is empty.
4835 **
4836 ** P3 is either NULL or a string that was generated by the xBestIndex
4837 ** method of the module.  The interpretation of the P3 string is left
4838 ** to the module implementation.
4839 **
4840 ** This opcode invokes the xFilter method on the virtual table specified
4841 ** by P1.  The integer query plan parameter to xFilter is the top of the
4842 ** stack.  Next down on the stack is the argc parameter.  Beneath the
4843 ** next of stack are argc additional parameters which are passed to
4844 ** xFilter as argv. The topmost parameter (i.e. 3rd element popped from
4845 ** the stack) becomes argv[argc-1] when passed to xFilter.
4846 **
4847 ** The integer query plan parameter, argc, and all argv stack values
4848 ** are popped from the stack before this instruction completes.
4849 **
4850 ** A jump is made to P2 if the result set after filtering would be
4851 ** empty.
4852 */
4853 case OP_VFilter: {   /* no-push */
4854   int nArg;
4855 
4856   const sqlite3_module *pModule;
4857 
4858   Cursor *pCur = p->apCsr[pOp->p1];
4859   assert( pCur->pVtabCursor );
4860   pModule = pCur->pVtabCursor->pVtab->pModule;
4861 
4862   /* Grab the index number and argc parameters off the top of the stack. */
4863   assert( (&pTos[-1])>=p->aStack );
4864   assert( (pTos[0].flags&MEM_Int)!=0 && pTos[-1].flags==MEM_Int );
4865   nArg = pTos[-1].u.i;
4866 
4867   /* Invoke the xFilter method */
4868   {
4869     int res = 0;
4870     int i;
4871     Mem **apArg = p->apArg;
4872     for(i = 0; i<nArg; i++){
4873       apArg[i] = &pTos[i+1-2-nArg];
4874       storeTypeInfo(apArg[i], 0);
4875     }
4876 
4877     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4878     p->inVtabMethod = 1;
4879     rc = pModule->xFilter(pCur->pVtabCursor, pTos->u.i, pOp->p3, nArg, apArg);
4880     p->inVtabMethod = 0;
4881     if( rc==SQLITE_OK ){
4882       res = pModule->xEof(pCur->pVtabCursor);
4883     }
4884     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4885 
4886     if( res ){
4887       pc = pOp->p2 - 1;
4888     }
4889   }
4890 
4891   /* Pop the index number, argc value and parameters off the stack */
4892   popStack(&pTos, 2+nArg);
4893   break;
4894 }
4895 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4896 
4897 #ifndef SQLITE_OMIT_VIRTUALTABLE
4898 /* Opcode: VRowid P1 * *
4899 **
4900 ** Push an integer onto the stack which is the rowid of
4901 ** the virtual-table that the P1 cursor is pointing to.
4902 */
4903 case OP_VRowid: {
4904   const sqlite3_module *pModule;
4905 
4906   Cursor *pCur = p->apCsr[pOp->p1];
4907   assert( pCur->pVtabCursor );
4908   pModule = pCur->pVtabCursor->pVtab->pModule;
4909   if( pModule->xRowid==0 ){
4910     sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xRowid", 0);
4911     rc = SQLITE_ERROR;
4912   } else {
4913     sqlite_int64 iRow;
4914 
4915     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4916     rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
4917     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4918 
4919     pTos++;
4920     pTos->flags = MEM_Int;
4921     pTos->u.i = iRow;
4922   }
4923 
4924   break;
4925 }
4926 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4927 
4928 #ifndef SQLITE_OMIT_VIRTUALTABLE
4929 /* Opcode: VColumn P1 P2 *
4930 **
4931 ** Push onto the stack the value of the P2-th column of
4932 ** the row of the virtual-table that the P1 cursor is pointing to.
4933 */
4934 case OP_VColumn: {
4935   const sqlite3_module *pModule;
4936 
4937   Cursor *pCur = p->apCsr[pOp->p1];
4938   assert( pCur->pVtabCursor );
4939   pModule = pCur->pVtabCursor->pVtab->pModule;
4940   if( pModule->xColumn==0 ){
4941     sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xColumn", 0);
4942     rc = SQLITE_ERROR;
4943   } else {
4944     sqlite3_context sContext;
4945     memset(&sContext, 0, sizeof(sContext));
4946     sContext.s.flags = MEM_Null;
4947     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4948     rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
4949 
4950     /* Copy the result of the function to the top of the stack. We
4951     ** do this regardless of whether or not an error occured to ensure any
4952     ** dynamic allocation in sContext.s (a Mem struct) is  released.
4953     */
4954     sqlite3VdbeChangeEncoding(&sContext.s, encoding);
4955     pTos++;
4956     pTos->flags = 0;
4957     sqlite3VdbeMemMove(pTos, &sContext.s);
4958 
4959     if( sqlite3SafetyOn(db) ){
4960       goto abort_due_to_misuse;
4961     }
4962     if( sqlite3VdbeMemTooBig(pTos) ){
4963       goto too_big;
4964     }
4965   }
4966 
4967   break;
4968 }
4969 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4970 
4971 #ifndef SQLITE_OMIT_VIRTUALTABLE
4972 /* Opcode: VNext P1 P2 *
4973 **
4974 ** Advance virtual table P1 to the next row in its result set and
4975 ** jump to instruction P2.  Or, if the virtual table has reached
4976 ** the end of its result set, then fall through to the next instruction.
4977 */
4978 case OP_VNext: {   /* no-push */
4979   const sqlite3_module *pModule;
4980   int res = 0;
4981 
4982   Cursor *pCur = p->apCsr[pOp->p1];
4983   assert( pCur->pVtabCursor );
4984   pModule = pCur->pVtabCursor->pVtab->pModule;
4985   if( pModule->xNext==0 ){
4986     sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xNext", 0);
4987     rc = SQLITE_ERROR;
4988   } else {
4989     /* Invoke the xNext() method of the module. There is no way for the
4990     ** underlying implementation to return an error if one occurs during
4991     ** xNext(). Instead, if an error occurs, true is returned (indicating that
4992     ** data is available) and the error code returned when xColumn or
4993     ** some other method is next invoked on the save virtual table cursor.
4994     */
4995     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4996     p->inVtabMethod = 1;
4997     rc = pModule->xNext(pCur->pVtabCursor);
4998     p->inVtabMethod = 0;
4999     if( rc==SQLITE_OK ){
5000       res = pModule->xEof(pCur->pVtabCursor);
5001     }
5002     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
5003 
5004     if( !res ){
5005       /* If there is data, jump to P2 */
5006       pc = pOp->p2 - 1;
5007     }
5008   }
5009 
5010   break;
5011 }
5012 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5013 
5014 #ifndef SQLITE_OMIT_VIRTUALTABLE
5015 /* Opcode: VRename * * P3
5016 **
5017 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
5018 ** This opcode invokes the corresponding xRename method. The value
5019 ** on the top of the stack is popped and passed as the zName argument
5020 ** to the xRename method.
5021 */
5022 case OP_VRename: {   /* no-push */
5023   sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
5024   assert( pVtab->pModule->xRename );
5025 
5026   Stringify(pTos, encoding);
5027 
5028   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
5029   sqlite3VtabLock(pVtab);
5030   rc = pVtab->pModule->xRename(pVtab, pTos->z);
5031   sqlite3VtabUnlock(db, pVtab);
5032   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
5033 
5034   popStack(&pTos, 1);
5035   break;
5036 }
5037 #endif
5038 
5039 #ifndef SQLITE_OMIT_VIRTUALTABLE
5040 /* Opcode: VUpdate P1 P2 P3
5041 **
5042 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
5043 ** This opcode invokes the corresponding xUpdate method. P2 values
5044 ** are taken from the stack to pass to the xUpdate invocation. The
5045 ** value on the top of the stack corresponds to the p2th element
5046 ** of the argv array passed to xUpdate.
5047 **
5048 ** The xUpdate method will do a DELETE or an INSERT or both.
5049 ** The argv[0] element (which corresponds to the P2-th element down
5050 ** on the stack) is the rowid of a row to delete.  If argv[0] is
5051 ** NULL then no deletion occurs.  The argv[1] element is the rowid
5052 ** of the new row.  This can be NULL to have the virtual table
5053 ** select the new rowid for itself.  The higher elements in the
5054 ** stack are the values of columns in the new row.
5055 **
5056 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
5057 ** a row to delete.
5058 **
5059 ** P1 is a boolean flag. If it is set to true and the xUpdate call
5060 ** is successful, then the value returned by sqlite3_last_insert_rowid()
5061 ** is set to the value of the rowid for the row just inserted.
5062 */
5063 case OP_VUpdate: {   /* no-push */
5064   sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
5065   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
5066   int nArg = pOp->p2;
5067   assert( pOp->p3type==P3_VTAB );
5068   if( pModule->xUpdate==0 ){
5069     sqlite3SetString(&p->zErrMsg, "read-only table", 0);
5070     rc = SQLITE_ERROR;
5071   }else{
5072     int i;
5073     sqlite_int64 rowid;
5074     Mem **apArg = p->apArg;
5075     Mem *pX = &pTos[1-nArg];
5076     for(i = 0; i<nArg; i++, pX++){
5077       storeTypeInfo(pX, 0);
5078       apArg[i] = pX;
5079     }
5080     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
5081     sqlite3VtabLock(pVtab);
5082     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
5083     sqlite3VtabUnlock(db, pVtab);
5084     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
5085     if( pOp->p1 && rc==SQLITE_OK ){
5086       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
5087       db->lastRowid = rowid;
5088     }
5089   }
5090   popStack(&pTos, nArg);
5091   break;
5092 }
5093 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5094 
5095 /* An other opcode is illegal...
5096 */
5097 default: {
5098   assert( 0 );
5099   break;
5100 }
5101 
5102 /*****************************************************************************
5103 ** The cases of the switch statement above this line should all be indented
5104 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
5105 ** readability.  From this point on down, the normal indentation rules are
5106 ** restored.
5107 *****************************************************************************/
5108     }
5109 
5110     /* Make sure the stack limit was not exceeded */
5111     assert( pTos<=pStackLimit );
5112 
5113 #ifdef VDBE_PROFILE
5114     {
5115       long long elapse = hwtime() - start;
5116       pOp->cycles += elapse;
5117       pOp->cnt++;
5118 #if 0
5119         fprintf(stdout, "%10lld ", elapse);
5120         sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
5121 #endif
5122     }
5123 #endif
5124 
5125 #ifdef SQLITE_TEST
5126     /* Keep track of the size of the largest BLOB or STR that has appeared
5127     ** on the top of the VDBE stack.
5128     */
5129     if( pTos>=p->aStack && (pTos->flags & (MEM_Blob|MEM_Str))!=0
5130          && pTos->n>sqlite3_max_blobsize ){
5131       sqlite3_max_blobsize = pTos->n;
5132     }
5133 #endif
5134 
5135     /* The following code adds nothing to the actual functionality
5136     ** of the program.  It is only here for testing and debugging.
5137     ** On the other hand, it does burn CPU cycles every time through
5138     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
5139     */
5140 #ifndef NDEBUG
5141     /* Sanity checking on the top element of the stack. If the previous
5142     ** instruction was VNoChange, then the flags field of the top
5143     ** of the stack is set to 0. This is technically invalid for a memory
5144     ** cell, so avoid calling MemSanity() in this case.
5145     */
5146     if( pTos>=p->aStack && pTos->flags ){
5147       sqlite3VdbeMemSanity(pTos);
5148       assert( !sqlite3VdbeMemTooBig(pTos) );
5149     }
5150     assert( pc>=-1 && pc<p->nOp );
5151 
5152 #ifdef SQLITE_DEBUG
5153     /* Code for tracing the vdbe stack. */
5154     if( p->trace && pTos>=p->aStack ){
5155       int i;
5156       fprintf(p->trace, "Stack:");
5157       for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
5158         if( pTos[i].flags & MEM_Null ){
5159           fprintf(p->trace, " NULL");
5160         }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
5161           fprintf(p->trace, " si:%lld", pTos[i].u.i);
5162         }else if( pTos[i].flags & MEM_Int ){
5163           fprintf(p->trace, " i:%lld", pTos[i].u.i);
5164         }else if( pTos[i].flags & MEM_Real ){
5165           fprintf(p->trace, " r:%g", pTos[i].r);
5166         }else{
5167           char zBuf[200];
5168           sqlite3VdbeMemPrettyPrint(&pTos[i], zBuf);
5169           fprintf(p->trace, " ");
5170           fprintf(p->trace, "%s", zBuf);
5171         }
5172       }
5173       if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
5174       fprintf(p->trace,"\n");
5175     }
5176 #endif  /* SQLITE_DEBUG */
5177 #endif  /* NDEBUG */
5178   }  /* The end of the for(;;) loop the loops through opcodes */
5179 
5180   /* If we reach this point, it means that execution is finished.
5181   */
5182 vdbe_halt:
5183   if( rc ){
5184     p->rc = rc;
5185     rc = SQLITE_ERROR;
5186   }else{
5187     rc = SQLITE_DONE;
5188   }
5189   sqlite3VdbeHalt(p);
5190   p->pTos = pTos;
5191   return rc;
5192 
5193   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
5194   ** is encountered.
5195   */
5196 too_big:
5197   sqlite3SetString(&p->zErrMsg, "string or blob too big", (char*)0);
5198   rc = SQLITE_TOOBIG;
5199   goto vdbe_halt;
5200 
5201   /* Jump to here if a malloc() fails.
5202   */
5203 no_mem:
5204   sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0);
5205   rc = SQLITE_NOMEM;
5206   goto vdbe_halt;
5207 
5208   /* Jump to here for an SQLITE_MISUSE error.
5209   */
5210 abort_due_to_misuse:
5211   rc = SQLITE_MISUSE;
5212   /* Fall thru into abort_due_to_error */
5213 
5214   /* Jump to here for any other kind of fatal error.  The "rc" variable
5215   ** should hold the error number.
5216   */
5217 abort_due_to_error:
5218   if( p->zErrMsg==0 ){
5219     if( sqlite3MallocFailed() ) rc = SQLITE_NOMEM;
5220     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
5221   }
5222   goto vdbe_halt;
5223 
5224   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
5225   ** flag.
5226   */
5227 abort_due_to_interrupt:
5228   assert( db->u1.isInterrupted );
5229   if( db->magic!=SQLITE_MAGIC_BUSY ){
5230     rc = SQLITE_MISUSE;
5231   }else{
5232     rc = SQLITE_INTERRUPT;
5233   }
5234   p->rc = rc;
5235   sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
5236   goto vdbe_halt;
5237 }
5238