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