Back to index

lightning-sunbird  0.9+nobinonly
vdbe.c
Go to the documentation of this file.
00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** The code in this file implements execution method of the 
00013 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
00014 ** handles housekeeping details such as creating and deleting
00015 ** VDBE instances.  This file is solely interested in executing
00016 ** the VDBE program.
00017 **
00018 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
00019 ** to a VDBE.
00020 **
00021 ** The SQL parser generates a program which is then executed by
00022 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
00023 ** similar in form to assembly language.  The program consists of
00024 ** a linear sequence of operations.  Each operation has an opcode 
00025 ** and 3 operands.  Operands P1 and P2 are integers.  Operand P3 
00026 ** is a null-terminated string.   The P2 operand must be non-negative.
00027 ** Opcodes will typically ignore one or more operands.  Many opcodes
00028 ** ignore all three operands.
00029 **
00030 ** Computation results are stored on a stack.  Each entry on the
00031 ** stack is either an integer, a null-terminated string, a floating point
00032 ** number, or the SQL "NULL" value.  An inplicit conversion from one
00033 ** type to the other occurs as necessary.
00034 ** 
00035 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
00036 ** function which does the work of interpreting a VDBE program.
00037 ** But other routines are also provided to help in building up
00038 ** a program instruction by instruction.
00039 **
00040 ** Various scripts scan this source file in order to generate HTML
00041 ** documentation, headers files, or other derived files.  The formatting
00042 ** of the code in this file is, therefore, important.  See other comments
00043 ** in this file for details.  If in doubt, do not deviate from existing
00044 ** commenting and indentation practices when changing or adding code.
00045 **
00046 ** $Id: vdbe.c,v 1.548 2006/03/22 22:10:08 drh Exp $
00047 */
00048 #include "sqliteInt.h"
00049 #include "os.h"
00050 #include <ctype.h>
00051 #include "vdbeInt.h"
00052 
00053 /*
00054 ** The following global variable is incremented every time a cursor
00055 ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes.  The test
00056 ** procedures use this information to make sure that indices are
00057 ** working correctly.  This variable has no function other than to
00058 ** help verify the correct operation of the library.
00059 */
00060 int sqlite3_search_count = 0;
00061 
00062 /*
00063 ** When this global variable is positive, it gets decremented once before
00064 ** each instruction in the VDBE.  When reaches zero, the SQLITE_Interrupt
00065 ** of the db.flags field is set in order to simulate and interrupt.
00066 **
00067 ** This facility is used for testing purposes only.  It does not function
00068 ** in an ordinary build.
00069 */
00070 int sqlite3_interrupt_count = 0;
00071 
00072 /*
00073 ** The next global variable is incremented each type the OP_Sort opcode
00074 ** is executed.  The test procedures use this information to make sure that
00075 ** sorting is occurring or not occuring at appropriate times.   This variable
00076 ** has no function other than to help verify the correct operation of the
00077 ** library.
00078 */
00079 int sqlite3_sort_count = 0;
00080 
00081 /*
00082 ** Release the memory associated with the given stack level.  This
00083 ** leaves the Mem.flags field in an inconsistent state.
00084 */
00085 #define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
00086 
00087 /*
00088 ** Convert the given stack entity into a string if it isn't one
00089 ** already. Return non-zero if a malloc() fails.
00090 */
00091 #define Stringify(P, enc) \
00092    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
00093      { goto no_mem; }
00094 
00095 /*
00096 ** Convert the given stack entity into a string that has been obtained
00097 ** from sqliteMalloc().  This is different from Stringify() above in that
00098 ** Stringify() will use the NBFS bytes of static string space if the string
00099 ** will fit but this routine always mallocs for space.
00100 ** Return non-zero if we run out of memory.
00101 */
00102 #define Dynamicify(P,enc) sqlite3VdbeMemDynamicify(P)
00103 
00104 /*
00105 ** The header of a record consists of a sequence variable-length integers.
00106 ** These integers are almost always small and are encoded as a single byte.
00107 ** The following macro takes advantage this fact to provide a fast decode
00108 ** of the integers in a record header.  It is faster for the common case
00109 ** where the integer is a single byte.  It is a little slower when the
00110 ** integer is two or more bytes.  But overall it is faster.
00111 **
00112 ** The following expressions are equivalent:
00113 **
00114 **     x = sqlite3GetVarint32( A, &B );
00115 **
00116 **     x = GetVarint( A, B );
00117 **
00118 */
00119 #define GetVarint(A,B)  ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
00120 
00121 /*
00122 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
00123 ** a pointer to a dynamically allocated string where some other entity
00124 ** is responsible for deallocating that string.  Because the stack entry
00125 ** does not control the string, it might be deleted without the stack
00126 ** entry knowing it.
00127 **
00128 ** This routine converts an ephemeral string into a dynamically allocated
00129 ** string that the stack entry itself controls.  In other words, it
00130 ** converts an MEM_Ephem string into an MEM_Dyn string.
00131 */
00132 #define Deephemeralize(P) \
00133    if( ((P)->flags&MEM_Ephem)!=0 \
00134        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
00135 
00136 /*
00137 ** Argument pMem points at a memory cell that will be passed to a
00138 ** user-defined function or returned to the user as the result of a query.
00139 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
00140 ** stack variables.  This routine sets the pMem->enc and pMem->type
00141 ** variables used by the sqlite3_value_*() routines.
00142 */
00143 #define storeTypeInfo(A,B) _storeTypeInfo(A)
00144 static void _storeTypeInfo(Mem *pMem){
00145   int flags = pMem->flags;
00146   if( flags & MEM_Null ){
00147     pMem->type = SQLITE_NULL;
00148   }
00149   else if( flags & MEM_Int ){
00150     pMem->type = SQLITE_INTEGER;
00151   }
00152   else if( flags & MEM_Real ){
00153     pMem->type = SQLITE_FLOAT;
00154   }
00155   else if( flags & MEM_Str ){
00156     pMem->type = SQLITE_TEXT;
00157   }else{
00158     pMem->type = SQLITE_BLOB;
00159   }
00160 }
00161 
00162 /*
00163 ** Pop the stack N times.
00164 */
00165 static void popStack(Mem **ppTos, int N){
00166   Mem *pTos = *ppTos;
00167   while( N>0 ){
00168     N--;
00169     Release(pTos);
00170     pTos--;
00171   }
00172   *ppTos = pTos;
00173 }
00174 
00175 /*
00176 ** Allocate cursor number iCur.  Return a pointer to it.  Return NULL
00177 ** if we run out of memory.
00178 */
00179 static Cursor *allocateCursor(Vdbe *p, int iCur, int iDb){
00180   Cursor *pCx;
00181   assert( iCur<p->nCursor );
00182   if( p->apCsr[iCur] ){
00183     sqlite3VdbeFreeCursor(p->apCsr[iCur]);
00184   }
00185   p->apCsr[iCur] = pCx = sqliteMalloc( sizeof(Cursor) );
00186   if( pCx ){
00187     pCx->iDb = iDb;
00188   }
00189   return pCx;
00190 }
00191 
00192 /*
00193 ** Try to convert a value into a numeric representation if we can
00194 ** do so without loss of information.  In other words, if the string
00195 ** looks like a number, convert it into a number.  If it does not
00196 ** look like a number, leave it alone.
00197 */
00198 static void applyNumericAffinity(Mem *pRec){
00199   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
00200     int realnum;
00201     sqlite3VdbeMemNulTerminate(pRec);
00202     if( (pRec->flags&MEM_Str)
00203          && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
00204       i64 value;
00205       sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
00206       if( !realnum && sqlite3atoi64(pRec->z, &value) ){
00207         sqlite3VdbeMemRelease(pRec);
00208         pRec->i = value;
00209         pRec->flags = MEM_Int;
00210       }else{
00211         sqlite3VdbeMemRealify(pRec);
00212       }
00213     }
00214   }
00215 }
00216 
00217 /*
00218 ** Processing is determine by the affinity parameter:
00219 **
00220 ** SQLITE_AFF_INTEGER:
00221 ** SQLITE_AFF_REAL:
00222 ** SQLITE_AFF_NUMERIC:
00223 **    Try to convert pRec to an integer representation or a 
00224 **    floating-point representation if an integer representation
00225 **    is not possible.  Note that the integer representation is
00226 **    always preferred, even if the affinity is REAL, because
00227 **    an integer representation is more space efficient on disk.
00228 **
00229 ** SQLITE_AFF_TEXT:
00230 **    Convert pRec to a text representation.
00231 **
00232 ** SQLITE_AFF_NONE:
00233 **    No-op.  pRec is unchanged.
00234 */
00235 static void applyAffinity(Mem *pRec, char affinity, u8 enc){
00236   if( affinity==SQLITE_AFF_TEXT ){
00237     /* Only attempt the conversion to TEXT if there is an integer or real
00238     ** representation (blob and NULL do not get converted) but no string
00239     ** representation.
00240     */
00241     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
00242       sqlite3VdbeMemStringify(pRec, enc);
00243     }
00244     pRec->flags &= ~(MEM_Real|MEM_Int);
00245   }else if( affinity!=SQLITE_AFF_NONE ){
00246     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
00247              || affinity==SQLITE_AFF_NUMERIC );
00248     applyNumericAffinity(pRec);
00249     if( pRec->flags & MEM_Real ){
00250       sqlite3VdbeIntegerAffinity(pRec);
00251     }
00252   }
00253 }
00254 
00255 /*
00256 ** Try to convert the type of a function argument or a result column
00257 ** into a numeric representation.  Use either INTEGER or REAL whichever
00258 ** is appropriate.  But only do the conversion if it is possible without
00259 ** loss of information and return the revised type of the argument.
00260 **
00261 ** This is an EXPERIMENTAL api and is subject to change or removal.
00262 */
00263 int sqlite3_value_numeric_type(sqlite3_value *pVal){
00264   Mem *pMem = (Mem*)pVal;
00265   applyNumericAffinity(pMem);
00266   storeTypeInfo(pMem, 0);
00267   return pMem->type;
00268 }
00269 
00270 /*
00271 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
00272 ** not the internal Mem* type.
00273 */
00274 void sqlite3ValueApplyAffinity(sqlite3_value *pVal, u8 affinity, u8 enc){
00275   applyAffinity((Mem *)pVal, affinity, enc);
00276 }
00277 
00278 #ifdef SQLITE_DEBUG
00279 /*
00280 ** Write a nice string representation of the contents of cell pMem
00281 ** into buffer zBuf, length nBuf.
00282 */
00283 void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
00284   char *zCsr = zBuf;
00285   int f = pMem->flags;
00286 
00287   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
00288 
00289   if( f&MEM_Blob ){
00290     int i;
00291     char c;
00292     if( f & MEM_Dyn ){
00293       c = 'z';
00294       assert( (f & (MEM_Static|MEM_Ephem))==0 );
00295     }else if( f & MEM_Static ){
00296       c = 't';
00297       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
00298     }else if( f & MEM_Ephem ){
00299       c = 'e';
00300       assert( (f & (MEM_Static|MEM_Dyn))==0 );
00301     }else{
00302       c = 's';
00303     }
00304 
00305     zCsr += sprintf(zCsr, "%c", c);
00306     zCsr += sprintf(zCsr, "%d[", pMem->n);
00307     for(i=0; i<16 && i<pMem->n; i++){
00308       zCsr += sprintf(zCsr, "%02X ", ((int)pMem->z[i] & 0xFF));
00309     }
00310     for(i=0; i<16 && i<pMem->n; i++){
00311       char z = pMem->z[i];
00312       if( z<32 || z>126 ) *zCsr++ = '.';
00313       else *zCsr++ = z;
00314     }
00315 
00316     zCsr += sprintf(zCsr, "]");
00317     *zCsr = '\0';
00318   }else if( f & MEM_Str ){
00319     int j, k;
00320     zBuf[0] = ' ';
00321     if( f & MEM_Dyn ){
00322       zBuf[1] = 'z';
00323       assert( (f & (MEM_Static|MEM_Ephem))==0 );
00324     }else if( f & MEM_Static ){
00325       zBuf[1] = 't';
00326       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
00327     }else if( f & MEM_Ephem ){
00328       zBuf[1] = 'e';
00329       assert( (f & (MEM_Static|MEM_Dyn))==0 );
00330     }else{
00331       zBuf[1] = 's';
00332     }
00333     k = 2;
00334     k += sprintf(&zBuf[k], "%d", pMem->n);
00335     zBuf[k++] = '[';
00336     for(j=0; j<15 && j<pMem->n; j++){
00337       u8 c = pMem->z[j];
00338       if( c>=0x20 && c<0x7f ){
00339         zBuf[k++] = c;
00340       }else{
00341         zBuf[k++] = '.';
00342       }
00343     }
00344     zBuf[k++] = ']';
00345     k += sprintf(&zBuf[k], encnames[pMem->enc]);
00346     zBuf[k++] = 0;
00347   }
00348 }
00349 #endif
00350 
00351 
00352 #ifdef VDBE_PROFILE
00353 /*
00354 ** The following routine only works on pentium-class processors.
00355 ** It uses the RDTSC opcode to read the cycle count value out of the
00356 ** processor and returns that value.  This can be used for high-res
00357 ** profiling.
00358 */
00359 __inline__ unsigned long long int hwtime(void){
00360   unsigned long long int x;
00361   __asm__("rdtsc\n\t"
00362           "mov %%edx, %%ecx\n\t"
00363           :"=A" (x));
00364   return x;
00365 }
00366 #endif
00367 
00368 /*
00369 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
00370 ** sqlite3_interrupt() routine has been called.  If it has been, then
00371 ** processing of the VDBE program is interrupted.
00372 **
00373 ** This macro added to every instruction that does a jump in order to
00374 ** implement a loop.  This test used to be on every single instruction,
00375 ** but that meant we more testing that we needed.  By only testing the
00376 ** flag on jump instructions, we get a (small) speed improvement.
00377 */
00378 #define CHECK_FOR_INTERRUPT \
00379    if( db->flags & SQLITE_Interrupt ) goto abort_due_to_interrupt;
00380 
00381 
00382 /*
00383 ** Execute as much of a VDBE program as we can then return.
00384 **
00385 ** sqlite3VdbeMakeReady() must be called before this routine in order to
00386 ** close the program with a final OP_Halt and to set up the callbacks
00387 ** and the error message pointer.
00388 **
00389 ** Whenever a row or result data is available, this routine will either
00390 ** invoke the result callback (if there is one) or return with
00391 ** SQLITE_ROW.
00392 **
00393 ** If an attempt is made to open a locked database, then this routine
00394 ** will either invoke the busy callback (if there is one) or it will
00395 ** return SQLITE_BUSY.
00396 **
00397 ** If an error occurs, an error message is written to memory obtained
00398 ** from sqliteMalloc() and p->zErrMsg is made to point to that memory.
00399 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
00400 **
00401 ** If the callback ever returns non-zero, then the program exits
00402 ** immediately.  There will be no error message but the p->rc field is
00403 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
00404 **
00405 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
00406 ** routine to return SQLITE_ERROR.
00407 **
00408 ** Other fatal errors return SQLITE_ERROR.
00409 **
00410 ** After this routine has finished, sqlite3VdbeFinalize() should be
00411 ** used to clean up the mess that was left behind.
00412 */
00413 int sqlite3VdbeExec(
00414   Vdbe *p                    /* The VDBE */
00415 ){
00416   int pc;                    /* The program counter */
00417   Op *pOp;                   /* Current operation */
00418   int rc = SQLITE_OK;        /* Value to return */
00419   sqlite3 *db = p->db;       /* The database */
00420   u8 encoding = ENC(db);     /* The database encoding */
00421   Mem *pTos;                 /* Top entry in the operand stack */
00422 #ifdef VDBE_PROFILE
00423   unsigned long long start;  /* CPU clock count at start of opcode */
00424   int origPc;                /* Program counter at start of opcode */
00425 #endif
00426 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
00427   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
00428 #endif
00429 #ifndef NDEBUG
00430   Mem *pStackLimit;
00431 #endif
00432 
00433   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
00434   assert( db->magic==SQLITE_MAGIC_BUSY );
00435   pTos = p->pTos;
00436   if( p->rc==SQLITE_NOMEM ){
00437     /* This happens if a malloc() inside a call to sqlite3_column_text() or
00438     ** sqlite3_column_text16() failed.  */
00439     goto no_mem;
00440   }
00441   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
00442   p->rc = SQLITE_OK;
00443   assert( p->explain==0 );
00444   if( p->popStack ){
00445     popStack(&pTos, p->popStack);
00446     p->popStack = 0;
00447   }
00448   p->resOnStack = 0;
00449   db->busyHandler.nBusy = 0;
00450   CHECK_FOR_INTERRUPT;
00451   for(pc=p->pc; rc==SQLITE_OK; pc++){
00452     assert( pc>=0 && pc<p->nOp );
00453     assert( pTos<=&p->aStack[pc] );
00454     if( sqlite3MallocFailed() ) goto no_mem;
00455 #ifdef VDBE_PROFILE
00456     origPc = pc;
00457     start = hwtime();
00458 #endif
00459     pOp = &p->aOp[pc];
00460 
00461     /* Only allow tracing if SQLITE_DEBUG is defined.
00462     */
00463 #ifdef SQLITE_DEBUG
00464     if( p->trace ){
00465       if( pc==0 ){
00466         printf("VDBE Execution Trace:\n");
00467         sqlite3VdbePrintSql(p);
00468       }
00469       sqlite3VdbePrintOp(p->trace, pc, pOp);
00470     }
00471     if( p->trace==0 && pc==0 && sqlite3OsFileExists("vdbe_sqltrace") ){
00472       sqlite3VdbePrintSql(p);
00473     }
00474 #endif
00475       
00476 
00477     /* Check to see if we need to simulate an interrupt.  This only happens
00478     ** if we have a special test build.
00479     */
00480 #ifdef SQLITE_TEST
00481     if( sqlite3_interrupt_count>0 ){
00482       sqlite3_interrupt_count--;
00483       if( sqlite3_interrupt_count==0 ){
00484         sqlite3_interrupt(db);
00485       }
00486     }
00487 #endif
00488 
00489 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
00490     /* Call the progress callback if it is configured and the required number
00491     ** of VDBE ops have been executed (either since this invocation of
00492     ** sqlite3VdbeExec() or since last time the progress callback was called).
00493     ** If the progress callback returns non-zero, exit the virtual machine with
00494     ** a return code SQLITE_ABORT.
00495     */
00496     if( db->xProgress ){
00497       if( db->nProgressOps==nProgressOps ){
00498         if( db->xProgress(db->pProgressArg)!=0 ){
00499           rc = SQLITE_ABORT;
00500           continue; /* skip to the next iteration of the for loop */
00501         }
00502         nProgressOps = 0;
00503       }
00504       nProgressOps++;
00505     }
00506 #endif
00507 
00508 #ifndef NDEBUG
00509     /* This is to check that the return value of static function
00510     ** opcodeNoPush() (see vdbeaux.c) returns values that match the
00511     ** implementation of the virtual machine in this file. If
00512     ** opcodeNoPush() returns non-zero, then the stack is guarenteed
00513     ** not to grow when the opcode is executed. If it returns zero, then
00514     ** the stack may grow by at most 1.
00515     **
00516     ** The global wrapper function sqlite3VdbeOpcodeUsesStack() is not 
00517     ** available if NDEBUG is defined at build time.
00518     */ 
00519     pStackLimit = pTos;
00520     if( !sqlite3VdbeOpcodeNoPush(pOp->opcode) ){
00521       pStackLimit++;
00522     }
00523 #endif
00524 
00525     switch( pOp->opcode ){
00526 
00527 /*****************************************************************************
00528 ** What follows is a massive switch statement where each case implements a
00529 ** separate instruction in the virtual machine.  If we follow the usual
00530 ** indentation conventions, each case should be indented by 6 spaces.  But
00531 ** that is a lot of wasted space on the left margin.  So the code within
00532 ** the switch statement will break with convention and be flush-left. Another
00533 ** big comment (similar to this one) will mark the point in the code where
00534 ** we transition back to normal indentation.
00535 **
00536 ** The formatting of each case is important.  The makefile for SQLite
00537 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
00538 ** file looking for lines that begin with "case OP_".  The opcodes.h files
00539 ** will be filled with #defines that give unique integer values to each
00540 ** opcode and the opcodes.c file is filled with an array of strings where
00541 ** each string is the symbolic name for the corresponding opcode.  If the
00542 ** case statement is followed by a comment of the form "/# same as ... #/"
00543 ** that comment is used to determine the particular value of the opcode.
00544 **
00545 ** If a comment on the same line as the "case OP_" construction contains
00546 ** the word "no-push", then the opcode is guarenteed not to grow the 
00547 ** vdbe stack when it is executed. See function opcode() in
00548 ** vdbeaux.c for details.
00549 **
00550 ** Documentation about VDBE opcodes is generated by scanning this file
00551 ** for lines of that contain "Opcode:".  That line and all subsequent
00552 ** comment lines are used in the generation of the opcode.html documentation
00553 ** file.
00554 **
00555 ** SUMMARY:
00556 **
00557 **     Formatting is important to scripts that scan this file.
00558 **     Do not deviate from the formatting style currently in use.
00559 **
00560 *****************************************************************************/
00561 
00562 /* Opcode:  Goto * P2 *
00563 **
00564 ** An unconditional jump to address P2.
00565 ** The next instruction executed will be 
00566 ** the one at index P2 from the beginning of
00567 ** the program.
00568 */
00569 case OP_Goto: {             /* no-push */
00570   CHECK_FOR_INTERRUPT;
00571   pc = pOp->p2 - 1;
00572   break;
00573 }
00574 
00575 /* Opcode:  Gosub * P2 *
00576 **
00577 ** Push the current address plus 1 onto the return address stack
00578 ** and then jump to address P2.
00579 **
00580 ** The return address stack is of limited depth.  If too many
00581 ** OP_Gosub operations occur without intervening OP_Returns, then
00582 ** the return address stack will fill up and processing will abort
00583 ** with a fatal error.
00584 */
00585 case OP_Gosub: {            /* no-push */
00586   assert( p->returnDepth<sizeof(p->returnStack)/sizeof(p->returnStack[0]) );
00587   p->returnStack[p->returnDepth++] = pc+1;
00588   pc = pOp->p2 - 1;
00589   break;
00590 }
00591 
00592 /* Opcode:  Return * * *
00593 **
00594 ** Jump immediately to the next instruction after the last unreturned
00595 ** OP_Gosub.  If an OP_Return has occurred for all OP_Gosubs, then
00596 ** processing aborts with a fatal error.
00597 */
00598 case OP_Return: {           /* no-push */
00599   assert( p->returnDepth>0 );
00600   p->returnDepth--;
00601   pc = p->returnStack[p->returnDepth] - 1;
00602   break;
00603 }
00604 
00605 /* Opcode:  Halt P1 P2 P3
00606 **
00607 ** Exit immediately.  All open cursors, Fifos, etc are closed
00608 ** automatically.
00609 **
00610 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
00611 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
00612 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
00613 ** whether or not to rollback the current transaction.  Do not rollback
00614 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
00615 ** then back out all changes that have occurred during this execution of the
00616 ** VDBE, but do not rollback the transaction. 
00617 **
00618 ** If P3 is not null then it is an error message string.
00619 **
00620 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
00621 ** every program.  So a jump past the last instruction of the program
00622 ** is the same as executing Halt.
00623 */
00624 case OP_Halt: {            /* no-push */
00625   p->pTos = pTos;
00626   p->rc = pOp->p1;
00627   p->pc = pc;
00628   p->errorAction = pOp->p2;
00629   if( pOp->p3 ){
00630     sqlite3SetString(&p->zErrMsg, pOp->p3, (char*)0);
00631   }
00632   rc = sqlite3VdbeHalt(p);
00633   assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
00634   if( rc==SQLITE_BUSY ){
00635     p->rc = SQLITE_BUSY;
00636     return SQLITE_BUSY;
00637   }
00638   return p->rc ? SQLITE_ERROR : SQLITE_DONE;
00639 }
00640 
00641 /* Opcode: Integer P1 * *
00642 **
00643 ** The 32-bit integer value P1 is pushed onto the stack.
00644 */
00645 case OP_Integer: {
00646   pTos++;
00647   pTos->flags = MEM_Int;
00648   pTos->i = pOp->p1;
00649   break;
00650 }
00651 
00652 /* Opcode: Int64 * * P3
00653 **
00654 ** P3 is a string representation of an integer.  Convert that integer
00655 ** to a 64-bit value and push it onto the stack.
00656 */
00657 case OP_Int64: {
00658   pTos++;
00659   assert( pOp->p3!=0 );
00660   pTos->flags = MEM_Str|MEM_Static|MEM_Term;
00661   pTos->z = pOp->p3;
00662   pTos->n = strlen(pTos->z);
00663   pTos->enc = SQLITE_UTF8;
00664   pTos->i = sqlite3VdbeIntValue(pTos);
00665   pTos->flags |= MEM_Int;
00666   break;
00667 }
00668 
00669 /* Opcode: Real * * P3
00670 **
00671 ** The string value P3 is converted to a real and pushed on to the stack.
00672 */
00673 case OP_Real: {            /* same as TK_FLOAT, */
00674   pTos++;
00675   pTos->flags = MEM_Str|MEM_Static|MEM_Term;
00676   pTos->z = pOp->p3;
00677   pTos->n = strlen(pTos->z);
00678   pTos->enc = SQLITE_UTF8;
00679   pTos->r = sqlite3VdbeRealValue(pTos);
00680   pTos->flags |= MEM_Real;
00681   sqlite3VdbeChangeEncoding(pTos, encoding);
00682   break;
00683 }
00684 
00685 /* Opcode: String8 * * P3
00686 **
00687 ** P3 points to a nul terminated UTF-8 string. This opcode is transformed 
00688 ** into an OP_String before it is executed for the first time.
00689 */
00690 case OP_String8: {         /* same as TK_STRING */
00691   assert( pOp->p3!=0 );
00692   pOp->opcode = OP_String;
00693   pOp->p1 = strlen(pOp->p3);
00694 
00695 #ifndef SQLITE_OMIT_UTF16
00696   if( encoding!=SQLITE_UTF8 ){
00697     pTos++;
00698     sqlite3VdbeMemSetStr(pTos, pOp->p3, -1, SQLITE_UTF8, SQLITE_STATIC);
00699     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pTos, encoding) ) goto no_mem;
00700     if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pTos) ) goto no_mem;
00701     pTos->flags &= ~(MEM_Dyn);
00702     pTos->flags |= MEM_Static;
00703     if( pOp->p3type==P3_DYNAMIC ){
00704       sqliteFree(pOp->p3);
00705     }
00706     pOp->p3type = P3_DYNAMIC;
00707     pOp->p3 = pTos->z;
00708     pOp->p1 = pTos->n;
00709     break;
00710   }
00711 #endif
00712   /* Otherwise fall through to the next case, OP_String */
00713 }
00714   
00715 /* Opcode: String P1 * P3
00716 **
00717 ** The string value P3 of length P1 (bytes) is pushed onto the stack.
00718 */
00719 case OP_String: {
00720   pTos++;
00721   assert( pOp->p3!=0 );
00722   pTos->flags = MEM_Str|MEM_Static|MEM_Term;
00723   pTos->z = pOp->p3;
00724   pTos->n = pOp->p1;
00725   pTos->enc = encoding;
00726   break;
00727 }
00728 
00729 /* Opcode: Null * * *
00730 **
00731 ** Push a NULL onto the stack.
00732 */
00733 case OP_Null: {
00734   pTos++;
00735   pTos->flags = MEM_Null;
00736   pTos->n = 0;
00737   break;
00738 }
00739 
00740 
00741 #ifndef SQLITE_OMIT_BLOB_LITERAL
00742 /* Opcode: HexBlob * * P3
00743 **
00744 ** P3 is an UTF-8 SQL hex encoding of a blob. The blob is pushed onto the
00745 ** vdbe stack.
00746 **
00747 ** The first time this instruction executes, in transforms itself into a
00748 ** 'Blob' opcode with a binary blob as P3.
00749 */
00750 case OP_HexBlob: {            /* same as TK_BLOB */
00751   pOp->opcode = OP_Blob;
00752   pOp->p1 = strlen(pOp->p3)/2;
00753   if( pOp->p1 ){
00754     char *zBlob = sqlite3HexToBlob(pOp->p3);
00755     if( !zBlob ) goto no_mem;
00756     if( pOp->p3type==P3_DYNAMIC ){
00757       sqliteFree(pOp->p3);
00758     }
00759     pOp->p3 = zBlob;
00760     pOp->p3type = P3_DYNAMIC;
00761   }else{
00762     if( pOp->p3type==P3_DYNAMIC ){
00763       sqliteFree(pOp->p3);
00764     }
00765     pOp->p3type = P3_STATIC;
00766     pOp->p3 = "";
00767   }
00768 
00769   /* Fall through to the next case, OP_Blob. */
00770 }
00771 
00772 /* Opcode: Blob P1 * P3
00773 **
00774 ** P3 points to a blob of data P1 bytes long. Push this
00775 ** value onto the stack. This instruction is not coded directly
00776 ** by the compiler. Instead, the compiler layer specifies
00777 ** an OP_HexBlob opcode, with the hex string representation of
00778 ** the blob as P3. This opcode is transformed to an OP_Blob
00779 ** the first time it is executed.
00780 */
00781 case OP_Blob: {
00782   pTos++;
00783   sqlite3VdbeMemSetStr(pTos, pOp->p3, pOp->p1, 0, 0);
00784   break;
00785 }
00786 #endif /* SQLITE_OMIT_BLOB_LITERAL */
00787 
00788 /* Opcode: Variable P1 * *
00789 **
00790 ** Push the value of variable P1 onto the stack.  A variable is
00791 ** an unknown in the original SQL string as handed to sqlite3_compile().
00792 ** Any occurance of the '?' character in the original SQL is considered
00793 ** a variable.  Variables in the SQL string are number from left to
00794 ** right beginning with 1.  The values of variables are set using the
00795 ** sqlite3_bind() API.
00796 */
00797 case OP_Variable: {
00798   int j = pOp->p1 - 1;
00799   assert( j>=0 && j<p->nVar );
00800 
00801   pTos++;
00802   sqlite3VdbeMemShallowCopy(pTos, &p->aVar[j], MEM_Static);
00803   break;
00804 }
00805 
00806 /* Opcode: Pop P1 * *
00807 **
00808 ** P1 elements are popped off of the top of stack and discarded.
00809 */
00810 case OP_Pop: {            /* no-push */
00811   assert( pOp->p1>=0 );
00812   popStack(&pTos, pOp->p1);
00813   assert( pTos>=&p->aStack[-1] );
00814   break;
00815 }
00816 
00817 /* Opcode: Dup P1 P2 *
00818 **
00819 ** A copy of the P1-th element of the stack 
00820 ** is made and pushed onto the top of the stack.
00821 ** The top of the stack is element 0.  So the
00822 ** instruction "Dup 0 0 0" will make a copy of the
00823 ** top of the stack.
00824 **
00825 ** If the content of the P1-th element is a dynamically
00826 ** allocated string, then a new copy of that string
00827 ** is made if P2==0.  If P2!=0, then just a pointer
00828 ** to the string is copied.
00829 **
00830 ** Also see the Pull instruction.
00831 */
00832 case OP_Dup: {
00833   Mem *pFrom = &pTos[-pOp->p1];
00834   assert( pFrom<=pTos && pFrom>=p->aStack );
00835   pTos++;
00836   sqlite3VdbeMemShallowCopy(pTos, pFrom, MEM_Ephem);
00837   if( pOp->p2 ){
00838     Deephemeralize(pTos);
00839   }
00840   break;
00841 }
00842 
00843 /* Opcode: Pull P1 * *
00844 **
00845 ** The P1-th element is removed from its current location on 
00846 ** the stack and pushed back on top of the stack.  The
00847 ** top of the stack is element 0, so "Pull 0 0 0" is
00848 ** a no-op.  "Pull 1 0 0" swaps the top two elements of
00849 ** the stack.
00850 **
00851 ** See also the Dup instruction.
00852 */
00853 case OP_Pull: {            /* no-push */
00854   Mem *pFrom = &pTos[-pOp->p1];
00855   int i;
00856   Mem ts;
00857 
00858   ts = *pFrom;
00859   Deephemeralize(pTos);
00860   for(i=0; i<pOp->p1; i++, pFrom++){
00861     Deephemeralize(&pFrom[1]);
00862     assert( (pFrom->flags & MEM_Ephem)==0 );
00863     *pFrom = pFrom[1];
00864     if( pFrom->flags & MEM_Short ){
00865       assert( pFrom->flags & (MEM_Str|MEM_Blob) );
00866       assert( pFrom->z==pFrom[1].zShort );
00867       pFrom->z = pFrom->zShort;
00868     }
00869   }
00870   *pTos = ts;
00871   if( pTos->flags & MEM_Short ){
00872     assert( pTos->flags & (MEM_Str|MEM_Blob) );
00873     assert( pTos->z==pTos[-pOp->p1].zShort );
00874     pTos->z = pTos->zShort;
00875   }
00876   break;
00877 }
00878 
00879 /* Opcode: Push P1 * *
00880 **
00881 ** Overwrite the value of the P1-th element down on the
00882 ** stack (P1==0 is the top of the stack) with the value
00883 ** of the top of the stack.  Then pop the top of the stack.
00884 */
00885 case OP_Push: {            /* no-push */
00886   Mem *pTo = &pTos[-pOp->p1];
00887 
00888   assert( pTo>=p->aStack );
00889   sqlite3VdbeMemMove(pTo, pTos);
00890   pTos--;
00891   break;
00892 }
00893 
00894 /* Opcode: Callback P1 * *
00895 **
00896 ** The top P1 values on the stack represent a single result row from
00897 ** a query.  This opcode causes the sqlite3_step() call to terminate
00898 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
00899 ** structure to provide access to the top P1 values as the result
00900 ** row.  When the sqlite3_step() function is run again, the top P1
00901 ** values will be automatically popped from the stack before the next
00902 ** instruction executes.
00903 */
00904 case OP_Callback: {            /* no-push */
00905   Mem *pMem;
00906   Mem *pFirstColumn;
00907   assert( p->nResColumn==pOp->p1 );
00908 
00909   /* Data in the pager might be moved or changed out from under us
00910   ** in between the return from this sqlite3_step() call and the
00911   ** next call to sqlite3_step().  So deephermeralize everything on 
00912   ** the stack.  Note that ephemeral data is never stored in memory 
00913   ** cells so we do not have to worry about them.
00914   */
00915   pFirstColumn = &pTos[0-pOp->p1];
00916   for(pMem = p->aStack; pMem<pFirstColumn; pMem++){
00917     Deephemeralize(pMem);
00918   }
00919 
00920   /* Invalidate all ephemeral cursor row caches */
00921   p->cacheCtr = (p->cacheCtr + 2)|1;
00922 
00923   /* Make sure the results of the current row are \000 terminated
00924   ** and have an assigned type.  The results are deephemeralized as
00925   ** as side effect.
00926   */
00927   for(; pMem<=pTos; pMem++ ){
00928     sqlite3VdbeMemNulTerminate(pMem);
00929     storeTypeInfo(pMem, encoding);
00930   }
00931 
00932   /* Set up the statement structure so that it will pop the current
00933   ** results from the stack when the statement returns.
00934   */
00935   p->resOnStack = 1;
00936   p->nCallback++;
00937   p->popStack = pOp->p1;
00938   p->pc = pc + 1;
00939   p->pTos = pTos;
00940   return SQLITE_ROW;
00941 }
00942 
00943 /* Opcode: Concat P1 P2 *
00944 **
00945 ** Look at the first P1+2 elements of the stack.  Append them all 
00946 ** together with the lowest element first.  The original P1+2 elements
00947 ** are popped from the stack if P2==0 and retained if P2==1.  If
00948 ** any element of the stack is NULL, then the result is NULL.
00949 **
00950 ** When P1==1, this routine makes a copy of the top stack element
00951 ** into memory obtained from sqliteMalloc().
00952 */
00953 case OP_Concat: {           /* same as TK_CONCAT */
00954   char *zNew;
00955   int nByte;
00956   int nField;
00957   int i, j;
00958   Mem *pTerm;
00959 
00960   /* Loop through the stack elements to see how long the result will be. */
00961   nField = pOp->p1 + 2;
00962   pTerm = &pTos[1-nField];
00963   nByte = 0;
00964   for(i=0; i<nField; i++, pTerm++){
00965     assert( pOp->p2==0 || (pTerm->flags&MEM_Str) );
00966     if( pTerm->flags&MEM_Null ){
00967       nByte = -1;
00968       break;
00969     }
00970     Stringify(pTerm, encoding);
00971     nByte += pTerm->n;
00972   }
00973 
00974   if( nByte<0 ){
00975     /* If nByte is less than zero, then there is a NULL value on the stack.
00976     ** In this case just pop the values off the stack (if required) and
00977     ** push on a NULL.
00978     */
00979     if( pOp->p2==0 ){
00980       popStack(&pTos, nField);
00981     }
00982     pTos++;
00983     pTos->flags = MEM_Null;
00984   }else{
00985     /* Otherwise malloc() space for the result and concatenate all the
00986     ** stack values.
00987     */
00988     zNew = sqliteMallocRaw( nByte+2 );
00989     if( zNew==0 ) goto no_mem;
00990     j = 0;
00991     pTerm = &pTos[1-nField];
00992     for(i=j=0; i<nField; i++, pTerm++){
00993       int n = pTerm->n;
00994       assert( pTerm->flags & (MEM_Str|MEM_Blob) );
00995       memcpy(&zNew[j], pTerm->z, n);
00996       j += n;
00997     }
00998     zNew[j] = 0;
00999     zNew[j+1] = 0;
01000     assert( j==nByte );
01001 
01002     if( pOp->p2==0 ){
01003       popStack(&pTos, nField);
01004     }
01005     pTos++;
01006     pTos->n = j;
01007     pTos->flags = MEM_Str|MEM_Dyn|MEM_Term;
01008     pTos->xDel = 0;
01009     pTos->enc = encoding;
01010     pTos->z = zNew;
01011   }
01012   break;
01013 }
01014 
01015 /* Opcode: Add * * *
01016 **
01017 ** Pop the top two elements from the stack, add them together,
01018 ** and push the result back onto the stack.  If either element
01019 ** is a string then it is converted to a double using the atof()
01020 ** function before the addition.
01021 ** If either operand is NULL, the result is NULL.
01022 */
01023 /* Opcode: Multiply * * *
01024 **
01025 ** Pop the top two elements from the stack, multiply them together,
01026 ** and push the result back onto the stack.  If either element
01027 ** is a string then it is converted to a double using the atof()
01028 ** function before the multiplication.
01029 ** If either operand is NULL, the result is NULL.
01030 */
01031 /* Opcode: Subtract * * *
01032 **
01033 ** Pop the top two elements from the stack, subtract the
01034 ** first (what was on top of the stack) from the second (the
01035 ** next on stack)
01036 ** and push the result back onto the stack.  If either element
01037 ** is a string then it is converted to a double using the atof()
01038 ** function before the subtraction.
01039 ** If either operand is NULL, the result is NULL.
01040 */
01041 /* Opcode: Divide * * *
01042 **
01043 ** Pop the top two elements from the stack, divide the
01044 ** first (what was on top of the stack) from the second (the
01045 ** next on stack)
01046 ** and push the result back onto the stack.  If either element
01047 ** is a string then it is converted to a double using the atof()
01048 ** function before the division.  Division by zero returns NULL.
01049 ** If either operand is NULL, the result is NULL.
01050 */
01051 /* Opcode: Remainder * * *
01052 **
01053 ** Pop the top two elements from the stack, divide the
01054 ** first (what was on top of the stack) from the second (the
01055 ** next on stack)
01056 ** and push the remainder after division onto the stack.  If either element
01057 ** is a string then it is converted to a double using the atof()
01058 ** function before the division.  Division by zero returns NULL.
01059 ** If either operand is NULL, the result is NULL.
01060 */
01061 case OP_Add:                   /* same as TK_PLUS, no-push */
01062 case OP_Subtract:              /* same as TK_MINUS, no-push */
01063 case OP_Multiply:              /* same as TK_STAR, no-push */
01064 case OP_Divide:                /* same as TK_SLASH, no-push */
01065 case OP_Remainder: {           /* same as TK_REM, no-push */
01066   Mem *pNos = &pTos[-1];
01067   int flags;
01068   assert( pNos>=p->aStack );
01069   flags = pTos->flags | pNos->flags;
01070   if( (flags & MEM_Null)!=0 ){
01071     Release(pTos);
01072     pTos--;
01073     Release(pTos);
01074     pTos->flags = MEM_Null;
01075   }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){
01076     i64 a, b;
01077     a = pTos->i;
01078     b = pNos->i;
01079     switch( pOp->opcode ){
01080       case OP_Add:         b += a;       break;
01081       case OP_Subtract:    b -= a;       break;
01082       case OP_Multiply:    b *= a;       break;
01083       case OP_Divide: {
01084         if( a==0 ) goto divide_by_zero;
01085         b /= a;
01086         break;
01087       }
01088       default: {
01089         if( a==0 ) goto divide_by_zero;
01090         b %= a;
01091         break;
01092       }
01093     }
01094     Release(pTos);
01095     pTos--;
01096     Release(pTos);
01097     pTos->i = b;
01098     pTos->flags = MEM_Int;
01099   }else{
01100     double a, b;
01101     a = sqlite3VdbeRealValue(pTos);
01102     b = sqlite3VdbeRealValue(pNos);
01103     switch( pOp->opcode ){
01104       case OP_Add:         b += a;       break;
01105       case OP_Subtract:    b -= a;       break;
01106       case OP_Multiply:    b *= a;       break;
01107       case OP_Divide: {
01108         if( a==0.0 ) goto divide_by_zero;
01109         b /= a;
01110         break;
01111       }
01112       default: {
01113         int ia = (int)a;
01114         int ib = (int)b;
01115         if( ia==0.0 ) goto divide_by_zero;
01116         b = ib % ia;
01117         break;
01118       }
01119     }
01120     Release(pTos);
01121     pTos--;
01122     Release(pTos);
01123     pTos->r = b;
01124     pTos->flags = MEM_Real;
01125     if( (flags & MEM_Real)==0 ){
01126       sqlite3VdbeIntegerAffinity(pTos);
01127     }
01128   }
01129   break;
01130 
01131 divide_by_zero:
01132   Release(pTos);
01133   pTos--;
01134   Release(pTos);
01135   pTos->flags = MEM_Null;
01136   break;
01137 }
01138 
01139 /* Opcode: CollSeq * * P3
01140 **
01141 ** P3 is a pointer to a CollSeq struct. If the next call to a user function
01142 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
01143 ** be returned. This is used by the built-in min(), max() and nullif()
01144 ** functions.
01145 **
01146 ** The interface used by the implementation of the aforementioned functions
01147 ** to retrieve the collation sequence set by this opcode is not available
01148 ** publicly, only to user functions defined in func.c.
01149 */
01150 case OP_CollSeq: {             /* no-push */
01151   assert( pOp->p3type==P3_COLLSEQ );
01152   break;
01153 }
01154 
01155 /* Opcode: Function P1 P2 P3
01156 **
01157 ** Invoke a user function (P3 is a pointer to a Function structure that
01158 ** defines the function) with P2 arguments taken from the stack.  Pop all
01159 ** arguments from the stack and push back the result.
01160 **
01161 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
01162 ** function was determined to be constant at compile time. If the first
01163 ** argument was constant then bit 0 of P1 is set. This is used to determine
01164 ** whether meta data associated with a user function argument using the
01165 ** sqlite3_set_auxdata() API may be safely retained until the next
01166 ** invocation of this opcode.
01167 **
01168 ** See also: AggStep and AggFinal
01169 */
01170 case OP_Function: {
01171   int i;
01172   Mem *pArg;
01173   sqlite3_context ctx;
01174   sqlite3_value **apVal;
01175   int n = pOp->p2;
01176 
01177   apVal = p->apArg;
01178   assert( apVal || n==0 );
01179 
01180   pArg = &pTos[1-n];
01181   for(i=0; i<n; i++, pArg++){
01182     apVal[i] = pArg;
01183     storeTypeInfo(pArg, encoding);
01184   }
01185 
01186   assert( pOp->p3type==P3_FUNCDEF || pOp->p3type==P3_VDBEFUNC );
01187   if( pOp->p3type==P3_FUNCDEF ){
01188     ctx.pFunc = (FuncDef*)pOp->p3;
01189     ctx.pVdbeFunc = 0;
01190   }else{
01191     ctx.pVdbeFunc = (VdbeFunc*)pOp->p3;
01192     ctx.pFunc = ctx.pVdbeFunc->pFunc;
01193   }
01194 
01195   ctx.s.flags = MEM_Null;
01196   ctx.s.z = 0;
01197   ctx.s.xDel = 0;
01198   ctx.isError = 0;
01199   if( ctx.pFunc->needCollSeq ){
01200     assert( pOp>p->aOp );
01201     assert( pOp[-1].p3type==P3_COLLSEQ );
01202     assert( pOp[-1].opcode==OP_CollSeq );
01203     ctx.pColl = (CollSeq *)pOp[-1].p3;
01204   }
01205   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
01206   (*ctx.pFunc->xFunc)(&ctx, n, apVal);
01207   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
01208   if( sqlite3MallocFailed() ) goto no_mem;
01209   popStack(&pTos, n);
01210 
01211   /* If any auxilary data functions have been called by this user function,
01212   ** immediately call the destructor for any non-static values.
01213   */
01214   if( ctx.pVdbeFunc ){
01215     sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
01216     pOp->p3 = (char *)ctx.pVdbeFunc;
01217     pOp->p3type = P3_VDBEFUNC;
01218   }
01219 
01220   /* If the function returned an error, throw an exception */
01221   if( ctx.isError ){
01222     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
01223     rc = SQLITE_ERROR;
01224   }
01225 
01226   /* Copy the result of the function to the top of the stack */
01227   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
01228   pTos++;
01229   pTos->flags = 0;
01230   sqlite3VdbeMemMove(pTos, &ctx.s);
01231   break;
01232 }
01233 
01234 /* Opcode: BitAnd * * *
01235 **
01236 ** Pop the top two elements from the stack.  Convert both elements
01237 ** to integers.  Push back onto the stack the bit-wise AND of the
01238 ** two elements.
01239 ** If either operand is NULL, the result is NULL.
01240 */
01241 /* Opcode: BitOr * * *
01242 **
01243 ** Pop the top two elements from the stack.  Convert both elements
01244 ** to integers.  Push back onto the stack the bit-wise OR of the
01245 ** two elements.
01246 ** If either operand is NULL, the result is NULL.
01247 */
01248 /* Opcode: ShiftLeft * * *
01249 **
01250 ** Pop the top two elements from the stack.  Convert both elements
01251 ** to integers.  Push back onto the stack the second element shifted
01252 ** left by N bits where N is the top element on the stack.
01253 ** If either operand is NULL, the result is NULL.
01254 */
01255 /* Opcode: ShiftRight * * *
01256 **
01257 ** Pop the top two elements from the stack.  Convert both elements
01258 ** to integers.  Push back onto the stack the second element shifted
01259 ** right by N bits where N is the top element on the stack.
01260 ** If either operand is NULL, the result is NULL.
01261 */
01262 case OP_BitAnd:                 /* same as TK_BITAND, no-push */
01263 case OP_BitOr:                  /* same as TK_BITOR, no-push */
01264 case OP_ShiftLeft:              /* same as TK_LSHIFT, no-push */
01265 case OP_ShiftRight: {           /* same as TK_RSHIFT, no-push */
01266   Mem *pNos = &pTos[-1];
01267   i64 a, b;
01268 
01269   assert( pNos>=p->aStack );
01270   if( (pTos->flags | pNos->flags) & MEM_Null ){
01271     popStack(&pTos, 2);
01272     pTos++;
01273     pTos->flags = MEM_Null;
01274     break;
01275   }
01276   a = sqlite3VdbeIntValue(pNos);
01277   b = sqlite3VdbeIntValue(pTos);
01278   switch( pOp->opcode ){
01279     case OP_BitAnd:      a &= b;     break;
01280     case OP_BitOr:       a |= b;     break;
01281     case OP_ShiftLeft:   a <<= b;    break;
01282     case OP_ShiftRight:  a >>= b;    break;
01283     default:   /* CANT HAPPEN */     break;
01284   }
01285   Release(pTos);
01286   pTos--;
01287   Release(pTos);
01288   pTos->i = a;
01289   pTos->flags = MEM_Int;
01290   break;
01291 }
01292 
01293 /* Opcode: AddImm  P1 * *
01294 ** 
01295 ** Add the value P1 to whatever is on top of the stack.  The result
01296 ** is always an integer.
01297 **
01298 ** To force the top of the stack to be an integer, just add 0.
01299 */
01300 case OP_AddImm: {            /* no-push */
01301   assert( pTos>=p->aStack );
01302   sqlite3VdbeMemIntegerify(pTos);
01303   pTos->i += pOp->p1;
01304   break;
01305 }
01306 
01307 /* Opcode: ForceInt P1 P2 *
01308 **
01309 ** Convert the top of the stack into an integer.  If the current top of
01310 ** the stack is not numeric (meaning that is is a NULL or a string that
01311 ** does not look like an integer or floating point number) then pop the
01312 ** stack and jump to P2.  If the top of the stack is numeric then
01313 ** convert it into the least integer that is greater than or equal to its
01314 ** current value if P1==0, or to the least integer that is strictly
01315 ** greater than its current value if P1==1.
01316 */
01317 case OP_ForceInt: {            /* no-push */
01318   i64 v;
01319   assert( pTos>=p->aStack );
01320   applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
01321   if( (pTos->flags & (MEM_Int|MEM_Real))==0 ){
01322     Release(pTos);
01323     pTos--;
01324     pc = pOp->p2 - 1;
01325     break;
01326   }
01327   if( pTos->flags & MEM_Int ){
01328     v = pTos->i + (pOp->p1!=0);
01329   }else{
01330     /* FIX ME:  should this not be assert( pTos->flags & MEM_Real ) ??? */
01331     sqlite3VdbeMemRealify(pTos);
01332     v = (int)pTos->r;
01333     if( pTos->r>(double)v ) v++;
01334     if( pOp->p1 && pTos->r==(double)v ) v++;
01335   }
01336   Release(pTos);
01337   pTos->i = v;
01338   pTos->flags = MEM_Int;
01339   break;
01340 }
01341 
01342 /* Opcode: MustBeInt P1 P2 *
01343 ** 
01344 ** Force the top of the stack to be an integer.  If the top of the
01345 ** stack is not an integer and cannot be converted into an integer
01346 ** with out data loss, then jump immediately to P2, or if P2==0
01347 ** raise an SQLITE_MISMATCH exception.
01348 **
01349 ** If the top of the stack is not an integer and P2 is not zero and
01350 ** P1 is 1, then the stack is popped.  In all other cases, the depth
01351 ** of the stack is unchanged.
01352 */
01353 case OP_MustBeInt: {            /* no-push */
01354   assert( pTos>=p->aStack );
01355   applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
01356   if( (pTos->flags & MEM_Int)==0 ){
01357     if( pOp->p2==0 ){
01358       rc = SQLITE_MISMATCH;
01359       goto abort_due_to_error;
01360     }else{
01361       if( pOp->p1 ) popStack(&pTos, 1);
01362       pc = pOp->p2 - 1;
01363     }
01364   }else{
01365     Release(pTos);
01366     pTos->flags = MEM_Int;
01367   }
01368   break;
01369 }
01370 
01371 /* Opcode: RealAffinity * * *
01372 **
01373 ** If the top of the stack is an integer, convert it to a real value.
01374 **
01375 ** This opcode is used when extracting information from a column that
01376 ** has REAL affinity.  Such column values may still be stored as
01377 ** integers, for space efficiency, but after extraction we want them
01378 ** to have only a real value.
01379 */
01380 case OP_RealAffinity: {                  /* no-push */
01381   assert( pTos>=p->aStack );
01382   if( pTos->flags & MEM_Int ){
01383     sqlite3VdbeMemRealify(pTos);
01384   }
01385   break;
01386 }
01387 
01388 #ifndef SQLITE_OMIT_CAST
01389 /* Opcode: ToText * * *
01390 **
01391 ** Force the value on the top of the stack to be text.
01392 ** If the value is numeric, convert it to a string using the
01393 ** equivalent of printf().  Blob values are unchanged and
01394 ** are afterwards simply interpreted as text.
01395 **
01396 ** A NULL value is not changed by this routine.  It remains NULL.
01397 */
01398 case OP_ToText: {                  /* same as TK_TO_TEXT, no-push */
01399   assert( pTos>=p->aStack );
01400   if( pTos->flags & MEM_Null ) break;
01401   assert( MEM_Str==(MEM_Blob>>3) );
01402   pTos->flags |= (pTos->flags&MEM_Blob)>>3;
01403   applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
01404   assert( pTos->flags & MEM_Str );
01405   pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
01406   break;
01407 }
01408 
01409 /* Opcode: ToBlob * * *
01410 **
01411 ** Force the value on the top of the stack to be a BLOB.
01412 ** If the value is numeric, convert it to a string first.
01413 ** Strings are simply reinterpreted as blobs with no change
01414 ** to the underlying data.
01415 **
01416 ** A NULL value is not changed by this routine.  It remains NULL.
01417 */
01418 case OP_ToBlob: {                  /* same as TK_TO_BLOB, no-push */
01419   assert( pTos>=p->aStack );
01420   if( pTos->flags & MEM_Null ) break;
01421   if( (pTos->flags & MEM_Blob)==0 ){
01422     applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
01423     assert( pTos->flags & MEM_Str );
01424     pTos->flags |= MEM_Blob;
01425   }
01426   pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Str);
01427   break;
01428 }
01429 
01430 /* Opcode: ToNumeric * * *
01431 **
01432 ** Force the value on the top of the stack to be numeric (either an
01433 ** integer or a floating-point number.)
01434 ** If the value is text or blob, try to convert it to an using the
01435 ** equivalent of atoi() or atof() and store 0 if no such conversion 
01436 ** is possible.
01437 **
01438 ** A NULL value is not changed by this routine.  It remains NULL.
01439 */
01440 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, no-push */
01441   assert( pTos>=p->aStack );
01442   if( (pTos->flags & MEM_Null)==0 ){
01443     sqlite3VdbeMemNumerify(pTos);
01444   }
01445   break;
01446 }
01447 #endif /* SQLITE_OMIT_CAST */
01448 
01449 /* Opcode: ToInt * * *
01450 **
01451 ** Force the value on the top of the stack to be an integer.  If
01452 ** The value is currently a real number, drop its fractional part.
01453 ** If the value is text or blob, try to convert it to an integer using the
01454 ** equivalent of atoi() and store 0 if no such conversion is possible.
01455 **
01456 ** A NULL value is not changed by this routine.  It remains NULL.
01457 */
01458 case OP_ToInt: {                  /* same as TK_TO_INT, no-push */
01459   assert( pTos>=p->aStack );
01460   if( (pTos->flags & MEM_Null)==0 ){
01461     sqlite3VdbeMemIntegerify(pTos);
01462   }
01463   break;
01464 }
01465 
01466 #ifndef SQLITE_OMIT_CAST
01467 /* Opcode: ToReal * * *
01468 **
01469 ** Force the value on the top of the stack to be a floating point number.
01470 ** If The value is currently an integer, convert it.
01471 ** If the value is text or blob, try to convert it to an integer using the
01472 ** equivalent of atoi() and store 0 if no such conversion is possible.
01473 **
01474 ** A NULL value is not changed by this routine.  It remains NULL.
01475 */
01476 case OP_ToReal: {                  /* same as TK_TO_REAL, no-push */
01477   assert( pTos>=p->aStack );
01478   if( (pTos->flags & MEM_Null)==0 ){
01479     sqlite3VdbeMemRealify(pTos);
01480   }
01481   break;
01482 }
01483 #endif /* SQLITE_OMIT_CAST */
01484 
01485 /* Opcode: Eq P1 P2 P3
01486 **
01487 ** Pop the top two elements from the stack.  If they are equal, then
01488 ** jump to instruction P2.  Otherwise, continue to the next instruction.
01489 **
01490 ** If the 0x100 bit of P1 is true and either operand is NULL then take the
01491 ** jump.  If the 0x100 bit of P1 is clear then fall thru if either operand
01492 ** is NULL.
01493 **
01494 ** If the 0x200 bit of P1 is set and either operand is NULL then
01495 ** both operands are converted to integers prior to comparison.
01496 ** NULL operands are converted to zero and non-NULL operands are
01497 ** converted to 1.  Thus, for example, with 0x200 set,  NULL==NULL is true
01498 ** whereas it would normally be NULL.  Similarly,  NULL==123 is false when
01499 ** 0x200 is set but is NULL when the 0x200 bit of P1 is clear.
01500 **
01501 ** The least significant byte of P1 (mask 0xff) must be an affinity character -
01502 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
01503 ** to coerce both values
01504 ** according to the affinity before the comparison is made. If the byte is
01505 ** 0x00, then numeric affinity is used.
01506 **
01507 ** Once any conversions have taken place, and neither value is NULL, 
01508 ** the values are compared. If both values are blobs, or both are text,
01509 ** then memcmp() is used to determine the results of the comparison. If
01510 ** both values are numeric, then a numeric comparison is used. If the
01511 ** two values are of different types, then they are inequal.
01512 **
01513 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01514 ** stack if the jump would have been taken, or a 0 if not.  Push a
01515 ** NULL if either operand was NULL.
01516 **
01517 ** If P3 is not NULL it is a pointer to a collating sequence (a CollSeq
01518 ** structure) that defines how to compare text.
01519 */
01520 /* Opcode: Ne P1 P2 P3
01521 **
01522 ** This works just like the Eq opcode except that the jump is taken if
01523 ** the operands from the stack are not equal.  See the Eq opcode for
01524 ** additional information.
01525 */
01526 /* Opcode: Lt P1 P2 P3
01527 **
01528 ** This works just like the Eq opcode except that the jump is taken if
01529 ** the 2nd element down on the stack is less than the top of the stack.
01530 ** See the Eq opcode for additional information.
01531 */
01532 /* Opcode: Le P1 P2 P3
01533 **
01534 ** This works just like the Eq opcode except that the jump is taken if
01535 ** the 2nd element down on the stack is less than or equal to the
01536 ** top of the stack.  See the Eq opcode for additional information.
01537 */
01538 /* Opcode: Gt P1 P2 P3
01539 **
01540 ** This works just like the Eq opcode except that the jump is taken if
01541 ** the 2nd element down on the stack is greater than the top of the stack.
01542 ** See the Eq opcode for additional information.
01543 */
01544 /* Opcode: Ge P1 P2 P3
01545 **
01546 ** This works just like the Eq opcode except that the jump is taken if
01547 ** the 2nd element down on the stack is greater than or equal to the
01548 ** top of the stack.  See the Eq opcode for additional information.
01549 */
01550 case OP_Eq:               /* same as TK_EQ, no-push */
01551 case OP_Ne:               /* same as TK_NE, no-push */
01552 case OP_Lt:               /* same as TK_LT, no-push */
01553 case OP_Le:               /* same as TK_LE, no-push */
01554 case OP_Gt:               /* same as TK_GT, no-push */
01555 case OP_Ge: {             /* same as TK_GE, no-push */
01556   Mem *pNos;
01557   int flags;
01558   int res;
01559   char affinity;
01560 
01561   pNos = &pTos[-1];
01562   flags = pTos->flags|pNos->flags;
01563 
01564   /* If either value is a NULL P2 is not zero, take the jump if the least
01565   ** significant byte of P1 is true. If P2 is zero, then push a NULL onto
01566   ** the stack.
01567   */
01568   if( flags&MEM_Null ){
01569     if( (pOp->p1 & 0x200)!=0 ){
01570       /* The 0x200 bit of P1 means, roughly "do not treat NULL as the
01571       ** magic SQL value it normally is - treat it as if it were another
01572       ** integer".
01573       **
01574       ** With 0x200 set, if either operand is NULL then both operands
01575       ** are converted to integers prior to being passed down into the
01576       ** normal comparison logic below.  NULL operands are converted to
01577       ** zero and non-NULL operands are converted to 1.  Thus, for example,
01578       ** with 0x200 set,  NULL==NULL is true whereas it would normally
01579       ** be NULL.  Similarly,  NULL!=123 is true.
01580       */
01581       sqlite3VdbeMemSetInt64(pTos, (pTos->flags & MEM_Null)==0);
01582       sqlite3VdbeMemSetInt64(pNos, (pNos->flags & MEM_Null)==0);
01583     }else{
01584       /* If the 0x200 bit of P1 is clear and either operand is NULL then
01585       ** the result is always NULL.  The jump is taken if the 0x100 bit
01586       ** of P1 is set.
01587       */
01588       popStack(&pTos, 2);
01589       if( pOp->p2 ){
01590         if( pOp->p1 & 0x100 ){
01591           pc = pOp->p2-1;
01592         }
01593       }else{
01594         pTos++;
01595         pTos->flags = MEM_Null;
01596       }
01597       break;
01598     }
01599   }
01600 
01601   affinity = pOp->p1 & 0xFF;
01602   if( affinity ){
01603     applyAffinity(pNos, affinity, encoding);
01604     applyAffinity(pTos, affinity, encoding);
01605   }
01606 
01607   assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 );
01608   res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3);
01609   switch( pOp->opcode ){
01610     case OP_Eq:    res = res==0;     break;
01611     case OP_Ne:    res = res!=0;     break;
01612     case OP_Lt:    res = res<0;      break;
01613     case OP_Le:    res = res<=0;     break;
01614     case OP_Gt:    res = res>0;      break;
01615     default:       res = res>=0;     break;
01616   }
01617 
01618   popStack(&pTos, 2);
01619   if( pOp->p2 ){
01620     if( res ){
01621       pc = pOp->p2-1;
01622     }
01623   }else{
01624     pTos++;
01625     pTos->flags = MEM_Int;
01626     pTos->i = res;
01627   }
01628   break;
01629 }
01630 
01631 /* Opcode: And * * *
01632 **
01633 ** Pop two values off the stack.  Take the logical AND of the
01634 ** two values and push the resulting boolean value back onto the
01635 ** stack. 
01636 */
01637 /* Opcode: Or * * *
01638 **
01639 ** Pop two values off the stack.  Take the logical OR of the
01640 ** two values and push the resulting boolean value back onto the
01641 ** stack. 
01642 */
01643 case OP_And:              /* same as TK_AND, no-push */
01644 case OP_Or: {             /* same as TK_OR, no-push */
01645   Mem *pNos = &pTos[-1];
01646   int v1, v2;    /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
01647 
01648   assert( pNos>=p->aStack );
01649   if( pTos->flags & MEM_Null ){
01650     v1 = 2;
01651   }else{
01652     sqlite3VdbeMemIntegerify(pTos);
01653     v1 = pTos->i==0;
01654   }
01655   if( pNos->flags & MEM_Null ){
01656     v2 = 2;
01657   }else{
01658     sqlite3VdbeMemIntegerify(pNos);
01659     v2 = pNos->i==0;
01660   }
01661   if( pOp->opcode==OP_And ){
01662     static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
01663     v1 = and_logic[v1*3+v2];
01664   }else{
01665     static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
01666     v1 = or_logic[v1*3+v2];
01667   }
01668   popStack(&pTos, 2);
01669   pTos++;
01670   if( v1==2 ){
01671     pTos->flags = MEM_Null;
01672   }else{
01673     pTos->i = v1==0;
01674     pTos->flags = MEM_Int;
01675   }
01676   break;
01677 }
01678 
01679 /* Opcode: Negative * * *
01680 **
01681 ** Treat the top of the stack as a numeric quantity.  Replace it
01682 ** with its additive inverse.  If the top of the stack is NULL
01683 ** its value is unchanged.
01684 */
01685 /* Opcode: AbsValue * * *
01686 **
01687 ** Treat the top of the stack as a numeric quantity.  Replace it
01688 ** with its absolute value. If the top of the stack is NULL
01689 ** its value is unchanged.
01690 */
01691 case OP_Negative:              /* same as TK_UMINUS, no-push */
01692 case OP_AbsValue: {
01693   assert( pTos>=p->aStack );
01694   if( pTos->flags & MEM_Real ){
01695     neg_abs_real_case:
01696     Release(pTos);
01697     if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
01698       pTos->r = -pTos->r;
01699     }
01700     pTos->flags = MEM_Real;
01701   }else if( pTos->flags & MEM_Int ){
01702     Release(pTos);
01703     if( pOp->opcode==OP_Negative || pTos->i<0 ){
01704       pTos->i = -pTos->i;
01705     }
01706     pTos->flags = MEM_Int;
01707   }else if( pTos->flags & MEM_Null ){
01708     /* Do nothing */
01709   }else{
01710     sqlite3VdbeMemNumerify(pTos);
01711     goto neg_abs_real_case;
01712   }
01713   break;
01714 }
01715 
01716 /* Opcode: Not * * *
01717 **
01718 ** Interpret the top of the stack as a boolean value.  Replace it
01719 ** with its complement.  If the top of the stack is NULL its value
01720 ** is unchanged.
01721 */
01722 case OP_Not: {                /* same as TK_NOT, no-push */
01723   assert( pTos>=p->aStack );
01724   if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
01725   sqlite3VdbeMemIntegerify(pTos);
01726   assert( (pTos->flags & MEM_Dyn)==0 );
01727   pTos->i = !pTos->i;
01728   pTos->flags = MEM_Int;
01729   break;
01730 }
01731 
01732 /* Opcode: BitNot * * *
01733 **
01734 ** Interpret the top of the stack as an value.  Replace it
01735 ** with its ones-complement.  If the top of the stack is NULL its
01736 ** value is unchanged.
01737 */
01738 case OP_BitNot: {             /* same as TK_BITNOT, no-push */
01739   assert( pTos>=p->aStack );
01740   if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
01741   sqlite3VdbeMemIntegerify(pTos);
01742   assert( (pTos->flags & MEM_Dyn)==0 );
01743   pTos->i = ~pTos->i;
01744   pTos->flags = MEM_Int;
01745   break;
01746 }
01747 
01748 /* Opcode: Noop * * *
01749 **
01750 ** Do nothing.  This instruction is often useful as a jump
01751 ** destination.
01752 */
01753 /*
01754 ** The magic Explain opcode are only inserted when explain==2 (which
01755 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
01756 ** This opcode records information from the optimizer.  It is the
01757 ** the same as a no-op.  This opcodesnever appears in a real VM program.
01758 */
01759 case OP_Explain:
01760 case OP_Noop: {            /* no-push */
01761   break;
01762 }
01763 
01764 /* Opcode: If P1 P2 *
01765 **
01766 ** Pop a single boolean from the stack.  If the boolean popped is
01767 ** true, then jump to p2.  Otherwise continue to the next instruction.
01768 ** An integer is false if zero and true otherwise.  A string is
01769 ** false if it has zero length and true otherwise.
01770 **
01771 ** If the value popped of the stack is NULL, then take the jump if P1
01772 ** is true and fall through if P1 is false.
01773 */
01774 /* Opcode: IfNot P1 P2 *
01775 **
01776 ** Pop a single boolean from the stack.  If the boolean popped is
01777 ** false, then jump to p2.  Otherwise continue to the next instruction.
01778 ** An integer is false if zero and true otherwise.  A string is
01779 ** false if it has zero length and true otherwise.
01780 **
01781 ** If the value popped of the stack is NULL, then take the jump if P1
01782 ** is true and fall through if P1 is false.
01783 */
01784 case OP_If:                 /* no-push */
01785 case OP_IfNot: {            /* no-push */
01786   int c;
01787   assert( pTos>=p->aStack );
01788   if( pTos->flags & MEM_Null ){
01789     c = pOp->p1;
01790   }else{
01791 #ifdef SQLITE_OMIT_FLOATING_POINT
01792     c = sqlite3VdbeIntValue(pTos);
01793 #else
01794     c = sqlite3VdbeRealValue(pTos)!=0.0;
01795 #endif
01796     if( pOp->opcode==OP_IfNot ) c = !c;
01797   }
01798   Release(pTos);
01799   pTos--;
01800   if( c ) pc = pOp->p2-1;
01801   break;
01802 }
01803 
01804 /* Opcode: IsNull P1 P2 *
01805 **
01806 ** If any of the top abs(P1) values on the stack are NULL, then jump
01807 ** to P2.  Pop the stack P1 times if P1>0.   If P1<0 leave the stack
01808 ** unchanged.
01809 */
01810 case OP_IsNull: {            /* same as TK_ISNULL, no-push */
01811   int i, cnt;
01812   Mem *pTerm;
01813   cnt = pOp->p1;
01814   if( cnt<0 ) cnt = -cnt;
01815   pTerm = &pTos[1-cnt];
01816   assert( pTerm>=p->aStack );
01817   for(i=0; i<cnt; i++, pTerm++){
01818     if( pTerm->flags & MEM_Null ){
01819       pc = pOp->p2-1;
01820       break;
01821     }
01822   }
01823   if( pOp->p1>0 ) popStack(&pTos, cnt);
01824   break;
01825 }
01826 
01827 /* Opcode: NotNull P1 P2 *
01828 **
01829 ** Jump to P2 if the top P1 values on the stack are all not NULL.  Pop the
01830 ** stack if P1 times if P1 is greater than zero.  If P1 is less than
01831 ** zero then leave the stack unchanged.
01832 */
01833 case OP_NotNull: {            /* same as TK_NOTNULL, no-push */
01834   int i, cnt;
01835   cnt = pOp->p1;
01836   if( cnt<0 ) cnt = -cnt;
01837   assert( &pTos[1-cnt] >= p->aStack );
01838   for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
01839   if( i>=cnt ) pc = pOp->p2-1;
01840   if( pOp->p1>0 ) popStack(&pTos, cnt);
01841   break;
01842 }
01843 
01844 /* Opcode: SetNumColumns P1 P2 *
01845 **
01846 ** Before the OP_Column opcode can be executed on a cursor, this
01847 ** opcode must be called to set the number of fields in the table.
01848 **
01849 ** This opcode sets the number of columns for cursor P1 to P2.
01850 **
01851 ** If OP_KeyAsData is to be applied to cursor P1, it must be executed
01852 ** before this op-code.
01853 */
01854 case OP_SetNumColumns: {       /* no-push */
01855   Cursor *pC;
01856   assert( (pOp->p1)<p->nCursor );
01857   assert( p->apCsr[pOp->p1]!=0 );
01858   pC = p->apCsr[pOp->p1];
01859   pC->nField = pOp->p2;
01860   break;
01861 }
01862 
01863 /* Opcode: Column P1 P2 P3
01864 **
01865 ** Interpret the data that cursor P1 points to as a structure built using
01866 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
01867 ** information about the format of the data.) Push onto the stack the value
01868 ** of the P2-th column contained in the data. If there are less that (P2+1) 
01869 ** values in the record, push a NULL onto the stack.
01870 **
01871 ** If the KeyAsData opcode has previously executed on this cursor, then the
01872 ** field might be extracted from the key rather than the data.
01873 **
01874 ** If the column contains fewer than P2 fields, then push a NULL.  Or
01875 ** if P3 is of type P3_MEM, then push the P3 value.  The P3 value will
01876 ** be default value for a column that has been added using the ALTER TABLE
01877 ** ADD COLUMN command.  If P3 is an ordinary string, just push a NULL.
01878 ** When P3 is a string it is really just a comment describing the value
01879 ** to be pushed, not a default value.
01880 */
01881 case OP_Column: {
01882   u32 payloadSize;   /* Number of bytes in the record */
01883   int p1 = pOp->p1;  /* P1 value of the opcode */
01884   int p2 = pOp->p2;  /* column number to retrieve */
01885   Cursor *pC = 0;    /* The VDBE cursor */
01886   char *zRec;        /* Pointer to complete record-data */
01887   BtCursor *pCrsr;   /* The BTree cursor */
01888   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
01889   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
01890   u32 nField;        /* number of fields in the record */
01891   int len;           /* The length of the serialized data for the column */
01892   int i;             /* Loop counter */
01893   char *zData;       /* Part of the record being decoded */
01894   Mem sMem;          /* For storing the record being decoded */
01895 
01896   sMem.flags = 0;
01897   assert( p1<p->nCursor );
01898   pTos++;
01899   pTos->flags = MEM_Null;
01900 
01901   /* This block sets the variable payloadSize to be the total number of
01902   ** bytes in the record.
01903   **
01904   ** zRec is set to be the complete text of the record if it is available.
01905   ** The complete record text is always available for pseudo-tables
01906   ** If the record is stored in a cursor, the complete record text
01907   ** might be available in the  pC->aRow cache.  Or it might not be.
01908   ** If the data is unavailable,  zRec is set to NULL.
01909   **
01910   ** We also compute the number of columns in the record.  For cursors,
01911   ** the number of columns is stored in the Cursor.nField element.  For
01912   ** records on the stack, the next entry down on the stack is an integer
01913   ** which is the number of records.
01914   */
01915   pC = p->apCsr[p1];
01916   assert( pC!=0 );
01917   if( pC->pCursor!=0 ){
01918     /* The record is stored in a B-Tree */
01919     rc = sqlite3VdbeCursorMoveto(pC);
01920     if( rc ) goto abort_due_to_error;
01921     zRec = 0;
01922     pCrsr = pC->pCursor;
01923     if( pC->nullRow ){
01924       payloadSize = 0;
01925     }else if( pC->cacheStatus==p->cacheCtr ){
01926       payloadSize = pC->payloadSize;
01927       zRec = (char*)pC->aRow;
01928     }else if( pC->isIndex ){
01929       i64 payloadSize64;
01930       sqlite3BtreeKeySize(pCrsr, &payloadSize64);
01931       payloadSize = payloadSize64;
01932     }else{
01933       sqlite3BtreeDataSize(pCrsr, &payloadSize);
01934     }
01935     nField = pC->nField;
01936   }else if( pC->pseudoTable ){
01937     /* The record is the sole entry of a pseudo-table */
01938     payloadSize = pC->nData;
01939     zRec = pC->pData;
01940     pC->cacheStatus = CACHE_STALE;
01941     assert( payloadSize==0 || zRec!=0 );
01942     nField = pC->nField;
01943     pCrsr = 0;
01944   }else{
01945     zRec = 0;
01946     payloadSize = 0;
01947     pCrsr = 0;
01948     nField = 0;
01949   }
01950 
01951   /* If payloadSize is 0, then just push a NULL onto the stack. */
01952   if( payloadSize==0 ){
01953     assert( pTos->flags==MEM_Null );
01954     break;
01955   }
01956 
01957   assert( p2<nField );
01958 
01959   /* Read and parse the table header.  Store the results of the parse
01960   ** into the record header cache fields of the cursor.
01961   */
01962   if( pC && pC->cacheStatus==p->cacheCtr ){
01963     aType = pC->aType;
01964     aOffset = pC->aOffset;
01965   }else{
01966     u8 *zIdx;        /* Index into header */
01967     u8 *zEndHdr;     /* Pointer to first byte after the header */
01968     u32 offset;      /* Offset into the data */
01969     int szHdrSz;     /* Size of the header size field at start of record */
01970     int avail;       /* Number of bytes of available data */
01971 
01972     aType = pC->aType;
01973     if( aType==0 ){
01974       pC->aType = aType = sqliteMallocRaw( 2*nField*sizeof(aType) );
01975     }
01976     if( aType==0 ){
01977       goto no_mem;
01978     }
01979     pC->aOffset = aOffset = &aType[nField];
01980     pC->payloadSize = payloadSize;
01981     pC->cacheStatus = p->cacheCtr;
01982 
01983     /* Figure out how many bytes are in the header */
01984     if( zRec ){
01985       zData = zRec;
01986     }else{
01987       if( pC->isIndex ){
01988         zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
01989       }else{
01990         zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
01991       }
01992       /* If KeyFetch()/DataFetch() managed to get the entire payload,
01993       ** save the payload in the pC->aRow cache.  That will save us from
01994       ** having to make additional calls to fetch the content portion of
01995       ** the record.
01996       */
01997       if( avail>=payloadSize ){
01998         zRec = zData;
01999         pC->aRow = (u8*)zData;
02000       }else{
02001         pC->aRow = 0;
02002       }
02003     }
02004     assert( zRec!=0 || avail>=payloadSize || avail>=9 );
02005     szHdrSz = GetVarint((u8*)zData, offset);
02006 
02007     /* The KeyFetch() or DataFetch() above are fast and will get the entire
02008     ** record header in most cases.  But they will fail to get the complete
02009     ** record header if the record header does not fit on a single page
02010     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
02011     ** acquire the complete header text.
02012     */
02013     if( !zRec && avail<offset ){
02014       rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
02015       if( rc!=SQLITE_OK ){
02016         goto op_column_out;
02017       }
02018       zData = sMem.z;
02019     }
02020     zEndHdr = (u8 *)&zData[offset];
02021     zIdx = (u8 *)&zData[szHdrSz];
02022 
02023     /* Scan the header and use it to fill in the aType[] and aOffset[]
02024     ** arrays.  aType[i] will contain the type integer for the i-th
02025     ** column and aOffset[i] will contain the offset from the beginning
02026     ** of the record to the start of the data for the i-th column
02027     */
02028     for(i=0; i<nField; i++){
02029       if( zIdx<zEndHdr ){
02030         aOffset[i] = offset;
02031         zIdx += GetVarint(zIdx, aType[i]);
02032         offset += sqlite3VdbeSerialTypeLen(aType[i]);
02033       }else{
02034         /* If i is less that nField, then there are less fields in this
02035         ** record than SetNumColumns indicated there are columns in the
02036         ** table. Set the offset for any extra columns not present in
02037         ** the record to 0. This tells code below to push a NULL onto the
02038         ** stack instead of deserializing a value from the record.
02039         */
02040         aOffset[i] = 0;
02041       }
02042     }
02043     Release(&sMem);
02044     sMem.flags = MEM_Null;
02045 
02046     /* If we have read more header data than was contained in the header,
02047     ** or if the end of the last field appears to be past the end of the
02048     ** record, then we must be dealing with a corrupt database.
02049     */
02050     if( zIdx>zEndHdr || offset>payloadSize ){
02051       rc = SQLITE_CORRUPT_BKPT;
02052       goto op_column_out;
02053     }
02054   }
02055 
02056   /* Get the column information. If aOffset[p2] is non-zero, then 
02057   ** deserialize the value from the record. If aOffset[p2] is zero,
02058   ** then there are not enough fields in the record to satisfy the
02059   ** request.  In this case, set the value NULL or to P3 if P3 is
02060   ** a pointer to a Mem object.
02061   */
02062   if( aOffset[p2] ){
02063     assert( rc==SQLITE_OK );
02064     if( zRec ){
02065       zData = &zRec[aOffset[p2]];
02066     }else{
02067       len = sqlite3VdbeSerialTypeLen(aType[p2]);
02068       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex,&sMem);
02069       if( rc!=SQLITE_OK ){
02070         goto op_column_out;
02071       }
02072       zData = sMem.z;
02073     }
02074     sqlite3VdbeSerialGet((u8*)zData, aType[p2], pTos);
02075     pTos->enc = encoding;
02076   }else{
02077     if( pOp->p3type==P3_MEM ){
02078       sqlite3VdbeMemShallowCopy(pTos, (Mem *)(pOp->p3), MEM_Static);
02079     }else{
02080       pTos->flags = MEM_Null;
02081     }
02082   }
02083 
02084   /* If we dynamically allocated space to hold the data (in the
02085   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
02086   ** dynamically allocated space over to the pTos structure.
02087   ** This prevents a memory copy.
02088   */
02089   if( (sMem.flags & MEM_Dyn)!=0 ){
02090     assert( pTos->flags & MEM_Ephem );
02091     assert( pTos->flags & (MEM_Str|MEM_Blob) );
02092     assert( pTos->z==sMem.z );
02093     assert( sMem.flags & MEM_Term );
02094     pTos->flags &= ~MEM_Ephem;
02095     pTos->flags |= MEM_Dyn|MEM_Term;
02096   }
02097 
02098   /* pTos->z might be pointing to sMem.zShort[].  Fix that so that we
02099   ** can abandon sMem */
02100   rc = sqlite3VdbeMemMakeWriteable(pTos);
02101 
02102 op_column_out:
02103   break;
02104 }
02105 
02106 /* Opcode: MakeRecord P1 P2 P3
02107 **
02108 ** Convert the top abs(P1) entries of the stack into a single entry
02109 ** suitable for use as a data record in a database table or as a key
02110 ** in an index.  The details of the format are irrelavant as long as
02111 ** the OP_Column opcode can decode the record later and as long as the
02112 ** sqlite3VdbeRecordCompare function will correctly compare two encoded
02113 ** records.  Refer to source code comments for the details of the record
02114 ** format.
02115 **
02116 ** The original stack entries are popped from the stack if P1>0 but
02117 ** remain on the stack if P1<0.
02118 **
02119 ** If P2 is not zero and one or more of the entries are NULL, then jump
02120 ** to the address given by P2.  This feature can be used to skip a
02121 ** uniqueness test on indices.
02122 **
02123 ** P3 may be a string that is P1 characters long.  The nth character of the
02124 ** string indicates the column affinity that should be used for the nth
02125 ** field of the index key (i.e. the first character of P3 corresponds to the
02126 ** lowest element on the stack).
02127 **
02128 ** The mapping from character to affinity is given by the SQLITE_AFF_
02129 ** macros defined in sqliteInt.h.
02130 **
02131 ** If P3 is NULL then all index fields have the affinity NONE.
02132 **
02133 ** See also OP_MakeIdxRec
02134 */
02135 /* Opcode: MakeIdxRec P1 P2 P3
02136 **
02137 ** This opcode works just OP_MakeRecord except that it reads an extra
02138 ** integer from the stack (thus reading a total of abs(P1+1) entries)
02139 ** and appends that extra integer to the end of the record as a varint.
02140 ** This results in an index key.
02141 */
02142 case OP_MakeIdxRec:
02143 case OP_MakeRecord: {
02144   /* Assuming the record contains N fields, the record format looks
02145   ** like this:
02146   **
02147   ** ------------------------------------------------------------------------
02148   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
02149   ** ------------------------------------------------------------------------
02150   **
02151   ** Data(0) is taken from the lowest element of the stack and data(N-1) is
02152   ** the top of the stack.
02153   **
02154   ** Each type field is a varint representing the serial type of the 
02155   ** corresponding data element (see sqlite3VdbeSerialType()). The
02156   ** hdr-size field is also a varint which is the offset from the beginning
02157   ** of the record to data0.
02158   */
02159   unsigned char *zNewRecord;
02160   unsigned char *zCsr;
02161   Mem *pRec;
02162   Mem *pRowid = 0;
02163   int nData = 0;         /* Number of bytes of data space */
02164   int nHdr = 0;          /* Number of bytes of header space */
02165   int nByte = 0;         /* Space required for this record */
02166   int nVarint;           /* Number of bytes in a varint */
02167   u32 serial_type;       /* Type field */
02168   int containsNull = 0;  /* True if any of the data fields are NULL */
02169   char zTemp[NBFS];      /* Space to hold small records */
02170   Mem *pData0;
02171 
02172   int leaveOnStack;      /* If true, leave the entries on the stack */
02173   int nField;            /* Number of fields in the record */
02174   int jumpIfNull;        /* Jump here if non-zero and any entries are NULL. */
02175   int addRowid;          /* True to append a rowid column at the end */
02176   char *zAffinity;       /* The affinity string for the record */
02177   int file_format;       /* File format to use for encoding */
02178 
02179   leaveOnStack = ((pOp->p1<0)?1:0);
02180   nField = pOp->p1 * (leaveOnStack?-1:1);
02181   jumpIfNull = pOp->p2;
02182   addRowid = pOp->opcode==OP_MakeIdxRec;
02183   zAffinity = pOp->p3;
02184 
02185   pData0 = &pTos[1-nField];
02186   assert( pData0>=p->aStack );
02187   containsNull = 0;
02188   file_format = p->minWriteFileFormat;
02189 
02190   /* Loop through the elements that will make up the record to figure
02191   ** out how much space is required for the new record.
02192   */
02193   for(pRec=pData0; pRec<=pTos; pRec++){
02194     if( zAffinity ){
02195       applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
02196     }
02197     if( pRec->flags&MEM_Null ){
02198       containsNull = 1;
02199     }
02200     serial_type = sqlite3VdbeSerialType(pRec, file_format);
02201     nData += sqlite3VdbeSerialTypeLen(serial_type);
02202     nHdr += sqlite3VarintLen(serial_type);
02203   }
02204 
02205   /* If we have to append a varint rowid to this record, set 'rowid'
02206   ** to the value of the rowid and increase nByte by the amount of space
02207   ** required to store it and the 0x00 seperator byte.
02208   */
02209   if( addRowid ){
02210     pRowid = &pTos[0-nField];
02211     assert( pRowid>=p->aStack );
02212     sqlite3VdbeMemIntegerify(pRowid);
02213     serial_type = sqlite3VdbeSerialType(pRowid, 0);
02214     nData += sqlite3VdbeSerialTypeLen(serial_type);
02215     nHdr += sqlite3VarintLen(serial_type);
02216   }
02217 
02218   /* Add the initial header varint and total the size */
02219   nHdr += nVarint = sqlite3VarintLen(nHdr);
02220   if( nVarint<sqlite3VarintLen(nHdr) ){
02221     nHdr++;
02222   }
02223   nByte = nHdr+nData;
02224 
02225   /* Allocate space for the new record. */
02226   if( nByte>sizeof(zTemp) ){
02227     zNewRecord = sqliteMallocRaw(nByte);
02228     if( !zNewRecord ){
02229       goto no_mem;
02230     }
02231   }else{
02232     zNewRecord = (u8*)zTemp;
02233   }
02234 
02235   /* Write the record */
02236   zCsr = zNewRecord;
02237   zCsr += sqlite3PutVarint(zCsr, nHdr);
02238   for(pRec=pData0; pRec<=pTos; pRec++){
02239     serial_type = sqlite3VdbeSerialType(pRec, file_format);
02240     zCsr += sqlite3PutVarint(zCsr, serial_type);      /* serial type */
02241   }
02242   if( addRowid ){
02243     zCsr += sqlite3PutVarint(zCsr, sqlite3VdbeSerialType(pRowid, 0));
02244   }
02245   for(pRec=pData0; pRec<=pTos; pRec++){
02246     zCsr += sqlite3VdbeSerialPut(zCsr, pRec, file_format);  /* serial data */
02247   }
02248   if( addRowid ){
02249     zCsr += sqlite3VdbeSerialPut(zCsr, pRowid, 0);
02250   }
02251   assert( zCsr==(zNewRecord+nByte) );
02252 
02253   /* Pop entries off the stack if required. Push the new record on. */
02254   if( !leaveOnStack ){
02255     popStack(&pTos, nField+addRowid);
02256   }
02257   pTos++;
02258   pTos->n = nByte;
02259   if( nByte<=sizeof(zTemp) ){
02260     assert( zNewRecord==(unsigned char *)zTemp );
02261     pTos->z = pTos->zShort;
02262     memcpy(pTos->zShort, zTemp, nByte);
02263     pTos->flags = MEM_Blob | MEM_Short;
02264   }else{
02265     assert( zNewRecord!=(unsigned char *)zTemp );
02266     pTos->z = (char*)zNewRecord;
02267     pTos->flags = MEM_Blob | MEM_Dyn;
02268     pTos->xDel = 0;
02269   }
02270   pTos->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
02271 
02272   /* If a NULL was encountered and jumpIfNull is non-zero, take the jump. */
02273   if( jumpIfNull && containsNull ){
02274     pc = jumpIfNull - 1;
02275   }
02276   break;
02277 }
02278 
02279 /* Opcode: Statement P1 * *
02280 **
02281 ** Begin an individual statement transaction which is part of a larger
02282 ** BEGIN..COMMIT transaction.  This is needed so that the statement
02283 ** can be rolled back after an error without having to roll back the
02284 ** entire transaction.  The statement transaction will automatically
02285 ** commit when the VDBE halts.
02286 **
02287 ** The statement is begun on the database file with index P1.  The main
02288 ** database file has an index of 0 and the file used for temporary tables
02289 ** has an index of 1.
02290 */
02291 case OP_Statement: {       /* no-push */
02292   int i = pOp->p1;
02293   Btree *pBt;
02294   if( i>=0 && i<db->nDb && (pBt = db->aDb[i].pBt)!=0 && !(db->autoCommit) ){
02295     assert( sqlite3BtreeIsInTrans(pBt) );
02296     if( !sqlite3BtreeIsInStmt(pBt) ){
02297       rc = sqlite3BtreeBeginStmt(pBt);
02298     }
02299   }
02300   break;
02301 }
02302 
02303 /* Opcode: AutoCommit P1 P2 *
02304 **
02305 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
02306 ** back any currently active btree transactions. If there are any active
02307 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
02308 **
02309 ** This instruction causes the VM to halt.
02310 */
02311 case OP_AutoCommit: {       /* no-push */
02312   u8 i = pOp->p1;
02313   u8 rollback = pOp->p2;
02314 
02315   assert( i==1 || i==0 );
02316   assert( i==1 || rollback==0 );
02317 
02318   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
02319 
02320   if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
02321     /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
02322     ** still running, and a transaction is active, return an error indicating
02323     ** that the other VMs must complete first. 
02324     */
02325     sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit", 
02326         " transaction - SQL statements in progress", (char*)0);
02327     rc = SQLITE_ERROR;
02328   }else if( i!=db->autoCommit ){
02329     if( pOp->p2 ){
02330       assert( i==1 );
02331       sqlite3RollbackAll(db);
02332       db->autoCommit = 1;
02333     }else{
02334       db->autoCommit = i;
02335       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
02336         p->pTos = pTos;
02337         p->pc = pc;
02338         db->autoCommit = 1-i;
02339         p->rc = SQLITE_BUSY;
02340         return SQLITE_BUSY;
02341       }
02342     }
02343     return SQLITE_DONE;
02344   }else{
02345     sqlite3SetString(&p->zErrMsg,
02346         (!i)?"cannot start a transaction within a transaction":(
02347         (rollback)?"cannot rollback - no transaction is active":
02348                    "cannot commit - no transaction is active"), (char*)0);
02349          
02350     rc = SQLITE_ERROR;
02351   }
02352   break;
02353 }
02354 
02355 /* Opcode: Transaction P1 P2 *
02356 **
02357 ** Begin a transaction.  The transaction ends when a Commit or Rollback
02358 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
02359 ** transaction might also be rolled back if an error is encountered.
02360 **
02361 ** P1 is the index of the database file on which the transaction is
02362 ** started.  Index 0 is the main database file and index 1 is the
02363 ** file used for temporary tables.
02364 **
02365 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
02366 ** obtained on the database file when a write-transaction is started.  No
02367 ** other process can start another write transaction while this transaction is
02368 ** underway.  Starting a write transaction also creates a rollback journal. A
02369 ** write transaction must be started before any changes can be made to the
02370 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
02371 ** on the file.
02372 **
02373 ** If P2 is zero, then a read-lock is obtained on the database file.
02374 */
02375 case OP_Transaction: {       /* no-push */
02376   int i = pOp->p1;
02377   Btree *pBt;
02378 
02379   assert( i>=0 && i<db->nDb );
02380   pBt = db->aDb[i].pBt;
02381 
02382   if( pBt ){
02383     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
02384     if( rc==SQLITE_BUSY ){
02385       p->pc = pc;
02386       p->rc = SQLITE_BUSY;
02387       p->pTos = pTos;
02388       return SQLITE_BUSY;
02389     }
02390     if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
02391       goto abort_due_to_error;
02392     }
02393   }
02394   break;
02395 }
02396 
02397 /* Opcode: ReadCookie P1 P2 *
02398 **
02399 ** Read cookie number P2 from database P1 and push it onto the stack.
02400 ** P2==0 is the schema version.  P2==1 is the database format.
02401 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
02402 ** the main database file and P1==1 is the database file used to store
02403 ** temporary tables.
02404 **
02405 ** There must be a read-lock on the database (either a transaction
02406 ** must be started or there must be an open cursor) before
02407 ** executing this instruction.
02408 */
02409 case OP_ReadCookie: {
02410   int iMeta;
02411   assert( pOp->p2<SQLITE_N_BTREE_META );
02412   assert( pOp->p1>=0 && pOp->p1<db->nDb );
02413   assert( db->aDb[pOp->p1].pBt!=0 );
02414   /* The indexing of meta values at the schema layer is off by one from
02415   ** the indexing in the btree layer.  The btree considers meta[0] to
02416   ** be the number of free pages in the database (a read-only value)
02417   ** and meta[1] to be the schema cookie.  The schema layer considers
02418   ** meta[1] to be the schema cookie.  So we have to shift the index
02419   ** by one in the following statement.
02420   */
02421   rc = sqlite3BtreeGetMeta(db->aDb[pOp->p1].pBt, 1 + pOp->p2, (u32 *)&iMeta);
02422   pTos++;
02423   pTos->i = iMeta;
02424   pTos->flags = MEM_Int;
02425   break;
02426 }
02427 
02428 /* Opcode: SetCookie P1 P2 *
02429 **
02430 ** Write the top of the stack into cookie number P2 of database P1.
02431 ** P2==0 is the schema version.  P2==1 is the database format.
02432 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
02433 ** the main database file and P1==1 is the database file used to store
02434 ** temporary tables.
02435 **
02436 ** A transaction must be started before executing this opcode.
02437 */
02438 case OP_SetCookie: {       /* no-push */
02439   Db *pDb;
02440   assert( pOp->p2<SQLITE_N_BTREE_META );
02441   assert( pOp->p1>=0 && pOp->p1<db->nDb );
02442   pDb = &db->aDb[pOp->p1];
02443   assert( pDb->pBt!=0 );
02444   assert( pTos>=p->aStack );
02445   sqlite3VdbeMemIntegerify(pTos);
02446   /* See note about index shifting on OP_ReadCookie */
02447   rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pTos->i);
02448   if( pOp->p2==0 ){
02449     /* When the schema cookie changes, record the new cookie internally */
02450     pDb->pSchema->schema_cookie = pTos->i;
02451     db->flags |= SQLITE_InternChanges;
02452   }else if( pOp->p2==1 ){
02453     /* Record changes in the file format */
02454     pDb->pSchema->file_format = pTos->i;
02455   }
02456   assert( (pTos->flags & MEM_Dyn)==0 );
02457   pTos--;
02458   if( pOp->p1==1 ){
02459     /* Invalidate all prepared statements whenever the TEMP database
02460     ** schema is changed.  Ticket #1644 */
02461     sqlite3ExpirePreparedStatements(db);
02462   }
02463   break;
02464 }
02465 
02466 /* Opcode: VerifyCookie P1 P2 *
02467 **
02468 ** Check the value of global database parameter number 0 (the
02469 ** schema version) and make sure it is equal to P2.  
02470 ** P1 is the database number which is 0 for the main database file
02471 ** and 1 for the file holding temporary tables and some higher number
02472 ** for auxiliary databases.
02473 **
02474 ** The cookie changes its value whenever the database schema changes.
02475 ** This operation is used to detect when that the cookie has changed
02476 ** and that the current process needs to reread the schema.
02477 **
02478 ** Either a transaction needs to have been started or an OP_Open needs
02479 ** to be executed (to establish a read lock) before this opcode is
02480 ** invoked.
02481 */
02482 case OP_VerifyCookie: {       /* no-push */
02483   int iMeta;
02484   Btree *pBt;
02485   assert( pOp->p1>=0 && pOp->p1<db->nDb );
02486   pBt = db->aDb[pOp->p1].pBt;
02487   if( pBt ){
02488     rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
02489   }else{
02490     rc = SQLITE_OK;
02491     iMeta = 0;
02492   }
02493   if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
02494     sqlite3SetString(&p->zErrMsg, "database schema has changed", (char*)0);
02495     rc = SQLITE_SCHEMA;
02496   }
02497   break;
02498 }
02499 
02500 /* Opcode: OpenRead P1 P2 P3
02501 **
02502 ** Open a read-only cursor for the database table whose root page is
02503 ** P2 in a database file.  The database file is determined by an 
02504 ** integer from the top of the stack.  0 means the main database and
02505 ** 1 means the database used for temporary tables.  Give the new 
02506 ** cursor an identifier of P1.  The P1 values need not be contiguous
02507 ** but all P1 values should be small integers.  It is an error for
02508 ** P1 to be negative.
02509 **
02510 ** If P2==0 then take the root page number from the next of the stack.
02511 **
02512 ** There will be a read lock on the database whenever there is an
02513 ** open cursor.  If the database was unlocked prior to this instruction
02514 ** then a read lock is acquired as part of this instruction.  A read
02515 ** lock allows other processes to read the database but prohibits
02516 ** any other process from modifying the database.  The read lock is
02517 ** released when all cursors are closed.  If this instruction attempts
02518 ** to get a read lock but fails, the script terminates with an
02519 ** SQLITE_BUSY error code.
02520 **
02521 ** The P3 value is a pointer to a KeyInfo structure that defines the
02522 ** content and collating sequence of indices.  P3 is NULL for cursors
02523 ** that are not pointing to indices.
02524 **
02525 ** See also OpenWrite.
02526 */
02527 /* Opcode: OpenWrite P1 P2 P3
02528 **
02529 ** Open a read/write cursor named P1 on the table or index whose root
02530 ** page is P2.  If P2==0 then take the root page number from the stack.
02531 **
02532 ** The P3 value is a pointer to a KeyInfo structure that defines the
02533 ** content and collating sequence of indices.  P3 is NULL for cursors
02534 ** that are not pointing to indices.
02535 **
02536 ** This instruction works just like OpenRead except that it opens the cursor
02537 ** in read/write mode.  For a given table, there can be one or more read-only
02538 ** cursors or a single read/write cursor but not both.
02539 **
02540 ** See also OpenRead.
02541 */
02542 case OP_OpenRead:          /* no-push */
02543 case OP_OpenWrite: {       /* no-push */
02544   int i = pOp->p1;
02545   int p2 = pOp->p2;
02546   int wrFlag;
02547   Btree *pX;
02548   int iDb;
02549   Cursor *pCur;
02550   Db *pDb;
02551   
02552   assert( pTos>=p->aStack );
02553   sqlite3VdbeMemIntegerify(pTos);
02554   iDb = pTos->i;
02555   assert( (pTos->flags & MEM_Dyn)==0 );
02556   pTos--;
02557   assert( iDb>=0 && iDb<db->nDb );
02558   pDb = &db->aDb[iDb];
02559   pX = pDb->pBt;
02560   assert( pX!=0 );
02561   if( pOp->opcode==OP_OpenWrite ){
02562     wrFlag = 1;
02563     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
02564       p->minWriteFileFormat = pDb->pSchema->file_format;
02565     }
02566   }else{
02567     wrFlag = 0;
02568   }
02569   if( p2<=0 ){
02570     assert( pTos>=p->aStack );
02571     sqlite3VdbeMemIntegerify(pTos);
02572     p2 = pTos->i;
02573     assert( (pTos->flags & MEM_Dyn)==0 );
02574     pTos--;
02575     assert( p2>=2 );
02576   }
02577   assert( i>=0 );
02578   pCur = allocateCursor(p, i, iDb);
02579   if( pCur==0 ) goto no_mem;
02580   pCur->nullRow = 1;
02581   if( pX==0 ) break;
02582   /* We always provide a key comparison function.  If the table being
02583   ** opened is of type INTKEY, the comparision function will be ignored. */
02584   rc = sqlite3BtreeCursor(pX, p2, wrFlag,
02585            sqlite3VdbeRecordCompare, pOp->p3,
02586            &pCur->pCursor);
02587   if( pOp->p3type==P3_KEYINFO ){
02588     pCur->pKeyInfo = (KeyInfo*)pOp->p3;
02589     pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
02590     pCur->pKeyInfo->enc = ENC(p->db);
02591   }else{
02592     pCur->pKeyInfo = 0;
02593     pCur->pIncrKey = &pCur->bogusIncrKey;
02594   }
02595   switch( rc ){
02596     case SQLITE_BUSY: {
02597       p->pc = pc;
02598       p->rc = SQLITE_BUSY;
02599       p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
02600       return SQLITE_BUSY;
02601     }
02602     case SQLITE_OK: {
02603       int flags = sqlite3BtreeFlags(pCur->pCursor);
02604       /* Sanity checking.  Only the lower four bits of the flags byte should
02605       ** be used.  Bit 3 (mask 0x08) is unpreditable.  The lower 3 bits
02606       ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
02607       ** 2 (zerodata for indices).  If these conditions are not met it can
02608       ** only mean that we are dealing with a corrupt database file
02609       */
02610       if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
02611         rc = SQLITE_CORRUPT_BKPT;
02612         goto abort_due_to_error;
02613       }
02614       pCur->isTable = (flags & BTREE_INTKEY)!=0;
02615       pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
02616       /* If P3==0 it means we are expected to open a table.  If P3!=0 then
02617       ** we expect to be opening an index.  If this is not what happened,
02618       ** then the database is corrupt
02619       */
02620       if( (pCur->isTable && pOp->p3type==P3_KEYINFO)
02621        || (pCur->isIndex && pOp->p3type!=P3_KEYINFO) ){
02622         rc = SQLITE_CORRUPT_BKPT;
02623         goto abort_due_to_error;
02624       }
02625       break;
02626     }
02627     case SQLITE_EMPTY: {
02628       pCur->isTable = pOp->p3type!=P3_KEYINFO;
02629       pCur->isIndex = !pCur->isTable;
02630       rc = SQLITE_OK;
02631       break;
02632     }
02633     default: {
02634       goto abort_due_to_error;
02635     }
02636   }
02637   break;
02638 }
02639 
02640 /* Opcode: OpenVirtual P1 P2 P3
02641 **
02642 ** Open a new cursor P1 to a transient or virtual table.
02643 ** The cursor is always opened read/write even if 
02644 ** the main database is read-only.  The transient or virtual
02645 ** table is deleted automatically when the cursor is closed.
02646 **
02647 ** P2 is the number of columns in the virtual table.
02648 ** The cursor points to a BTree table if P3==0 and to a BTree index
02649 ** if P3 is not 0.  If P3 is not NULL, it points to a KeyInfo structure
02650 ** that defines the format of keys in the index.
02651 */
02652 case OP_OpenVirtual: {       /* no-push */
02653   int i = pOp->p1;
02654   Cursor *pCx;
02655   assert( i>=0 );
02656   pCx = allocateCursor(p, i, -1);
02657   if( pCx==0 ) goto no_mem;
02658   pCx->nullRow = 1;
02659   rc = sqlite3BtreeFactory(db, 0, 1, TEMP_PAGES, &pCx->pBt);
02660   if( rc==SQLITE_OK ){
02661     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
02662   }
02663   if( rc==SQLITE_OK ){
02664     /* If a transient index is required, create it by calling
02665     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
02666     ** opening it. If a transient table is required, just use the
02667     ** automatically created table with root-page 1 (an INTKEY table).
02668     */
02669     if( pOp->p3 ){
02670       int pgno;
02671       assert( pOp->p3type==P3_KEYINFO );
02672       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA); 
02673       if( rc==SQLITE_OK ){
02674         assert( pgno==MASTER_ROOT+1 );
02675         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, sqlite3VdbeRecordCompare,
02676             pOp->p3, &pCx->pCursor);
02677         pCx->pKeyInfo = (KeyInfo*)pOp->p3;
02678         pCx->pKeyInfo->enc = ENC(p->db);
02679         pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
02680       }
02681       pCx->isTable = 0;
02682     }else{
02683       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, 0, &pCx->pCursor);
02684       pCx->isTable = 1;
02685       pCx->pIncrKey = &pCx->bogusIncrKey;
02686     }
02687   }
02688   pCx->nField = pOp->p2;
02689   pCx->isIndex = !pCx->isTable;
02690   break;
02691 }
02692 
02693 /* Opcode: OpenPseudo P1 * *
02694 **
02695 ** Open a new cursor that points to a fake table that contains a single
02696 ** row of data.  Any attempt to write a second row of data causes the
02697 ** first row to be deleted.  All data is deleted when the cursor is
02698 ** closed.
02699 **
02700 ** A pseudo-table created by this opcode is useful for holding the
02701 ** NEW or OLD tables in a trigger.  Also used to hold the a single
02702 ** row output from the sorter so that the row can be decomposed into
02703 ** individual columns using the OP_Column opcode.
02704 */
02705 case OP_OpenPseudo: {       /* no-push */
02706   int i = pOp->p1;
02707   Cursor *pCx;
02708   assert( i>=0 );
02709   pCx = allocateCursor(p, i, -1);
02710   if( pCx==0 ) goto no_mem;
02711   pCx->nullRow = 1;
02712   pCx->pseudoTable = 1;
02713   pCx->pIncrKey = &pCx->bogusIncrKey;
02714   pCx->isTable = 1;
02715   pCx->isIndex = 0;
02716   break;
02717 }
02718 
02719 /* Opcode: Close P1 * *
02720 **
02721 ** Close a cursor previously opened as P1.  If P1 is not
02722 ** currently open, this instruction is a no-op.
02723 */
02724 case OP_Close: {       /* no-push */
02725   int i = pOp->p1;
02726   if( i>=0 && i<p->nCursor ){
02727     sqlite3VdbeFreeCursor(p->apCsr[i]);
02728     p->apCsr[i] = 0;
02729   }
02730   break;
02731 }
02732 
02733 /* Opcode: MoveGe P1 P2 *
02734 **
02735 ** Pop the top of the stack and use its value as a key.  Reposition
02736 ** cursor P1 so that it points to the smallest entry that is greater
02737 ** than or equal to the key that was popped ffrom the stack.
02738 ** If there are no records greater than or equal to the key and P2 
02739 ** is not zero, then jump to P2.
02740 **
02741 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
02742 */
02743 /* Opcode: MoveGt P1 P2 *
02744 **
02745 ** Pop the top of the stack and use its value as a key.  Reposition
02746 ** cursor P1 so that it points to the smallest entry that is greater
02747 ** than the key from the stack.
02748 ** If there are no records greater than the key and P2 is not zero,
02749 ** then jump to P2.
02750 **
02751 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
02752 */
02753 /* Opcode: MoveLt P1 P2 *
02754 **
02755 ** Pop the top of the stack and use its value as a key.  Reposition
02756 ** cursor P1 so that it points to the largest entry that is less
02757 ** than the key from the stack.
02758 ** If there are no records less than the key and P2 is not zero,
02759 ** then jump to P2.
02760 **
02761 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
02762 */
02763 /* Opcode: MoveLe P1 P2 *
02764 **
02765 ** Pop the top of the stack and use its value as a key.  Reposition
02766 ** cursor P1 so that it points to the largest entry that is less than
02767 ** or equal to the key that was popped from the stack.
02768 ** If there are no records less than or eqal to the key and P2 is not zero,
02769 ** then jump to P2.
02770 **
02771 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
02772 */
02773 case OP_MoveLt:         /* no-push */
02774 case OP_MoveLe:         /* no-push */
02775 case OP_MoveGe:         /* no-push */
02776 case OP_MoveGt: {       /* no-push */
02777   int i = pOp->p1;
02778   Cursor *pC;
02779 
02780   assert( pTos>=p->aStack );
02781   assert( i>=0 && i<p->nCursor );
02782   pC = p->apCsr[i];
02783   assert( pC!=0 );
02784   if( pC->pCursor!=0 ){
02785     int res, oc;
02786     oc = pOp->opcode;
02787     pC->nullRow = 0;
02788     *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
02789     if( pC->isTable ){
02790       i64 iKey;
02791       sqlite3VdbeMemIntegerify(pTos);
02792       iKey = intToKey(pTos->i);
02793       if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){
02794         pC->movetoTarget = iKey;
02795         pC->deferredMoveto = 1;
02796         assert( (pTos->flags & MEM_Dyn)==0 );
02797         pTos--;
02798         break;
02799       }
02800       rc = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, &res);
02801       if( rc!=SQLITE_OK ){
02802         goto abort_due_to_error;
02803       }
02804       pC->lastRowid = pTos->i;
02805       pC->rowidIsValid = res==0;
02806     }else{
02807       assert( pTos->flags & MEM_Blob );
02808       /* Stringify(pTos, encoding); */
02809       rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
02810       if( rc!=SQLITE_OK ){
02811         goto abort_due_to_error;
02812       }
02813       pC->rowidIsValid = 0;
02814     }
02815     pC->deferredMoveto = 0;
02816     pC->cacheStatus = CACHE_STALE;
02817     *pC->pIncrKey = 0;
02818     sqlite3_search_count++;
02819     if( oc==OP_MoveGe || oc==OP_MoveGt ){
02820       if( res<0 ){
02821         rc = sqlite3BtreeNext(pC->pCursor, &res);
02822         if( rc!=SQLITE_OK ) goto abort_due_to_error;
02823         pC->rowidIsValid = 0;
02824       }else{
02825         res = 0;
02826       }
02827     }else{
02828       assert( oc==OP_MoveLt || oc==OP_MoveLe );
02829       if( res>=0 ){
02830         rc = sqlite3BtreePrevious(pC->pCursor, &res);
02831         if( rc!=SQLITE_OK ) goto abort_due_to_error;
02832         pC->rowidIsValid = 0;
02833       }else{
02834         /* res might be negative because the table is empty.  Check to
02835         ** see if this is the case.
02836         */
02837         res = sqlite3BtreeEof(pC->pCursor);
02838       }
02839     }
02840     if( res ){
02841       if( pOp->p2>0 ){
02842         pc = pOp->p2 - 1;
02843       }else{
02844         pC->nullRow = 1;
02845       }
02846     }
02847   }
02848   Release(pTos);
02849   pTos--;
02850   break;
02851 }
02852 
02853 /* Opcode: Distinct P1 P2 *
02854 **
02855 ** Use the top of the stack as a record created using MakeRecord.  P1 is a
02856 ** cursor on a table that declared as an index.  If that table contains an
02857 ** entry that matches the top of the stack fall thru.  If the top of the stack
02858 ** matches no entry in P1 then jump to P2.
02859 **
02860 ** The cursor is left pointing at the matching entry if it exists.  The
02861 ** record on the top of the stack is not popped.
02862 **
02863 ** This instruction is similar to NotFound except that this operation
02864 ** does not pop the key from the stack.
02865 **
02866 ** The instruction is used to implement the DISTINCT operator on SELECT
02867 ** statements.  The P1 table is not a true index but rather a record of
02868 ** all results that have produced so far.  
02869 **
02870 ** See also: Found, NotFound, MoveTo, IsUnique, NotExists
02871 */
02872 /* Opcode: Found P1 P2 *
02873 **
02874 ** Top of the stack holds a blob constructed by MakeRecord.  P1 is an index.
02875 ** If an entry that matches the top of the stack exists in P1 then
02876 ** jump to P2.  If the top of the stack does not match any entry in P1
02877 ** then fall thru.  The P1 cursor is left pointing at the matching entry
02878 ** if it exists.  The blob is popped off the top of the stack.
02879 **
02880 ** This instruction is used to implement the IN operator where the
02881 ** left-hand side is a SELECT statement.  P1 is not a true index but
02882 ** is instead a temporary index that holds the results of the SELECT
02883 ** statement.  This instruction just checks to see if the left-hand side
02884 ** of the IN operator (stored on the top of the stack) exists in the
02885 ** result of the SELECT statement.
02886 **
02887 ** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
02888 */
02889 /* Opcode: NotFound P1 P2 *
02890 **
02891 ** The top of the stack holds a blob constructed by MakeRecord.  P1 is
02892 ** an index.  If no entry exists in P1 that matches the blob then jump
02893 ** to P1.  If an entry does existing, fall through.  The cursor is left
02894 ** pointing to the entry that matches.  The blob is popped from the stack.
02895 **
02896 ** The difference between this operation and Distinct is that
02897 ** Distinct does not pop the key from the stack.
02898 **
02899 ** See also: Distinct, Found, MoveTo, NotExists, IsUnique
02900 */
02901 case OP_Distinct:       /* no-push */
02902 case OP_NotFound:       /* no-push */
02903 case OP_Found: {        /* no-push */
02904   int i = pOp->p1;
02905   int alreadyExists = 0;
02906   Cursor *pC;
02907   assert( pTos>=p->aStack );
02908   assert( i>=0 && i<p->nCursor );
02909   assert( p->apCsr[i]!=0 );
02910   if( (pC = p->apCsr[i])->pCursor!=0 ){
02911     int res, rx;
02912     assert( pC->isTable==0 );
02913     Stringify(pTos, encoding);
02914     rx = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
02915     alreadyExists = rx==SQLITE_OK && res==0;
02916     pC->deferredMoveto = 0;
02917     pC->cacheStatus = CACHE_STALE;
02918   }
02919   if( pOp->opcode==OP_Found ){
02920     if( alreadyExists ) pc = pOp->p2 - 1;
02921   }else{
02922     if( !alreadyExists ) pc = pOp->p2 - 1;
02923   }
02924   if( pOp->opcode!=OP_Distinct ){
02925     Release(pTos);
02926     pTos--;
02927   }
02928   break;
02929 }
02930 
02931 /* Opcode: IsUnique P1 P2 *
02932 **
02933 ** The top of the stack is an integer record number.  Call this
02934 ** record number R.  The next on the stack is an index key created
02935 ** using MakeIdxRec.  Call it K.  This instruction pops R from the
02936 ** stack but it leaves K unchanged.
02937 **
02938 ** P1 is an index.  So it has no data and its key consists of a
02939 ** record generated by OP_MakeRecord where the last field is the 
02940 ** rowid of the entry that the index refers to.
02941 ** 
02942 ** This instruction asks if there is an entry in P1 where the
02943 ** fields matches K but the rowid is different from R.
02944 ** If there is no such entry, then there is an immediate
02945 ** jump to P2.  If any entry does exist where the index string
02946 ** matches K but the record number is not R, then the record
02947 ** number for that entry is pushed onto the stack and control
02948 ** falls through to the next instruction.
02949 **
02950 ** See also: Distinct, NotFound, NotExists, Found
02951 */
02952 case OP_IsUnique: {        /* no-push */
02953   int i = pOp->p1;
02954   Mem *pNos = &pTos[-1];
02955   Cursor *pCx;
02956   BtCursor *pCrsr;
02957   i64 R;
02958 
02959   /* Pop the value R off the top of the stack
02960   */
02961   assert( pNos>=p->aStack );
02962   sqlite3VdbeMemIntegerify(pTos);
02963   R = pTos->i;
02964   assert( (pTos->flags & MEM_Dyn)==0 );
02965   pTos--;
02966   assert( i>=0 && i<=p->nCursor );
02967   pCx = p->apCsr[i];
02968   assert( pCx!=0 );
02969   pCrsr = pCx->pCursor;
02970   if( pCrsr!=0 ){
02971     int res;
02972     i64 v;         /* The record number on the P1 entry that matches K */
02973     char *zKey;    /* The value of K */
02974     int nKey;      /* Number of bytes in K */
02975     int len;       /* Number of bytes in K without the rowid at the end */
02976     int szRowid;   /* Size of the rowid column at the end of zKey */
02977 
02978     /* Make sure K is a string and make zKey point to K
02979     */
02980     Stringify(pNos, encoding);
02981     zKey = pNos->z;
02982     nKey = pNos->n;
02983 
02984     szRowid = sqlite3VdbeIdxRowidLen((u8*)zKey);
02985     len = nKey-szRowid;
02986 
02987     /* Search for an entry in P1 where all but the last four bytes match K.
02988     ** If there is no such entry, jump immediately to P2.
02989     */
02990     assert( pCx->deferredMoveto==0 );
02991     pCx->cacheStatus = CACHE_STALE;
02992     rc = sqlite3BtreeMoveto(pCrsr, zKey, len, &res);
02993     if( rc!=SQLITE_OK ){
02994       goto abort_due_to_error;
02995     }
02996     if( res<0 ){
02997       rc = sqlite3BtreeNext(pCrsr, &res);
02998       if( res ){
02999         pc = pOp->p2 - 1;
03000         break;
03001       }
03002     }
03003     rc = sqlite3VdbeIdxKeyCompare(pCx, len, (u8*)zKey, &res); 
03004     if( rc!=SQLITE_OK ) goto abort_due_to_error;
03005     if( res>0 ){
03006       pc = pOp->p2 - 1;
03007       break;
03008     }
03009 
03010     /* At this point, pCrsr is pointing to an entry in P1 where all but
03011     ** the final entry (the rowid) matches K.  Check to see if the
03012     ** final rowid column is different from R.  If it equals R then jump
03013     ** immediately to P2.
03014     */
03015     rc = sqlite3VdbeIdxRowid(pCrsr, &v);
03016     if( rc!=SQLITE_OK ){
03017       goto abort_due_to_error;
03018     }
03019     if( v==R ){
03020       pc = pOp->p2 - 1;
03021       break;
03022     }
03023 
03024     /* The final varint of the key is different from R.  Push it onto
03025     ** the stack.  (The record number of an entry that violates a UNIQUE
03026     ** constraint.)
03027     */
03028     pTos++;
03029     pTos->i = v;
03030     pTos->flags = MEM_Int;
03031   }
03032   break;
03033 }
03034 
03035 /* Opcode: NotExists P1 P2 *
03036 **
03037 ** Use the top of the stack as a integer key.  If a record with that key
03038 ** does not exist in table of P1, then jump to P2.  If the record
03039 ** does exist, then fall thru.  The cursor is left pointing to the
03040 ** record if it exists.  The integer key is popped from the stack.
03041 **
03042 ** The difference between this operation and NotFound is that this
03043 ** operation assumes the key is an integer and that P1 is a table whereas
03044 ** NotFound assumes key is a blob constructed from MakeRecord and
03045 ** P1 is an index.
03046 **
03047 ** See also: Distinct, Found, MoveTo, NotFound, IsUnique
03048 */
03049 case OP_NotExists: {        /* no-push */
03050   int i = pOp->p1;
03051   Cursor *pC;
03052   BtCursor *pCrsr;
03053   assert( pTos>=p->aStack );
03054   assert( i>=0 && i<p->nCursor );
03055   assert( p->apCsr[i]!=0 );
03056   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
03057     int res;
03058     u64 iKey;
03059     assert( pTos->flags & MEM_Int );
03060     assert( p->apCsr[i]->isTable );
03061     iKey = intToKey(pTos->i);
03062     rc = sqlite3BtreeMoveto(pCrsr, 0, iKey, &res);
03063     pC->lastRowid = pTos->i;
03064     pC->rowidIsValid = res==0;
03065     pC->nullRow = 0;
03066     pC->cacheStatus = CACHE_STALE;
03067     if( res!=0 ){
03068       pc = pOp->p2 - 1;
03069       pC->rowidIsValid = 0;
03070     }
03071   }
03072   Release(pTos);
03073   pTos--;
03074   break;
03075 }
03076 
03077 /* Opcode: Sequence P1 * *
03078 **
03079 ** Push an integer onto the stack which is the next available
03080 ** sequence number for cursor P1.  The sequence number on the
03081 ** cursor is incremented after the push.
03082 */
03083 case OP_Sequence: {
03084   int i = pOp->p1;
03085   assert( pTos>=p->aStack );
03086   assert( i>=0 && i<p->nCursor );
03087   assert( p->apCsr[i]!=0 );
03088   pTos++;
03089   pTos->i = p->apCsr[i]->seqCount++;
03090   pTos->flags = MEM_Int;
03091   break;
03092 }
03093 
03094 
03095 /* Opcode: NewRowid P1 P2 *
03096 **
03097 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
03098 ** The record number is not previously used as a key in the database
03099 ** table that cursor P1 points to.  The new record number is pushed 
03100 ** onto the stack.
03101 **
03102 ** If P2>0 then P2 is a memory cell that holds the largest previously
03103 ** generated record number.  No new record numbers are allowed to be less
03104 ** than this value.  When this value reaches its maximum, a SQLITE_FULL
03105 ** error is generated.  The P2 memory cell is updated with the generated
03106 ** record number.  This P2 mechanism is used to help implement the
03107 ** AUTOINCREMENT feature.
03108 */
03109 case OP_NewRowid: {
03110   int i = pOp->p1;
03111   i64 v = 0;
03112   Cursor *pC;
03113   assert( i>=0 && i<p->nCursor );
03114   assert( p->apCsr[i]!=0 );
03115   if( (pC = p->apCsr[i])->pCursor==0 ){
03116     /* The zero initialization above is all that is needed */
03117   }else{
03118     /* The next rowid or record number (different terms for the same
03119     ** thing) is obtained in a two-step algorithm.
03120     **
03121     ** First we attempt to find the largest existing rowid and add one
03122     ** to that.  But if the largest existing rowid is already the maximum
03123     ** positive integer, we have to fall through to the second
03124     ** probabilistic algorithm
03125     **
03126     ** The second algorithm is to select a rowid at random and see if
03127     ** it already exists in the table.  If it does not exist, we have
03128     ** succeeded.  If the random rowid does exist, we select a new one
03129     ** and try again, up to 1000 times.
03130     **
03131     ** For a table with less than 2 billion entries, the probability
03132     ** of not finding a unused rowid is about 1.0e-300.  This is a 
03133     ** non-zero probability, but it is still vanishingly small and should
03134     ** never cause a problem.  You are much, much more likely to have a
03135     ** hardware failure than for this algorithm to fail.
03136     **
03137     ** The analysis in the previous paragraph assumes that you have a good
03138     ** source of random numbers.  Is a library function like lrand48()
03139     ** good enough?  Maybe. Maybe not. It's hard to know whether there
03140     ** might be subtle bugs is some implementations of lrand48() that
03141     ** could cause problems. To avoid uncertainty, SQLite uses its own 
03142     ** random number generator based on the RC4 algorithm.
03143     **
03144     ** To promote locality of reference for repetitive inserts, the
03145     ** first few attempts at chosing a random rowid pick values just a little
03146     ** larger than the previous rowid.  This has been shown experimentally
03147     ** to double the speed of the COPY operation.
03148     */
03149     int res, rx=SQLITE_OK, cnt;
03150     i64 x;
03151     cnt = 0;
03152     if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
03153           BTREE_INTKEY ){
03154       rc = SQLITE_CORRUPT_BKPT;
03155       goto abort_due_to_error;
03156     }
03157     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
03158     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
03159 
03160 #ifdef SQLITE_32BIT_ROWID
03161 #   define MAX_ROWID 0x7fffffff
03162 #else
03163     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
03164     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
03165     ** to provide the constant while making all compilers happy.
03166     */
03167 #   define MAX_ROWID  ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
03168 #endif
03169 
03170     if( !pC->useRandomRowid ){
03171       if( pC->nextRowidValid ){
03172         v = pC->nextRowid;
03173       }else{
03174         rc = sqlite3BtreeLast(pC->pCursor, &res);
03175         if( rc!=SQLITE_OK ){
03176           goto abort_due_to_error;
03177         }
03178         if( res ){
03179           v = 1;
03180         }else{
03181           sqlite3BtreeKeySize(pC->pCursor, &v);
03182           v = keyToInt(v);
03183           if( v==MAX_ROWID ){
03184             pC->useRandomRowid = 1;
03185           }else{
03186             v++;
03187           }
03188         }
03189       }
03190 
03191 #ifndef SQLITE_OMIT_AUTOINCREMENT
03192       if( pOp->p2 ){
03193         Mem *pMem;
03194         assert( pOp->p2>0 && pOp->p2<p->nMem );  /* P2 is a valid memory cell */
03195         pMem = &p->aMem[pOp->p2];
03196         sqlite3VdbeMemIntegerify(pMem);
03197         assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P2) holds an integer */
03198         if( pMem->i==MAX_ROWID || pC->useRandomRowid ){
03199           rc = SQLITE_FULL;
03200           goto abort_due_to_error;
03201         }
03202         if( v<pMem->i+1 ){
03203           v = pMem->i + 1;
03204         }
03205         pMem->i = v;
03206       }
03207 #endif
03208 
03209       if( v<MAX_ROWID ){
03210         pC->nextRowidValid = 1;
03211         pC->nextRowid = v+1;
03212       }else{
03213         pC->nextRowidValid = 0;
03214       }
03215     }
03216     if( pC->useRandomRowid ){
03217       assert( pOp->p2==0 );  /* SQLITE_FULL must have occurred prior to this */
03218       v = db->priorNewRowid;
03219       cnt = 0;
03220       do{
03221         if( v==0 || cnt>2 ){
03222           sqlite3Randomness(sizeof(v), &v);
03223           if( cnt<5 ) v &= 0xffffff;
03224         }else{
03225           unsigned char r;
03226           sqlite3Randomness(1, &r);
03227           v += r + 1;
03228         }
03229         if( v==0 ) continue;
03230         x = intToKey(v);
03231         rx = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)x, &res);
03232         cnt++;
03233       }while( cnt<1000 && rx==SQLITE_OK && res==0 );
03234       db->priorNewRowid = v;
03235       if( rx==SQLITE_OK && res==0 ){
03236         rc = SQLITE_FULL;
03237         goto abort_due_to_error;
03238       }
03239     }
03240     pC->rowidIsValid = 0;
03241     pC->deferredMoveto = 0;
03242     pC->cacheStatus = CACHE_STALE;
03243   }
03244   pTos++;
03245   pTos->i = v;
03246   pTos->flags = MEM_Int;
03247   break;
03248 }
03249 
03250 /* Opcode: Insert P1 P2 P3
03251 **
03252 ** Write an entry into the table of cursor P1.  A new entry is
03253 ** created if it doesn't already exist or the data for an existing
03254 ** entry is overwritten.  The data is the value on the top of the
03255 ** stack.  The key is the next value down on the stack.  The key must
03256 ** be an integer.  The stack is popped twice by this instruction.
03257 **
03258 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
03259 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P2 is set,
03260 ** then rowid is stored for subsequent return by the
03261 ** sqlite3_last_insert_rowid() function (otherwise it's unmodified).
03262 **
03263 ** This instruction only works on tables.  The equivalent instruction
03264 ** for indices is OP_IdxInsert.
03265 */
03266 case OP_Insert: {         /* no-push */
03267   Mem *pNos = &pTos[-1];
03268   int i = pOp->p1;
03269   Cursor *pC;
03270   assert( pNos>=p->aStack );
03271   assert( i>=0 && i<p->nCursor );
03272   assert( p->apCsr[i]!=0 );
03273   if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){
03274     i64 iKey;   /* The integer ROWID or key for the record to be inserted */
03275 
03276     assert( pNos->flags & MEM_Int );
03277     assert( pC->isTable );
03278     iKey = intToKey(pNos->i);
03279 
03280     if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
03281     if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->i;
03282     if( pC->nextRowidValid && pNos->i>=pC->nextRowid ){
03283       pC->nextRowidValid = 0;
03284     }
03285     if( pTos->flags & MEM_Null ){
03286       pTos->z = 0;
03287       pTos->n = 0;
03288     }else{
03289       assert( pTos->flags & (MEM_Blob|MEM_Str) );
03290     }
03291     if( pC->pseudoTable ){
03292       sqliteFree(pC->pData);
03293       pC->iKey = iKey;
03294       pC->nData = pTos->n;
03295       if( pTos->flags & MEM_Dyn ){
03296         pC->pData = pTos->z;
03297         pTos->flags = MEM_Null;
03298       }else{
03299         pC->pData = sqliteMallocRaw( pC->nData+2 );
03300         if( !pC->pData ) goto no_mem;
03301         memcpy(pC->pData, pTos->z, pC->nData);
03302         pC->pData[pC->nData] = 0;
03303         pC->pData[pC->nData+1] = 0;
03304       }
03305       pC->nullRow = 0;
03306     }else{
03307       rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey, pTos->z, pTos->n);
03308     }
03309     
03310     pC->rowidIsValid = 0;
03311     pC->deferredMoveto = 0;
03312     pC->cacheStatus = CACHE_STALE;
03313 
03314     /* Invoke the update-hook if required. */
03315     if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
03316       const char *zDb = db->aDb[pC->iDb].zName;
03317       const char *zTbl = pOp->p3;
03318       int op = ((pOp->p2 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
03319       assert( pC->isTable );
03320       db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
03321       assert( pC->iDb>=0 );
03322     }
03323   }
03324   popStack(&pTos, 2);
03325 
03326   break;
03327 }
03328 
03329 /* Opcode: Delete P1 P2 P3
03330 **
03331 ** Delete the record at which the P1 cursor is currently pointing.
03332 **
03333 ** The cursor will be left pointing at either the next or the previous
03334 ** record in the table. If it is left pointing at the next record, then
03335 ** the next Next instruction will be a no-op.  Hence it is OK to delete
03336 ** a record from within an Next loop.
03337 **
03338 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
03339 ** incremented (otherwise not).
03340 **
03341 ** If P1 is a pseudo-table, then this instruction is a no-op.
03342 */
03343 case OP_Delete: {        /* no-push */
03344   int i = pOp->p1;
03345   Cursor *pC;
03346   assert( i>=0 && i<p->nCursor );
03347   pC = p->apCsr[i];
03348   assert( pC!=0 );
03349   if( pC->pCursor!=0 ){
03350     i64 iKey;
03351 
03352     /* If the update-hook will be invoked, set iKey to the rowid of the
03353     ** row being deleted.
03354     */
03355     if( db->xUpdateCallback && pOp->p3 ){
03356       assert( pC->isTable );
03357       if( pC->rowidIsValid ){
03358         iKey = pC->lastRowid;
03359       }else{
03360         rc = sqlite3BtreeKeySize(pC->pCursor, &iKey);
03361         if( rc ){
03362           goto abort_due_to_error;
03363         }
03364         iKey = keyToInt(iKey);
03365       }
03366     }
03367 
03368     rc = sqlite3VdbeCursorMoveto(pC);
03369     if( rc ) goto abort_due_to_error;
03370     rc = sqlite3BtreeDelete(pC->pCursor);
03371     pC->nextRowidValid = 0;
03372     pC->cacheStatus = CACHE_STALE;
03373 
03374     /* Invoke the update-hook if required. */
03375     if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
03376       const char *zDb = db->aDb[pC->iDb].zName;
03377       const char *zTbl = pOp->p3;
03378       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
03379       assert( pC->iDb>=0 );
03380     }
03381   }
03382   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
03383   break;
03384 }
03385 
03386 /* Opcode: ResetCount P1 * *
03387 **
03388 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
03389 ** then the value of the change counter is copied to the database handle
03390 ** change counter (returned by subsequent calls to sqlite3_changes())
03391 ** before it is reset. This is used by trigger programs.
03392 */
03393 case OP_ResetCount: {        /* no-push */
03394   if( pOp->p1 ){
03395     sqlite3VdbeSetChanges(db, p->nChange);
03396   }
03397   p->nChange = 0;
03398   break;
03399 }
03400 
03401 /* Opcode: RowData P1 * *
03402 **
03403 ** Push onto the stack the complete row data for cursor P1.
03404 ** There is no interpretation of the data.  It is just copied
03405 ** onto the stack exactly as it is found in the database file.
03406 **
03407 ** If the cursor is not pointing to a valid row, a NULL is pushed
03408 ** onto the stack.
03409 */
03410 /* Opcode: RowKey P1 * *
03411 **
03412 ** Push onto the stack the complete row key for cursor P1.
03413 ** There is no interpretation of the key.  It is just copied
03414 ** onto the stack exactly as it is found in the database file.
03415 **
03416 ** If the cursor is not pointing to a valid row, a NULL is pushed
03417 ** onto the stack.
03418 */
03419 case OP_RowKey:
03420 case OP_RowData: {
03421   int i = pOp->p1;
03422   Cursor *pC;
03423   u32 n;
03424 
03425   /* Note that RowKey and RowData are really exactly the same instruction */
03426   pTos++;
03427   assert( i>=0 && i<p->nCursor );
03428   pC = p->apCsr[i];
03429   assert( pC->isTable || pOp->opcode==OP_RowKey );
03430   assert( pC->isIndex || pOp->opcode==OP_RowData );
03431   assert( pC!=0 );
03432   if( pC->nullRow ){
03433     pTos->flags = MEM_Null;
03434   }else if( pC->pCursor!=0 ){
03435     BtCursor *pCrsr = pC->pCursor;
03436     rc = sqlite3VdbeCursorMoveto(pC);
03437     if( rc ) goto abort_due_to_error;
03438     if( pC->nullRow ){
03439       pTos->flags = MEM_Null;
03440       break;
03441     }else if( pC->isIndex ){
03442       i64 n64;
03443       assert( !pC->isTable );
03444       sqlite3BtreeKeySize(pCrsr, &n64);
03445       n = n64;
03446     }else{
03447       sqlite3BtreeDataSize(pCrsr, &n);
03448     }
03449     pTos->n = n;
03450     if( n<=NBFS ){
03451       pTos->flags = MEM_Blob | MEM_Short;
03452       pTos->z = pTos->zShort;
03453     }else{
03454       char *z = sqliteMallocRaw( n );
03455       if( z==0 ) goto no_mem;
03456       pTos->flags = MEM_Blob | MEM_Dyn;
03457       pTos->xDel = 0;
03458       pTos->z = z;
03459     }
03460     if( pC->isIndex ){
03461       sqlite3BtreeKey(pCrsr, 0, n, pTos->z);
03462     }else{
03463       sqlite3BtreeData(pCrsr, 0, n, pTos->z);
03464     }
03465   }else if( pC->pseudoTable ){
03466     pTos->n = pC->nData;
03467     pTos->z = pC->pData;
03468     pTos->flags = MEM_Blob|MEM_Ephem;
03469   }else{
03470     pTos->flags = MEM_Null;
03471   }
03472   pTos->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
03473   break;
03474 }
03475 
03476 /* Opcode: Rowid P1 * *
03477 **
03478 ** Push onto the stack an integer which is the key of the table entry that
03479 ** P1 is currently point to.
03480 */
03481 case OP_Rowid: {
03482   int i = pOp->p1;
03483   Cursor *pC;
03484   i64 v;
03485 
03486   assert( i>=0 && i<p->nCursor );
03487   pC = p->apCsr[i];
03488   assert( pC!=0 );
03489   rc = sqlite3VdbeCursorMoveto(pC);
03490   if( rc ) goto abort_due_to_error;
03491   pTos++;
03492   if( pC->rowidIsValid ){
03493     v = pC->lastRowid;
03494   }else if( pC->pseudoTable ){
03495     v = keyToInt(pC->iKey);
03496   }else if( pC->nullRow || pC->pCursor==0 ){
03497     pTos->flags = MEM_Null;
03498     break;
03499   }else{
03500     assert( pC->pCursor!=0 );
03501     sqlite3BtreeKeySize(pC->pCursor, &v);
03502     v = keyToInt(v);
03503   }
03504   pTos->i = v;
03505   pTos->flags = MEM_Int;
03506   break;
03507 }
03508 
03509 /* Opcode: NullRow P1 * *
03510 **
03511 ** Move the cursor P1 to a null row.  Any OP_Column operations
03512 ** that occur while the cursor is on the null row will always push 
03513 ** a NULL onto the stack.
03514 */
03515 case OP_NullRow: {        /* no-push */
03516   int i = pOp->p1;
03517   Cursor *pC;
03518 
03519   assert( i>=0 && i<p->nCursor );
03520   pC = p->apCsr[i];
03521   assert( pC!=0 );
03522   pC->nullRow = 1;
03523   pC->rowidIsValid = 0;
03524   break;
03525 }
03526 
03527 /* Opcode: Last P1 P2 *
03528 **
03529 ** The next use of the Rowid or Column or Next instruction for P1 
03530 ** will refer to the last entry in the database table or index.
03531 ** If the table or index is empty and P2>0, then jump immediately to P2.
03532 ** If P2 is 0 or if the table or index is not empty, fall through
03533 ** to the following instruction.
03534 */
03535 case OP_Last: {        /* no-push */
03536   int i = pOp->p1;
03537   Cursor *pC;
03538   BtCursor *pCrsr;
03539 
03540   assert( i>=0 && i<p->nCursor );
03541   pC = p->apCsr[i];
03542   assert( pC!=0 );
03543   if( (pCrsr = pC->pCursor)!=0 ){
03544     int res;
03545     rc = sqlite3BtreeLast(pCrsr, &res);
03546     pC->nullRow = res;
03547     pC->deferredMoveto = 0;
03548     pC->cacheStatus = CACHE_STALE;
03549     if( res && pOp->p2>0 ){
03550       pc = pOp->p2 - 1;
03551     }
03552   }else{
03553     pC->nullRow = 0;
03554   }
03555   break;
03556 }
03557 
03558 
03559 /* Opcode: Sort P1 P2 *
03560 **
03561 ** This opcode does exactly the same thing as OP_Rewind except that
03562 ** it increments an undocumented global variable used for testing.
03563 **
03564 ** Sorting is accomplished by writing records into a sorting index,
03565 ** then rewinding that index and playing it back from beginning to
03566 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
03567 ** rewinding so that the global variable will be incremented and
03568 ** regression tests can determine whether or not the optimizer is
03569 ** correctly optimizing out sorts.
03570 */
03571 case OP_Sort: {        /* no-push */
03572   sqlite3_sort_count++;
03573   sqlite3_search_count--;
03574   /* Fall through into OP_Rewind */
03575 }
03576 /* Opcode: Rewind P1 P2 *
03577 **
03578 ** The next use of the Rowid or Column or Next instruction for P1 
03579 ** will refer to the first entry in the database table or index.
03580 ** If the table or index is empty and P2>0, then jump immediately to P2.
03581 ** If P2 is 0 or if the table or index is not empty, fall through
03582 ** to the following instruction.
03583 */
03584 case OP_Rewind: {        /* no-push */
03585   int i = pOp->p1;
03586   Cursor *pC;
03587   BtCursor *pCrsr;
03588   int res;
03589 
03590   assert( i>=0 && i<p->nCursor );
03591   pC = p->apCsr[i];
03592   assert( pC!=0 );
03593   if( (pCrsr = pC->pCursor)!=0 ){
03594     rc = sqlite3BtreeFirst(pCrsr, &res);
03595     pC->atFirst = res==0;
03596     pC->deferredMoveto = 0;
03597     pC->cacheStatus = CACHE_STALE;
03598   }else{
03599     res = 1;
03600   }
03601   pC->nullRow = res;
03602   if( res && pOp->p2>0 ){
03603     pc = pOp->p2 - 1;
03604   }
03605   break;
03606 }
03607 
03608 /* Opcode: Next P1 P2 *
03609 **
03610 ** Advance cursor P1 so that it points to the next key/data pair in its
03611 ** table or index.  If there are no more key/value pairs then fall through
03612 ** to the following instruction.  But if the cursor advance was successful,
03613 ** jump immediately to P2.
03614 **
03615 ** See also: Prev
03616 */
03617 /* Opcode: Prev P1 P2 *
03618 **
03619 ** Back up cursor P1 so that it points to the previous key/data pair in its
03620 ** table or index.  If there is no previous key/value pairs then fall through
03621 ** to the following instruction.  But if the cursor backup was successful,
03622 ** jump immediately to P2.
03623 */
03624 case OP_Prev:          /* no-push */
03625 case OP_Next: {        /* no-push */
03626   Cursor *pC;
03627   BtCursor *pCrsr;
03628 
03629   CHECK_FOR_INTERRUPT;
03630   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
03631   pC = p->apCsr[pOp->p1];
03632   assert( pC!=0 );
03633   if( (pCrsr = pC->pCursor)!=0 ){
03634     int res;
03635     if( pC->nullRow ){
03636       res = 1;
03637     }else{
03638       assert( pC->deferredMoveto==0 );
03639       rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
03640                                   sqlite3BtreePrevious(pCrsr, &res);
03641       pC->nullRow = res;
03642       pC->cacheStatus = CACHE_STALE;
03643     }
03644     if( res==0 ){
03645       pc = pOp->p2 - 1;
03646       sqlite3_search_count++;
03647     }
03648   }else{
03649     pC->nullRow = 1;
03650   }
03651   pC->rowidIsValid = 0;
03652   break;
03653 }
03654 
03655 /* Opcode: IdxInsert P1 * *
03656 **
03657 ** The top of the stack holds a SQL index key made using either the
03658 ** MakeIdxRec or MakeRecord instructions.  This opcode writes that key
03659 ** into the index P1.  Data for the entry is nil.
03660 **
03661 ** This instruction only works for indices.  The equivalent instruction
03662 ** for tables is OP_Insert.
03663 */
03664 case OP_IdxInsert: {        /* no-push */
03665   int i = pOp->p1;
03666   Cursor *pC;
03667   BtCursor *pCrsr;
03668   assert( pTos>=p->aStack );
03669   assert( i>=0 && i<p->nCursor );
03670   assert( p->apCsr[i]!=0 );
03671   assert( pTos->flags & MEM_Blob );
03672   assert( pOp->p2==0 );
03673   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
03674     int nKey = pTos->n;
03675     const char *zKey = pTos->z;
03676     assert( pC->isTable==0 );
03677     rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0);
03678     assert( pC->deferredMoveto==0 );
03679     pC->cacheStatus = CACHE_STALE;
03680   }
03681   Release(pTos);
03682   pTos--;
03683   break;
03684 }
03685 
03686 /* Opcode: IdxDelete P1 * *
03687 **
03688 ** The top of the stack is an index key built using the either the
03689 ** MakeIdxRec or MakeRecord opcodes.
03690 ** This opcode removes that entry from the index.
03691 */
03692 case OP_IdxDelete: {        /* no-push */
03693   int i = pOp->p1;
03694   Cursor *pC;
03695   BtCursor *pCrsr;
03696   assert( pTos>=p->aStack );
03697   assert( pTos->flags & MEM_Blob );
03698   assert( i>=0 && i<p->nCursor );
03699   assert( p->apCsr[i]!=0 );
03700   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
03701     int res;
03702     rc = sqlite3BtreeMoveto(pCrsr, pTos->z, pTos->n, &res);
03703     if( rc==SQLITE_OK && res==0 ){
03704       rc = sqlite3BtreeDelete(pCrsr);
03705     }
03706     assert( pC->deferredMoveto==0 );
03707     pC->cacheStatus = CACHE_STALE;
03708   }
03709   Release(pTos);
03710   pTos--;
03711   break;
03712 }
03713 
03714 /* Opcode: IdxRowid P1 * *
03715 **
03716 ** Push onto the stack an integer which is the last entry in the record at
03717 ** the end of the index key pointed to by cursor P1.  This integer should be
03718 ** the rowid of the table entry to which this index entry points.
03719 **
03720 ** See also: Rowid, MakeIdxRec.
03721 */
03722 case OP_IdxRowid: {
03723   int i = pOp->p1;
03724   BtCursor *pCrsr;
03725   Cursor *pC;
03726 
03727   assert( i>=0 && i<p->nCursor );
03728   assert( p->apCsr[i]!=0 );
03729   pTos++;
03730   pTos->flags = MEM_Null;
03731   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
03732     i64 rowid;
03733 
03734     assert( pC->deferredMoveto==0 );
03735     assert( pC->isTable==0 );
03736     if( pC->nullRow ){
03737       pTos->flags = MEM_Null;
03738     }else{
03739       rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
03740       if( rc!=SQLITE_OK ){
03741         goto abort_due_to_error;
03742       }
03743       pTos->flags = MEM_Int;
03744       pTos->i = rowid;
03745     }
03746   }
03747   break;
03748 }
03749 
03750 /* Opcode: IdxGT P1 P2 *
03751 **
03752 ** The top of the stack is an index entry that omits the ROWID.  Compare
03753 ** the top of stack against the index that P1 is currently pointing to.
03754 ** Ignore the ROWID on the P1 index.
03755 **
03756 ** The top of the stack might have fewer columns that P1.
03757 **
03758 ** If the P1 index entry is greater than the top of the stack
03759 ** then jump to P2.  Otherwise fall through to the next instruction.
03760 ** In either case, the stack is popped once.
03761 */
03762 /* Opcode: IdxGE P1 P2 P3
03763 **
03764 ** The top of the stack is an index entry that omits the ROWID.  Compare
03765 ** the top of stack against the index that P1 is currently pointing to.
03766 ** Ignore the ROWID on the P1 index.
03767 **
03768 ** If the P1 index entry is greater than or equal to the top of the stack
03769 ** then jump to P2.  Otherwise fall through to the next instruction.
03770 ** In either case, the stack is popped once.
03771 **
03772 ** If P3 is the "+" string (or any other non-NULL string) then the
03773 ** index taken from the top of the stack is temporarily increased by
03774 ** an epsilon prior to the comparison.  This make the opcode work
03775 ** like IdxGT except that if the key from the stack is a prefix of
03776 ** the key in the cursor, the result is false whereas it would be
03777 ** true with IdxGT.
03778 */
03779 /* Opcode: IdxLT P1 P2 P3
03780 **
03781 ** The top of the stack is an index entry that omits the ROWID.  Compare
03782 ** the top of stack against the index that P1 is currently pointing to.
03783 ** Ignore the ROWID on the P1 index.
03784 **
03785 ** If the P1 index entry is less than  the top of the stack
03786 ** then jump to P2.  Otherwise fall through to the next instruction.
03787 ** In either case, the stack is popped once.
03788 **
03789 ** If P3 is the "+" string (or any other non-NULL string) then the
03790 ** index taken from the top of the stack is temporarily increased by
03791 ** an epsilon prior to the comparison.  This makes the opcode work
03792 ** like IdxLE.
03793 */
03794 case OP_IdxLT:          /* no-push */
03795 case OP_IdxGT:          /* no-push */
03796 case OP_IdxGE: {        /* no-push */
03797   int i= pOp->p1;
03798   Cursor *pC;
03799 
03800   assert( i>=0 && i<p->nCursor );
03801   assert( p->apCsr[i]!=0 );
03802   assert( pTos>=p->aStack );
03803   if( (pC = p->apCsr[i])->pCursor!=0 ){
03804     int res;
03805  
03806     assert( pTos->flags & MEM_Blob );  /* Created using OP_Make*Key */
03807     Stringify(pTos, encoding);
03808     assert( pC->deferredMoveto==0 );
03809     *pC->pIncrKey = pOp->p3!=0;
03810     assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT );
03811     rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, (u8*)pTos->z, &res);
03812     *pC->pIncrKey = 0;
03813     if( rc!=SQLITE_OK ){
03814       break;
03815     }
03816     if( pOp->opcode==OP_IdxLT ){
03817       res = -res;
03818     }else if( pOp->opcode==OP_IdxGE ){
03819       res++;
03820     }
03821     if( res>0 ){
03822       pc = pOp->p2 - 1 ;
03823     }
03824   }
03825   Release(pTos);
03826   pTos--;
03827   break;
03828 }
03829 
03830 /* Opcode: IdxIsNull P1 P2 *
03831 **
03832 ** The top of the stack contains an index entry such as might be generated
03833 ** by the MakeIdxRec opcode.  This routine looks at the first P1 fields of
03834 ** that key.  If any of the first P1 fields are NULL, then a jump is made
03835 ** to address P2.  Otherwise we fall straight through.
03836 **
03837 ** The index entry is always popped from the stack.
03838 */
03839 case OP_IdxIsNull: {        /* no-push */
03840   int i = pOp->p1;
03841   int k, n;
03842   const char *z;
03843   u32 serial_type;
03844 
03845   assert( pTos>=p->aStack );
03846   assert( pTos->flags & MEM_Blob );
03847   z = pTos->z;
03848   n = pTos->n;
03849   k = sqlite3GetVarint32((u8*)z, &serial_type);
03850   for(; k<n && i>0; i--){
03851     k += sqlite3GetVarint32((u8*)&z[k], &serial_type);
03852     if( serial_type==0 ){   /* Serial type 0 is a NULL */
03853       pc = pOp->p2-1;
03854       break;
03855     }
03856   }
03857   Release(pTos);
03858   pTos--;
03859   break;
03860 }
03861 
03862 /* Opcode: Destroy P1 P2 *
03863 **
03864 ** Delete an entire database table or index whose root page in the database
03865 ** file is given by P1.
03866 **
03867 ** The table being destroyed is in the main database file if P2==0.  If
03868 ** P2==1 then the table to be clear is in the auxiliary database file
03869 ** that is used to store tables create using CREATE TEMPORARY TABLE.
03870 **
03871 ** If AUTOVACUUM is enabled then it is possible that another root page
03872 ** might be moved into the newly deleted root page in order to keep all
03873 ** root pages contiguous at the beginning of the database.  The former
03874 ** value of the root page that moved - its value before the move occurred -
03875 ** is pushed onto the stack.  If no page movement was required (because
03876 ** the table being dropped was already the last one in the database) then
03877 ** a zero is pushed onto the stack.  If AUTOVACUUM is disabled
03878 ** then a zero is pushed onto the stack.
03879 **
03880 ** See also: Clear
03881 */
03882 case OP_Destroy: {
03883   int iMoved;
03884   if( db->activeVdbeCnt>1 ){
03885     rc = SQLITE_LOCKED;
03886   }else{
03887     assert( db->activeVdbeCnt==1 );
03888     rc = sqlite3BtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1, &iMoved);
03889     pTos++;
03890     pTos->flags = MEM_Int;
03891     pTos->i = iMoved;
03892   #ifndef SQLITE_OMIT_AUTOVACUUM
03893     if( rc==SQLITE_OK && iMoved!=0 ){
03894       sqlite3RootPageMoved(&db->aDb[pOp->p2], iMoved, pOp->p1);
03895     }
03896   #endif
03897   }
03898   break;
03899 }
03900 
03901 /* Opcode: Clear P1 P2 *
03902 **
03903 ** Delete all contents of the database table or index whose root page
03904 ** in the database file is given by P1.  But, unlike Destroy, do not
03905 ** remove the table or index from the database file.
03906 **
03907 ** The table being clear is in the main database file if P2==0.  If
03908 ** P2==1 then the table to be clear is in the auxiliary database file
03909 ** that is used to store tables create using CREATE TEMPORARY TABLE.
03910 **
03911 ** See also: Destroy
03912 */
03913 case OP_Clear: {        /* no-push */
03914 
03915   /* For consistency with the way other features of SQLite operate
03916   ** with a truncate, we will also skip the update callback.
03917   */
03918 #if 0
03919   Btree *pBt = db->aDb[pOp->p2].pBt;
03920   if( db->xUpdateCallback && pOp->p3 ){
03921     const char *zDb = db->aDb[pOp->p2].zName;
03922     const char *zTbl = pOp->p3;
03923     BtCursor *pCur = 0;
03924     int fin = 0;
03925 
03926     rc = sqlite3BtreeCursor(pBt, pOp->p1, 0, 0, 0, &pCur);
03927     if( rc!=SQLITE_OK ){
03928       goto abort_due_to_error;
03929     }
03930     for(
03931       rc=sqlite3BtreeFirst(pCur, &fin); 
03932       rc==SQLITE_OK && !fin; 
03933       rc=sqlite3BtreeNext(pCur, &fin)
03934     ){
03935       i64 iKey;
03936       rc = sqlite3BtreeKeySize(pCur, &iKey);
03937       if( rc ){
03938         break;
03939       }
03940       iKey = keyToInt(iKey);
03941       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
03942     }
03943     sqlite3BtreeCloseCursor(pCur);
03944     if( rc!=SQLITE_OK ){
03945       goto abort_due_to_error;
03946     }
03947   }
03948 #endif
03949   rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
03950   break;
03951 }
03952 
03953 /* Opcode: CreateTable P1 * *
03954 **
03955 ** Allocate a new table in the main database file if P2==0 or in the
03956 ** auxiliary database file if P2==1.  Push the page number
03957 ** for the root page of the new table onto the stack.
03958 **
03959 ** The difference between a table and an index is this:  A table must
03960 ** have a 4-byte integer key and can have arbitrary data.  An index
03961 ** has an arbitrary key but no data.
03962 **
03963 ** See also: CreateIndex
03964 */
03965 /* Opcode: CreateIndex P1 * *
03966 **
03967 ** Allocate a new index in the main database file if P2==0 or in the
03968 ** auxiliary database file if P2==1.  Push the page number of the
03969 ** root page of the new index onto the stack.
03970 **
03971 ** See documentation on OP_CreateTable for additional information.
03972 */
03973 case OP_CreateIndex:
03974 case OP_CreateTable: {
03975   int pgno;
03976   int flags;
03977   Db *pDb;
03978   assert( pOp->p1>=0 && pOp->p1<db->nDb );
03979   pDb = &db->aDb[pOp->p1];
03980   assert( pDb->pBt!=0 );
03981   if( pOp->opcode==OP_CreateTable ){
03982     /* flags = BTREE_INTKEY; */
03983     flags = BTREE_LEAFDATA|BTREE_INTKEY;
03984   }else{
03985     flags = BTREE_ZERODATA;
03986   }
03987   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
03988   pTos++;
03989   if( rc==SQLITE_OK ){
03990     pTos->i = pgno;
03991     pTos->flags = MEM_Int;
03992   }else{
03993     pTos->flags = MEM_Null;
03994   }
03995   break;
03996 }
03997 
03998 /* Opcode: ParseSchema P1 * P3
03999 **
04000 ** Read and parse all entries from the SQLITE_MASTER table of database P1
04001 ** that match the WHERE clause P3.
04002 **
04003 ** This opcode invokes the parser to create a new virtual machine,
04004 ** then runs the new virtual machine.  It is thus a reentrant opcode.
04005 */
04006 case OP_ParseSchema: {        /* no-push */
04007   char *zSql;
04008   int iDb = pOp->p1;
04009   const char *zMaster;
04010   InitData initData;
04011 
04012   assert( iDb>=0 && iDb<db->nDb );
04013   if( !DbHasProperty(db, iDb, DB_SchemaLoaded) ) break;
04014   zMaster = SCHEMA_TABLE(iDb);
04015   initData.db = db;
04016   initData.pzErrMsg = &p->zErrMsg;
04017   zSql = sqlite3MPrintf(
04018      "SELECT name, rootpage, sql, %d FROM '%q'.%s WHERE %s",
04019      pOp->p1, db->aDb[iDb].zName, zMaster, pOp->p3);
04020   if( zSql==0 ) goto no_mem;
04021   sqlite3SafetyOff(db);
04022   assert( db->init.busy==0 );
04023   db->init.busy = 1;
04024   assert( !sqlite3MallocFailed() );
04025   rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
04026   sqliteFree(zSql);
04027   db->init.busy = 0;
04028   sqlite3SafetyOn(db);
04029   if( rc==SQLITE_NOMEM ){
04030     sqlite3FailedMalloc();
04031     goto no_mem;
04032   }
04033   break;  
04034 }
04035 
04036 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
04037 /* Opcode: LoadAnalysis P1 * *
04038 **
04039 ** Read the sqlite_stat1 table for database P1 and load the content
04040 ** of that table into the internal index hash table.  This will cause
04041 ** the analysis to be used when preparing all subsequent queries.
04042 */
04043 case OP_LoadAnalysis: {        /* no-push */
04044   int iDb = pOp->p1;
04045   assert( iDb>=0 && iDb<db->nDb );
04046   sqlite3AnalysisLoad(db, iDb);
04047   break;  
04048 }
04049 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)  */
04050 
04051 /* Opcode: DropTable P1 * P3
04052 **
04053 ** Remove the internal (in-memory) data structures that describe
04054 ** the table named P3 in database P1.  This is called after a table
04055 ** is dropped in order to keep the internal representation of the
04056 ** schema consistent with what is on disk.
04057 */
04058 case OP_DropTable: {        /* no-push */
04059   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p3);
04060   break;
04061 }
04062 
04063 /* Opcode: DropIndex P1 * P3
04064 **
04065 ** Remove the internal (in-memory) data structures that describe
04066 ** the index named P3 in database P1.  This is called after an index
04067 ** is dropped in order to keep the internal representation of the
04068 ** schema consistent with what is on disk.
04069 */
04070 case OP_DropIndex: {        /* no-push */
04071   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p3);
04072   break;
04073 }
04074 
04075 /* Opcode: DropTrigger P1 * P3
04076 **
04077 ** Remove the internal (in-memory) data structures that describe
04078 ** the trigger named P3 in database P1.  This is called after a trigger
04079 ** is dropped in order to keep the internal representation of the
04080 ** schema consistent with what is on disk.
04081 */
04082 case OP_DropTrigger: {        /* no-push */
04083   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p3);
04084   break;
04085 }
04086 
04087 
04088 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
04089 /* Opcode: IntegrityCk * P2 *
04090 **
04091 ** Do an analysis of the currently open database.  Push onto the
04092 ** stack the text of an error message describing any problems.
04093 ** If there are no errors, push a "ok" onto the stack.
04094 **
04095 ** The root page numbers of all tables in the database are integer
04096 ** values on the stack.  This opcode pulls as many integers as it
04097 ** can off of the stack and uses those numbers as the root pages.
04098 **
04099 ** If P2 is not zero, the check is done on the auxiliary database
04100 ** file, not the main database file.
04101 **
04102 ** This opcode is used for testing purposes only.
04103 */
04104 case OP_IntegrityCk: {
04105   int nRoot;
04106   int *aRoot;
04107   int j;
04108   char *z;
04109 
04110   for(nRoot=0; &pTos[-nRoot]>=p->aStack; nRoot++){
04111     if( (pTos[-nRoot].flags & MEM_Int)==0 ) break;
04112   }
04113   assert( nRoot>0 );
04114   aRoot = sqliteMallocRaw( sizeof(int*)*(nRoot+1) );
04115   if( aRoot==0 ) goto no_mem;
04116   for(j=0; j<nRoot; j++){
04117     Mem *pMem = &pTos[-j];
04118     aRoot[j] = pMem->i;
04119   }
04120   aRoot[j] = 0;
04121   popStack(&pTos, nRoot);
04122   pTos++;
04123   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot);
04124   if( z==0 || z[0]==0 ){
04125     if( z ) sqliteFree(z);
04126     pTos->z = "ok";
04127     pTos->n = 2;
04128     pTos->flags = MEM_Str | MEM_Static | MEM_Term;
04129   }else{
04130     pTos->z = z;
04131     pTos->n = strlen(z);
04132     pTos->flags = MEM_Str | MEM_Dyn | MEM_Term;
04133     pTos->xDel = 0;
04134   }
04135   pTos->enc = SQLITE_UTF8;
04136   sqlite3VdbeChangeEncoding(pTos, encoding);
04137   sqliteFree(aRoot);
04138   break;
04139 }
04140 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
04141 
04142 /* Opcode: FifoWrite * * *
04143 **
04144 ** Write the integer on the top of the stack
04145 ** into the Fifo.
04146 */
04147 case OP_FifoWrite: {        /* no-push */
04148   assert( pTos>=p->aStack );
04149   sqlite3VdbeMemIntegerify(pTos);
04150   sqlite3VdbeFifoPush(&p->sFifo, pTos->i);
04151   assert( (pTos->flags & MEM_Dyn)==0 );
04152   pTos--;
04153   break;
04154 }
04155 
04156 /* Opcode: FifoRead * P2 *
04157 **
04158 ** Attempt to read a single integer from the Fifo
04159 ** and push it onto the stack.  If the Fifo is empty
04160 ** push nothing but instead jump to P2.
04161 */
04162 case OP_FifoRead: {
04163   i64 v;
04164   CHECK_FOR_INTERRUPT;
04165   if( sqlite3VdbeFifoPop(&p->sFifo, &v)==SQLITE_DONE ){
04166     pc = pOp->p2 - 1;
04167   }else{
04168     pTos++;
04169     pTos->i = v;
04170     pTos->flags = MEM_Int;
04171   }
04172   break;
04173 }
04174 
04175 #ifndef SQLITE_OMIT_TRIGGER
04176 /* Opcode: ContextPush * * * 
04177 **
04178 ** Save the current Vdbe context such that it can be restored by a ContextPop
04179 ** opcode. The context stores the last insert row id, the last statement change
04180 ** count, and the current statement change count.
04181 */
04182 case OP_ContextPush: {        /* no-push */
04183   int i = p->contextStackTop++;
04184   Context *pContext;
04185 
04186   assert( i>=0 );
04187   /* FIX ME: This should be allocated as part of the vdbe at compile-time */
04188   if( i>=p->contextStackDepth ){
04189     p->contextStackDepth = i+1;
04190     sqliteReallocOrFree((void**)&p->contextStack, sizeof(Context)*(i+1));
04191     if( p->contextStack==0 ) goto no_mem;
04192   }
04193   pContext = &p->contextStack[i];
04194   pContext->lastRowid = db->lastRowid;
04195   pContext->nChange = p->nChange;
04196   pContext->sFifo = p->sFifo;
04197   sqlite3VdbeFifoInit(&p->sFifo);
04198   break;
04199 }
04200 
04201 /* Opcode: ContextPop * * * 
04202 **
04203 ** Restore the Vdbe context to the state it was in when contextPush was last
04204 ** executed. The context stores the last insert row id, the last statement
04205 ** change count, and the current statement change count.
04206 */
04207 case OP_ContextPop: {        /* no-push */
04208   Context *pContext = &p->contextStack[--p->contextStackTop];
04209   assert( p->contextStackTop>=0 );
04210   db->lastRowid = pContext->lastRowid;
04211   p->nChange = pContext->nChange;
04212   sqlite3VdbeFifoClear(&p->sFifo);
04213   p->sFifo = pContext->sFifo;
04214   break;
04215 }
04216 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
04217 
04218 /* Opcode: MemStore P1 P2 *
04219 **
04220 ** Write the top of the stack into memory location P1.
04221 ** P1 should be a small integer since space is allocated
04222 ** for all memory locations between 0 and P1 inclusive.
04223 **
04224 ** After the data is stored in the memory location, the
04225 ** stack is popped once if P2 is 1.  If P2 is zero, then
04226 ** the original data remains on the stack.
04227 */
04228 case OP_MemStore: {        /* no-push */
04229   assert( pTos>=p->aStack );
04230   assert( pOp->p1>=0 && pOp->p1<p->nMem );
04231   rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], pTos);
04232   pTos--;
04233 
04234   /* If P2 is 0 then fall thru to the next opcode, OP_MemLoad, that will
04235   ** restore the top of the stack to its original value.
04236   */
04237   if( pOp->p2 ){
04238     break;
04239   }
04240 }
04241 /* Opcode: MemLoad P1 * *
04242 **
04243 ** Push a copy of the value in memory location P1 onto the stack.
04244 **
04245 ** If the value is a string, then the value pushed is a pointer to
04246 ** the string that is stored in the memory location.  If the memory
04247 ** location is subsequently changed (using OP_MemStore) then the
04248 ** value pushed onto the stack will change too.
04249 */
04250 case OP_MemLoad: {
04251   int i = pOp->p1;
04252   assert( i>=0 && i<p->nMem );
04253   pTos++;
04254   sqlite3VdbeMemShallowCopy(pTos, &p->aMem[i], MEM_Ephem);
04255   break;
04256 }
04257 
04258 #ifndef SQLITE_OMIT_AUTOINCREMENT
04259 /* Opcode: MemMax P1 * *
04260 **
04261 ** Set the value of memory cell P1 to the maximum of its current value
04262 ** and the value on the top of the stack.  The stack is unchanged.
04263 **
04264 ** This instruction throws an error if the memory cell is not initially
04265 ** an integer.
04266 */
04267 case OP_MemMax: {        /* no-push */
04268   int i = pOp->p1;
04269   Mem *pMem;
04270   assert( pTos>=p->aStack );
04271   assert( i>=0 && i<p->nMem );
04272   pMem = &p->aMem[i];
04273   sqlite3VdbeMemIntegerify(pMem);
04274   sqlite3VdbeMemIntegerify(pTos);
04275   if( pMem->i<pTos->i){
04276     pMem->i = pTos->i;
04277   }
04278   break;
04279 }
04280 #endif /* SQLITE_OMIT_AUTOINCREMENT */
04281 
04282 /* Opcode: MemIncr P1 P2 *
04283 **
04284 ** Increment the integer valued memory cell P2 by the value in P1.
04285 **
04286 ** It is illegal to use this instruction on a memory cell that does
04287 ** not contain an integer.  An assertion fault will result if you try.
04288 */
04289 case OP_MemIncr: {        /* no-push */
04290   int i = pOp->p2;
04291   Mem *pMem;
04292   assert( i>=0 && i<p->nMem );
04293   pMem = &p->aMem[i];
04294   assert( pMem->flags==MEM_Int );
04295   pMem->i += pOp->p1;
04296   break;
04297 }
04298 
04299 /* Opcode: IfMemPos P1 P2 *
04300 **
04301 ** If the value of memory cell P1 is 1 or greater, jump to P2.
04302 **
04303 ** It is illegal to use this instruction on a memory cell that does
04304 ** not contain an integer.  An assertion fault will result if you try.
04305 */
04306 case OP_IfMemPos: {        /* no-push */
04307   int i = pOp->p1;
04308   Mem *pMem;
04309   assert( i>=0 && i<p->nMem );
04310   pMem = &p->aMem[i];
04311   assert( pMem->flags==MEM_Int );
04312   if( pMem->i>0 ){
04313      pc = pOp->p2 - 1;
04314   }
04315   break;
04316 }
04317 
04318 /* Opcode: IfMemNeg P1 P2 *
04319 **
04320 ** If the value of memory cell P1 is less than zero, jump to P2. 
04321 **
04322 ** It is illegal to use this instruction on a memory cell that does
04323 ** not contain an integer.  An assertion fault will result if you try.
04324 */
04325 case OP_IfMemNeg: {        /* no-push */
04326   int i = pOp->p1;
04327   Mem *pMem;
04328   assert( i>=0 && i<p->nMem );
04329   pMem = &p->aMem[i];
04330   assert( pMem->flags==MEM_Int );
04331   if( pMem->i<0 ){
04332      pc = pOp->p2 - 1;
04333   }
04334   break;
04335 }
04336 
04337 /* Opcode: IfMemZero P1 P2 *
04338 **
04339 ** If the value of memory cell P1 is exactly 0, jump to P2. 
04340 **
04341 ** It is illegal to use this instruction on a memory cell that does
04342 ** not contain an integer.  An assertion fault will result if you try.
04343 */
04344 case OP_IfMemZero: {        /* no-push */
04345   int i = pOp->p1;
04346   Mem *pMem;
04347   assert( i>=0 && i<p->nMem );
04348   pMem = &p->aMem[i];
04349   assert( pMem->flags==MEM_Int );
04350   if( pMem->i==0 ){
04351      pc = pOp->p2 - 1;
04352   }
04353   break;
04354 }
04355 
04356 /* Opcode: MemNull P1 * *
04357 **
04358 ** Store a NULL in memory cell P1
04359 */
04360 case OP_MemNull: {
04361   assert( pOp->p1>=0 && pOp->p1<p->nMem );
04362   sqlite3VdbeMemSetNull(&p->aMem[pOp->p1]);
04363   break;
04364 }
04365 
04366 /* Opcode: MemInt P1 P2 *
04367 **
04368 ** Store the integer value P1 in memory cell P2.
04369 */
04370 case OP_MemInt: {
04371   assert( pOp->p2>=0 && pOp->p2<p->nMem );
04372   sqlite3VdbeMemSetInt64(&p->aMem[pOp->p2], pOp->p1);
04373   break;
04374 }
04375 
04376 /* Opcode: MemMove P1 P2 *
04377 **
04378 ** Move the content of memory cell P2 over to memory cell P1.
04379 ** Any prior content of P1 is erased.  Memory cell P2 is left
04380 ** containing a NULL.
04381 */
04382 case OP_MemMove: {
04383   assert( pOp->p1>=0 && pOp->p1<p->nMem );
04384   assert( pOp->p2>=0 && pOp->p2<p->nMem );
04385   rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], &p->aMem[pOp->p2]);
04386   break;
04387 }
04388 
04389 /* Opcode: AggStep P1 P2 P3
04390 **
04391 ** Execute the step function for an aggregate.  The
04392 ** function has P2 arguments.  P3 is a pointer to the FuncDef
04393 ** structure that specifies the function.  Use memory location
04394 ** P1 as the accumulator.
04395 **
04396 ** The P2 arguments are popped from the stack.
04397 */
04398 case OP_AggStep: {        /* no-push */
04399   int n = pOp->p2;
04400   int i;
04401   Mem *pMem, *pRec;
04402   sqlite3_context ctx;
04403   sqlite3_value **apVal;
04404 
04405   assert( n>=0 );
04406   pRec = &pTos[1-n];
04407   assert( pRec>=p->aStack );
04408   apVal = p->apArg;
04409   assert( apVal || n==0 );
04410   for(i=0; i<n; i++, pRec++){
04411     apVal[i] = pRec;
04412     storeTypeInfo(pRec, encoding);
04413   }
04414   ctx.pFunc = (FuncDef*)pOp->p3;
04415   assert( pOp->p1>=0 && pOp->p1<p->nMem );
04416   ctx.pMem = pMem = &p->aMem[pOp->p1];
04417   pMem->n++;
04418   ctx.s.flags = MEM_Null;
04419   ctx.s.z = 0;
04420   ctx.s.xDel = 0;
04421   ctx.isError = 0;
04422   ctx.pColl = 0;
04423   if( ctx.pFunc->needCollSeq ){
04424     assert( pOp>p->aOp );
04425     assert( pOp[-1].p3type==P3_COLLSEQ );
04426     assert( pOp[-1].opcode==OP_CollSeq );
04427     ctx.pColl = (CollSeq *)pOp[-1].p3;
04428   }
04429   (ctx.pFunc->xStep)(&ctx, n, apVal);
04430   popStack(&pTos, n);
04431   if( ctx.isError ){
04432     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
04433     rc = SQLITE_ERROR;
04434   }
04435   sqlite3VdbeMemRelease(&ctx.s);
04436   break;
04437 }
04438 
04439 /* Opcode: AggFinal P1 P2 P3
04440 **
04441 ** Execute the finalizer function for an aggregate.  P1 is
04442 ** the memory location that is the accumulator for the aggregate.
04443 **
04444 ** P2 is the number of arguments that the step function takes and
04445 ** P3 is a pointer to the FuncDef for this function.  The P2
04446 ** argument is not used by this opcode.  It is only there to disambiguate
04447 ** functions that can take varying numbers of arguments.  The
04448 ** P3 argument is only needed for the degenerate case where
04449 ** the step function was not previously called.
04450 */
04451 case OP_AggFinal: {        /* no-push */
04452   Mem *pMem;
04453   assert( pOp->p1>=0 && pOp->p1<p->nMem );
04454   pMem = &p->aMem[pOp->p1];
04455   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
04456   rc = sqlite3VdbeMemFinalize(pMem, (FuncDef*)pOp->p3);
04457   if( rc==SQLITE_ERROR ){
04458     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pMem), (char*)0);
04459   }
04460   break;
04461 }
04462 
04463 
04464 /* Opcode: Vacuum * * *
04465 **
04466 ** Vacuum the entire database.  This opcode will cause other virtual
04467 ** machines to be created and run.  It may not be called from within
04468 ** a transaction.
04469 */
04470 case OP_Vacuum: {        /* no-push */
04471   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; 
04472   rc = sqlite3RunVacuum(&p->zErrMsg, db);
04473   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
04474   break;
04475 }
04476 
04477 /* Opcode: Expire P1 * *
04478 **
04479 ** Cause precompiled statements to become expired. An expired statement
04480 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
04481 ** (via sqlite3_step()).
04482 ** 
04483 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
04484 ** then only the currently executing statement is affected. 
04485 */
04486 case OP_Expire: {        /* no-push */
04487   if( !pOp->p1 ){
04488     sqlite3ExpirePreparedStatements(db);
04489   }else{
04490     p->expired = 1;
04491   }
04492   break;
04493 }
04494 
04495 #ifndef SQLITE_OMIT_SHARED_CACHE
04496 /* Opcode: TableLock P1 P2 P3
04497 **
04498 ** Obtain a lock on a particular table. This instruction is only used when
04499 ** the shared-cache feature is enabled. 
04500 **
04501 ** If P1 is not negative, then it is the index of the database
04502 ** in sqlite3.aDb[] and a read-lock is required. If P1 is negative, a 
04503 ** write-lock is required. In this case the index of the database is the 
04504 ** absolute value of P1 minus one (iDb = abs(P1) - 1;) and a write-lock is
04505 ** required. 
04506 **
04507 ** P2 contains the root-page of the table to lock.
04508 **
04509 ** P3 contains a pointer to the name of the table being locked. This is only
04510 ** used to generate an error message if the lock cannot be obtained.
04511 */
04512 case OP_TableLock: {        /* no-push */
04513   int p1 = pOp->p1; 
04514   u8 isWriteLock = (p1<0);
04515   if( isWriteLock ){
04516     p1 = (-1*p1)-1;
04517   }
04518   rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
04519   if( rc==SQLITE_LOCKED ){
04520     const char *z = (const char *)pOp->p3;
04521     sqlite3SetString(&p->zErrMsg, "database table is locked: ", z, (char*)0);
04522   }
04523   break;
04524 }
04525 #endif /* SHARED_OMIT_SHARED_CACHE */
04526 
04527 /* An other opcode is illegal...
04528 */
04529 default: {
04530   assert( 0 );
04531   break;
04532 }
04533 
04534 /*****************************************************************************
04535 ** The cases of the switch statement above this line should all be indented
04536 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
04537 ** readability.  From this point on down, the normal indentation rules are
04538 ** restored.
04539 *****************************************************************************/
04540     }
04541 
04542     /* Make sure the stack limit was not exceeded */
04543     assert( pTos<=pStackLimit );
04544 
04545 #ifdef VDBE_PROFILE
04546     {
04547       long long elapse = hwtime() - start;
04548       pOp->cycles += elapse;
04549       pOp->cnt++;
04550 #if 0
04551         fprintf(stdout, "%10lld ", elapse);
04552         sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
04553 #endif
04554     }
04555 #endif
04556 
04557     /* The following code adds nothing to the actual functionality
04558     ** of the program.  It is only here for testing and debugging.
04559     ** On the other hand, it does burn CPU cycles every time through
04560     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
04561     */
04562 #ifndef NDEBUG
04563     /* Sanity checking on the top element of the stack */
04564     if( pTos>=p->aStack ){
04565       sqlite3VdbeMemSanity(pTos);
04566     }
04567     assert( pc>=-1 && pc<p->nOp );
04568 #ifdef SQLITE_DEBUG
04569     /* Code for tracing the vdbe stack. */
04570     if( p->trace && pTos>=p->aStack ){
04571       int i;
04572       fprintf(p->trace, "Stack:");
04573       for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
04574         if( pTos[i].flags & MEM_Null ){
04575           fprintf(p->trace, " NULL");
04576         }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
04577           fprintf(p->trace, " si:%lld", pTos[i].i);
04578         }else if( pTos[i].flags & MEM_Int ){
04579           fprintf(p->trace, " i:%lld", pTos[i].i);
04580         }else if( pTos[i].flags & MEM_Real ){
04581           fprintf(p->trace, " r:%g", pTos[i].r);
04582         }else{
04583           char zBuf[100];
04584           sqlite3VdbeMemPrettyPrint(&pTos[i], zBuf);
04585           fprintf(p->trace, " ");
04586           fprintf(p->trace, "%s", zBuf);
04587         }
04588       }
04589       if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
04590       fprintf(p->trace,"\n");
04591     }
04592 #endif  /* SQLITE_DEBUG */
04593 #endif  /* NDEBUG */
04594   }  /* The end of the for(;;) loop the loops through opcodes */
04595 
04596   /* If we reach this point, it means that execution is finished.
04597   */
04598 vdbe_halt:
04599   if( rc ){
04600     p->rc = rc;
04601     rc = SQLITE_ERROR;
04602   }else{
04603     rc = SQLITE_DONE;
04604   }
04605   sqlite3VdbeHalt(p);
04606   p->pTos = pTos;
04607   return rc;
04608 
04609   /* Jump to here if a malloc() fails.  It's hard to get a malloc()
04610   ** to fail on a modern VM computer, so this code is untested.
04611   */
04612 no_mem:
04613   sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0);
04614   rc = SQLITE_NOMEM;
04615   goto vdbe_halt;
04616 
04617   /* Jump to here for an SQLITE_MISUSE error.
04618   */
04619 abort_due_to_misuse:
04620   rc = SQLITE_MISUSE;
04621   /* Fall thru into abort_due_to_error */
04622 
04623   /* Jump to here for any other kind of fatal error.  The "rc" variable
04624   ** should hold the error number.
04625   */
04626 abort_due_to_error:
04627   if( p->zErrMsg==0 ){
04628     if( sqlite3MallocFailed() ) rc = SQLITE_NOMEM;
04629     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
04630   }
04631   goto vdbe_halt;
04632 
04633   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
04634   ** flag.
04635   */
04636 abort_due_to_interrupt:
04637   assert( db->flags & SQLITE_Interrupt );
04638   db->flags &= ~SQLITE_Interrupt;
04639   if( db->magic!=SQLITE_MAGIC_BUSY ){
04640     rc = SQLITE_MISUSE;
04641   }else{
04642     rc = SQLITE_INTERRUPT;
04643   }
04644   p->rc = rc;
04645   sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
04646   goto vdbe_halt;
04647 }