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