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

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:57 2011 by Doxygen 1.6.1