xref: /sqlite-3.40.0/src/vdbe.c (revision 5665b3ea)
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.630 2007/06/24 16:11:03 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         b /= a;
1157         break;
1158       }
1159       default: {
1160         if( a==0 ) goto divide_by_zero;
1161         b %= a;
1162         break;
1163       }
1164     }
1165     Release(pTos);
1166     pTos--;
1167     Release(pTos);
1168     pTos->u.i = b;
1169     pTos->flags = MEM_Int;
1170   }else{
1171     double a, b;
1172     a = sqlite3VdbeRealValue(pTos);
1173     b = sqlite3VdbeRealValue(pNos);
1174     switch( pOp->opcode ){
1175       case OP_Add:         b += a;       break;
1176       case OP_Subtract:    b -= a;       break;
1177       case OP_Multiply:    b *= a;       break;
1178       case OP_Divide: {
1179         if( a==0.0 ) goto divide_by_zero;
1180         b /= a;
1181         break;
1182       }
1183       default: {
1184         i64 ia = (i64)a;
1185         i64 ib = (i64)b;
1186         if( ia==0 ) goto divide_by_zero;
1187         b = ib % ia;
1188         break;
1189       }
1190     }
1191     if( sqlite3_isnan(b) ){
1192       goto divide_by_zero;
1193     }
1194     Release(pTos);
1195     pTos--;
1196     Release(pTos);
1197     pTos->r = b;
1198     pTos->flags = MEM_Real;
1199     if( (flags & MEM_Real)==0 ){
1200       sqlite3VdbeIntegerAffinity(pTos);
1201     }
1202   }
1203   break;
1204 
1205 divide_by_zero:
1206   Release(pTos);
1207   pTos--;
1208   Release(pTos);
1209   pTos->flags = MEM_Null;
1210   break;
1211 }
1212 
1213 /* Opcode: CollSeq * * P3
1214 **
1215 ** P3 is a pointer to a CollSeq struct. If the next call to a user function
1216 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1217 ** be returned. This is used by the built-in min(), max() and nullif()
1218 ** functions.
1219 **
1220 ** The interface used by the implementation of the aforementioned functions
1221 ** to retrieve the collation sequence set by this opcode is not available
1222 ** publicly, only to user functions defined in func.c.
1223 */
1224 case OP_CollSeq: {             /* no-push */
1225   assert( pOp->p3type==P3_COLLSEQ );
1226   break;
1227 }
1228 
1229 /* Opcode: Function P1 P2 P3
1230 **
1231 ** Invoke a user function (P3 is a pointer to a Function structure that
1232 ** defines the function) with P2 arguments taken from the stack.  Pop all
1233 ** arguments from the stack and push back the result.
1234 **
1235 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
1236 ** function was determined to be constant at compile time. If the first
1237 ** argument was constant then bit 0 of P1 is set. This is used to determine
1238 ** whether meta data associated with a user function argument using the
1239 ** sqlite3_set_auxdata() API may be safely retained until the next
1240 ** invocation of this opcode.
1241 **
1242 ** See also: AggStep and AggFinal
1243 */
1244 case OP_Function: {
1245   int i;
1246   Mem *pArg;
1247   sqlite3_context ctx;
1248   sqlite3_value **apVal;
1249   int n = pOp->p2;
1250 
1251   apVal = p->apArg;
1252   assert( apVal || n==0 );
1253 
1254   pArg = &pTos[1-n];
1255   for(i=0; i<n; i++, pArg++){
1256     apVal[i] = pArg;
1257     storeTypeInfo(pArg, encoding);
1258   }
1259 
1260   assert( pOp->p3type==P3_FUNCDEF || pOp->p3type==P3_VDBEFUNC );
1261   if( pOp->p3type==P3_FUNCDEF ){
1262     ctx.pFunc = (FuncDef*)pOp->p3;
1263     ctx.pVdbeFunc = 0;
1264   }else{
1265     ctx.pVdbeFunc = (VdbeFunc*)pOp->p3;
1266     ctx.pFunc = ctx.pVdbeFunc->pFunc;
1267   }
1268 
1269   ctx.s.flags = MEM_Null;
1270   ctx.s.z = 0;
1271   ctx.s.xDel = 0;
1272   ctx.isError = 0;
1273   if( ctx.pFunc->needCollSeq ){
1274     assert( pOp>p->aOp );
1275     assert( pOp[-1].p3type==P3_COLLSEQ );
1276     assert( pOp[-1].opcode==OP_CollSeq );
1277     ctx.pColl = (CollSeq *)pOp[-1].p3;
1278   }
1279   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
1280   (*ctx.pFunc->xFunc)(&ctx, n, apVal);
1281   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
1282   if( sqlite3MallocFailed() ) goto no_mem;
1283   popStack(&pTos, n);
1284 
1285   /* If any auxilary data functions have been called by this user function,
1286   ** immediately call the destructor for any non-static values.
1287   */
1288   if( ctx.pVdbeFunc ){
1289     sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
1290     pOp->p3 = (char *)ctx.pVdbeFunc;
1291     pOp->p3type = P3_VDBEFUNC;
1292   }
1293 
1294   /* If the function returned an error, throw an exception */
1295   if( ctx.isError ){
1296     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
1297     rc = SQLITE_ERROR;
1298   }
1299 
1300   /* Copy the result of the function to the top of the stack */
1301   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
1302   pTos++;
1303   pTos->flags = 0;
1304   sqlite3VdbeMemMove(pTos, &ctx.s);
1305   if( sqlite3VdbeMemTooBig(pTos) ){
1306     goto too_big;
1307   }
1308   break;
1309 }
1310 
1311 /* Opcode: BitAnd * * *
1312 **
1313 ** Pop the top two elements from the stack.  Convert both elements
1314 ** to integers.  Push back onto the stack the bit-wise AND of the
1315 ** two elements.
1316 ** If either operand is NULL, the result is NULL.
1317 */
1318 /* Opcode: BitOr * * *
1319 **
1320 ** Pop the top two elements from the stack.  Convert both elements
1321 ** to integers.  Push back onto the stack the bit-wise OR of the
1322 ** two elements.
1323 ** If either operand is NULL, the result is NULL.
1324 */
1325 /* Opcode: ShiftLeft * * *
1326 **
1327 ** Pop the top two elements from the stack.  Convert both elements
1328 ** to integers.  Push back onto the stack the second element shifted
1329 ** left by N bits where N is the top element on the stack.
1330 ** If either operand is NULL, the result is NULL.
1331 */
1332 /* Opcode: ShiftRight * * *
1333 **
1334 ** Pop the top two elements from the stack.  Convert both elements
1335 ** to integers.  Push back onto the stack the second element shifted
1336 ** right by N bits where N is the top element on the stack.
1337 ** If either operand is NULL, the result is NULL.
1338 */
1339 case OP_BitAnd:                 /* same as TK_BITAND, no-push */
1340 case OP_BitOr:                  /* same as TK_BITOR, no-push */
1341 case OP_ShiftLeft:              /* same as TK_LSHIFT, no-push */
1342 case OP_ShiftRight: {           /* same as TK_RSHIFT, no-push */
1343   Mem *pNos = &pTos[-1];
1344   i64 a, b;
1345 
1346   assert( pNos>=p->aStack );
1347   if( (pTos->flags | pNos->flags) & MEM_Null ){
1348     popStack(&pTos, 2);
1349     pTos++;
1350     pTos->flags = MEM_Null;
1351     break;
1352   }
1353   a = sqlite3VdbeIntValue(pNos);
1354   b = sqlite3VdbeIntValue(pTos);
1355   switch( pOp->opcode ){
1356     case OP_BitAnd:      a &= b;     break;
1357     case OP_BitOr:       a |= b;     break;
1358     case OP_ShiftLeft:   a <<= b;    break;
1359     case OP_ShiftRight:  a >>= b;    break;
1360     default:   /* CANT HAPPEN */     break;
1361   }
1362   Release(pTos);
1363   pTos--;
1364   Release(pTos);
1365   pTos->u.i = a;
1366   pTos->flags = MEM_Int;
1367   break;
1368 }
1369 
1370 /* Opcode: AddImm  P1 * *
1371 **
1372 ** Add the value P1 to whatever is on top of the stack.  The result
1373 ** is always an integer.
1374 **
1375 ** To force the top of the stack to be an integer, just add 0.
1376 */
1377 case OP_AddImm: {            /* no-push */
1378   assert( pTos>=p->aStack );
1379   sqlite3VdbeMemIntegerify(pTos);
1380   pTos->u.i += pOp->p1;
1381   break;
1382 }
1383 
1384 /* Opcode: ForceInt P1 P2 *
1385 **
1386 ** Convert the top of the stack into an integer.  If the current top of
1387 ** the stack is not numeric (meaning that is is a NULL or a string that
1388 ** does not look like an integer or floating point number) then pop the
1389 ** stack and jump to P2.  If the top of the stack is numeric then
1390 ** convert it into the least integer that is greater than or equal to its
1391 ** current value if P1==0, or to the least integer that is strictly
1392 ** greater than its current value if P1==1.
1393 */
1394 case OP_ForceInt: {            /* no-push */
1395   i64 v;
1396   assert( pTos>=p->aStack );
1397   applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
1398   if( (pTos->flags & (MEM_Int|MEM_Real))==0 ){
1399     Release(pTos);
1400     pTos--;
1401     pc = pOp->p2 - 1;
1402     break;
1403   }
1404   if( pTos->flags & MEM_Int ){
1405     v = pTos->u.i + (pOp->p1!=0);
1406   }else{
1407     /* FIX ME:  should this not be assert( pTos->flags & MEM_Real ) ??? */
1408     sqlite3VdbeMemRealify(pTos);
1409     v = (int)pTos->r;
1410     if( pTos->r>(double)v ) v++;
1411     if( pOp->p1 && pTos->r==(double)v ) v++;
1412   }
1413   Release(pTos);
1414   pTos->u.i = v;
1415   pTos->flags = MEM_Int;
1416   break;
1417 }
1418 
1419 /* Opcode: MustBeInt P1 P2 *
1420 **
1421 ** Force the top of the stack to be an integer.  If the top of the
1422 ** stack is not an integer and cannot be converted into an integer
1423 ** with out data loss, then jump immediately to P2, or if P2==0
1424 ** raise an SQLITE_MISMATCH exception.
1425 **
1426 ** If the top of the stack is not an integer and P2 is not zero and
1427 ** P1 is 1, then the stack is popped.  In all other cases, the depth
1428 ** of the stack is unchanged.
1429 */
1430 case OP_MustBeInt: {            /* no-push */
1431   assert( pTos>=p->aStack );
1432   applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
1433   if( (pTos->flags & MEM_Int)==0 ){
1434     if( pOp->p2==0 ){
1435       rc = SQLITE_MISMATCH;
1436       goto abort_due_to_error;
1437     }else{
1438       if( pOp->p1 ) popStack(&pTos, 1);
1439       pc = pOp->p2 - 1;
1440     }
1441   }else{
1442     Release(pTos);
1443     pTos->flags = MEM_Int;
1444   }
1445   break;
1446 }
1447 
1448 /* Opcode: RealAffinity * * *
1449 **
1450 ** If the top of the stack is an integer, convert it to a real value.
1451 **
1452 ** This opcode is used when extracting information from a column that
1453 ** has REAL affinity.  Such column values may still be stored as
1454 ** integers, for space efficiency, but after extraction we want them
1455 ** to have only a real value.
1456 */
1457 case OP_RealAffinity: {                  /* no-push */
1458   assert( pTos>=p->aStack );
1459   if( pTos->flags & MEM_Int ){
1460     sqlite3VdbeMemRealify(pTos);
1461   }
1462   break;
1463 }
1464 
1465 #ifndef SQLITE_OMIT_CAST
1466 /* Opcode: ToText * * *
1467 **
1468 ** Force the value on the top of the stack to be text.
1469 ** If the value is numeric, convert it to a string using the
1470 ** equivalent of printf().  Blob values are unchanged and
1471 ** are afterwards simply interpreted as text.
1472 **
1473 ** A NULL value is not changed by this routine.  It remains NULL.
1474 */
1475 case OP_ToText: {                  /* same as TK_TO_TEXT, no-push */
1476   assert( pTos>=p->aStack );
1477   if( pTos->flags & MEM_Null ) break;
1478   assert( MEM_Str==(MEM_Blob>>3) );
1479   pTos->flags |= (pTos->flags&MEM_Blob)>>3;
1480   applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
1481   rc = ExpandBlob(pTos);
1482   assert( pTos->flags & MEM_Str );
1483   pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
1484   break;
1485 }
1486 
1487 /* Opcode: ToBlob * * *
1488 **
1489 ** Force the value on the top of the stack to be a BLOB.
1490 ** If the value is numeric, convert it to a string first.
1491 ** Strings are simply reinterpreted as blobs with no change
1492 ** to the underlying data.
1493 **
1494 ** A NULL value is not changed by this routine.  It remains NULL.
1495 */
1496 case OP_ToBlob: {                  /* same as TK_TO_BLOB, no-push */
1497   assert( pTos>=p->aStack );
1498   if( pTos->flags & MEM_Null ) break;
1499   if( (pTos->flags & MEM_Blob)==0 ){
1500     applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
1501     assert( pTos->flags & MEM_Str );
1502     pTos->flags |= MEM_Blob;
1503   }
1504   pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Str);
1505   break;
1506 }
1507 
1508 /* Opcode: ToNumeric * * *
1509 **
1510 ** Force the value on the top of the stack to be numeric (either an
1511 ** integer or a floating-point number.)
1512 ** If the value is text or blob, try to convert it to an using the
1513 ** equivalent of atoi() or atof() and store 0 if no such conversion
1514 ** is possible.
1515 **
1516 ** A NULL value is not changed by this routine.  It remains NULL.
1517 */
1518 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, no-push */
1519   assert( pTos>=p->aStack );
1520   if( (pTos->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
1521     sqlite3VdbeMemNumerify(pTos);
1522   }
1523   break;
1524 }
1525 #endif /* SQLITE_OMIT_CAST */
1526 
1527 /* Opcode: ToInt * * *
1528 **
1529 ** Force the value on the top of the stack to be an integer.  If
1530 ** The value is currently a real number, drop its fractional part.
1531 ** If the value is text or blob, try to convert it to an integer using the
1532 ** equivalent of atoi() and store 0 if no such conversion is possible.
1533 **
1534 ** A NULL value is not changed by this routine.  It remains NULL.
1535 */
1536 case OP_ToInt: {                  /* same as TK_TO_INT, no-push */
1537   assert( pTos>=p->aStack );
1538   if( (pTos->flags & MEM_Null)==0 ){
1539     sqlite3VdbeMemIntegerify(pTos);
1540   }
1541   break;
1542 }
1543 
1544 #ifndef SQLITE_OMIT_CAST
1545 /* Opcode: ToReal * * *
1546 **
1547 ** Force the value on the top of the stack to be a floating point number.
1548 ** If The value is currently an integer, convert it.
1549 ** If the value is text or blob, try to convert it to an integer using the
1550 ** equivalent of atoi() and store 0 if no such conversion is possible.
1551 **
1552 ** A NULL value is not changed by this routine.  It remains NULL.
1553 */
1554 case OP_ToReal: {                  /* same as TK_TO_REAL, no-push */
1555   assert( pTos>=p->aStack );
1556   if( (pTos->flags & MEM_Null)==0 ){
1557     sqlite3VdbeMemRealify(pTos);
1558   }
1559   break;
1560 }
1561 #endif /* SQLITE_OMIT_CAST */
1562 
1563 /* Opcode: Eq P1 P2 P3
1564 **
1565 ** Pop the top two elements from the stack.  If they are equal, then
1566 ** jump to instruction P2.  Otherwise, continue to the next instruction.
1567 **
1568 ** If the 0x100 bit of P1 is true and either operand is NULL then take the
1569 ** jump.  If the 0x100 bit of P1 is clear then fall thru if either operand
1570 ** is NULL.
1571 **
1572 ** If the 0x200 bit of P1 is set and either operand is NULL then
1573 ** both operands are converted to integers prior to comparison.
1574 ** NULL operands are converted to zero and non-NULL operands are
1575 ** converted to 1.  Thus, for example, with 0x200 set,  NULL==NULL is true
1576 ** whereas it would normally be NULL.  Similarly,  NULL==123 is false when
1577 ** 0x200 is set but is NULL when the 0x200 bit of P1 is clear.
1578 **
1579 ** The least significant byte of P1 (mask 0xff) must be an affinity character -
1580 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1581 ** to coerce both values
1582 ** according to the affinity before the comparison is made. If the byte is
1583 ** 0x00, then numeric affinity is used.
1584 **
1585 ** Once any conversions have taken place, and neither value is NULL,
1586 ** the values are compared. If both values are blobs, or both are text,
1587 ** then memcmp() is used to determine the results of the comparison. If
1588 ** both values are numeric, then a numeric comparison is used. If the
1589 ** two values are of different types, then they are inequal.
1590 **
1591 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
1592 ** stack if the jump would have been taken, or a 0 if not.  Push a
1593 ** NULL if either operand was NULL.
1594 **
1595 ** If P3 is not NULL it is a pointer to a collating sequence (a CollSeq
1596 ** structure) that defines how to compare text.
1597 */
1598 /* Opcode: Ne P1 P2 P3
1599 **
1600 ** This works just like the Eq opcode except that the jump is taken if
1601 ** the operands from the stack are not equal.  See the Eq opcode for
1602 ** additional information.
1603 */
1604 /* Opcode: Lt P1 P2 P3
1605 **
1606 ** This works just like the Eq opcode except that the jump is taken if
1607 ** the 2nd element down on the stack is less than the top of the stack.
1608 ** See the Eq opcode for additional information.
1609 */
1610 /* Opcode: Le P1 P2 P3
1611 **
1612 ** This works just like the Eq opcode except that the jump is taken if
1613 ** the 2nd element down on the stack is less than or equal to the
1614 ** top of the stack.  See the Eq opcode for additional information.
1615 */
1616 /* Opcode: Gt P1 P2 P3
1617 **
1618 ** This works just like the Eq opcode except that the jump is taken if
1619 ** the 2nd element down on the stack is greater than the top of the stack.
1620 ** See the Eq opcode for additional information.
1621 */
1622 /* Opcode: Ge P1 P2 P3
1623 **
1624 ** This works just like the Eq opcode except that the jump is taken if
1625 ** the 2nd element down on the stack is greater than or equal to the
1626 ** top of the stack.  See the Eq opcode for additional information.
1627 */
1628 case OP_Eq:               /* same as TK_EQ, no-push */
1629 case OP_Ne:               /* same as TK_NE, no-push */
1630 case OP_Lt:               /* same as TK_LT, no-push */
1631 case OP_Le:               /* same as TK_LE, no-push */
1632 case OP_Gt:               /* same as TK_GT, no-push */
1633 case OP_Ge: {             /* same as TK_GE, no-push */
1634   Mem *pNos;
1635   int flags;
1636   int res;
1637   char affinity;
1638 
1639   pNos = &pTos[-1];
1640   flags = pTos->flags|pNos->flags;
1641 
1642   /* If either value is a NULL P2 is not zero, take the jump if the least
1643   ** significant byte of P1 is true. If P2 is zero, then push a NULL onto
1644   ** the stack.
1645   */
1646   if( flags&MEM_Null ){
1647     if( (pOp->p1 & 0x200)!=0 ){
1648       /* The 0x200 bit of P1 means, roughly "do not treat NULL as the
1649       ** magic SQL value it normally is - treat it as if it were another
1650       ** integer".
1651       **
1652       ** With 0x200 set, if either operand is NULL then both operands
1653       ** are converted to integers prior to being passed down into the
1654       ** normal comparison logic below.  NULL operands are converted to
1655       ** zero and non-NULL operands are converted to 1.  Thus, for example,
1656       ** with 0x200 set,  NULL==NULL is true whereas it would normally
1657       ** be NULL.  Similarly,  NULL!=123 is true.
1658       */
1659       sqlite3VdbeMemSetInt64(pTos, (pTos->flags & MEM_Null)==0);
1660       sqlite3VdbeMemSetInt64(pNos, (pNos->flags & MEM_Null)==0);
1661     }else{
1662       /* If the 0x200 bit of P1 is clear and either operand is NULL then
1663       ** the result is always NULL.  The jump is taken if the 0x100 bit
1664       ** of P1 is set.
1665       */
1666       popStack(&pTos, 2);
1667       if( pOp->p2 ){
1668         if( pOp->p1 & 0x100 ){
1669           pc = pOp->p2-1;
1670         }
1671       }else{
1672         pTos++;
1673         pTos->flags = MEM_Null;
1674       }
1675       break;
1676     }
1677   }
1678 
1679   affinity = pOp->p1 & 0xFF;
1680   if( affinity ){
1681     applyAffinity(pNos, affinity, encoding);
1682     applyAffinity(pTos, affinity, encoding);
1683   }
1684 
1685   assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 );
1686   ExpandBlob(pNos);
1687   ExpandBlob(pTos);
1688   res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3);
1689   switch( pOp->opcode ){
1690     case OP_Eq:    res = res==0;     break;
1691     case OP_Ne:    res = res!=0;     break;
1692     case OP_Lt:    res = res<0;      break;
1693     case OP_Le:    res = res<=0;     break;
1694     case OP_Gt:    res = res>0;      break;
1695     default:       res = res>=0;     break;
1696   }
1697 
1698   popStack(&pTos, 2);
1699   if( pOp->p2 ){
1700     if( res ){
1701       pc = pOp->p2-1;
1702     }
1703   }else{
1704     pTos++;
1705     pTos->flags = MEM_Int;
1706     pTos->u.i = res;
1707   }
1708   break;
1709 }
1710 
1711 /* Opcode: And * * *
1712 **
1713 ** Pop two values off the stack.  Take the logical AND of the
1714 ** two values and push the resulting boolean value back onto the
1715 ** stack.
1716 */
1717 /* Opcode: Or * * *
1718 **
1719 ** Pop two values off the stack.  Take the logical OR of the
1720 ** two values and push the resulting boolean value back onto the
1721 ** stack.
1722 */
1723 case OP_And:              /* same as TK_AND, no-push */
1724 case OP_Or: {             /* same as TK_OR, no-push */
1725   Mem *pNos = &pTos[-1];
1726   int v1, v2;    /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
1727 
1728   assert( pNos>=p->aStack );
1729   if( pTos->flags & MEM_Null ){
1730     v1 = 2;
1731   }else{
1732     sqlite3VdbeMemIntegerify(pTos);
1733     v1 = pTos->u.i==0;
1734   }
1735   if( pNos->flags & MEM_Null ){
1736     v2 = 2;
1737   }else{
1738     sqlite3VdbeMemIntegerify(pNos);
1739     v2 = pNos->u.i==0;
1740   }
1741   if( pOp->opcode==OP_And ){
1742     static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
1743     v1 = and_logic[v1*3+v2];
1744   }else{
1745     static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
1746     v1 = or_logic[v1*3+v2];
1747   }
1748   popStack(&pTos, 2);
1749   pTos++;
1750   if( v1==2 ){
1751     pTos->flags = MEM_Null;
1752   }else{
1753     pTos->u.i = v1==0;
1754     pTos->flags = MEM_Int;
1755   }
1756   break;
1757 }
1758 
1759 /* Opcode: Negative * * *
1760 **
1761 ** Treat the top of the stack as a numeric quantity.  Replace it
1762 ** with its additive inverse.  If the top of the stack is NULL
1763 ** its value is unchanged.
1764 */
1765 /* Opcode: AbsValue * * *
1766 **
1767 ** Treat the top of the stack as a numeric quantity.  Replace it
1768 ** with its absolute value. If the top of the stack is NULL
1769 ** its value is unchanged.
1770 */
1771 case OP_Negative:              /* same as TK_UMINUS, no-push */
1772 case OP_AbsValue: {
1773   assert( pTos>=p->aStack );
1774   if( (pTos->flags & (MEM_Real|MEM_Int|MEM_Null))==0 ){
1775     sqlite3VdbeMemNumerify(pTos);
1776   }
1777   if( pTos->flags & MEM_Real ){
1778     Release(pTos);
1779     if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
1780       pTos->r = -pTos->r;
1781     }
1782     pTos->flags = MEM_Real;
1783   }else if( pTos->flags & MEM_Int ){
1784     Release(pTos);
1785     if( pOp->opcode==OP_Negative || pTos->u.i<0 ){
1786       pTos->u.i = -pTos->u.i;
1787     }
1788     pTos->flags = MEM_Int;
1789   }
1790   break;
1791 }
1792 
1793 /* Opcode: Not * * *
1794 **
1795 ** Interpret the top of the stack as a boolean value.  Replace it
1796 ** with its complement.  If the top of the stack is NULL its value
1797 ** is unchanged.
1798 */
1799 case OP_Not: {                /* same as TK_NOT, no-push */
1800   assert( pTos>=p->aStack );
1801   if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
1802   sqlite3VdbeMemIntegerify(pTos);
1803   assert( (pTos->flags & MEM_Dyn)==0 );
1804   pTos->u.i = !pTos->u.i;
1805   pTos->flags = MEM_Int;
1806   break;
1807 }
1808 
1809 /* Opcode: BitNot * * *
1810 **
1811 ** Interpret the top of the stack as an value.  Replace it
1812 ** with its ones-complement.  If the top of the stack is NULL its
1813 ** value is unchanged.
1814 */
1815 case OP_BitNot: {             /* same as TK_BITNOT, no-push */
1816   assert( pTos>=p->aStack );
1817   if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
1818   sqlite3VdbeMemIntegerify(pTos);
1819   assert( (pTos->flags & MEM_Dyn)==0 );
1820   pTos->u.i = ~pTos->u.i;
1821   pTos->flags = MEM_Int;
1822   break;
1823 }
1824 
1825 /* Opcode: Noop * * *
1826 **
1827 ** Do nothing.  This instruction is often useful as a jump
1828 ** destination.
1829 */
1830 /*
1831 ** The magic Explain opcode are only inserted when explain==2 (which
1832 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
1833 ** This opcode records information from the optimizer.  It is the
1834 ** the same as a no-op.  This opcodesnever appears in a real VM program.
1835 */
1836 case OP_Explain:
1837 case OP_Noop: {            /* no-push */
1838   break;
1839 }
1840 
1841 /* Opcode: If P1 P2 *
1842 **
1843 ** Pop a single boolean from the stack.  If the boolean popped is
1844 ** true, then jump to p2.  Otherwise continue to the next instruction.
1845 ** An integer is false if zero and true otherwise.  A string is
1846 ** false if it has zero length and true otherwise.
1847 **
1848 ** If the value popped of the stack is NULL, then take the jump if P1
1849 ** is true and fall through if P1 is false.
1850 */
1851 /* Opcode: IfNot P1 P2 *
1852 **
1853 ** Pop a single boolean from the stack.  If the boolean popped is
1854 ** false, then jump to p2.  Otherwise continue to the next instruction.
1855 ** An integer is false if zero and true otherwise.  A string is
1856 ** false if it has zero length and true otherwise.
1857 **
1858 ** If the value popped of the stack is NULL, then take the jump if P1
1859 ** is true and fall through if P1 is false.
1860 */
1861 case OP_If:                 /* no-push */
1862 case OP_IfNot: {            /* no-push */
1863   int c;
1864   assert( pTos>=p->aStack );
1865   if( pTos->flags & MEM_Null ){
1866     c = pOp->p1;
1867   }else{
1868 #ifdef SQLITE_OMIT_FLOATING_POINT
1869     c = sqlite3VdbeIntValue(pTos);
1870 #else
1871     c = sqlite3VdbeRealValue(pTos)!=0.0;
1872 #endif
1873     if( pOp->opcode==OP_IfNot ) c = !c;
1874   }
1875   Release(pTos);
1876   pTos--;
1877   if( c ) pc = pOp->p2-1;
1878   break;
1879 }
1880 
1881 /* Opcode: IsNull P1 P2 *
1882 **
1883 ** Check the top of the stack and jump to P2 if the top of the stack
1884 ** is NULL.  If P1 is positive, then pop P1 elements from the stack
1885 ** regardless of whether or not the jump is taken.  If P1 is negative,
1886 ** pop -P1 elements from the stack only if the jump is taken and leave
1887 ** the stack unchanged if the jump is not taken.
1888 */
1889 case OP_IsNull: {            /* same as TK_ISNULL, no-push */
1890   if( pTos->flags & MEM_Null ){
1891     pc = pOp->p2-1;
1892     if( pOp->p1<0 ){
1893       popStack(&pTos, -pOp->p1);
1894     }
1895   }
1896   if( pOp->p1>0 ){
1897     popStack(&pTos, pOp->p1);
1898   }
1899   break;
1900 }
1901 
1902 /* Opcode: NotNull P1 P2 *
1903 **
1904 ** Jump to P2 if the top abs(P1) values on the stack are all not NULL.
1905 ** Regardless of whether or not the jump is taken, pop the stack
1906 ** P1 times if P1 is greater than zero.  But if P1 is negative,
1907 ** leave the stack unchanged.
1908 */
1909 case OP_NotNull: {            /* same as TK_NOTNULL, no-push */
1910   int i, cnt;
1911   cnt = pOp->p1;
1912   if( cnt<0 ) cnt = -cnt;
1913   assert( &pTos[1-cnt] >= p->aStack );
1914   for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
1915   if( i>=cnt ) pc = pOp->p2-1;
1916   if( pOp->p1>0 ) popStack(&pTos, cnt);
1917   break;
1918 }
1919 
1920 /* Opcode: SetNumColumns P1 P2 *
1921 **
1922 ** Before the OP_Column opcode can be executed on a cursor, this
1923 ** opcode must be called to set the number of fields in the table.
1924 **
1925 ** This opcode sets the number of columns for cursor P1 to P2.
1926 **
1927 ** If OP_KeyAsData is to be applied to cursor P1, it must be executed
1928 ** before this op-code.
1929 */
1930 case OP_SetNumColumns: {       /* no-push */
1931   Cursor *pC;
1932   assert( (pOp->p1)<p->nCursor );
1933   assert( p->apCsr[pOp->p1]!=0 );
1934   pC = p->apCsr[pOp->p1];
1935   pC->nField = pOp->p2;
1936   break;
1937 }
1938 
1939 /* Opcode: Column P1 P2 P3
1940 **
1941 ** Interpret the data that cursor P1 points to as a structure built using
1942 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
1943 ** information about the format of the data.) Push onto the stack the value
1944 ** of the P2-th column contained in the data. If there are less that (P2+1)
1945 ** values in the record, push a NULL onto the stack.
1946 **
1947 ** If the KeyAsData opcode has previously executed on this cursor, then the
1948 ** field might be extracted from the key rather than the data.
1949 **
1950 ** If the column contains fewer than P2 fields, then push a NULL.  Or
1951 ** if P3 is of type P3_MEM, then push the P3 value.  The P3 value will
1952 ** be default value for a column that has been added using the ALTER TABLE
1953 ** ADD COLUMN command.  If P3 is an ordinary string, just push a NULL.
1954 ** When P3 is a string it is really just a comment describing the value
1955 ** to be pushed, not a default value.
1956 */
1957 case OP_Column: {
1958   u32 payloadSize;   /* Number of bytes in the record */
1959   int p1 = pOp->p1;  /* P1 value of the opcode */
1960   int p2 = pOp->p2;  /* column number to retrieve */
1961   Cursor *pC = 0;    /* The VDBE cursor */
1962   char *zRec;        /* Pointer to complete record-data */
1963   BtCursor *pCrsr;   /* The BTree cursor */
1964   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
1965   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
1966   u32 nField;        /* number of fields in the record */
1967   int len;           /* The length of the serialized data for the column */
1968   int i;             /* Loop counter */
1969   char *zData;       /* Part of the record being decoded */
1970   Mem sMem;          /* For storing the record being decoded */
1971 
1972   sMem.flags = 0;
1973   assert( p1<p->nCursor );
1974   pTos++;
1975   pTos->flags = MEM_Null;
1976 
1977   /* This block sets the variable payloadSize to be the total number of
1978   ** bytes in the record.
1979   **
1980   ** zRec is set to be the complete text of the record if it is available.
1981   ** The complete record text is always available for pseudo-tables
1982   ** If the record is stored in a cursor, the complete record text
1983   ** might be available in the  pC->aRow cache.  Or it might not be.
1984   ** If the data is unavailable,  zRec is set to NULL.
1985   **
1986   ** We also compute the number of columns in the record.  For cursors,
1987   ** the number of columns is stored in the Cursor.nField element.  For
1988   ** records on the stack, the next entry down on the stack is an integer
1989   ** which is the number of records.
1990   */
1991   pC = p->apCsr[p1];
1992 #ifndef SQLITE_OMIT_VIRTUALTABLE
1993   assert( pC->pVtabCursor==0 );
1994 #endif
1995   assert( pC!=0 );
1996   if( pC->pCursor!=0 ){
1997     /* The record is stored in a B-Tree */
1998     rc = sqlite3VdbeCursorMoveto(pC);
1999     if( rc ) goto abort_due_to_error;
2000     zRec = 0;
2001     pCrsr = pC->pCursor;
2002     if( pC->nullRow ){
2003       payloadSize = 0;
2004     }else if( pC->cacheStatus==p->cacheCtr ){
2005       payloadSize = pC->payloadSize;
2006       zRec = (char*)pC->aRow;
2007     }else if( pC->isIndex ){
2008       i64 payloadSize64;
2009       sqlite3BtreeKeySize(pCrsr, &payloadSize64);
2010       payloadSize = payloadSize64;
2011     }else{
2012       sqlite3BtreeDataSize(pCrsr, &payloadSize);
2013     }
2014     nField = pC->nField;
2015   }else if( pC->pseudoTable ){
2016     /* The record is the sole entry of a pseudo-table */
2017     payloadSize = pC->nData;
2018     zRec = pC->pData;
2019     pC->cacheStatus = CACHE_STALE;
2020     assert( payloadSize==0 || zRec!=0 );
2021     nField = pC->nField;
2022     pCrsr = 0;
2023   }else{
2024     zRec = 0;
2025     payloadSize = 0;
2026     pCrsr = 0;
2027     nField = 0;
2028   }
2029 
2030   /* If payloadSize is 0, then just push a NULL onto the stack. */
2031   if( payloadSize==0 ){
2032     assert( pTos->flags==MEM_Null );
2033     break;
2034   }
2035   if( payloadSize>SQLITE_MAX_LENGTH ){
2036     goto too_big;
2037   }
2038 
2039   assert( p2<nField );
2040 
2041   /* Read and parse the table header.  Store the results of the parse
2042   ** into the record header cache fields of the cursor.
2043   */
2044   if( pC && pC->cacheStatus==p->cacheCtr ){
2045     aType = pC->aType;
2046     aOffset = pC->aOffset;
2047   }else{
2048     u8 *zIdx;        /* Index into header */
2049     u8 *zEndHdr;     /* Pointer to first byte after the header */
2050     u32 offset;      /* Offset into the data */
2051     int szHdrSz;     /* Size of the header size field at start of record */
2052     int avail;       /* Number of bytes of available data */
2053 
2054     aType = pC->aType;
2055     if( aType==0 ){
2056       pC->aType = aType = sqliteMallocRaw( 2*nField*sizeof(aType) );
2057     }
2058     if( aType==0 ){
2059       goto no_mem;
2060     }
2061     pC->aOffset = aOffset = &aType[nField];
2062     pC->payloadSize = payloadSize;
2063     pC->cacheStatus = p->cacheCtr;
2064 
2065     /* Figure out how many bytes are in the header */
2066     if( zRec ){
2067       zData = zRec;
2068     }else{
2069       if( pC->isIndex ){
2070         zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
2071       }else{
2072         zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
2073       }
2074       /* If KeyFetch()/DataFetch() managed to get the entire payload,
2075       ** save the payload in the pC->aRow cache.  That will save us from
2076       ** having to make additional calls to fetch the content portion of
2077       ** the record.
2078       */
2079       if( avail>=payloadSize ){
2080         zRec = zData;
2081         pC->aRow = (u8*)zData;
2082       }else{
2083         pC->aRow = 0;
2084       }
2085     }
2086     /* The following assert is true in all cases accept when
2087     ** the database file has been corrupted externally.
2088     **    assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
2089     szHdrSz = GetVarint((u8*)zData, offset);
2090 
2091     /* The KeyFetch() or DataFetch() above are fast and will get the entire
2092     ** record header in most cases.  But they will fail to get the complete
2093     ** record header if the record header does not fit on a single page
2094     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
2095     ** acquire the complete header text.
2096     */
2097     if( !zRec && avail<offset ){
2098       rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
2099       if( rc!=SQLITE_OK ){
2100         goto op_column_out;
2101       }
2102       zData = sMem.z;
2103     }
2104     zEndHdr = (u8 *)&zData[offset];
2105     zIdx = (u8 *)&zData[szHdrSz];
2106 
2107     /* Scan the header and use it to fill in the aType[] and aOffset[]
2108     ** arrays.  aType[i] will contain the type integer for the i-th
2109     ** column and aOffset[i] will contain the offset from the beginning
2110     ** of the record to the start of the data for the i-th column
2111     */
2112     for(i=0; i<nField; i++){
2113       if( zIdx<zEndHdr ){
2114         aOffset[i] = offset;
2115         zIdx += GetVarint(zIdx, aType[i]);
2116         offset += sqlite3VdbeSerialTypeLen(aType[i]);
2117       }else{
2118         /* If i is less that nField, then there are less fields in this
2119         ** record than SetNumColumns indicated there are columns in the
2120         ** table. Set the offset for any extra columns not present in
2121         ** the record to 0. This tells code below to push a NULL onto the
2122         ** stack instead of deserializing a value from the record.
2123         */
2124         aOffset[i] = 0;
2125       }
2126     }
2127     Release(&sMem);
2128     sMem.flags = MEM_Null;
2129 
2130     /* If we have read more header data than was contained in the header,
2131     ** or if the end of the last field appears to be past the end of the
2132     ** record, then we must be dealing with a corrupt database.
2133     */
2134     if( zIdx>zEndHdr || offset>payloadSize ){
2135       rc = SQLITE_CORRUPT_BKPT;
2136       goto op_column_out;
2137     }
2138   }
2139 
2140   /* Get the column information. If aOffset[p2] is non-zero, then
2141   ** deserialize the value from the record. If aOffset[p2] is zero,
2142   ** then there are not enough fields in the record to satisfy the
2143   ** request.  In this case, set the value NULL or to P3 if P3 is
2144   ** a pointer to a Mem object.
2145   */
2146   if( aOffset[p2] ){
2147     assert( rc==SQLITE_OK );
2148     if( zRec ){
2149       zData = &zRec[aOffset[p2]];
2150     }else{
2151       len = sqlite3VdbeSerialTypeLen(aType[p2]);
2152       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex,&sMem);
2153       if( rc!=SQLITE_OK ){
2154         goto op_column_out;
2155       }
2156       zData = sMem.z;
2157     }
2158     sqlite3VdbeSerialGet((u8*)zData, aType[p2], pTos);
2159     pTos->enc = encoding;
2160   }else{
2161     if( pOp->p3type==P3_MEM ){
2162       sqlite3VdbeMemShallowCopy(pTos, (Mem *)(pOp->p3), MEM_Static);
2163     }else{
2164       pTos->flags = MEM_Null;
2165     }
2166   }
2167 
2168   /* If we dynamically allocated space to hold the data (in the
2169   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
2170   ** dynamically allocated space over to the pTos structure.
2171   ** This prevents a memory copy.
2172   */
2173   if( (sMem.flags & MEM_Dyn)!=0 ){
2174     assert( pTos->flags & MEM_Ephem );
2175     assert( pTos->flags & (MEM_Str|MEM_Blob) );
2176     assert( pTos->z==sMem.z );
2177     assert( sMem.flags & MEM_Term );
2178     pTos->flags &= ~MEM_Ephem;
2179     pTos->flags |= MEM_Dyn|MEM_Term;
2180   }
2181 
2182   /* pTos->z might be pointing to sMem.zShort[].  Fix that so that we
2183   ** can abandon sMem */
2184   rc = sqlite3VdbeMemMakeWriteable(pTos);
2185 
2186 op_column_out:
2187   break;
2188 }
2189 
2190 /* Opcode: MakeRecord P1 P2 P3
2191 **
2192 ** Convert the top abs(P1) entries of the stack into a single entry
2193 ** suitable for use as a data record in a database table or as a key
2194 ** in an index.  The details of the format are irrelavant as long as
2195 ** the OP_Column opcode can decode the record later and as long as the
2196 ** sqlite3VdbeRecordCompare function will correctly compare two encoded
2197 ** records.  Refer to source code comments for the details of the record
2198 ** format.
2199 **
2200 ** The original stack entries are popped from the stack if P1>0 but
2201 ** remain on the stack if P1<0.
2202 **
2203 ** If P2 is not zero and one or more of the entries are NULL, then jump
2204 ** to the address given by P2.  This feature can be used to skip a
2205 ** uniqueness test on indices.
2206 **
2207 ** P3 may be a string that is P1 characters long.  The nth character of the
2208 ** string indicates the column affinity that should be used for the nth
2209 ** field of the index key (i.e. the first character of P3 corresponds to the
2210 ** lowest element on the stack).
2211 **
2212 ** The mapping from character to affinity is given by the SQLITE_AFF_
2213 ** macros defined in sqliteInt.h.
2214 **
2215 ** If P3 is NULL then all index fields have the affinity NONE.
2216 **
2217 ** See also OP_MakeIdxRec
2218 */
2219 /* Opcode: MakeIdxRec P1 P2 P3
2220 **
2221 ** This opcode works just OP_MakeRecord except that it reads an extra
2222 ** integer from the stack (thus reading a total of abs(P1+1) entries)
2223 ** and appends that extra integer to the end of the record as a varint.
2224 ** This results in an index key.
2225 */
2226 case OP_MakeIdxRec:
2227 case OP_MakeRecord: {
2228   /* Assuming the record contains N fields, the record format looks
2229   ** like this:
2230   **
2231   ** ------------------------------------------------------------------------
2232   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2233   ** ------------------------------------------------------------------------
2234   **
2235   ** Data(0) is taken from the lowest element of the stack and data(N-1) is
2236   ** the top of the stack.
2237   **
2238   ** Each type field is a varint representing the serial type of the
2239   ** corresponding data element (see sqlite3VdbeSerialType()). The
2240   ** hdr-size field is also a varint which is the offset from the beginning
2241   ** of the record to data0.
2242   */
2243   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
2244   Mem *pRec;             /* The new record */
2245   Mem *pRowid = 0;       /* Rowid appended to the new record */
2246   u64 nData = 0;         /* Number of bytes of data space */
2247   int nHdr = 0;          /* Number of bytes of header space */
2248   u64 nByte = 0;         /* Data space required for this record */
2249   int nZero = 0;         /* Number of zero bytes at the end of the record */
2250   int nVarint;           /* Number of bytes in a varint */
2251   u32 serial_type;       /* Type field */
2252   int containsNull = 0;  /* True if any of the data fields are NULL */
2253   Mem *pData0;           /* Bottom of the stack */
2254   int leaveOnStack;      /* If true, leave the entries on the stack */
2255   int nField;            /* Number of fields in the record */
2256   int jumpIfNull;        /* Jump here if non-zero and any entries are NULL. */
2257   int addRowid;          /* True to append a rowid column at the end */
2258   char *zAffinity;       /* The affinity string for the record */
2259   int file_format;       /* File format to use for encoding */
2260   int i;                 /* Space used in zNewRecord[] */
2261   char zTemp[NBFS];      /* Space to hold small records */
2262 
2263   leaveOnStack = ((pOp->p1<0)?1:0);
2264   nField = pOp->p1 * (leaveOnStack?-1:1);
2265   jumpIfNull = pOp->p2;
2266   addRowid = pOp->opcode==OP_MakeIdxRec;
2267   zAffinity = pOp->p3;
2268 
2269   pData0 = &pTos[1-nField];
2270   assert( pData0>=p->aStack );
2271   containsNull = 0;
2272   file_format = p->minWriteFileFormat;
2273 
2274   /* Loop through the elements that will make up the record to figure
2275   ** out how much space is required for the new record.
2276   */
2277   for(pRec=pData0; pRec<=pTos; pRec++){
2278     int len;
2279     if( zAffinity ){
2280       applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
2281     }
2282     if( pRec->flags&MEM_Null ){
2283       containsNull = 1;
2284     }
2285     if( pRec->flags&MEM_Zero && pRec->n>0 ){
2286       ExpandBlob(pRec);
2287     }
2288     serial_type = sqlite3VdbeSerialType(pRec, file_format);
2289     len = sqlite3VdbeSerialTypeLen(serial_type);
2290     nData += len;
2291     nHdr += sqlite3VarintLen(serial_type);
2292     if( pRec->flags & MEM_Zero ){
2293       /* Only pure zero-filled BLOBs can be input to this Opcode.
2294       ** We do not allow blobs with a prefix and a zero-filled tail. */
2295       nZero += pRec->u.i;
2296     }else if( len ){
2297       nZero = 0;
2298     }
2299   }
2300 
2301   /* If we have to append a varint rowid to this record, set pRowid
2302   ** to the value of the rowid and increase nByte by the amount of space
2303   ** required to store it.
2304   */
2305   if( addRowid ){
2306     pRowid = &pTos[0-nField];
2307     assert( pRowid>=p->aStack );
2308     sqlite3VdbeMemIntegerify(pRowid);
2309     serial_type = sqlite3VdbeSerialType(pRowid, 0);
2310     nData += sqlite3VdbeSerialTypeLen(serial_type);
2311     nHdr += sqlite3VarintLen(serial_type);
2312     nZero = 0;
2313   }
2314 
2315   /* Add the initial header varint and total the size */
2316   nHdr += nVarint = sqlite3VarintLen(nHdr);
2317   if( nVarint<sqlite3VarintLen(nHdr) ){
2318     nHdr++;
2319   }
2320   nByte = nHdr+nData-nZero;
2321   if( nByte>SQLITE_MAX_LENGTH ){
2322     goto too_big;
2323   }
2324 
2325   /* Allocate space for the new record. */
2326   if( nByte>sizeof(zTemp) ){
2327     zNewRecord = sqliteMallocRaw(nByte);
2328     if( !zNewRecord ){
2329       goto no_mem;
2330     }
2331   }else{
2332     zNewRecord = (u8*)zTemp;
2333   }
2334 
2335   /* Write the record */
2336   i = sqlite3PutVarint(zNewRecord, nHdr);
2337   for(pRec=pData0; pRec<=pTos; pRec++){
2338     serial_type = sqlite3VdbeSerialType(pRec, file_format);
2339     i += sqlite3PutVarint(&zNewRecord[i], serial_type);      /* serial type */
2340   }
2341   if( addRowid ){
2342     i += sqlite3PutVarint(&zNewRecord[i], sqlite3VdbeSerialType(pRowid, 0));
2343   }
2344   for(pRec=pData0; pRec<=pTos; pRec++){  /* serial data */
2345     i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
2346   }
2347   if( addRowid ){
2348     i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRowid, 0);
2349   }
2350   assert( i==nByte );
2351 
2352   /* Pop entries off the stack if required. Push the new record on. */
2353   if( !leaveOnStack ){
2354     popStack(&pTos, nField+addRowid);
2355   }
2356   pTos++;
2357   pTos->n = nByte;
2358   if( nByte<=sizeof(zTemp) ){
2359     assert( zNewRecord==(unsigned char *)zTemp );
2360     pTos->z = pTos->zShort;
2361     memcpy(pTos->zShort, zTemp, nByte);
2362     pTos->flags = MEM_Blob | MEM_Short;
2363   }else{
2364     assert( zNewRecord!=(unsigned char *)zTemp );
2365     pTos->z = (char*)zNewRecord;
2366     pTos->flags = MEM_Blob | MEM_Dyn;
2367     pTos->xDel = 0;
2368   }
2369   if( nZero ){
2370     pTos->u.i = nZero;
2371     pTos->flags |= MEM_Zero;
2372   }
2373   pTos->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
2374 
2375   /* If a NULL was encountered and jumpIfNull is non-zero, take the jump. */
2376   if( jumpIfNull && containsNull ){
2377     pc = jumpIfNull - 1;
2378   }
2379   break;
2380 }
2381 
2382 /* Opcode: Statement P1 * *
2383 **
2384 ** Begin an individual statement transaction which is part of a larger
2385 ** BEGIN..COMMIT transaction.  This is needed so that the statement
2386 ** can be rolled back after an error without having to roll back the
2387 ** entire transaction.  The statement transaction will automatically
2388 ** commit when the VDBE halts.
2389 **
2390 ** The statement is begun on the database file with index P1.  The main
2391 ** database file has an index of 0 and the file used for temporary tables
2392 ** has an index of 1.
2393 */
2394 case OP_Statement: {       /* no-push */
2395   int i = pOp->p1;
2396   Btree *pBt;
2397   if( i>=0 && i<db->nDb && (pBt = db->aDb[i].pBt)!=0 && !(db->autoCommit) ){
2398     assert( sqlite3BtreeIsInTrans(pBt) );
2399     if( !sqlite3BtreeIsInStmt(pBt) ){
2400       rc = sqlite3BtreeBeginStmt(pBt);
2401     }
2402   }
2403   break;
2404 }
2405 
2406 /* Opcode: AutoCommit P1 P2 *
2407 **
2408 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
2409 ** back any currently active btree transactions. If there are any active
2410 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
2411 **
2412 ** This instruction causes the VM to halt.
2413 */
2414 case OP_AutoCommit: {       /* no-push */
2415   u8 i = pOp->p1;
2416   u8 rollback = pOp->p2;
2417 
2418   assert( i==1 || i==0 );
2419   assert( i==1 || rollback==0 );
2420 
2421   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
2422 
2423   if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
2424     /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
2425     ** still running, and a transaction is active, return an error indicating
2426     ** that the other VMs must complete first.
2427     */
2428     sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit",
2429         " transaction - SQL statements in progress", (char*)0);
2430     rc = SQLITE_ERROR;
2431   }else if( i!=db->autoCommit ){
2432     if( pOp->p2 ){
2433       assert( i==1 );
2434       sqlite3RollbackAll(db);
2435       db->autoCommit = 1;
2436     }else{
2437       db->autoCommit = i;
2438       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
2439         p->pTos = pTos;
2440         p->pc = pc;
2441         db->autoCommit = 1-i;
2442         p->rc = SQLITE_BUSY;
2443         return SQLITE_BUSY;
2444       }
2445     }
2446     if( p->rc==SQLITE_OK ){
2447       return SQLITE_DONE;
2448     }else{
2449       return SQLITE_ERROR;
2450     }
2451   }else{
2452     sqlite3SetString(&p->zErrMsg,
2453         (!i)?"cannot start a transaction within a transaction":(
2454         (rollback)?"cannot rollback - no transaction is active":
2455                    "cannot commit - no transaction is active"), (char*)0);
2456 
2457     rc = SQLITE_ERROR;
2458   }
2459   break;
2460 }
2461 
2462 /* Opcode: Transaction P1 P2 *
2463 **
2464 ** Begin a transaction.  The transaction ends when a Commit or Rollback
2465 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
2466 ** transaction might also be rolled back if an error is encountered.
2467 **
2468 ** P1 is the index of the database file on which the transaction is
2469 ** started.  Index 0 is the main database file and index 1 is the
2470 ** file used for temporary tables.
2471 **
2472 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
2473 ** obtained on the database file when a write-transaction is started.  No
2474 ** other process can start another write transaction while this transaction is
2475 ** underway.  Starting a write transaction also creates a rollback journal. A
2476 ** write transaction must be started before any changes can be made to the
2477 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
2478 ** on the file.
2479 **
2480 ** If P2 is zero, then a read-lock is obtained on the database file.
2481 */
2482 case OP_Transaction: {       /* no-push */
2483   int i = pOp->p1;
2484   Btree *pBt;
2485 
2486   assert( i>=0 && i<db->nDb );
2487   pBt = db->aDb[i].pBt;
2488 
2489   if( pBt ){
2490     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
2491     if( rc==SQLITE_BUSY ){
2492       p->pc = pc;
2493       p->rc = SQLITE_BUSY;
2494       p->pTos = pTos;
2495       return SQLITE_BUSY;
2496     }
2497     if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
2498       goto abort_due_to_error;
2499     }
2500   }
2501   break;
2502 }
2503 
2504 /* Opcode: ReadCookie P1 P2 *
2505 **
2506 ** Read cookie number P2 from database P1 and push it onto the stack.
2507 ** P2==0 is the schema version.  P2==1 is the database format.
2508 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
2509 ** the main database file and P1==1 is the database file used to store
2510 ** temporary tables.
2511 **
2512 ** If P1 is negative, then this is a request to read the size of a
2513 ** databases free-list. P2 must be set to 1 in this case. The actual
2514 ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
2515 ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
2516 **
2517 ** There must be a read-lock on the database (either a transaction
2518 ** must be started or there must be an open cursor) before
2519 ** executing this instruction.
2520 */
2521 case OP_ReadCookie: {
2522   int iMeta;
2523   int iDb = pOp->p1;
2524   int iCookie = pOp->p2;
2525 
2526   assert( pOp->p2<SQLITE_N_BTREE_META );
2527   if( iDb<0 ){
2528     iDb = (-1*(iDb+1));
2529     iCookie *= -1;
2530   }
2531   assert( iDb>=0 && iDb<db->nDb );
2532   assert( db->aDb[iDb].pBt!=0 );
2533   /* The indexing of meta values at the schema layer is off by one from
2534   ** the indexing in the btree layer.  The btree considers meta[0] to
2535   ** be the number of free pages in the database (a read-only value)
2536   ** and meta[1] to be the schema cookie.  The schema layer considers
2537   ** meta[1] to be the schema cookie.  So we have to shift the index
2538   ** by one in the following statement.
2539   */
2540   rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
2541   pTos++;
2542   pTos->u.i = iMeta;
2543   pTos->flags = MEM_Int;
2544   break;
2545 }
2546 
2547 /* Opcode: SetCookie P1 P2 *
2548 **
2549 ** Write the top of the stack into cookie number P2 of database P1.
2550 ** P2==0 is the schema version.  P2==1 is the database format.
2551 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
2552 ** the main database file and P1==1 is the database file used to store
2553 ** temporary tables.
2554 **
2555 ** A transaction must be started before executing this opcode.
2556 */
2557 case OP_SetCookie: {       /* no-push */
2558   Db *pDb;
2559   assert( pOp->p2<SQLITE_N_BTREE_META );
2560   assert( pOp->p1>=0 && pOp->p1<db->nDb );
2561   pDb = &db->aDb[pOp->p1];
2562   assert( pDb->pBt!=0 );
2563   assert( pTos>=p->aStack );
2564   sqlite3VdbeMemIntegerify(pTos);
2565   /* See note about index shifting on OP_ReadCookie */
2566   rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pTos->u.i);
2567   if( pOp->p2==0 ){
2568     /* When the schema cookie changes, record the new cookie internally */
2569     pDb->pSchema->schema_cookie = pTos->u.i;
2570     db->flags |= SQLITE_InternChanges;
2571   }else if( pOp->p2==1 ){
2572     /* Record changes in the file format */
2573     pDb->pSchema->file_format = pTos->u.i;
2574   }
2575   assert( (pTos->flags & MEM_Dyn)==0 );
2576   pTos--;
2577   if( pOp->p1==1 ){
2578     /* Invalidate all prepared statements whenever the TEMP database
2579     ** schema is changed.  Ticket #1644 */
2580     sqlite3ExpirePreparedStatements(db);
2581   }
2582   break;
2583 }
2584 
2585 /* Opcode: VerifyCookie P1 P2 *
2586 **
2587 ** Check the value of global database parameter number 0 (the
2588 ** schema version) and make sure it is equal to P2.
2589 ** P1 is the database number which is 0 for the main database file
2590 ** and 1 for the file holding temporary tables and some higher number
2591 ** for auxiliary databases.
2592 **
2593 ** The cookie changes its value whenever the database schema changes.
2594 ** This operation is used to detect when that the cookie has changed
2595 ** and that the current process needs to reread the schema.
2596 **
2597 ** Either a transaction needs to have been started or an OP_Open needs
2598 ** to be executed (to establish a read lock) before this opcode is
2599 ** invoked.
2600 */
2601 case OP_VerifyCookie: {       /* no-push */
2602   int iMeta;
2603   Btree *pBt;
2604   assert( pOp->p1>=0 && pOp->p1<db->nDb );
2605   pBt = db->aDb[pOp->p1].pBt;
2606   if( pBt ){
2607     rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
2608   }else{
2609     rc = SQLITE_OK;
2610     iMeta = 0;
2611   }
2612   if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
2613     sqlite3SetString(&p->zErrMsg, "database schema has changed", (char*)0);
2614     /* If the schema-cookie from the database file matches the cookie
2615     ** stored with the in-memory representation of the schema, do
2616     ** not reload the schema from the database file.
2617     **
2618     ** If virtual-tables are in use, this is not just an optimisation.
2619     ** Often, v-tables store their data in other SQLite tables, which
2620     ** are queried from within xNext() and other v-table methods using
2621     ** prepared queries. If such a query is out-of-date, we do not want to
2622     ** discard the database schema, as the user code implementing the
2623     ** v-table would have to be ready for the sqlite3_vtab structure itself
2624     ** to be invalidated whenever sqlite3_step() is called from within
2625     ** a v-table method.
2626     */
2627     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
2628       sqlite3ResetInternalSchema(db, pOp->p1);
2629     }
2630 
2631     sqlite3ExpirePreparedStatements(db);
2632     rc = SQLITE_SCHEMA;
2633   }
2634   break;
2635 }
2636 
2637 /* Opcode: OpenRead P1 P2 P3
2638 **
2639 ** Open a read-only cursor for the database table whose root page is
2640 ** P2 in a database file.  The database file is determined by an
2641 ** integer from the top of the stack.  0 means the main database and
2642 ** 1 means the database used for temporary tables.  Give the new
2643 ** cursor an identifier of P1.  The P1 values need not be contiguous
2644 ** but all P1 values should be small integers.  It is an error for
2645 ** P1 to be negative.
2646 **
2647 ** If P2==0 then take the root page number from the next of the stack.
2648 **
2649 ** There will be a read lock on the database whenever there is an
2650 ** open cursor.  If the database was unlocked prior to this instruction
2651 ** then a read lock is acquired as part of this instruction.  A read
2652 ** lock allows other processes to read the database but prohibits
2653 ** any other process from modifying the database.  The read lock is
2654 ** released when all cursors are closed.  If this instruction attempts
2655 ** to get a read lock but fails, the script terminates with an
2656 ** SQLITE_BUSY error code.
2657 **
2658 ** The P3 value is a pointer to a KeyInfo structure that defines the
2659 ** content and collating sequence of indices.  P3 is NULL for cursors
2660 ** that are not pointing to indices.
2661 **
2662 ** See also OpenWrite.
2663 */
2664 /* Opcode: OpenWrite P1 P2 P3
2665 **
2666 ** Open a read/write cursor named P1 on the table or index whose root
2667 ** page is P2.  If P2==0 then take the root page number from the stack.
2668 **
2669 ** The P3 value is a pointer to a KeyInfo structure that defines the
2670 ** content and collating sequence of indices.  P3 is NULL for cursors
2671 ** that are not pointing to indices.
2672 **
2673 ** This instruction works just like OpenRead except that it opens the cursor
2674 ** in read/write mode.  For a given table, there can be one or more read-only
2675 ** cursors or a single read/write cursor but not both.
2676 **
2677 ** See also OpenRead.
2678 */
2679 case OP_OpenRead:          /* no-push */
2680 case OP_OpenWrite: {       /* no-push */
2681   int i = pOp->p1;
2682   int p2 = pOp->p2;
2683   int wrFlag;
2684   Btree *pX;
2685   int iDb;
2686   Cursor *pCur;
2687   Db *pDb;
2688 
2689   assert( pTos>=p->aStack );
2690   sqlite3VdbeMemIntegerify(pTos);
2691   iDb = pTos->u.i;
2692   assert( (pTos->flags & MEM_Dyn)==0 );
2693   pTos--;
2694   assert( iDb>=0 && iDb<db->nDb );
2695   pDb = &db->aDb[iDb];
2696   pX = pDb->pBt;
2697   assert( pX!=0 );
2698   if( pOp->opcode==OP_OpenWrite ){
2699     wrFlag = 1;
2700     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
2701       p->minWriteFileFormat = pDb->pSchema->file_format;
2702     }
2703   }else{
2704     wrFlag = 0;
2705   }
2706   if( p2<=0 ){
2707     assert( pTos>=p->aStack );
2708     sqlite3VdbeMemIntegerify(pTos);
2709     p2 = pTos->u.i;
2710     assert( (pTos->flags & MEM_Dyn)==0 );
2711     pTos--;
2712     assert( p2>=2 );
2713   }
2714   assert( i>=0 );
2715   pCur = allocateCursor(p, i, iDb);
2716   if( pCur==0 ) goto no_mem;
2717   pCur->nullRow = 1;
2718   if( pX==0 ) break;
2719   /* We always provide a key comparison function.  If the table being
2720   ** opened is of type INTKEY, the comparision function will be ignored. */
2721   rc = sqlite3BtreeCursor(pX, p2, wrFlag,
2722            sqlite3VdbeRecordCompare, pOp->p3,
2723            &pCur->pCursor);
2724   if( pOp->p3type==P3_KEYINFO ){
2725     pCur->pKeyInfo = (KeyInfo*)pOp->p3;
2726     pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
2727     pCur->pKeyInfo->enc = ENC(p->db);
2728   }else{
2729     pCur->pKeyInfo = 0;
2730     pCur->pIncrKey = &pCur->bogusIncrKey;
2731   }
2732   switch( rc ){
2733     case SQLITE_BUSY: {
2734       p->pc = pc;
2735       p->rc = SQLITE_BUSY;
2736       p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
2737       return SQLITE_BUSY;
2738     }
2739     case SQLITE_OK: {
2740       int flags = sqlite3BtreeFlags(pCur->pCursor);
2741       /* Sanity checking.  Only the lower four bits of the flags byte should
2742       ** be used.  Bit 3 (mask 0x08) is unpreditable.  The lower 3 bits
2743       ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
2744       ** 2 (zerodata for indices).  If these conditions are not met it can
2745       ** only mean that we are dealing with a corrupt database file
2746       */
2747       if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
2748         rc = SQLITE_CORRUPT_BKPT;
2749         goto abort_due_to_error;
2750       }
2751       pCur->isTable = (flags & BTREE_INTKEY)!=0;
2752       pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
2753       /* If P3==0 it means we are expected to open a table.  If P3!=0 then
2754       ** we expect to be opening an index.  If this is not what happened,
2755       ** then the database is corrupt
2756       */
2757       if( (pCur->isTable && pOp->p3type==P3_KEYINFO)
2758        || (pCur->isIndex && pOp->p3type!=P3_KEYINFO) ){
2759         rc = SQLITE_CORRUPT_BKPT;
2760         goto abort_due_to_error;
2761       }
2762       break;
2763     }
2764     case SQLITE_EMPTY: {
2765       pCur->isTable = pOp->p3type!=P3_KEYINFO;
2766       pCur->isIndex = !pCur->isTable;
2767       rc = SQLITE_OK;
2768       break;
2769     }
2770     default: {
2771       goto abort_due_to_error;
2772     }
2773   }
2774   break;
2775 }
2776 
2777 /* Opcode: OpenEphemeral P1 P2 P3
2778 **
2779 ** Open a new cursor P1 to a transient table.
2780 ** The cursor is always opened read/write even if
2781 ** the main database is read-only.  The transient or virtual
2782 ** table is deleted automatically when the cursor is closed.
2783 **
2784 ** P2 is the number of columns in the virtual table.
2785 ** The cursor points to a BTree table if P3==0 and to a BTree index
2786 ** if P3 is not 0.  If P3 is not NULL, it points to a KeyInfo structure
2787 ** that defines the format of keys in the index.
2788 **
2789 ** This opcode was once called OpenTemp.  But that created
2790 ** confusion because the term "temp table", might refer either
2791 ** to a TEMP table at the SQL level, or to a table opened by
2792 ** this opcode.  Then this opcode was call OpenVirtual.  But
2793 ** that created confusion with the whole virtual-table idea.
2794 */
2795 case OP_OpenEphemeral: {       /* no-push */
2796   int i = pOp->p1;
2797   Cursor *pCx;
2798   assert( i>=0 );
2799   pCx = allocateCursor(p, i, -1);
2800   if( pCx==0 ) goto no_mem;
2801   pCx->nullRow = 1;
2802   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, &pCx->pBt);
2803   if( rc==SQLITE_OK ){
2804     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
2805   }
2806   if( rc==SQLITE_OK ){
2807     /* If a transient index is required, create it by calling
2808     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
2809     ** opening it. If a transient table is required, just use the
2810     ** automatically created table with root-page 1 (an INTKEY table).
2811     */
2812     if( pOp->p3 ){
2813       int pgno;
2814       assert( pOp->p3type==P3_KEYINFO );
2815       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA);
2816       if( rc==SQLITE_OK ){
2817         assert( pgno==MASTER_ROOT+1 );
2818         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, sqlite3VdbeRecordCompare,
2819             pOp->p3, &pCx->pCursor);
2820         pCx->pKeyInfo = (KeyInfo*)pOp->p3;
2821         pCx->pKeyInfo->enc = ENC(p->db);
2822         pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
2823       }
2824       pCx->isTable = 0;
2825     }else{
2826       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, 0, &pCx->pCursor);
2827       pCx->isTable = 1;
2828       pCx->pIncrKey = &pCx->bogusIncrKey;
2829     }
2830   }
2831   pCx->nField = pOp->p2;
2832   pCx->isIndex = !pCx->isTable;
2833   break;
2834 }
2835 
2836 /* Opcode: OpenPseudo P1 * *
2837 **
2838 ** Open a new cursor that points to a fake table that contains a single
2839 ** row of data.  Any attempt to write a second row of data causes the
2840 ** first row to be deleted.  All data is deleted when the cursor is
2841 ** closed.
2842 **
2843 ** A pseudo-table created by this opcode is useful for holding the
2844 ** NEW or OLD tables in a trigger.  Also used to hold the a single
2845 ** row output from the sorter so that the row can be decomposed into
2846 ** individual columns using the OP_Column opcode.
2847 */
2848 case OP_OpenPseudo: {       /* no-push */
2849   int i = pOp->p1;
2850   Cursor *pCx;
2851   assert( i>=0 );
2852   pCx = allocateCursor(p, i, -1);
2853   if( pCx==0 ) goto no_mem;
2854   pCx->nullRow = 1;
2855   pCx->pseudoTable = 1;
2856   pCx->pIncrKey = &pCx->bogusIncrKey;
2857   pCx->isTable = 1;
2858   pCx->isIndex = 0;
2859   break;
2860 }
2861 
2862 /* Opcode: Close P1 * *
2863 **
2864 ** Close a cursor previously opened as P1.  If P1 is not
2865 ** currently open, this instruction is a no-op.
2866 */
2867 case OP_Close: {       /* no-push */
2868   int i = pOp->p1;
2869   if( i>=0 && i<p->nCursor ){
2870     sqlite3VdbeFreeCursor(p, p->apCsr[i]);
2871     p->apCsr[i] = 0;
2872   }
2873   break;
2874 }
2875 
2876 /* Opcode: MoveGe P1 P2 *
2877 **
2878 ** Pop the top of the stack and use its value as a key.  Reposition
2879 ** cursor P1 so that it points to the smallest entry that is greater
2880 ** than or equal to the key that was popped ffrom the stack.
2881 ** If there are no records greater than or equal to the key and P2
2882 ** is not zero, then jump to P2.
2883 **
2884 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
2885 */
2886 /* Opcode: MoveGt P1 P2 *
2887 **
2888 ** Pop the top of the stack and use its value as a key.  Reposition
2889 ** cursor P1 so that it points to the smallest entry that is greater
2890 ** than the key from the stack.
2891 ** If there are no records greater than the key and P2 is not zero,
2892 ** then jump to P2.
2893 **
2894 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
2895 */
2896 /* Opcode: MoveLt P1 P2 *
2897 **
2898 ** Pop the top of the stack and use its value as a key.  Reposition
2899 ** cursor P1 so that it points to the largest entry that is less
2900 ** than the key from the stack.
2901 ** If there are no records less than the key and P2 is not zero,
2902 ** then jump to P2.
2903 **
2904 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
2905 */
2906 /* Opcode: MoveLe P1 P2 *
2907 **
2908 ** Pop the top of the stack and use its value as a key.  Reposition
2909 ** cursor P1 so that it points to the largest entry that is less than
2910 ** or equal to the key that was popped from the stack.
2911 ** If there are no records less than or eqal to the key and P2 is not zero,
2912 ** then jump to P2.
2913 **
2914 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
2915 */
2916 case OP_MoveLt:         /* no-push */
2917 case OP_MoveLe:         /* no-push */
2918 case OP_MoveGe:         /* no-push */
2919 case OP_MoveGt: {       /* no-push */
2920   int i = pOp->p1;
2921   Cursor *pC;
2922 
2923   assert( pTos>=p->aStack );
2924   assert( i>=0 && i<p->nCursor );
2925   pC = p->apCsr[i];
2926   assert( pC!=0 );
2927   if( pC->pCursor!=0 ){
2928     int res, oc;
2929     oc = pOp->opcode;
2930     pC->nullRow = 0;
2931     *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
2932     if( pC->isTable ){
2933       i64 iKey;
2934       sqlite3VdbeMemIntegerify(pTos);
2935       iKey = intToKey(pTos->u.i);
2936       if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){
2937         pC->movetoTarget = iKey;
2938         pC->deferredMoveto = 1;
2939         assert( (pTos->flags & MEM_Dyn)==0 );
2940         pTos--;
2941         break;
2942       }
2943       rc = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, 0, &res);
2944       if( rc!=SQLITE_OK ){
2945         goto abort_due_to_error;
2946       }
2947       pC->lastRowid = pTos->u.i;
2948       pC->rowidIsValid = res==0;
2949     }else{
2950       assert( pTos->flags & MEM_Blob );
2951       ExpandBlob(pTos);
2952       rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
2953       if( rc!=SQLITE_OK ){
2954         goto abort_due_to_error;
2955       }
2956       pC->rowidIsValid = 0;
2957     }
2958     pC->deferredMoveto = 0;
2959     pC->cacheStatus = CACHE_STALE;
2960     *pC->pIncrKey = 0;
2961 #ifdef SQLITE_TEST
2962     sqlite3_search_count++;
2963 #endif
2964     if( oc==OP_MoveGe || oc==OP_MoveGt ){
2965       if( res<0 ){
2966         rc = sqlite3BtreeNext(pC->pCursor, &res);
2967         if( rc!=SQLITE_OK ) goto abort_due_to_error;
2968         pC->rowidIsValid = 0;
2969       }else{
2970         res = 0;
2971       }
2972     }else{
2973       assert( oc==OP_MoveLt || oc==OP_MoveLe );
2974       if( res>=0 ){
2975         rc = sqlite3BtreePrevious(pC->pCursor, &res);
2976         if( rc!=SQLITE_OK ) goto abort_due_to_error;
2977         pC->rowidIsValid = 0;
2978       }else{
2979         /* res might be negative because the table is empty.  Check to
2980         ** see if this is the case.
2981         */
2982         res = sqlite3BtreeEof(pC->pCursor);
2983       }
2984     }
2985     if( res ){
2986       if( pOp->p2>0 ){
2987         pc = pOp->p2 - 1;
2988       }else{
2989         pC->nullRow = 1;
2990       }
2991     }
2992   }
2993   Release(pTos);
2994   pTos--;
2995   break;
2996 }
2997 
2998 /* Opcode: Distinct P1 P2 *
2999 **
3000 ** Use the top of the stack as a record created using MakeRecord.  P1 is a
3001 ** cursor on a table that declared as an index.  If that table contains an
3002 ** entry that matches the top of the stack fall thru.  If the top of the stack
3003 ** matches no entry in P1 then jump to P2.
3004 **
3005 ** The cursor is left pointing at the matching entry if it exists.  The
3006 ** record on the top of the stack is not popped.
3007 **
3008 ** This instruction is similar to NotFound except that this operation
3009 ** does not pop the key from the stack.
3010 **
3011 ** The instruction is used to implement the DISTINCT operator on SELECT
3012 ** statements.  The P1 table is not a true index but rather a record of
3013 ** all results that have produced so far.
3014 **
3015 ** See also: Found, NotFound, MoveTo, IsUnique, NotExists
3016 */
3017 /* Opcode: Found P1 P2 *
3018 **
3019 ** Top of the stack holds a blob constructed by MakeRecord.  P1 is an index.
3020 ** If an entry that matches the top of the stack exists in P1 then
3021 ** jump to P2.  If the top of the stack does not match any entry in P1
3022 ** then fall thru.  The P1 cursor is left pointing at the matching entry
3023 ** if it exists.  The blob is popped off the top of the stack.
3024 **
3025 ** This instruction is used to implement the IN operator where the
3026 ** left-hand side is a SELECT statement.  P1 is not a true index but
3027 ** is instead a temporary index that holds the results of the SELECT
3028 ** statement.  This instruction just checks to see if the left-hand side
3029 ** of the IN operator (stored on the top of the stack) exists in the
3030 ** result of the SELECT statement.
3031 **
3032 ** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
3033 */
3034 /* Opcode: NotFound P1 P2 *
3035 **
3036 ** The top of the stack holds a blob constructed by MakeRecord.  P1 is
3037 ** an index.  If no entry exists in P1 that matches the blob then jump
3038 ** to P2.  If an entry does existing, fall through.  The cursor is left
3039 ** pointing to the entry that matches.  The blob is popped from the stack.
3040 **
3041 ** The difference between this operation and Distinct is that
3042 ** Distinct does not pop the key from the stack.
3043 **
3044 ** See also: Distinct, Found, MoveTo, NotExists, IsUnique
3045 */
3046 case OP_Distinct:       /* no-push */
3047 case OP_NotFound:       /* no-push */
3048 case OP_Found: {        /* no-push */
3049   int i = pOp->p1;
3050   int alreadyExists = 0;
3051   Cursor *pC;
3052   assert( pTos>=p->aStack );
3053   assert( i>=0 && i<p->nCursor );
3054   assert( p->apCsr[i]!=0 );
3055   if( (pC = p->apCsr[i])->pCursor!=0 ){
3056     int res, rx;
3057     assert( pC->isTable==0 );
3058     assert( pTos->flags & MEM_Blob );
3059     Stringify(pTos, encoding);
3060     rx = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
3061     alreadyExists = rx==SQLITE_OK && res==0;
3062     pC->deferredMoveto = 0;
3063     pC->cacheStatus = CACHE_STALE;
3064   }
3065   if( pOp->opcode==OP_Found ){
3066     if( alreadyExists ) pc = pOp->p2 - 1;
3067   }else{
3068     if( !alreadyExists ) pc = pOp->p2 - 1;
3069   }
3070   if( pOp->opcode!=OP_Distinct ){
3071     Release(pTos);
3072     pTos--;
3073   }
3074   break;
3075 }
3076 
3077 /* Opcode: IsUnique P1 P2 *
3078 **
3079 ** The top of the stack is an integer record number.  Call this
3080 ** record number R.  The next on the stack is an index key created
3081 ** using MakeIdxRec.  Call it K.  This instruction pops R from the
3082 ** stack but it leaves K unchanged.
3083 **
3084 ** P1 is an index.  So it has no data and its key consists of a
3085 ** record generated by OP_MakeRecord where the last field is the
3086 ** rowid of the entry that the index refers to.
3087 **
3088 ** This instruction asks if there is an entry in P1 where the
3089 ** fields matches K but the rowid is different from R.
3090 ** If there is no such entry, then there is an immediate
3091 ** jump to P2.  If any entry does exist where the index string
3092 ** matches K but the record number is not R, then the record
3093 ** number for that entry is pushed onto the stack and control
3094 ** falls through to the next instruction.
3095 **
3096 ** See also: Distinct, NotFound, NotExists, Found
3097 */
3098 case OP_IsUnique: {        /* no-push */
3099   int i = pOp->p1;
3100   Mem *pNos = &pTos[-1];
3101   Cursor *pCx;
3102   BtCursor *pCrsr;
3103   i64 R;
3104 
3105   /* Pop the value R off the top of the stack
3106   */
3107   assert( pNos>=p->aStack );
3108   sqlite3VdbeMemIntegerify(pTos);
3109   R = pTos->u.i;
3110   assert( (pTos->flags & MEM_Dyn)==0 );
3111   pTos--;
3112   assert( i>=0 && i<p->nCursor );
3113   pCx = p->apCsr[i];
3114   assert( pCx!=0 );
3115   pCrsr = pCx->pCursor;
3116   if( pCrsr!=0 ){
3117     int res;
3118     i64 v;         /* The record number on the P1 entry that matches K */
3119     char *zKey;    /* The value of K */
3120     int nKey;      /* Number of bytes in K */
3121     int len;       /* Number of bytes in K without the rowid at the end */
3122     int szRowid;   /* Size of the rowid column at the end of zKey */
3123 
3124     /* Make sure K is a string and make zKey point to K
3125     */
3126     assert( pNos->flags & MEM_Blob );
3127     Stringify(pNos, encoding);
3128     zKey = pNos->z;
3129     nKey = pNos->n;
3130 
3131     szRowid = sqlite3VdbeIdxRowidLen((u8*)zKey);
3132     len = nKey-szRowid;
3133 
3134     /* Search for an entry in P1 where all but the last four bytes match K.
3135     ** If there is no such entry, jump immediately to P2.
3136     */
3137     assert( pCx->deferredMoveto==0 );
3138     pCx->cacheStatus = CACHE_STALE;
3139     rc = sqlite3BtreeMoveto(pCrsr, zKey, len, 0, &res);
3140     if( rc!=SQLITE_OK ){
3141       goto abort_due_to_error;
3142     }
3143     if( res<0 ){
3144       rc = sqlite3BtreeNext(pCrsr, &res);
3145       if( res ){
3146         pc = pOp->p2 - 1;
3147         break;
3148       }
3149     }
3150     rc = sqlite3VdbeIdxKeyCompare(pCx, len, (u8*)zKey, &res);
3151     if( rc!=SQLITE_OK ) goto abort_due_to_error;
3152     if( res>0 ){
3153       pc = pOp->p2 - 1;
3154       break;
3155     }
3156 
3157     /* At this point, pCrsr is pointing to an entry in P1 where all but
3158     ** the final entry (the rowid) matches K.  Check to see if the
3159     ** final rowid column is different from R.  If it equals R then jump
3160     ** immediately to P2.
3161     */
3162     rc = sqlite3VdbeIdxRowid(pCrsr, &v);
3163     if( rc!=SQLITE_OK ){
3164       goto abort_due_to_error;
3165     }
3166     if( v==R ){
3167       pc = pOp->p2 - 1;
3168       break;
3169     }
3170 
3171     /* The final varint of the key is different from R.  Push it onto
3172     ** the stack.  (The record number of an entry that violates a UNIQUE
3173     ** constraint.)
3174     */
3175     pTos++;
3176     pTos->u.i = v;
3177     pTos->flags = MEM_Int;
3178   }
3179   break;
3180 }
3181 
3182 /* Opcode: NotExists P1 P2 *
3183 **
3184 ** Use the top of the stack as a integer key.  If a record with that key
3185 ** does not exist in table of P1, then jump to P2.  If the record
3186 ** does exist, then fall thru.  The cursor is left pointing to the
3187 ** record if it exists.  The integer key is popped from the stack.
3188 **
3189 ** The difference between this operation and NotFound is that this
3190 ** operation assumes the key is an integer and that P1 is a table whereas
3191 ** NotFound assumes key is a blob constructed from MakeRecord and
3192 ** P1 is an index.
3193 **
3194 ** See also: Distinct, Found, MoveTo, NotFound, IsUnique
3195 */
3196 case OP_NotExists: {        /* no-push */
3197   int i = pOp->p1;
3198   Cursor *pC;
3199   BtCursor *pCrsr;
3200   assert( pTos>=p->aStack );
3201   assert( i>=0 && i<p->nCursor );
3202   assert( p->apCsr[i]!=0 );
3203   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3204     int res;
3205     u64 iKey;
3206     assert( pTos->flags & MEM_Int );
3207     assert( p->apCsr[i]->isTable );
3208     iKey = intToKey(pTos->u.i);
3209     rc = sqlite3BtreeMoveto(pCrsr, 0, iKey, 0,&res);
3210     pC->lastRowid = pTos->u.i;
3211     pC->rowidIsValid = res==0;
3212     pC->nullRow = 0;
3213     pC->cacheStatus = CACHE_STALE;
3214     /* res might be uninitialized if rc!=SQLITE_OK.  But if rc!=SQLITE_OK
3215     ** processing is about to abort so we really do not care whether or not
3216     ** the following jump is taken.  (In other words, do not stress over
3217     ** the error that valgrind sometimes shows on the next statement when
3218     ** running ioerr.test and similar failure-recovery test scripts.) */
3219     if( res!=0 ){
3220       pc = pOp->p2 - 1;
3221       pC->rowidIsValid = 0;
3222     }
3223   }
3224   Release(pTos);
3225   pTos--;
3226   break;
3227 }
3228 
3229 /* Opcode: Sequence P1 * *
3230 **
3231 ** Push an integer onto the stack which is the next available
3232 ** sequence number for cursor P1.  The sequence number on the
3233 ** cursor is incremented after the push.
3234 */
3235 case OP_Sequence: {
3236   int i = pOp->p1;
3237   assert( pTos>=p->aStack );
3238   assert( i>=0 && i<p->nCursor );
3239   assert( p->apCsr[i]!=0 );
3240   pTos++;
3241   pTos->u.i = p->apCsr[i]->seqCount++;
3242   pTos->flags = MEM_Int;
3243   break;
3244 }
3245 
3246 
3247 /* Opcode: NewRowid P1 P2 *
3248 **
3249 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
3250 ** The record number is not previously used as a key in the database
3251 ** table that cursor P1 points to.  The new record number is pushed
3252 ** onto the stack.
3253 **
3254 ** If P2>0 then P2 is a memory cell that holds the largest previously
3255 ** generated record number.  No new record numbers are allowed to be less
3256 ** than this value.  When this value reaches its maximum, a SQLITE_FULL
3257 ** error is generated.  The P2 memory cell is updated with the generated
3258 ** record number.  This P2 mechanism is used to help implement the
3259 ** AUTOINCREMENT feature.
3260 */
3261 case OP_NewRowid: {
3262   int i = pOp->p1;
3263   i64 v = 0;
3264   Cursor *pC;
3265   assert( i>=0 && i<p->nCursor );
3266   assert( p->apCsr[i]!=0 );
3267   if( (pC = p->apCsr[i])->pCursor==0 ){
3268     /* The zero initialization above is all that is needed */
3269   }else{
3270     /* The next rowid or record number (different terms for the same
3271     ** thing) is obtained in a two-step algorithm.
3272     **
3273     ** First we attempt to find the largest existing rowid and add one
3274     ** to that.  But if the largest existing rowid is already the maximum
3275     ** positive integer, we have to fall through to the second
3276     ** probabilistic algorithm
3277     **
3278     ** The second algorithm is to select a rowid at random and see if
3279     ** it already exists in the table.  If it does not exist, we have
3280     ** succeeded.  If the random rowid does exist, we select a new one
3281     ** and try again, up to 1000 times.
3282     **
3283     ** For a table with less than 2 billion entries, the probability
3284     ** of not finding a unused rowid is about 1.0e-300.  This is a
3285     ** non-zero probability, but it is still vanishingly small and should
3286     ** never cause a problem.  You are much, much more likely to have a
3287     ** hardware failure than for this algorithm to fail.
3288     **
3289     ** The analysis in the previous paragraph assumes that you have a good
3290     ** source of random numbers.  Is a library function like lrand48()
3291     ** good enough?  Maybe. Maybe not. It's hard to know whether there
3292     ** might be subtle bugs is some implementations of lrand48() that
3293     ** could cause problems. To avoid uncertainty, SQLite uses its own
3294     ** random number generator based on the RC4 algorithm.
3295     **
3296     ** To promote locality of reference for repetitive inserts, the
3297     ** first few attempts at chosing a random rowid pick values just a little
3298     ** larger than the previous rowid.  This has been shown experimentally
3299     ** to double the speed of the COPY operation.
3300     */
3301     int res, rx=SQLITE_OK, cnt;
3302     i64 x;
3303     cnt = 0;
3304     if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
3305           BTREE_INTKEY ){
3306       rc = SQLITE_CORRUPT_BKPT;
3307       goto abort_due_to_error;
3308     }
3309     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
3310     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
3311 
3312 #ifdef SQLITE_32BIT_ROWID
3313 #   define MAX_ROWID 0x7fffffff
3314 #else
3315     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
3316     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
3317     ** to provide the constant while making all compilers happy.
3318     */
3319 #   define MAX_ROWID  ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
3320 #endif
3321 
3322     if( !pC->useRandomRowid ){
3323       if( pC->nextRowidValid ){
3324         v = pC->nextRowid;
3325       }else{
3326         rc = sqlite3BtreeLast(pC->pCursor, &res);
3327         if( rc!=SQLITE_OK ){
3328           goto abort_due_to_error;
3329         }
3330         if( res ){
3331           v = 1;
3332         }else{
3333           sqlite3BtreeKeySize(pC->pCursor, &v);
3334           v = keyToInt(v);
3335           if( v==MAX_ROWID ){
3336             pC->useRandomRowid = 1;
3337           }else{
3338             v++;
3339           }
3340         }
3341       }
3342 
3343 #ifndef SQLITE_OMIT_AUTOINCREMENT
3344       if( pOp->p2 ){
3345         Mem *pMem;
3346         assert( pOp->p2>0 && pOp->p2<p->nMem );  /* P2 is a valid memory cell */
3347         pMem = &p->aMem[pOp->p2];
3348         sqlite3VdbeMemIntegerify(pMem);
3349         assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P2) holds an integer */
3350         if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
3351           rc = SQLITE_FULL;
3352           goto abort_due_to_error;
3353         }
3354         if( v<pMem->u.i+1 ){
3355           v = pMem->u.i + 1;
3356         }
3357         pMem->u.i = v;
3358       }
3359 #endif
3360 
3361       if( v<MAX_ROWID ){
3362         pC->nextRowidValid = 1;
3363         pC->nextRowid = v+1;
3364       }else{
3365         pC->nextRowidValid = 0;
3366       }
3367     }
3368     if( pC->useRandomRowid ){
3369       assert( pOp->p2==0 );  /* SQLITE_FULL must have occurred prior to this */
3370       v = db->priorNewRowid;
3371       cnt = 0;
3372       do{
3373         if( v==0 || cnt>2 ){
3374           sqlite3Randomness(sizeof(v), &v);
3375           if( cnt<5 ) v &= 0xffffff;
3376         }else{
3377           unsigned char r;
3378           sqlite3Randomness(1, &r);
3379           v += r + 1;
3380         }
3381         if( v==0 ) continue;
3382         x = intToKey(v);
3383         rx = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)x, 0, &res);
3384         cnt++;
3385       }while( cnt<1000 && rx==SQLITE_OK && res==0 );
3386       db->priorNewRowid = v;
3387       if( rx==SQLITE_OK && res==0 ){
3388         rc = SQLITE_FULL;
3389         goto abort_due_to_error;
3390       }
3391     }
3392     pC->rowidIsValid = 0;
3393     pC->deferredMoveto = 0;
3394     pC->cacheStatus = CACHE_STALE;
3395   }
3396   pTos++;
3397   pTos->u.i = v;
3398   pTos->flags = MEM_Int;
3399   break;
3400 }
3401 
3402 /* Opcode: Insert P1 P2 P3
3403 **
3404 ** Write an entry into the table of cursor P1.  A new entry is
3405 ** created if it doesn't already exist or the data for an existing
3406 ** entry is overwritten.  The data is the value on the top of the
3407 ** stack.  The key is the next value down on the stack.  The key must
3408 ** be an integer.  The stack is popped twice by this instruction.
3409 **
3410 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
3411 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P2 is set,
3412 ** then rowid is stored for subsequent return by the
3413 ** sqlite3_last_insert_rowid() function (otherwise it's unmodified).
3414 **
3415 ** Parameter P3 may point to a string containing the table-name, or
3416 ** may be NULL. If it is not NULL, then the update-hook
3417 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
3418 **
3419 ** This instruction only works on tables.  The equivalent instruction
3420 ** for indices is OP_IdxInsert.
3421 */
3422 case OP_Insert: {         /* no-push */
3423   Mem *pNos = &pTos[-1];
3424   int i = pOp->p1;
3425   Cursor *pC;
3426   assert( pNos>=p->aStack );
3427   assert( i>=0 && i<p->nCursor );
3428   assert( p->apCsr[i]!=0 );
3429   if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){
3430     i64 iKey;   /* The integer ROWID or key for the record to be inserted */
3431 
3432     assert( pNos->flags & MEM_Int );
3433     assert( pC->isTable );
3434     iKey = intToKey(pNos->u.i);
3435 
3436     if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
3437     if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->u.i;
3438     if( pC->nextRowidValid && pNos->u.i>=pC->nextRowid ){
3439       pC->nextRowidValid = 0;
3440     }
3441     if( pTos->flags & MEM_Null ){
3442       pTos->z = 0;
3443       pTos->n = 0;
3444     }else{
3445       assert( pTos->flags & (MEM_Blob|MEM_Str) );
3446     }
3447     if( pC->pseudoTable ){
3448       sqliteFree(pC->pData);
3449       pC->iKey = iKey;
3450       pC->nData = pTos->n;
3451       if( pTos->flags & MEM_Dyn ){
3452         pC->pData = pTos->z;
3453         pTos->flags = MEM_Null;
3454       }else{
3455         pC->pData = sqliteMallocRaw( pC->nData+2 );
3456         if( !pC->pData ) goto no_mem;
3457         memcpy(pC->pData, pTos->z, pC->nData);
3458         pC->pData[pC->nData] = 0;
3459         pC->pData[pC->nData+1] = 0;
3460       }
3461       pC->nullRow = 0;
3462     }else{
3463       int nZero;
3464       if( pTos->flags & MEM_Zero ){
3465         nZero = pTos->u.i;
3466       }else{
3467         nZero = 0;
3468       }
3469       rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
3470                               pTos->z, pTos->n, nZero,
3471                               pOp->p2 & OPFLAG_APPEND);
3472     }
3473 
3474     pC->rowidIsValid = 0;
3475     pC->deferredMoveto = 0;
3476     pC->cacheStatus = CACHE_STALE;
3477 
3478     /* Invoke the update-hook if required. */
3479     if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
3480       const char *zDb = db->aDb[pC->iDb].zName;
3481       const char *zTbl = pOp->p3;
3482       int op = ((pOp->p2 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
3483       assert( pC->isTable );
3484       db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
3485       assert( pC->iDb>=0 );
3486     }
3487   }
3488   popStack(&pTos, 2);
3489 
3490   break;
3491 }
3492 
3493 /* Opcode: Delete P1 P2 P3
3494 **
3495 ** Delete the record at which the P1 cursor is currently pointing.
3496 **
3497 ** The cursor will be left pointing at either the next or the previous
3498 ** record in the table. If it is left pointing at the next record, then
3499 ** the next Next instruction will be a no-op.  Hence it is OK to delete
3500 ** a record from within an Next loop.
3501 **
3502 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
3503 ** incremented (otherwise not).
3504 **
3505 ** If P1 is a pseudo-table, then this instruction is a no-op.
3506 */
3507 case OP_Delete: {        /* no-push */
3508   int i = pOp->p1;
3509   Cursor *pC;
3510   assert( i>=0 && i<p->nCursor );
3511   pC = p->apCsr[i];
3512   assert( pC!=0 );
3513   if( pC->pCursor!=0 ){
3514     i64 iKey;
3515 
3516     /* If the update-hook will be invoked, set iKey to the rowid of the
3517     ** row being deleted.
3518     */
3519     if( db->xUpdateCallback && pOp->p3 ){
3520       assert( pC->isTable );
3521       if( pC->rowidIsValid ){
3522         iKey = pC->lastRowid;
3523       }else{
3524         rc = sqlite3BtreeKeySize(pC->pCursor, &iKey);
3525         if( rc ){
3526           goto abort_due_to_error;
3527         }
3528         iKey = keyToInt(iKey);
3529       }
3530     }
3531 
3532     rc = sqlite3VdbeCursorMoveto(pC);
3533     if( rc ) goto abort_due_to_error;
3534     rc = sqlite3BtreeDelete(pC->pCursor);
3535     pC->nextRowidValid = 0;
3536     pC->cacheStatus = CACHE_STALE;
3537 
3538     /* Invoke the update-hook if required. */
3539     if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
3540       const char *zDb = db->aDb[pC->iDb].zName;
3541       const char *zTbl = pOp->p3;
3542       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
3543       assert( pC->iDb>=0 );
3544     }
3545   }
3546   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
3547   break;
3548 }
3549 
3550 /* Opcode: ResetCount P1 * *
3551 **
3552 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
3553 ** then the value of the change counter is copied to the database handle
3554 ** change counter (returned by subsequent calls to sqlite3_changes())
3555 ** before it is reset. This is used by trigger programs.
3556 */
3557 case OP_ResetCount: {        /* no-push */
3558   if( pOp->p1 ){
3559     sqlite3VdbeSetChanges(db, p->nChange);
3560   }
3561   p->nChange = 0;
3562   break;
3563 }
3564 
3565 /* Opcode: RowData P1 * *
3566 **
3567 ** Push onto the stack the complete row data for cursor P1.
3568 ** There is no interpretation of the data.  It is just copied
3569 ** onto the stack exactly as it is found in the database file.
3570 **
3571 ** If the cursor is not pointing to a valid row, a NULL is pushed
3572 ** onto the stack.
3573 */
3574 /* Opcode: RowKey P1 * *
3575 **
3576 ** Push onto the stack the complete row key for cursor P1.
3577 ** There is no interpretation of the key.  It is just copied
3578 ** onto the stack exactly as it is found in the database file.
3579 **
3580 ** If the cursor is not pointing to a valid row, a NULL is pushed
3581 ** onto the stack.
3582 */
3583 case OP_RowKey:
3584 case OP_RowData: {
3585   int i = pOp->p1;
3586   Cursor *pC;
3587   u32 n;
3588 
3589   /* Note that RowKey and RowData are really exactly the same instruction */
3590   pTos++;
3591   assert( i>=0 && i<p->nCursor );
3592   pC = p->apCsr[i];
3593   assert( pC->isTable || pOp->opcode==OP_RowKey );
3594   assert( pC->isIndex || pOp->opcode==OP_RowData );
3595   assert( pC!=0 );
3596   if( pC->nullRow ){
3597     pTos->flags = MEM_Null;
3598   }else if( pC->pCursor!=0 ){
3599     BtCursor *pCrsr = pC->pCursor;
3600     rc = sqlite3VdbeCursorMoveto(pC);
3601     if( rc ) goto abort_due_to_error;
3602     if( pC->nullRow ){
3603       pTos->flags = MEM_Null;
3604       break;
3605     }else if( pC->isIndex ){
3606       i64 n64;
3607       assert( !pC->isTable );
3608       sqlite3BtreeKeySize(pCrsr, &n64);
3609       if( n64>SQLITE_MAX_LENGTH ){
3610         goto too_big;
3611       }
3612       n = n64;
3613     }else{
3614       sqlite3BtreeDataSize(pCrsr, &n);
3615     }
3616     if( n>SQLITE_MAX_LENGTH ){
3617       goto too_big;
3618     }
3619     pTos->n = n;
3620     if( n<=NBFS ){
3621       pTos->flags = MEM_Blob | MEM_Short;
3622       pTos->z = pTos->zShort;
3623     }else{
3624       char *z = sqliteMallocRaw( n );
3625       if( z==0 ) goto no_mem;
3626       pTos->flags = MEM_Blob | MEM_Dyn;
3627       pTos->xDel = 0;
3628       pTos->z = z;
3629     }
3630     if( pC->isIndex ){
3631       rc = sqlite3BtreeKey(pCrsr, 0, n, pTos->z);
3632     }else{
3633       rc = sqlite3BtreeData(pCrsr, 0, n, pTos->z);
3634     }
3635   }else if( pC->pseudoTable ){
3636     pTos->n = pC->nData;
3637     assert( pC->nData<=SQLITE_MAX_LENGTH );
3638     pTos->z = pC->pData;
3639     pTos->flags = MEM_Blob|MEM_Ephem;
3640   }else{
3641     pTos->flags = MEM_Null;
3642   }
3643   pTos->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
3644   break;
3645 }
3646 
3647 /* Opcode: Rowid P1 * *
3648 **
3649 ** Push onto the stack an integer which is the key of the table entry that
3650 ** P1 is currently point to.
3651 */
3652 case OP_Rowid: {
3653   int i = pOp->p1;
3654   Cursor *pC;
3655   i64 v;
3656 
3657   assert( i>=0 && i<p->nCursor );
3658   pC = p->apCsr[i];
3659   assert( pC!=0 );
3660   rc = sqlite3VdbeCursorMoveto(pC);
3661   if( rc ) goto abort_due_to_error;
3662   pTos++;
3663   if( pC->rowidIsValid ){
3664     v = pC->lastRowid;
3665   }else if( pC->pseudoTable ){
3666     v = keyToInt(pC->iKey);
3667   }else if( pC->nullRow || pC->pCursor==0 ){
3668     pTos->flags = MEM_Null;
3669     break;
3670   }else{
3671     assert( pC->pCursor!=0 );
3672     sqlite3BtreeKeySize(pC->pCursor, &v);
3673     v = keyToInt(v);
3674   }
3675   pTos->u.i = v;
3676   pTos->flags = MEM_Int;
3677   break;
3678 }
3679 
3680 /* Opcode: NullRow P1 * *
3681 **
3682 ** Move the cursor P1 to a null row.  Any OP_Column operations
3683 ** that occur while the cursor is on the null row will always push
3684 ** a NULL onto the stack.
3685 */
3686 case OP_NullRow: {        /* no-push */
3687   int i = pOp->p1;
3688   Cursor *pC;
3689 
3690   assert( i>=0 && i<p->nCursor );
3691   pC = p->apCsr[i];
3692   assert( pC!=0 );
3693   pC->nullRow = 1;
3694   pC->rowidIsValid = 0;
3695   break;
3696 }
3697 
3698 /* Opcode: Last P1 P2 *
3699 **
3700 ** The next use of the Rowid or Column or Next instruction for P1
3701 ** will refer to the last entry in the database table or index.
3702 ** If the table or index is empty and P2>0, then jump immediately to P2.
3703 ** If P2 is 0 or if the table or index is not empty, fall through
3704 ** to the following instruction.
3705 */
3706 case OP_Last: {        /* no-push */
3707   int i = pOp->p1;
3708   Cursor *pC;
3709   BtCursor *pCrsr;
3710 
3711   assert( i>=0 && i<p->nCursor );
3712   pC = p->apCsr[i];
3713   assert( pC!=0 );
3714   if( (pCrsr = pC->pCursor)!=0 ){
3715     int res;
3716     rc = sqlite3BtreeLast(pCrsr, &res);
3717     pC->nullRow = res;
3718     pC->deferredMoveto = 0;
3719     pC->cacheStatus = CACHE_STALE;
3720     if( res && pOp->p2>0 ){
3721       pc = pOp->p2 - 1;
3722     }
3723   }else{
3724     pC->nullRow = 0;
3725   }
3726   break;
3727 }
3728 
3729 
3730 /* Opcode: Sort P1 P2 *
3731 **
3732 ** This opcode does exactly the same thing as OP_Rewind except that
3733 ** it increments an undocumented global variable used for testing.
3734 **
3735 ** Sorting is accomplished by writing records into a sorting index,
3736 ** then rewinding that index and playing it back from beginning to
3737 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
3738 ** rewinding so that the global variable will be incremented and
3739 ** regression tests can determine whether or not the optimizer is
3740 ** correctly optimizing out sorts.
3741 */
3742 case OP_Sort: {        /* no-push */
3743 #ifdef SQLITE_TEST
3744   sqlite3_sort_count++;
3745   sqlite3_search_count--;
3746 #endif
3747   /* Fall through into OP_Rewind */
3748 }
3749 /* Opcode: Rewind P1 P2 *
3750 **
3751 ** The next use of the Rowid or Column or Next instruction for P1
3752 ** will refer to the first entry in the database table or index.
3753 ** If the table or index is empty and P2>0, then jump immediately to P2.
3754 ** If P2 is 0 or if the table or index is not empty, fall through
3755 ** to the following instruction.
3756 */
3757 case OP_Rewind: {        /* no-push */
3758   int i = pOp->p1;
3759   Cursor *pC;
3760   BtCursor *pCrsr;
3761   int res;
3762 
3763   assert( i>=0 && i<p->nCursor );
3764   pC = p->apCsr[i];
3765   assert( pC!=0 );
3766   if( (pCrsr = pC->pCursor)!=0 ){
3767     rc = sqlite3BtreeFirst(pCrsr, &res);
3768     pC->atFirst = res==0;
3769     pC->deferredMoveto = 0;
3770     pC->cacheStatus = CACHE_STALE;
3771   }else{
3772     res = 1;
3773   }
3774   pC->nullRow = res;
3775   if( res && pOp->p2>0 ){
3776     pc = pOp->p2 - 1;
3777   }
3778   break;
3779 }
3780 
3781 /* Opcode: Next P1 P2 *
3782 **
3783 ** Advance cursor P1 so that it points to the next key/data pair in its
3784 ** table or index.  If there are no more key/value pairs then fall through
3785 ** to the following instruction.  But if the cursor advance was successful,
3786 ** jump immediately to P2.
3787 **
3788 ** See also: Prev
3789 */
3790 /* Opcode: Prev P1 P2 *
3791 **
3792 ** Back up cursor P1 so that it points to the previous key/data pair in its
3793 ** table or index.  If there is no previous key/value pairs then fall through
3794 ** to the following instruction.  But if the cursor backup was successful,
3795 ** jump immediately to P2.
3796 */
3797 case OP_Prev:          /* no-push */
3798 case OP_Next: {        /* no-push */
3799   Cursor *pC;
3800   BtCursor *pCrsr;
3801 
3802   CHECK_FOR_INTERRUPT;
3803   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3804   pC = p->apCsr[pOp->p1];
3805   if( pC==0 ){
3806     break;  /* See ticket #2273 */
3807   }
3808   if( (pCrsr = pC->pCursor)!=0 ){
3809     int res;
3810     if( pC->nullRow ){
3811       res = 1;
3812     }else{
3813       assert( pC->deferredMoveto==0 );
3814       rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
3815                                   sqlite3BtreePrevious(pCrsr, &res);
3816       pC->nullRow = res;
3817       pC->cacheStatus = CACHE_STALE;
3818     }
3819     if( res==0 ){
3820       pc = pOp->p2 - 1;
3821 #ifdef SQLITE_TEST
3822       sqlite3_search_count++;
3823 #endif
3824     }
3825   }else{
3826     pC->nullRow = 1;
3827   }
3828   pC->rowidIsValid = 0;
3829   break;
3830 }
3831 
3832 /* Opcode: IdxInsert P1 P2 *
3833 **
3834 ** The top of the stack holds a SQL index key made using either the
3835 ** MakeIdxRec or MakeRecord instructions.  This opcode writes that key
3836 ** into the index P1.  Data for the entry is nil.
3837 **
3838 ** P2 is a flag that provides a hint to the b-tree layer that this
3839 ** insert is likely to be an append.
3840 **
3841 ** This instruction only works for indices.  The equivalent instruction
3842 ** for tables is OP_Insert.
3843 */
3844 case OP_IdxInsert: {        /* no-push */
3845   int i = pOp->p1;
3846   Cursor *pC;
3847   BtCursor *pCrsr;
3848   assert( pTos>=p->aStack );
3849   assert( i>=0 && i<p->nCursor );
3850   assert( p->apCsr[i]!=0 );
3851   assert( pTos->flags & MEM_Blob );
3852   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3853     assert( pC->isTable==0 );
3854     rc = ExpandBlob(pTos);
3855     if( rc==SQLITE_OK ){
3856       int nKey = pTos->n;
3857       const char *zKey = pTos->z;
3858       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p2);
3859       assert( pC->deferredMoveto==0 );
3860       pC->cacheStatus = CACHE_STALE;
3861     }
3862   }
3863   Release(pTos);
3864   pTos--;
3865   break;
3866 }
3867 
3868 /* Opcode: IdxDelete P1 * *
3869 **
3870 ** The top of the stack is an index key built using the either the
3871 ** MakeIdxRec or MakeRecord opcodes.
3872 ** This opcode removes that entry from the index.
3873 */
3874 case OP_IdxDelete: {        /* no-push */
3875   int i = pOp->p1;
3876   Cursor *pC;
3877   BtCursor *pCrsr;
3878   assert( pTos>=p->aStack );
3879   assert( pTos->flags & MEM_Blob );
3880   assert( i>=0 && i<p->nCursor );
3881   assert( p->apCsr[i]!=0 );
3882   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3883     int res;
3884     rc = sqlite3BtreeMoveto(pCrsr, pTos->z, pTos->n, 0, &res);
3885     if( rc==SQLITE_OK && res==0 ){
3886       rc = sqlite3BtreeDelete(pCrsr);
3887     }
3888     assert( pC->deferredMoveto==0 );
3889     pC->cacheStatus = CACHE_STALE;
3890   }
3891   Release(pTos);
3892   pTos--;
3893   break;
3894 }
3895 
3896 /* Opcode: IdxRowid P1 * *
3897 **
3898 ** Push onto the stack an integer which is the last entry in the record at
3899 ** the end of the index key pointed to by cursor P1.  This integer should be
3900 ** the rowid of the table entry to which this index entry points.
3901 **
3902 ** See also: Rowid, MakeIdxRec.
3903 */
3904 case OP_IdxRowid: {
3905   int i = pOp->p1;
3906   BtCursor *pCrsr;
3907   Cursor *pC;
3908 
3909   assert( i>=0 && i<p->nCursor );
3910   assert( p->apCsr[i]!=0 );
3911   pTos++;
3912   pTos->flags = MEM_Null;
3913   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3914     i64 rowid;
3915 
3916     assert( pC->deferredMoveto==0 );
3917     assert( pC->isTable==0 );
3918     if( pC->nullRow ){
3919       pTos->flags = MEM_Null;
3920     }else{
3921       rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
3922       if( rc!=SQLITE_OK ){
3923         goto abort_due_to_error;
3924       }
3925       pTos->flags = MEM_Int;
3926       pTos->u.i = rowid;
3927     }
3928   }
3929   break;
3930 }
3931 
3932 /* Opcode: IdxGT P1 P2 *
3933 **
3934 ** The top of the stack is an index entry that omits the ROWID.  Compare
3935 ** the top of stack against the index that P1 is currently pointing to.
3936 ** Ignore the ROWID on the P1 index.
3937 **
3938 ** The top of the stack might have fewer columns that P1.
3939 **
3940 ** If the P1 index entry is greater than the top of the stack
3941 ** then jump to P2.  Otherwise fall through to the next instruction.
3942 ** In either case, the stack is popped once.
3943 */
3944 /* Opcode: IdxGE P1 P2 P3
3945 **
3946 ** The top of the stack is an index entry that omits the ROWID.  Compare
3947 ** the top of stack against the index that P1 is currently pointing to.
3948 ** Ignore the ROWID on the P1 index.
3949 **
3950 ** If the P1 index entry is greater than or equal to the top of the stack
3951 ** then jump to P2.  Otherwise fall through to the next instruction.
3952 ** In either case, the stack is popped once.
3953 **
3954 ** If P3 is the "+" string (or any other non-NULL string) then the
3955 ** index taken from the top of the stack is temporarily increased by
3956 ** an epsilon prior to the comparison.  This make the opcode work
3957 ** like IdxGT except that if the key from the stack is a prefix of
3958 ** the key in the cursor, the result is false whereas it would be
3959 ** true with IdxGT.
3960 */
3961 /* Opcode: IdxLT P1 P2 P3
3962 **
3963 ** The top of the stack is an index entry that omits the ROWID.  Compare
3964 ** the top of stack against the index that P1 is currently pointing to.
3965 ** Ignore the ROWID on the P1 index.
3966 **
3967 ** If the P1 index entry is less than  the top of the stack
3968 ** then jump to P2.  Otherwise fall through to the next instruction.
3969 ** In either case, the stack is popped once.
3970 **
3971 ** If P3 is the "+" string (or any other non-NULL string) then the
3972 ** index taken from the top of the stack is temporarily increased by
3973 ** an epsilon prior to the comparison.  This makes the opcode work
3974 ** like IdxLE.
3975 */
3976 case OP_IdxLT:          /* no-push */
3977 case OP_IdxGT:          /* no-push */
3978 case OP_IdxGE: {        /* no-push */
3979   int i= pOp->p1;
3980   Cursor *pC;
3981 
3982   assert( i>=0 && i<p->nCursor );
3983   assert( p->apCsr[i]!=0 );
3984   assert( pTos>=p->aStack );
3985   if( (pC = p->apCsr[i])->pCursor!=0 ){
3986     int res;
3987 
3988     assert( pTos->flags & MEM_Blob );  /* Created using OP_MakeRecord */
3989     assert( pC->deferredMoveto==0 );
3990     ExpandBlob(pTos);
3991     *pC->pIncrKey = pOp->p3!=0;
3992     assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT );
3993     rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, (u8*)pTos->z, &res);
3994     *pC->pIncrKey = 0;
3995     if( rc!=SQLITE_OK ){
3996       break;
3997     }
3998     if( pOp->opcode==OP_IdxLT ){
3999       res = -res;
4000     }else if( pOp->opcode==OP_IdxGE ){
4001       res++;
4002     }
4003     if( res>0 ){
4004       pc = pOp->p2 - 1 ;
4005     }
4006   }
4007   Release(pTos);
4008   pTos--;
4009   break;
4010 }
4011 
4012 /* Opcode: Destroy P1 P2 *
4013 **
4014 ** Delete an entire database table or index whose root page in the database
4015 ** file is given by P1.
4016 **
4017 ** The table being destroyed is in the main database file if P2==0.  If
4018 ** P2==1 then the table to be clear is in the auxiliary database file
4019 ** that is used to store tables create using CREATE TEMPORARY TABLE.
4020 **
4021 ** If AUTOVACUUM is enabled then it is possible that another root page
4022 ** might be moved into the newly deleted root page in order to keep all
4023 ** root pages contiguous at the beginning of the database.  The former
4024 ** value of the root page that moved - its value before the move occurred -
4025 ** is pushed onto the stack.  If no page movement was required (because
4026 ** the table being dropped was already the last one in the database) then
4027 ** a zero is pushed onto the stack.  If AUTOVACUUM is disabled
4028 ** then a zero is pushed onto the stack.
4029 **
4030 ** See also: Clear
4031 */
4032 case OP_Destroy: {
4033   int iMoved;
4034   int iCnt;
4035 #ifndef SQLITE_OMIT_VIRTUALTABLE
4036   Vdbe *pVdbe;
4037   iCnt = 0;
4038   for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
4039     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
4040       iCnt++;
4041     }
4042   }
4043 #else
4044   iCnt = db->activeVdbeCnt;
4045 #endif
4046   if( iCnt>1 ){
4047     rc = SQLITE_LOCKED;
4048   }else{
4049     assert( iCnt==1 );
4050     rc = sqlite3BtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1, &iMoved);
4051     pTos++;
4052     pTos->flags = MEM_Int;
4053     pTos->u.i = iMoved;
4054 #ifndef SQLITE_OMIT_AUTOVACUUM
4055     if( rc==SQLITE_OK && iMoved!=0 ){
4056       sqlite3RootPageMoved(&db->aDb[pOp->p2], iMoved, pOp->p1);
4057     }
4058 #endif
4059   }
4060   break;
4061 }
4062 
4063 /* Opcode: Clear P1 P2 *
4064 **
4065 ** Delete all contents of the database table or index whose root page
4066 ** in the database file is given by P1.  But, unlike Destroy, do not
4067 ** remove the table or index from the database file.
4068 **
4069 ** The table being clear is in the main database file if P2==0.  If
4070 ** P2==1 then the table to be clear is in the auxiliary database file
4071 ** that is used to store tables create using CREATE TEMPORARY TABLE.
4072 **
4073 ** See also: Destroy
4074 */
4075 case OP_Clear: {        /* no-push */
4076 
4077   /* For consistency with the way other features of SQLite operate
4078   ** with a truncate, we will also skip the update callback.
4079   */
4080 #if 0
4081   Btree *pBt = db->aDb[pOp->p2].pBt;
4082   if( db->xUpdateCallback && pOp->p3 ){
4083     const char *zDb = db->aDb[pOp->p2].zName;
4084     const char *zTbl = pOp->p3;
4085     BtCursor *pCur = 0;
4086     int fin = 0;
4087 
4088     rc = sqlite3BtreeCursor(pBt, pOp->p1, 0, 0, 0, &pCur);
4089     if( rc!=SQLITE_OK ){
4090       goto abort_due_to_error;
4091     }
4092     for(
4093       rc=sqlite3BtreeFirst(pCur, &fin);
4094       rc==SQLITE_OK && !fin;
4095       rc=sqlite3BtreeNext(pCur, &fin)
4096     ){
4097       i64 iKey;
4098       rc = sqlite3BtreeKeySize(pCur, &iKey);
4099       if( rc ){
4100         break;
4101       }
4102       iKey = keyToInt(iKey);
4103       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
4104     }
4105     sqlite3BtreeCloseCursor(pCur);
4106     if( rc!=SQLITE_OK ){
4107       goto abort_due_to_error;
4108     }
4109   }
4110 #endif
4111   rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
4112   break;
4113 }
4114 
4115 /* Opcode: CreateTable P1 * *
4116 **
4117 ** Allocate a new table in the main database file if P2==0 or in the
4118 ** auxiliary database file if P2==1.  Push the page number
4119 ** for the root page of the new table onto the stack.
4120 **
4121 ** The difference between a table and an index is this:  A table must
4122 ** have a 4-byte integer key and can have arbitrary data.  An index
4123 ** has an arbitrary key but no data.
4124 **
4125 ** See also: CreateIndex
4126 */
4127 /* Opcode: CreateIndex P1 * *
4128 **
4129 ** Allocate a new index in the main database file if P2==0 or in the
4130 ** auxiliary database file if P2==1.  Push the page number of the
4131 ** root page of the new index onto the stack.
4132 **
4133 ** See documentation on OP_CreateTable for additional information.
4134 */
4135 case OP_CreateIndex:
4136 case OP_CreateTable: {
4137   int pgno;
4138   int flags;
4139   Db *pDb;
4140   assert( pOp->p1>=0 && pOp->p1<db->nDb );
4141   pDb = &db->aDb[pOp->p1];
4142   assert( pDb->pBt!=0 );
4143   if( pOp->opcode==OP_CreateTable ){
4144     /* flags = BTREE_INTKEY; */
4145     flags = BTREE_LEAFDATA|BTREE_INTKEY;
4146   }else{
4147     flags = BTREE_ZERODATA;
4148   }
4149   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
4150   pTos++;
4151   if( rc==SQLITE_OK ){
4152     pTos->u.i = pgno;
4153     pTos->flags = MEM_Int;
4154   }else{
4155     pTos->flags = MEM_Null;
4156   }
4157   break;
4158 }
4159 
4160 /* Opcode: ParseSchema P1 P2 P3
4161 **
4162 ** Read and parse all entries from the SQLITE_MASTER table of database P1
4163 ** that match the WHERE clause P3.  P2 is the "force" flag.   Always do
4164 ** the parsing if P2 is true.  If P2 is false, then this routine is a
4165 ** no-op if the schema is not currently loaded.  In other words, if P2
4166 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
4167 ** schema is already loaded into the symbol table.
4168 **
4169 ** This opcode invokes the parser to create a new virtual machine,
4170 ** then runs the new virtual machine.  It is thus a reentrant opcode.
4171 */
4172 case OP_ParseSchema: {        /* no-push */
4173   char *zSql;
4174   int iDb = pOp->p1;
4175   const char *zMaster;
4176   InitData initData;
4177 
4178   assert( iDb>=0 && iDb<db->nDb );
4179   if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
4180     break;
4181   }
4182   zMaster = SCHEMA_TABLE(iDb);
4183   initData.db = db;
4184   initData.iDb = pOp->p1;
4185   initData.pzErrMsg = &p->zErrMsg;
4186   zSql = sqlite3MPrintf(
4187      "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
4188      db->aDb[iDb].zName, zMaster, pOp->p3);
4189   if( zSql==0 ) goto no_mem;
4190   sqlite3SafetyOff(db);
4191   assert( db->init.busy==0 );
4192   db->init.busy = 1;
4193   assert( !sqlite3MallocFailed() );
4194   rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
4195   if( rc==SQLITE_ABORT ) rc = initData.rc;
4196   sqliteFree(zSql);
4197   db->init.busy = 0;
4198   sqlite3SafetyOn(db);
4199   if( rc==SQLITE_NOMEM ){
4200     sqlite3FailedMalloc();
4201     goto no_mem;
4202   }
4203   break;
4204 }
4205 
4206 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
4207 /* Opcode: LoadAnalysis P1 * *
4208 **
4209 ** Read the sqlite_stat1 table for database P1 and load the content
4210 ** of that table into the internal index hash table.  This will cause
4211 ** the analysis to be used when preparing all subsequent queries.
4212 */
4213 case OP_LoadAnalysis: {        /* no-push */
4214   int iDb = pOp->p1;
4215   assert( iDb>=0 && iDb<db->nDb );
4216   rc = sqlite3AnalysisLoad(db, iDb);
4217   break;
4218 }
4219 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)  */
4220 
4221 /* Opcode: DropTable P1 * P3
4222 **
4223 ** Remove the internal (in-memory) data structures that describe
4224 ** the table named P3 in database P1.  This is called after a table
4225 ** is dropped in order to keep the internal representation of the
4226 ** schema consistent with what is on disk.
4227 */
4228 case OP_DropTable: {        /* no-push */
4229   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p3);
4230   break;
4231 }
4232 
4233 /* Opcode: DropIndex P1 * P3
4234 **
4235 ** Remove the internal (in-memory) data structures that describe
4236 ** the index named P3 in database P1.  This is called after an index
4237 ** is dropped in order to keep the internal representation of the
4238 ** schema consistent with what is on disk.
4239 */
4240 case OP_DropIndex: {        /* no-push */
4241   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p3);
4242   break;
4243 }
4244 
4245 /* Opcode: DropTrigger P1 * P3
4246 **
4247 ** Remove the internal (in-memory) data structures that describe
4248 ** the trigger named P3 in database P1.  This is called after a trigger
4249 ** is dropped in order to keep the internal representation of the
4250 ** schema consistent with what is on disk.
4251 */
4252 case OP_DropTrigger: {        /* no-push */
4253   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p3);
4254   break;
4255 }
4256 
4257 
4258 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
4259 /* Opcode: IntegrityCk P1 P2 *
4260 **
4261 ** Do an analysis of the currently open database.  Push onto the
4262 ** stack the text of an error message describing any problems.
4263 ** If no problems are found, push a NULL onto the stack.
4264 **
4265 ** P1 is the address of a memory cell that contains the maximum
4266 ** number of allowed errors.  At most mem[P1] errors will be reported.
4267 ** In other words, the analysis stops as soon as mem[P1] errors are
4268 ** seen.  Mem[P1] is updated with the number of errors remaining.
4269 **
4270 ** The root page numbers of all tables in the database are integer
4271 ** values on the stack.  This opcode pulls as many integers as it
4272 ** can off of the stack and uses those numbers as the root pages.
4273 **
4274 ** If P2 is not zero, the check is done on the auxiliary database
4275 ** file, not the main database file.
4276 **
4277 ** This opcode is used to implement the integrity_check pragma.
4278 */
4279 case OP_IntegrityCk: {
4280   int nRoot;
4281   int *aRoot;
4282   int j;
4283   int nErr;
4284   char *z;
4285   Mem *pnErr;
4286 
4287   for(nRoot=0; &pTos[-nRoot]>=p->aStack; nRoot++){
4288     if( (pTos[-nRoot].flags & MEM_Int)==0 ) break;
4289   }
4290   assert( nRoot>0 );
4291   aRoot = sqliteMallocRaw( sizeof(int*)*(nRoot+1) );
4292   if( aRoot==0 ) goto no_mem;
4293   j = pOp->p1;
4294   assert( j>=0 && j<p->nMem );
4295   pnErr = &p->aMem[j];
4296   assert( (pnErr->flags & MEM_Int)!=0 );
4297   for(j=0; j<nRoot; j++){
4298     Mem *pMem = &pTos[-j];
4299     aRoot[j] = pMem->u.i;
4300   }
4301   aRoot[j] = 0;
4302   popStack(&pTos, nRoot);
4303   pTos++;
4304   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot,
4305                                  pnErr->u.i, &nErr);
4306   pnErr->u.i -= nErr;
4307   if( nErr==0 ){
4308     assert( z==0 );
4309     pTos->flags = MEM_Null;
4310   }else{
4311     pTos->z = z;
4312     pTos->n = strlen(z);
4313     pTos->flags = MEM_Str | MEM_Dyn | MEM_Term;
4314     pTos->xDel = 0;
4315   }
4316   pTos->enc = SQLITE_UTF8;
4317   sqlite3VdbeChangeEncoding(pTos, encoding);
4318   sqliteFree(aRoot);
4319   break;
4320 }
4321 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
4322 
4323 /* Opcode: FifoWrite * * *
4324 **
4325 ** Write the integer on the top of the stack
4326 ** into the Fifo.
4327 */
4328 case OP_FifoWrite: {        /* no-push */
4329   assert( pTos>=p->aStack );
4330   sqlite3VdbeMemIntegerify(pTos);
4331   sqlite3VdbeFifoPush(&p->sFifo, pTos->u.i);
4332   assert( (pTos->flags & MEM_Dyn)==0 );
4333   pTos--;
4334   break;
4335 }
4336 
4337 /* Opcode: FifoRead * P2 *
4338 **
4339 ** Attempt to read a single integer from the Fifo
4340 ** and push it onto the stack.  If the Fifo is empty
4341 ** push nothing but instead jump to P2.
4342 */
4343 case OP_FifoRead: {
4344   i64 v;
4345   CHECK_FOR_INTERRUPT;
4346   if( sqlite3VdbeFifoPop(&p->sFifo, &v)==SQLITE_DONE ){
4347     pc = pOp->p2 - 1;
4348   }else{
4349     pTos++;
4350     pTos->u.i = v;
4351     pTos->flags = MEM_Int;
4352   }
4353   break;
4354 }
4355 
4356 #ifndef SQLITE_OMIT_TRIGGER
4357 /* Opcode: ContextPush * * *
4358 **
4359 ** Save the current Vdbe context such that it can be restored by a ContextPop
4360 ** opcode. The context stores the last insert row id, the last statement change
4361 ** count, and the current statement change count.
4362 */
4363 case OP_ContextPush: {        /* no-push */
4364   int i = p->contextStackTop++;
4365   Context *pContext;
4366 
4367   assert( i>=0 );
4368   /* FIX ME: This should be allocated as part of the vdbe at compile-time */
4369   if( i>=p->contextStackDepth ){
4370     p->contextStackDepth = i+1;
4371     p->contextStack = sqliteReallocOrFree(p->contextStack,
4372                                           sizeof(Context)*(i+1));
4373     if( p->contextStack==0 ) goto no_mem;
4374   }
4375   pContext = &p->contextStack[i];
4376   pContext->lastRowid = db->lastRowid;
4377   pContext->nChange = p->nChange;
4378   pContext->sFifo = p->sFifo;
4379   sqlite3VdbeFifoInit(&p->sFifo);
4380   break;
4381 }
4382 
4383 /* Opcode: ContextPop * * *
4384 **
4385 ** Restore the Vdbe context to the state it was in when contextPush was last
4386 ** executed. The context stores the last insert row id, the last statement
4387 ** change count, and the current statement change count.
4388 */
4389 case OP_ContextPop: {        /* no-push */
4390   Context *pContext = &p->contextStack[--p->contextStackTop];
4391   assert( p->contextStackTop>=0 );
4392   db->lastRowid = pContext->lastRowid;
4393   p->nChange = pContext->nChange;
4394   sqlite3VdbeFifoClear(&p->sFifo);
4395   p->sFifo = pContext->sFifo;
4396   break;
4397 }
4398 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
4399 
4400 /* Opcode: MemStore P1 P2 *
4401 **
4402 ** Write the top of the stack into memory location P1.
4403 ** P1 should be a small integer since space is allocated
4404 ** for all memory locations between 0 and P1 inclusive.
4405 **
4406 ** After the data is stored in the memory location, the
4407 ** stack is popped once if P2 is 1.  If P2 is zero, then
4408 ** the original data remains on the stack.
4409 */
4410 case OP_MemStore: {        /* no-push */
4411   assert( pTos>=p->aStack );
4412   assert( pOp->p1>=0 && pOp->p1<p->nMem );
4413   rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], pTos);
4414   pTos--;
4415 
4416   /* If P2 is 0 then fall thru to the next opcode, OP_MemLoad, that will
4417   ** restore the top of the stack to its original value.
4418   */
4419   if( pOp->p2 ){
4420     break;
4421   }
4422 }
4423 /* Opcode: MemLoad P1 * *
4424 **
4425 ** Push a copy of the value in memory location P1 onto the stack.
4426 **
4427 ** If the value is a string, then the value pushed is a pointer to
4428 ** the string that is stored in the memory location.  If the memory
4429 ** location is subsequently changed (using OP_MemStore) then the
4430 ** value pushed onto the stack will change too.
4431 */
4432 case OP_MemLoad: {
4433   int i = pOp->p1;
4434   assert( i>=0 && i<p->nMem );
4435   pTos++;
4436   sqlite3VdbeMemShallowCopy(pTos, &p->aMem[i], MEM_Ephem);
4437   break;
4438 }
4439 
4440 #ifndef SQLITE_OMIT_AUTOINCREMENT
4441 /* Opcode: MemMax P1 * *
4442 **
4443 ** Set the value of memory cell P1 to the maximum of its current value
4444 ** and the value on the top of the stack.  The stack is unchanged.
4445 **
4446 ** This instruction throws an error if the memory cell is not initially
4447 ** an integer.
4448 */
4449 case OP_MemMax: {        /* no-push */
4450   int i = pOp->p1;
4451   Mem *pMem;
4452   assert( pTos>=p->aStack );
4453   assert( i>=0 && i<p->nMem );
4454   pMem = &p->aMem[i];
4455   sqlite3VdbeMemIntegerify(pMem);
4456   sqlite3VdbeMemIntegerify(pTos);
4457   if( pMem->u.i<pTos->u.i){
4458     pMem->u.i = pTos->u.i;
4459   }
4460   break;
4461 }
4462 #endif /* SQLITE_OMIT_AUTOINCREMENT */
4463 
4464 /* Opcode: MemIncr P1 P2 *
4465 **
4466 ** Increment the integer valued memory cell P2 by the value in P1.
4467 **
4468 ** It is illegal to use this instruction on a memory cell that does
4469 ** not contain an integer.  An assertion fault will result if you try.
4470 */
4471 case OP_MemIncr: {        /* no-push */
4472   int i = pOp->p2;
4473   Mem *pMem;
4474   assert( i>=0 && i<p->nMem );
4475   pMem = &p->aMem[i];
4476   assert( pMem->flags==MEM_Int );
4477   pMem->u.i += pOp->p1;
4478   break;
4479 }
4480 
4481 /* Opcode: IfMemPos P1 P2 *
4482 **
4483 ** If the value of memory cell P1 is 1 or greater, jump to P2.
4484 **
4485 ** It is illegal to use this instruction on a memory cell that does
4486 ** not contain an integer.  An assertion fault will result if you try.
4487 */
4488 case OP_IfMemPos: {        /* no-push */
4489   int i = pOp->p1;
4490   Mem *pMem;
4491   assert( i>=0 && i<p->nMem );
4492   pMem = &p->aMem[i];
4493   assert( pMem->flags==MEM_Int );
4494   if( pMem->u.i>0 ){
4495      pc = pOp->p2 - 1;
4496   }
4497   break;
4498 }
4499 
4500 /* Opcode: IfMemNeg P1 P2 *
4501 **
4502 ** If the value of memory cell P1 is less than zero, jump to P2.
4503 **
4504 ** It is illegal to use this instruction on a memory cell that does
4505 ** not contain an integer.  An assertion fault will result if you try.
4506 */
4507 case OP_IfMemNeg: {        /* no-push */
4508   int i = pOp->p1;
4509   Mem *pMem;
4510   assert( i>=0 && i<p->nMem );
4511   pMem = &p->aMem[i];
4512   assert( pMem->flags==MEM_Int );
4513   if( pMem->u.i<0 ){
4514      pc = pOp->p2 - 1;
4515   }
4516   break;
4517 }
4518 
4519 /* Opcode: IfMemZero P1 P2 *
4520 **
4521 ** If the value of memory cell P1 is exactly 0, jump to P2.
4522 **
4523 ** It is illegal to use this instruction on a memory cell that does
4524 ** not contain an integer.  An assertion fault will result if you try.
4525 */
4526 case OP_IfMemZero: {        /* no-push */
4527   int i = pOp->p1;
4528   Mem *pMem;
4529   assert( i>=0 && i<p->nMem );
4530   pMem = &p->aMem[i];
4531   assert( pMem->flags==MEM_Int );
4532   if( pMem->u.i==0 ){
4533      pc = pOp->p2 - 1;
4534   }
4535   break;
4536 }
4537 
4538 /* Opcode: MemNull P1 * *
4539 **
4540 ** Store a NULL in memory cell P1
4541 */
4542 case OP_MemNull: {
4543   assert( pOp->p1>=0 && pOp->p1<p->nMem );
4544   sqlite3VdbeMemSetNull(&p->aMem[pOp->p1]);
4545   break;
4546 }
4547 
4548 /* Opcode: MemInt P1 P2 *
4549 **
4550 ** Store the integer value P1 in memory cell P2.
4551 */
4552 case OP_MemInt: {
4553   assert( pOp->p2>=0 && pOp->p2<p->nMem );
4554   sqlite3VdbeMemSetInt64(&p->aMem[pOp->p2], pOp->p1);
4555   break;
4556 }
4557 
4558 /* Opcode: MemMove P1 P2 *
4559 **
4560 ** Move the content of memory cell P2 over to memory cell P1.
4561 ** Any prior content of P1 is erased.  Memory cell P2 is left
4562 ** containing a NULL.
4563 */
4564 case OP_MemMove: {
4565   assert( pOp->p1>=0 && pOp->p1<p->nMem );
4566   assert( pOp->p2>=0 && pOp->p2<p->nMem );
4567   rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], &p->aMem[pOp->p2]);
4568   break;
4569 }
4570 
4571 /* Opcode: AggStep P1 P2 P3
4572 **
4573 ** Execute the step function for an aggregate.  The
4574 ** function has P2 arguments.  P3 is a pointer to the FuncDef
4575 ** structure that specifies the function.  Use memory location
4576 ** P1 as the accumulator.
4577 **
4578 ** The P2 arguments are popped from the stack.
4579 */
4580 case OP_AggStep: {        /* no-push */
4581   int n = pOp->p2;
4582   int i;
4583   Mem *pMem, *pRec;
4584   sqlite3_context ctx;
4585   sqlite3_value **apVal;
4586 
4587   assert( n>=0 );
4588   pRec = &pTos[1-n];
4589   assert( pRec>=p->aStack );
4590   apVal = p->apArg;
4591   assert( apVal || n==0 );
4592   for(i=0; i<n; i++, pRec++){
4593     apVal[i] = pRec;
4594     storeTypeInfo(pRec, encoding);
4595   }
4596   ctx.pFunc = (FuncDef*)pOp->p3;
4597   assert( pOp->p1>=0 && pOp->p1<p->nMem );
4598   ctx.pMem = pMem = &p->aMem[pOp->p1];
4599   pMem->n++;
4600   ctx.s.flags = MEM_Null;
4601   ctx.s.z = 0;
4602   ctx.s.xDel = 0;
4603   ctx.isError = 0;
4604   ctx.pColl = 0;
4605   if( ctx.pFunc->needCollSeq ){
4606     assert( pOp>p->aOp );
4607     assert( pOp[-1].p3type==P3_COLLSEQ );
4608     assert( pOp[-1].opcode==OP_CollSeq );
4609     ctx.pColl = (CollSeq *)pOp[-1].p3;
4610   }
4611   (ctx.pFunc->xStep)(&ctx, n, apVal);
4612   popStack(&pTos, n);
4613   if( ctx.isError ){
4614     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
4615     rc = SQLITE_ERROR;
4616   }
4617   sqlite3VdbeMemRelease(&ctx.s);
4618   break;
4619 }
4620 
4621 /* Opcode: AggFinal P1 P2 P3
4622 **
4623 ** Execute the finalizer function for an aggregate.  P1 is
4624 ** the memory location that is the accumulator for the aggregate.
4625 **
4626 ** P2 is the number of arguments that the step function takes and
4627 ** P3 is a pointer to the FuncDef for this function.  The P2
4628 ** argument is not used by this opcode.  It is only there to disambiguate
4629 ** functions that can take varying numbers of arguments.  The
4630 ** P3 argument is only needed for the degenerate case where
4631 ** the step function was not previously called.
4632 */
4633 case OP_AggFinal: {        /* no-push */
4634   Mem *pMem;
4635   assert( pOp->p1>=0 && pOp->p1<p->nMem );
4636   pMem = &p->aMem[pOp->p1];
4637   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
4638   rc = sqlite3VdbeMemFinalize(pMem, (FuncDef*)pOp->p3);
4639   if( rc==SQLITE_ERROR ){
4640     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pMem), (char*)0);
4641   }
4642   if( sqlite3VdbeMemTooBig(pMem) ){
4643     goto too_big;
4644   }
4645   break;
4646 }
4647 
4648 
4649 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
4650 /* Opcode: Vacuum * * *
4651 **
4652 ** Vacuum the entire database.  This opcode will cause other virtual
4653 ** machines to be created and run.  It may not be called from within
4654 ** a transaction.
4655 */
4656 case OP_Vacuum: {        /* no-push */
4657   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4658   rc = sqlite3RunVacuum(&p->zErrMsg, db);
4659   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4660   break;
4661 }
4662 #endif
4663 
4664 #if !defined(SQLITE_OMIT_AUTOVACUUM)
4665 /* Opcode: IncrVacuum P1 P2 *
4666 **
4667 ** Perform a single step of the incremental vacuum procedure on
4668 ** the P1 database. If the vacuum has finished, jump to instruction
4669 ** P2. Otherwise, fall through to the next instruction.
4670 */
4671 case OP_IncrVacuum: {        /* no-push */
4672   Btree *pBt;
4673 
4674   assert( pOp->p1>=0 && pOp->p1<db->nDb );
4675   pBt = db->aDb[pOp->p1].pBt;
4676   rc = sqlite3BtreeIncrVacuum(pBt);
4677   if( rc==SQLITE_DONE ){
4678     pc = pOp->p2 - 1;
4679     rc = SQLITE_OK;
4680   }
4681   break;
4682 }
4683 #endif
4684 
4685 /* Opcode: Expire P1 * *
4686 **
4687 ** Cause precompiled statements to become expired. An expired statement
4688 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
4689 ** (via sqlite3_step()).
4690 **
4691 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
4692 ** then only the currently executing statement is affected.
4693 */
4694 case OP_Expire: {        /* no-push */
4695   if( !pOp->p1 ){
4696     sqlite3ExpirePreparedStatements(db);
4697   }else{
4698     p->expired = 1;
4699   }
4700   break;
4701 }
4702 
4703 #ifndef SQLITE_OMIT_SHARED_CACHE
4704 /* Opcode: TableLock P1 P2 P3
4705 **
4706 ** Obtain a lock on a particular table. This instruction is only used when
4707 ** the shared-cache feature is enabled.
4708 **
4709 ** If P1 is not negative, then it is the index of the database
4710 ** in sqlite3.aDb[] and a read-lock is required. If P1 is negative, a
4711 ** write-lock is required. In this case the index of the database is the
4712 ** absolute value of P1 minus one (iDb = abs(P1) - 1;) and a write-lock is
4713 ** required.
4714 **
4715 ** P2 contains the root-page of the table to lock.
4716 **
4717 ** P3 contains a pointer to the name of the table being locked. This is only
4718 ** used to generate an error message if the lock cannot be obtained.
4719 */
4720 case OP_TableLock: {        /* no-push */
4721   int p1 = pOp->p1;
4722   u8 isWriteLock = (p1<0);
4723   if( isWriteLock ){
4724     p1 = (-1*p1)-1;
4725   }
4726   rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
4727   if( rc==SQLITE_LOCKED ){
4728     const char *z = (const char *)pOp->p3;
4729     sqlite3SetString(&p->zErrMsg, "database table is locked: ", z, (char*)0);
4730   }
4731   break;
4732 }
4733 #endif /* SQLITE_OMIT_SHARED_CACHE */
4734 
4735 #ifndef SQLITE_OMIT_VIRTUALTABLE
4736 /* Opcode: VBegin * * P3
4737 **
4738 ** P3 a pointer to an sqlite3_vtab structure. Call the xBegin method
4739 ** for that table.
4740 */
4741 case OP_VBegin: {   /* no-push */
4742   rc = sqlite3VtabBegin(db, (sqlite3_vtab *)pOp->p3);
4743   break;
4744 }
4745 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4746 
4747 #ifndef SQLITE_OMIT_VIRTUALTABLE
4748 /* Opcode: VCreate P1 * P3
4749 **
4750 ** P3 is the name of a virtual table in database P1. Call the xCreate method
4751 ** for that table.
4752 */
4753 case OP_VCreate: {   /* no-push */
4754   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p3, &p->zErrMsg);
4755   break;
4756 }
4757 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4758 
4759 #ifndef SQLITE_OMIT_VIRTUALTABLE
4760 /* Opcode: VDestroy P1 * P3
4761 **
4762 ** P3 is the name of a virtual table in database P1.  Call the xDestroy method
4763 ** of that table.
4764 */
4765 case OP_VDestroy: {   /* no-push */
4766   p->inVtabMethod = 2;
4767   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p3);
4768   p->inVtabMethod = 0;
4769   break;
4770 }
4771 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4772 
4773 #ifndef SQLITE_OMIT_VIRTUALTABLE
4774 /* Opcode: VOpen P1 * P3
4775 **
4776 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
4777 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
4778 ** table and stores that cursor in P1.
4779 */
4780 case OP_VOpen: {   /* no-push */
4781   Cursor *pCur = 0;
4782   sqlite3_vtab_cursor *pVtabCursor = 0;
4783 
4784   sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
4785   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
4786 
4787   assert(pVtab && pModule);
4788   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4789   rc = pModule->xOpen(pVtab, &pVtabCursor);
4790   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4791   if( SQLITE_OK==rc ){
4792     /* Initialise sqlite3_vtab_cursor base class */
4793     pVtabCursor->pVtab = pVtab;
4794 
4795     /* Initialise vdbe cursor object */
4796     pCur = allocateCursor(p, pOp->p1, -1);
4797     if( pCur ){
4798       pCur->pVtabCursor = pVtabCursor;
4799       pCur->pModule = pVtabCursor->pVtab->pModule;
4800     }else{
4801       pModule->xClose(pVtabCursor);
4802     }
4803   }
4804   break;
4805 }
4806 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4807 
4808 #ifndef SQLITE_OMIT_VIRTUALTABLE
4809 /* Opcode: VFilter P1 P2 P3
4810 **
4811 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
4812 ** the filtered result set is empty.
4813 **
4814 ** P3 is either NULL or a string that was generated by the xBestIndex
4815 ** method of the module.  The interpretation of the P3 string is left
4816 ** to the module implementation.
4817 **
4818 ** This opcode invokes the xFilter method on the virtual table specified
4819 ** by P1.  The integer query plan parameter to xFilter is the top of the
4820 ** stack.  Next down on the stack is the argc parameter.  Beneath the
4821 ** next of stack are argc additional parameters which are passed to
4822 ** xFilter as argv. The topmost parameter (i.e. 3rd element popped from
4823 ** the stack) becomes argv[argc-1] when passed to xFilter.
4824 **
4825 ** The integer query plan parameter, argc, and all argv stack values
4826 ** are popped from the stack before this instruction completes.
4827 **
4828 ** A jump is made to P2 if the result set after filtering would be
4829 ** empty.
4830 */
4831 case OP_VFilter: {   /* no-push */
4832   int nArg;
4833 
4834   const sqlite3_module *pModule;
4835 
4836   Cursor *pCur = p->apCsr[pOp->p1];
4837   assert( pCur->pVtabCursor );
4838   pModule = pCur->pVtabCursor->pVtab->pModule;
4839 
4840   /* Grab the index number and argc parameters off the top of the stack. */
4841   assert( (&pTos[-1])>=p->aStack );
4842   assert( (pTos[0].flags&MEM_Int)!=0 && pTos[-1].flags==MEM_Int );
4843   nArg = pTos[-1].u.i;
4844 
4845   /* Invoke the xFilter method */
4846   {
4847     int res = 0;
4848     int i;
4849     Mem **apArg = p->apArg;
4850     for(i = 0; i<nArg; i++){
4851       apArg[i] = &pTos[i+1-2-nArg];
4852       storeTypeInfo(apArg[i], 0);
4853     }
4854 
4855     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4856     p->inVtabMethod = 1;
4857     rc = pModule->xFilter(pCur->pVtabCursor, pTos->u.i, pOp->p3, nArg, apArg);
4858     p->inVtabMethod = 0;
4859     if( rc==SQLITE_OK ){
4860       res = pModule->xEof(pCur->pVtabCursor);
4861     }
4862     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4863 
4864     if( res ){
4865       pc = pOp->p2 - 1;
4866     }
4867   }
4868 
4869   /* Pop the index number, argc value and parameters off the stack */
4870   popStack(&pTos, 2+nArg);
4871   break;
4872 }
4873 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4874 
4875 #ifndef SQLITE_OMIT_VIRTUALTABLE
4876 /* Opcode: VRowid P1 * *
4877 **
4878 ** Push an integer onto the stack which is the rowid of
4879 ** the virtual-table that the P1 cursor is pointing to.
4880 */
4881 case OP_VRowid: {
4882   const sqlite3_module *pModule;
4883 
4884   Cursor *pCur = p->apCsr[pOp->p1];
4885   assert( pCur->pVtabCursor );
4886   pModule = pCur->pVtabCursor->pVtab->pModule;
4887   if( pModule->xRowid==0 ){
4888     sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xRowid", 0);
4889     rc = SQLITE_ERROR;
4890   } else {
4891     sqlite_int64 iRow;
4892 
4893     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4894     rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
4895     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4896 
4897     pTos++;
4898     pTos->flags = MEM_Int;
4899     pTos->u.i = iRow;
4900   }
4901 
4902   break;
4903 }
4904 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4905 
4906 #ifndef SQLITE_OMIT_VIRTUALTABLE
4907 /* Opcode: VColumn P1 P2 *
4908 **
4909 ** Push onto the stack the value of the P2-th column of
4910 ** the row of the virtual-table that the P1 cursor is pointing to.
4911 */
4912 case OP_VColumn: {
4913   const sqlite3_module *pModule;
4914 
4915   Cursor *pCur = p->apCsr[pOp->p1];
4916   assert( pCur->pVtabCursor );
4917   pModule = pCur->pVtabCursor->pVtab->pModule;
4918   if( pModule->xColumn==0 ){
4919     sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xColumn", 0);
4920     rc = SQLITE_ERROR;
4921   } else {
4922     sqlite3_context sContext;
4923     memset(&sContext, 0, sizeof(sContext));
4924     sContext.s.flags = MEM_Null;
4925     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4926     rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
4927 
4928     /* Copy the result of the function to the top of the stack. We
4929     ** do this regardless of whether or not an error occured to ensure any
4930     ** dynamic allocation in sContext.s (a Mem struct) is  released.
4931     */
4932     sqlite3VdbeChangeEncoding(&sContext.s, encoding);
4933     pTos++;
4934     pTos->flags = 0;
4935     sqlite3VdbeMemMove(pTos, &sContext.s);
4936 
4937     if( sqlite3SafetyOn(db) ){
4938       goto abort_due_to_misuse;
4939     }
4940     if( sqlite3VdbeMemTooBig(pTos) ){
4941       goto too_big;
4942     }
4943   }
4944 
4945   break;
4946 }
4947 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4948 
4949 #ifndef SQLITE_OMIT_VIRTUALTABLE
4950 /* Opcode: VNext P1 P2 *
4951 **
4952 ** Advance virtual table P1 to the next row in its result set and
4953 ** jump to instruction P2.  Or, if the virtual table has reached
4954 ** the end of its result set, then fall through to the next instruction.
4955 */
4956 case OP_VNext: {   /* no-push */
4957   const sqlite3_module *pModule;
4958   int res = 0;
4959 
4960   Cursor *pCur = p->apCsr[pOp->p1];
4961   assert( pCur->pVtabCursor );
4962   pModule = pCur->pVtabCursor->pVtab->pModule;
4963   if( pModule->xNext==0 ){
4964     sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xNext", 0);
4965     rc = SQLITE_ERROR;
4966   } else {
4967     /* Invoke the xNext() method of the module. There is no way for the
4968     ** underlying implementation to return an error if one occurs during
4969     ** xNext(). Instead, if an error occurs, true is returned (indicating that
4970     ** data is available) and the error code returned when xColumn or
4971     ** some other method is next invoked on the save virtual table cursor.
4972     */
4973     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4974     p->inVtabMethod = 1;
4975     rc = pModule->xNext(pCur->pVtabCursor);
4976     p->inVtabMethod = 0;
4977     if( rc==SQLITE_OK ){
4978       res = pModule->xEof(pCur->pVtabCursor);
4979     }
4980     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4981 
4982     if( !res ){
4983       /* If there is data, jump to P2 */
4984       pc = pOp->p2 - 1;
4985     }
4986   }
4987 
4988   break;
4989 }
4990 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4991 
4992 
4993 #ifndef SQLITE_OMIT_VIRTUALTABLE
4994 /* Opcode: VUpdate P1 P2 P3
4995 **
4996 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
4997 ** This opcode invokes the corresponding xUpdate method. P2 values
4998 ** are taken from the stack to pass to the xUpdate invocation. The
4999 ** value on the top of the stack corresponds to the p2th element
5000 ** of the argv array passed to xUpdate.
5001 **
5002 ** The xUpdate method will do a DELETE or an INSERT or both.
5003 ** The argv[0] element (which corresponds to the P2-th element down
5004 ** on the stack) is the rowid of a row to delete.  If argv[0] is
5005 ** NULL then no deletion occurs.  The argv[1] element is the rowid
5006 ** of the new row.  This can be NULL to have the virtual table
5007 ** select the new rowid for itself.  The higher elements in the
5008 ** stack are the values of columns in the new row.
5009 **
5010 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
5011 ** a row to delete.
5012 **
5013 ** P1 is a boolean flag. If it is set to true and the xUpdate call
5014 ** is successful, then the value returned by sqlite3_last_insert_rowid()
5015 ** is set to the value of the rowid for the row just inserted.
5016 */
5017 case OP_VUpdate: {   /* no-push */
5018   sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
5019   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
5020   int nArg = pOp->p2;
5021   assert( pOp->p3type==P3_VTAB );
5022   if( pModule->xUpdate==0 ){
5023     sqlite3SetString(&p->zErrMsg, "read-only table", 0);
5024     rc = SQLITE_ERROR;
5025   }else{
5026     int i;
5027     sqlite_int64 rowid;
5028     Mem **apArg = p->apArg;
5029     Mem *pX = &pTos[1-nArg];
5030     for(i = 0; i<nArg; i++, pX++){
5031       storeTypeInfo(pX, 0);
5032       apArg[i] = pX;
5033     }
5034     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
5035     sqlite3VtabLock(pVtab);
5036     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
5037     sqlite3VtabUnlock(db, pVtab);
5038     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
5039     if( pOp->p1 && rc==SQLITE_OK ){
5040       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
5041       db->lastRowid = rowid;
5042     }
5043   }
5044   popStack(&pTos, nArg);
5045   break;
5046 }
5047 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5048 
5049 /* An other opcode is illegal...
5050 */
5051 default: {
5052   assert( 0 );
5053   break;
5054 }
5055 
5056 /*****************************************************************************
5057 ** The cases of the switch statement above this line should all be indented
5058 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
5059 ** readability.  From this point on down, the normal indentation rules are
5060 ** restored.
5061 *****************************************************************************/
5062     }
5063 
5064     /* Make sure the stack limit was not exceeded */
5065     assert( pTos<=pStackLimit );
5066 
5067 #ifdef VDBE_PROFILE
5068     {
5069       long long elapse = hwtime() - start;
5070       pOp->cycles += elapse;
5071       pOp->cnt++;
5072 #if 0
5073         fprintf(stdout, "%10lld ", elapse);
5074         sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
5075 #endif
5076     }
5077 #endif
5078 
5079 #ifdef SQLITE_TEST
5080     /* Keep track of the size of the largest BLOB or STR that has appeared
5081     ** on the top of the VDBE stack.
5082     */
5083     if( pTos>=p->aStack && (pTos->flags & (MEM_Blob|MEM_Str))!=0
5084          && pTos->n>sqlite3_max_blobsize ){
5085       sqlite3_max_blobsize = pTos->n;
5086     }
5087 #endif
5088 
5089     /* The following code adds nothing to the actual functionality
5090     ** of the program.  It is only here for testing and debugging.
5091     ** On the other hand, it does burn CPU cycles every time through
5092     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
5093     */
5094 #ifndef NDEBUG
5095     /* Sanity checking on the top element of the stack. If the previous
5096     ** instruction was VNoChange, then the flags field of the top
5097     ** of the stack is set to 0. This is technically invalid for a memory
5098     ** cell, so avoid calling MemSanity() in this case.
5099     */
5100     if( pTos>=p->aStack && pTos->flags ){
5101       sqlite3VdbeMemSanity(pTos);
5102       assert( !sqlite3VdbeMemTooBig(pTos) );
5103     }
5104     assert( pc>=-1 && pc<p->nOp );
5105 
5106 #ifdef SQLITE_DEBUG
5107     /* Code for tracing the vdbe stack. */
5108     if( p->trace && pTos>=p->aStack ){
5109       int i;
5110       fprintf(p->trace, "Stack:");
5111       for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
5112         if( pTos[i].flags & MEM_Null ){
5113           fprintf(p->trace, " NULL");
5114         }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
5115           fprintf(p->trace, " si:%lld", pTos[i].u.i);
5116         }else if( pTos[i].flags & MEM_Int ){
5117           fprintf(p->trace, " i:%lld", pTos[i].u.i);
5118         }else if( pTos[i].flags & MEM_Real ){
5119           fprintf(p->trace, " r:%g", pTos[i].r);
5120         }else{
5121           char zBuf[200];
5122           sqlite3VdbeMemPrettyPrint(&pTos[i], zBuf);
5123           fprintf(p->trace, " ");
5124           fprintf(p->trace, "%s", zBuf);
5125         }
5126       }
5127       if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
5128       fprintf(p->trace,"\n");
5129     }
5130 #endif  /* SQLITE_DEBUG */
5131 #endif  /* NDEBUG */
5132   }  /* The end of the for(;;) loop the loops through opcodes */
5133 
5134   /* If we reach this point, it means that execution is finished.
5135   */
5136 vdbe_halt:
5137   if( rc ){
5138     p->rc = rc;
5139     rc = SQLITE_ERROR;
5140   }else{
5141     rc = SQLITE_DONE;
5142   }
5143   sqlite3VdbeHalt(p);
5144   p->pTos = pTos;
5145   return rc;
5146 
5147   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
5148   ** is encountered.
5149   */
5150 too_big:
5151   sqlite3SetString(&p->zErrMsg, "string or blob too big", (char*)0);
5152   rc = SQLITE_TOOBIG;
5153   goto vdbe_halt;
5154 
5155   /* Jump to here if a malloc() fails.
5156   */
5157 no_mem:
5158   sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0);
5159   rc = SQLITE_NOMEM;
5160   goto vdbe_halt;
5161 
5162   /* Jump to here for an SQLITE_MISUSE error.
5163   */
5164 abort_due_to_misuse:
5165   rc = SQLITE_MISUSE;
5166   /* Fall thru into abort_due_to_error */
5167 
5168   /* Jump to here for any other kind of fatal error.  The "rc" variable
5169   ** should hold the error number.
5170   */
5171 abort_due_to_error:
5172   if( p->zErrMsg==0 ){
5173     if( sqlite3MallocFailed() ) rc = SQLITE_NOMEM;
5174     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
5175   }
5176   goto vdbe_halt;
5177 
5178   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
5179   ** flag.
5180   */
5181 abort_due_to_interrupt:
5182   assert( db->u1.isInterrupted );
5183   if( db->magic!=SQLITE_MAGIC_BUSY ){
5184     rc = SQLITE_MISUSE;
5185   }else{
5186     rc = SQLITE_INTERRUPT;
5187   }
5188   p->rc = rc;
5189   sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
5190   goto vdbe_halt;
5191 }
5192