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