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