000001  /*
000002  ** 2001 September 15
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  ** The code in this file implements the function that runs the
000013  ** bytecode of a prepared statement.
000014  **
000015  ** Various scripts scan this source file in order to generate HTML
000016  ** documentation, headers files, or other derived files.  The formatting
000017  ** of the code in this file is, therefore, important.  See other comments
000018  ** in this file for details.  If in doubt, do not deviate from existing
000019  ** commenting and indentation practices when changing or adding code.
000020  */
000021  #include "sqliteInt.h"
000022  #include "vdbeInt.h"
000023  
000024  /*
000025  ** Invoke this macro on memory cells just prior to changing the
000026  ** value of the cell.  This macro verifies that shallow copies are
000027  ** not misused.  A shallow copy of a string or blob just copies a
000028  ** pointer to the string or blob, not the content.  If the original
000029  ** is changed while the copy is still in use, the string or blob might
000030  ** be changed out from under the copy.  This macro verifies that nothing
000031  ** like that ever happens.
000032  */
000033  #ifdef SQLITE_DEBUG
000034  # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
000035  #else
000036  # define memAboutToChange(P,M)
000037  #endif
000038  
000039  /*
000040  ** The following global variable is incremented every time a cursor
000041  ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
000042  ** procedures use this information to make sure that indices are
000043  ** working correctly.  This variable has no function other than to
000044  ** help verify the correct operation of the library.
000045  */
000046  #ifdef SQLITE_TEST
000047  int sqlite3_search_count = 0;
000048  #endif
000049  
000050  /*
000051  ** When this global variable is positive, it gets decremented once before
000052  ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
000053  ** field of the sqlite3 structure is set in order to simulate an interrupt.
000054  **
000055  ** This facility is used for testing purposes only.  It does not function
000056  ** in an ordinary build.
000057  */
000058  #ifdef SQLITE_TEST
000059  int sqlite3_interrupt_count = 0;
000060  #endif
000061  
000062  /*
000063  ** The next global variable is incremented each type the OP_Sort opcode
000064  ** is executed.  The test procedures use this information to make sure that
000065  ** sorting is occurring or not occurring at appropriate times.   This variable
000066  ** has no function other than to help verify the correct operation of the
000067  ** library.
000068  */
000069  #ifdef SQLITE_TEST
000070  int sqlite3_sort_count = 0;
000071  #endif
000072  
000073  /*
000074  ** The next global variable records the size of the largest MEM_Blob
000075  ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
000076  ** use this information to make sure that the zero-blob functionality
000077  ** is working correctly.   This variable has no function other than to
000078  ** help verify the correct operation of the library.
000079  */
000080  #ifdef SQLITE_TEST
000081  int sqlite3_max_blobsize = 0;
000082  static void updateMaxBlobsize(Mem *p){
000083    if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
000084      sqlite3_max_blobsize = p->n;
000085    }
000086  }
000087  #endif
000088  
000089  /*
000090  ** This macro evaluates to true if either the update hook or the preupdate
000091  ** hook are enabled for database connect DB.
000092  */
000093  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
000094  # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
000095  #else
000096  # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
000097  #endif
000098  
000099  /*
000100  ** The next global variable is incremented each time the OP_Found opcode
000101  ** is executed. This is used to test whether or not the foreign key
000102  ** operation implemented using OP_FkIsZero is working. This variable
000103  ** has no function other than to help verify the correct operation of the
000104  ** library.
000105  */
000106  #ifdef SQLITE_TEST
000107  int sqlite3_found_count = 0;
000108  #endif
000109  
000110  /*
000111  ** Test a register to see if it exceeds the current maximum blob size.
000112  ** If it does, record the new maximum blob size.
000113  */
000114  #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
000115  # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
000116  #else
000117  # define UPDATE_MAX_BLOBSIZE(P)
000118  #endif
000119  
000120  /*
000121  ** Invoke the VDBE coverage callback, if that callback is defined.  This
000122  ** feature is used for test suite validation only and does not appear an
000123  ** production builds.
000124  **
000125  ** M is an integer, 2 or 3, that indices how many different ways the
000126  ** branch can go.  It is usually 2.  "I" is the direction the branch
000127  ** goes.  0 means falls through.  1 means branch is taken.  2 means the
000128  ** second alternative branch is taken.
000129  **
000130  ** iSrcLine is the source code line (from the __LINE__ macro) that
000131  ** generated the VDBE instruction.  This instrumentation assumes that all
000132  ** source code is in a single file (the amalgamation).  Special values 1
000133  ** and 2 for the iSrcLine parameter mean that this particular branch is
000134  ** always taken or never taken, respectively.
000135  */
000136  #if !defined(SQLITE_VDBE_COVERAGE)
000137  # define VdbeBranchTaken(I,M)
000138  #else
000139  # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
000140    static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
000141      if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
000142        M = iSrcLine;
000143        /* Assert the truth of VdbeCoverageAlwaysTaken() and 
000144        ** VdbeCoverageNeverTaken() */
000145        assert( (M & I)==I );
000146      }else{
000147        if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
000148        sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
000149                                        iSrcLine,I,M);
000150      }
000151    }
000152  #endif
000153  
000154  /*
000155  ** Convert the given register into a string if it isn't one
000156  ** already. Return non-zero if a malloc() fails.
000157  */
000158  #define Stringify(P, enc) \
000159     if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
000160       { goto no_mem; }
000161  
000162  /*
000163  ** An ephemeral string value (signified by the MEM_Ephem flag) contains
000164  ** a pointer to a dynamically allocated string where some other entity
000165  ** is responsible for deallocating that string.  Because the register
000166  ** does not control the string, it might be deleted without the register
000167  ** knowing it.
000168  **
000169  ** This routine converts an ephemeral string into a dynamically allocated
000170  ** string that the register itself controls.  In other words, it
000171  ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
000172  */
000173  #define Deephemeralize(P) \
000174     if( ((P)->flags&MEM_Ephem)!=0 \
000175         && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
000176  
000177  /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
000178  #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
000179  
000180  /*
000181  ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
000182  ** if we run out of memory.
000183  */
000184  static VdbeCursor *allocateCursor(
000185    Vdbe *p,              /* The virtual machine */
000186    int iCur,             /* Index of the new VdbeCursor */
000187    int nField,           /* Number of fields in the table or index */
000188    int iDb,              /* Database the cursor belongs to, or -1 */
000189    u8 eCurType           /* Type of the new cursor */
000190  ){
000191    /* Find the memory cell that will be used to store the blob of memory
000192    ** required for this VdbeCursor structure. It is convenient to use a 
000193    ** vdbe memory cell to manage the memory allocation required for a
000194    ** VdbeCursor structure for the following reasons:
000195    **
000196    **   * Sometimes cursor numbers are used for a couple of different
000197    **     purposes in a vdbe program. The different uses might require
000198    **     different sized allocations. Memory cells provide growable
000199    **     allocations.
000200    **
000201    **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
000202    **     be freed lazily via the sqlite3_release_memory() API. This
000203    **     minimizes the number of malloc calls made by the system.
000204    **
000205    ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
000206    ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].
000207    ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
000208    */
000209    Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
000210  
000211    int nByte;
000212    VdbeCursor *pCx = 0;
000213    nByte = 
000214        ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + 
000215        (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
000216  
000217    assert( iCur>=0 && iCur<p->nCursor );
000218    if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
000219      sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
000220      p->apCsr[iCur] = 0;
000221    }
000222    if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
000223      p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
000224      memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
000225      pCx->eCurType = eCurType;
000226      pCx->iDb = iDb;
000227      pCx->nField = nField;
000228      pCx->aOffset = &pCx->aType[nField];
000229      if( eCurType==CURTYPE_BTREE ){
000230        pCx->uc.pCursor = (BtCursor*)
000231            &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
000232        sqlite3BtreeCursorZero(pCx->uc.pCursor);
000233      }
000234    }
000235    return pCx;
000236  }
000237  
000238  /*
000239  ** Try to convert a value into a numeric representation if we can
000240  ** do so without loss of information.  In other words, if the string
000241  ** looks like a number, convert it into a number.  If it does not
000242  ** look like a number, leave it alone.
000243  **
000244  ** If the bTryForInt flag is true, then extra effort is made to give
000245  ** an integer representation.  Strings that look like floating point
000246  ** values but which have no fractional component (example: '48.00')
000247  ** will have a MEM_Int representation when bTryForInt is true.
000248  **
000249  ** If bTryForInt is false, then if the input string contains a decimal
000250  ** point or exponential notation, the result is only MEM_Real, even
000251  ** if there is an exact integer representation of the quantity.
000252  */
000253  static void applyNumericAffinity(Mem *pRec, int bTryForInt){
000254    double rValue;
000255    i64 iValue;
000256    u8 enc = pRec->enc;
000257    assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
000258    if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
000259    if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
000260      pRec->u.i = iValue;
000261      pRec->flags |= MEM_Int;
000262    }else{
000263      pRec->u.r = rValue;
000264      pRec->flags |= MEM_Real;
000265      if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
000266    }
000267    /* TEXT->NUMERIC is many->one.  Hence, it is important to invalidate the
000268    ** string representation after computing a numeric equivalent, because the
000269    ** string representation might not be the canonical representation for the
000270    ** numeric value.  Ticket [343634942dd54ab57b7024] 2018-01-31. */
000271    pRec->flags &= ~MEM_Str;
000272  }
000273  
000274  /*
000275  ** Processing is determine by the affinity parameter:
000276  **
000277  ** SQLITE_AFF_INTEGER:
000278  ** SQLITE_AFF_REAL:
000279  ** SQLITE_AFF_NUMERIC:
000280  **    Try to convert pRec to an integer representation or a 
000281  **    floating-point representation if an integer representation
000282  **    is not possible.  Note that the integer representation is
000283  **    always preferred, even if the affinity is REAL, because
000284  **    an integer representation is more space efficient on disk.
000285  **
000286  ** SQLITE_AFF_TEXT:
000287  **    Convert pRec to a text representation.
000288  **
000289  ** SQLITE_AFF_BLOB:
000290  **    No-op.  pRec is unchanged.
000291  */
000292  static void applyAffinity(
000293    Mem *pRec,          /* The value to apply affinity to */
000294    char affinity,      /* The affinity to be applied */
000295    u8 enc              /* Use this text encoding */
000296  ){
000297    if( affinity>=SQLITE_AFF_NUMERIC ){
000298      assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
000299               || affinity==SQLITE_AFF_NUMERIC );
000300      if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
000301        if( (pRec->flags & MEM_Real)==0 ){
000302          if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
000303        }else{
000304          sqlite3VdbeIntegerAffinity(pRec);
000305        }
000306      }
000307    }else if( affinity==SQLITE_AFF_TEXT ){
000308      /* Only attempt the conversion to TEXT if there is an integer or real
000309      ** representation (blob and NULL do not get converted) but no string
000310      ** representation.  It would be harmless to repeat the conversion if 
000311      ** there is already a string rep, but it is pointless to waste those
000312      ** CPU cycles. */
000313      if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
000314        if( (pRec->flags&(MEM_Real|MEM_Int)) ){
000315          sqlite3VdbeMemStringify(pRec, enc, 1);
000316        }
000317      }
000318      pRec->flags &= ~(MEM_Real|MEM_Int);
000319    }
000320  }
000321  
000322  /*
000323  ** Try to convert the type of a function argument or a result column
000324  ** into a numeric representation.  Use either INTEGER or REAL whichever
000325  ** is appropriate.  But only do the conversion if it is possible without
000326  ** loss of information and return the revised type of the argument.
000327  */
000328  int sqlite3_value_numeric_type(sqlite3_value *pVal){
000329    int eType = sqlite3_value_type(pVal);
000330    if( eType==SQLITE_TEXT ){
000331      Mem *pMem = (Mem*)pVal;
000332      applyNumericAffinity(pMem, 0);
000333      eType = sqlite3_value_type(pVal);
000334    }
000335    return eType;
000336  }
000337  
000338  /*
000339  ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
000340  ** not the internal Mem* type.
000341  */
000342  void sqlite3ValueApplyAffinity(
000343    sqlite3_value *pVal, 
000344    u8 affinity, 
000345    u8 enc
000346  ){
000347    applyAffinity((Mem *)pVal, affinity, enc);
000348  }
000349  
000350  /*
000351  ** pMem currently only holds a string type (or maybe a BLOB that we can
000352  ** interpret as a string if we want to).  Compute its corresponding
000353  ** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
000354  ** accordingly.
000355  */
000356  static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
000357    assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
000358    assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
000359    if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
000360      return 0;
000361    }
000362    if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
000363      return MEM_Int;
000364    }
000365    return MEM_Real;
000366  }
000367  
000368  /*
000369  ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
000370  ** none.  
000371  **
000372  ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
000373  ** But it does set pMem->u.r and pMem->u.i appropriately.
000374  */
000375  static u16 numericType(Mem *pMem){
000376    if( pMem->flags & (MEM_Int|MEM_Real) ){
000377      return pMem->flags & (MEM_Int|MEM_Real);
000378    }
000379    if( pMem->flags & (MEM_Str|MEM_Blob) ){
000380      return computeNumericType(pMem);
000381    }
000382    return 0;
000383  }
000384  
000385  #ifdef SQLITE_DEBUG
000386  /*
000387  ** Write a nice string representation of the contents of cell pMem
000388  ** into buffer zBuf, length nBuf.
000389  */
000390  void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
000391    char *zCsr = zBuf;
000392    int f = pMem->flags;
000393  
000394    static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
000395  
000396    if( f&MEM_Blob ){
000397      int i;
000398      char c;
000399      if( f & MEM_Dyn ){
000400        c = 'z';
000401        assert( (f & (MEM_Static|MEM_Ephem))==0 );
000402      }else if( f & MEM_Static ){
000403        c = 't';
000404        assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
000405      }else if( f & MEM_Ephem ){
000406        c = 'e';
000407        assert( (f & (MEM_Static|MEM_Dyn))==0 );
000408      }else{
000409        c = 's';
000410      }
000411      *(zCsr++) = c;
000412      sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
000413      zCsr += sqlite3Strlen30(zCsr);
000414      for(i=0; i<16 && i<pMem->n; i++){
000415        sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
000416        zCsr += sqlite3Strlen30(zCsr);
000417      }
000418      for(i=0; i<16 && i<pMem->n; i++){
000419        char z = pMem->z[i];
000420        if( z<32 || z>126 ) *zCsr++ = '.';
000421        else *zCsr++ = z;
000422      }
000423      *(zCsr++) = ']';
000424      if( f & MEM_Zero ){
000425        sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
000426        zCsr += sqlite3Strlen30(zCsr);
000427      }
000428      *zCsr = '\0';
000429    }else if( f & MEM_Str ){
000430      int j, k;
000431      zBuf[0] = ' ';
000432      if( f & MEM_Dyn ){
000433        zBuf[1] = 'z';
000434        assert( (f & (MEM_Static|MEM_Ephem))==0 );
000435      }else if( f & MEM_Static ){
000436        zBuf[1] = 't';
000437        assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
000438      }else if( f & MEM_Ephem ){
000439        zBuf[1] = 'e';
000440        assert( (f & (MEM_Static|MEM_Dyn))==0 );
000441      }else{
000442        zBuf[1] = 's';
000443      }
000444      k = 2;
000445      sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
000446      k += sqlite3Strlen30(&zBuf[k]);
000447      zBuf[k++] = '[';
000448      for(j=0; j<15 && j<pMem->n; j++){
000449        u8 c = pMem->z[j];
000450        if( c>=0x20 && c<0x7f ){
000451          zBuf[k++] = c;
000452        }else{
000453          zBuf[k++] = '.';
000454        }
000455      }
000456      zBuf[k++] = ']';
000457      sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
000458      k += sqlite3Strlen30(&zBuf[k]);
000459      zBuf[k++] = 0;
000460    }
000461  }
000462  #endif
000463  
000464  #ifdef SQLITE_DEBUG
000465  /*
000466  ** Print the value of a register for tracing purposes:
000467  */
000468  static void memTracePrint(Mem *p){
000469    if( p->flags & MEM_Undefined ){
000470      printf(" undefined");
000471    }else if( p->flags & MEM_Null ){
000472      printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
000473    }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
000474      printf(" si:%lld", p->u.i);
000475    }else if( p->flags & MEM_Int ){
000476      printf(" i:%lld", p->u.i);
000477  #ifndef SQLITE_OMIT_FLOATING_POINT
000478    }else if( p->flags & MEM_Real ){
000479      printf(" r:%g", p->u.r);
000480  #endif
000481    }else if( p->flags & MEM_RowSet ){
000482      printf(" (rowset)");
000483    }else{
000484      char zBuf[200];
000485      sqlite3VdbeMemPrettyPrint(p, zBuf);
000486      printf(" %s", zBuf);
000487    }
000488    if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
000489  }
000490  static void registerTrace(int iReg, Mem *p){
000491    printf("REG[%d] = ", iReg);
000492    memTracePrint(p);
000493    printf("\n");
000494    sqlite3VdbeCheckMemInvariants(p);
000495  }
000496  #endif
000497  
000498  #ifdef SQLITE_DEBUG
000499  #  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
000500  #else
000501  #  define REGISTER_TRACE(R,M)
000502  #endif
000503  
000504  
000505  #ifdef VDBE_PROFILE
000506  
000507  /* 
000508  ** hwtime.h contains inline assembler code for implementing 
000509  ** high-performance timing routines.
000510  */
000511  #include "hwtime.h"
000512  
000513  #endif
000514  
000515  #ifndef NDEBUG
000516  /*
000517  ** This function is only called from within an assert() expression. It
000518  ** checks that the sqlite3.nTransaction variable is correctly set to
000519  ** the number of non-transaction savepoints currently in the 
000520  ** linked list starting at sqlite3.pSavepoint.
000521  ** 
000522  ** Usage:
000523  **
000524  **     assert( checkSavepointCount(db) );
000525  */
000526  static int checkSavepointCount(sqlite3 *db){
000527    int n = 0;
000528    Savepoint *p;
000529    for(p=db->pSavepoint; p; p=p->pNext) n++;
000530    assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
000531    return 1;
000532  }
000533  #endif
000534  
000535  /*
000536  ** Return the register of pOp->p2 after first preparing it to be
000537  ** overwritten with an integer value.
000538  */
000539  static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
000540    sqlite3VdbeMemSetNull(pOut);
000541    pOut->flags = MEM_Int;
000542    return pOut;
000543  }
000544  static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
000545    Mem *pOut;
000546    assert( pOp->p2>0 );
000547    assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
000548    pOut = &p->aMem[pOp->p2];
000549    memAboutToChange(p, pOut);
000550    if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
000551      return out2PrereleaseWithClear(pOut);
000552    }else{
000553      pOut->flags = MEM_Int;
000554      return pOut;
000555    }
000556  }
000557  
000558  
000559  /*
000560  ** Execute as much of a VDBE program as we can.
000561  ** This is the core of sqlite3_step().  
000562  */
000563  int sqlite3VdbeExec(
000564    Vdbe *p                    /* The VDBE */
000565  ){
000566    Op *aOp = p->aOp;          /* Copy of p->aOp */
000567    Op *pOp = aOp;             /* Current operation */
000568  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
000569    Op *pOrigOp;               /* Value of pOp at the top of the loop */
000570  #endif
000571  #ifdef SQLITE_DEBUG
000572    int nExtraDelete = 0;      /* Verifies FORDELETE and AUXDELETE flags */
000573  #endif
000574    int rc = SQLITE_OK;        /* Value to return */
000575    sqlite3 *db = p->db;       /* The database */
000576    u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
000577    u8 encoding = ENC(db);     /* The database encoding */
000578    int iCompare = 0;          /* Result of last comparison */
000579    unsigned nVmStep = 0;      /* Number of virtual machine steps */
000580  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
000581    unsigned nProgressLimit;   /* Invoke xProgress() when nVmStep reaches this */
000582  #endif
000583    Mem *aMem = p->aMem;       /* Copy of p->aMem */
000584    Mem *pIn1 = 0;             /* 1st input operand */
000585    Mem *pIn2 = 0;             /* 2nd input operand */
000586    Mem *pIn3 = 0;             /* 3rd input operand */
000587    Mem *pOut = 0;             /* Output operand */
000588  #ifdef VDBE_PROFILE
000589    u64 start;                 /* CPU clock count at start of opcode */
000590  #endif
000591    /*** INSERT STACK UNION HERE ***/
000592  
000593    assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
000594    sqlite3VdbeEnter(p);
000595    if( p->rc==SQLITE_NOMEM ){
000596      /* This happens if a malloc() inside a call to sqlite3_column_text() or
000597      ** sqlite3_column_text16() failed.  */
000598      goto no_mem;
000599    }
000600    assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
000601    assert( p->bIsReader || p->readOnly!=0 );
000602    p->iCurrentTime = 0;
000603    assert( p->explain==0 );
000604    p->pResultSet = 0;
000605    db->busyHandler.nBusy = 0;
000606    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
000607    sqlite3VdbeIOTraceSql(p);
000608  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
000609    if( db->xProgress ){
000610      u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
000611      assert( 0 < db->nProgressOps );
000612      nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
000613    }else{
000614      nProgressLimit = 0xffffffff;
000615    }
000616  #endif
000617  #ifdef SQLITE_DEBUG
000618    sqlite3BeginBenignMalloc();
000619    if( p->pc==0
000620     && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
000621    ){
000622      int i;
000623      int once = 1;
000624      sqlite3VdbePrintSql(p);
000625      if( p->db->flags & SQLITE_VdbeListing ){
000626        printf("VDBE Program Listing:\n");
000627        for(i=0; i<p->nOp; i++){
000628          sqlite3VdbePrintOp(stdout, i, &aOp[i]);
000629        }
000630      }
000631      if( p->db->flags & SQLITE_VdbeEQP ){
000632        for(i=0; i<p->nOp; i++){
000633          if( aOp[i].opcode==OP_Explain ){
000634            if( once ) printf("VDBE Query Plan:\n");
000635            printf("%s\n", aOp[i].p4.z);
000636            once = 0;
000637          }
000638        }
000639      }
000640      if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
000641    }
000642    sqlite3EndBenignMalloc();
000643  #endif
000644    for(pOp=&aOp[p->pc]; 1; pOp++){
000645      /* Errors are detected by individual opcodes, with an immediate
000646      ** jumps to abort_due_to_error. */
000647      assert( rc==SQLITE_OK );
000648  
000649      assert( pOp>=aOp && pOp<&aOp[p->nOp]);
000650  #ifdef VDBE_PROFILE
000651      start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
000652  #endif
000653      nVmStep++;
000654  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
000655      if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
000656  #endif
000657  
000658      /* Only allow tracing if SQLITE_DEBUG is defined.
000659      */
000660  #ifdef SQLITE_DEBUG
000661      if( db->flags & SQLITE_VdbeTrace ){
000662        sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
000663      }
000664  #endif
000665        
000666  
000667      /* Check to see if we need to simulate an interrupt.  This only happens
000668      ** if we have a special test build.
000669      */
000670  #ifdef SQLITE_TEST
000671      if( sqlite3_interrupt_count>0 ){
000672        sqlite3_interrupt_count--;
000673        if( sqlite3_interrupt_count==0 ){
000674          sqlite3_interrupt(db);
000675        }
000676      }
000677  #endif
000678  
000679      /* Sanity checking on other operands */
000680  #ifdef SQLITE_DEBUG
000681      {
000682        u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
000683        if( (opProperty & OPFLG_IN1)!=0 ){
000684          assert( pOp->p1>0 );
000685          assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
000686          assert( memIsValid(&aMem[pOp->p1]) );
000687          assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
000688          REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
000689        }
000690        if( (opProperty & OPFLG_IN2)!=0 ){
000691          assert( pOp->p2>0 );
000692          assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
000693          assert( memIsValid(&aMem[pOp->p2]) );
000694          assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
000695          REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
000696        }
000697        if( (opProperty & OPFLG_IN3)!=0 ){
000698          assert( pOp->p3>0 );
000699          assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
000700          assert( memIsValid(&aMem[pOp->p3]) );
000701          assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
000702          REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
000703        }
000704        if( (opProperty & OPFLG_OUT2)!=0 ){
000705          assert( pOp->p2>0 );
000706          assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
000707          memAboutToChange(p, &aMem[pOp->p2]);
000708        }
000709        if( (opProperty & OPFLG_OUT3)!=0 ){
000710          assert( pOp->p3>0 );
000711          assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
000712          memAboutToChange(p, &aMem[pOp->p3]);
000713        }
000714      }
000715  #endif
000716  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
000717      pOrigOp = pOp;
000718  #endif
000719    
000720      switch( pOp->opcode ){
000721  
000722  /*****************************************************************************
000723  ** What follows is a massive switch statement where each case implements a
000724  ** separate instruction in the virtual machine.  If we follow the usual
000725  ** indentation conventions, each case should be indented by 6 spaces.  But
000726  ** that is a lot of wasted space on the left margin.  So the code within
000727  ** the switch statement will break with convention and be flush-left. Another
000728  ** big comment (similar to this one) will mark the point in the code where
000729  ** we transition back to normal indentation.
000730  **
000731  ** The formatting of each case is important.  The makefile for SQLite
000732  ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
000733  ** file looking for lines that begin with "case OP_".  The opcodes.h files
000734  ** will be filled with #defines that give unique integer values to each
000735  ** opcode and the opcodes.c file is filled with an array of strings where
000736  ** each string is the symbolic name for the corresponding opcode.  If the
000737  ** case statement is followed by a comment of the form "/# same as ... #/"
000738  ** that comment is used to determine the particular value of the opcode.
000739  **
000740  ** Other keywords in the comment that follows each case are used to
000741  ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
000742  ** Keywords include: in1, in2, in3, out2, out3.  See
000743  ** the mkopcodeh.awk script for additional information.
000744  **
000745  ** Documentation about VDBE opcodes is generated by scanning this file
000746  ** for lines of that contain "Opcode:".  That line and all subsequent
000747  ** comment lines are used in the generation of the opcode.html documentation
000748  ** file.
000749  **
000750  ** SUMMARY:
000751  **
000752  **     Formatting is important to scripts that scan this file.
000753  **     Do not deviate from the formatting style currently in use.
000754  **
000755  *****************************************************************************/
000756  
000757  /* Opcode:  Goto * P2 * * *
000758  **
000759  ** An unconditional jump to address P2.
000760  ** The next instruction executed will be 
000761  ** the one at index P2 from the beginning of
000762  ** the program.
000763  **
000764  ** The P1 parameter is not actually used by this opcode.  However, it
000765  ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
000766  ** that this Goto is the bottom of a loop and that the lines from P2 down
000767  ** to the current line should be indented for EXPLAIN output.
000768  */
000769  case OP_Goto: {             /* jump */
000770  jump_to_p2_and_check_for_interrupt:
000771    pOp = &aOp[pOp->p2 - 1];
000772  
000773    /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
000774    ** OP_VNext, or OP_SorterNext) all jump here upon
000775    ** completion.  Check to see if sqlite3_interrupt() has been called
000776    ** or if the progress callback needs to be invoked. 
000777    **
000778    ** This code uses unstructured "goto" statements and does not look clean.
000779    ** But that is not due to sloppy coding habits. The code is written this
000780    ** way for performance, to avoid having to run the interrupt and progress
000781    ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
000782    ** faster according to "valgrind --tool=cachegrind" */
000783  check_for_interrupt:
000784    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
000785  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
000786    /* Call the progress callback if it is configured and the required number
000787    ** of VDBE ops have been executed (either since this invocation of
000788    ** sqlite3VdbeExec() or since last time the progress callback was called).
000789    ** If the progress callback returns non-zero, exit the virtual machine with
000790    ** a return code SQLITE_ABORT.
000791    */
000792    if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
000793      assert( db->nProgressOps!=0 );
000794      nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
000795      if( db->xProgress(db->pProgressArg) ){
000796        rc = SQLITE_INTERRUPT;
000797        goto abort_due_to_error;
000798      }
000799    }
000800  #endif
000801    
000802    break;
000803  }
000804  
000805  /* Opcode:  Gosub P1 P2 * * *
000806  **
000807  ** Write the current address onto register P1
000808  ** and then jump to address P2.
000809  */
000810  case OP_Gosub: {            /* jump */
000811    assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
000812    pIn1 = &aMem[pOp->p1];
000813    assert( VdbeMemDynamic(pIn1)==0 );
000814    memAboutToChange(p, pIn1);
000815    pIn1->flags = MEM_Int;
000816    pIn1->u.i = (int)(pOp-aOp);
000817    REGISTER_TRACE(pOp->p1, pIn1);
000818  
000819    /* Most jump operations do a goto to this spot in order to update
000820    ** the pOp pointer. */
000821  jump_to_p2:
000822    pOp = &aOp[pOp->p2 - 1];
000823    break;
000824  }
000825  
000826  /* Opcode:  Return P1 * * * *
000827  **
000828  ** Jump to the next instruction after the address in register P1.  After
000829  ** the jump, register P1 becomes undefined.
000830  */
000831  case OP_Return: {           /* in1 */
000832    pIn1 = &aMem[pOp->p1];
000833    assert( pIn1->flags==MEM_Int );
000834    pOp = &aOp[pIn1->u.i];
000835    pIn1->flags = MEM_Undefined;
000836    break;
000837  }
000838  
000839  /* Opcode: InitCoroutine P1 P2 P3 * *
000840  **
000841  ** Set up register P1 so that it will Yield to the coroutine
000842  ** located at address P3.
000843  **
000844  ** If P2!=0 then the coroutine implementation immediately follows
000845  ** this opcode.  So jump over the coroutine implementation to
000846  ** address P2.
000847  **
000848  ** See also: EndCoroutine
000849  */
000850  case OP_InitCoroutine: {     /* jump */
000851    assert( pOp->p1>0 &&  pOp->p1<=(p->nMem+1 - p->nCursor) );
000852    assert( pOp->p2>=0 && pOp->p2<p->nOp );
000853    assert( pOp->p3>=0 && pOp->p3<p->nOp );
000854    pOut = &aMem[pOp->p1];
000855    assert( !VdbeMemDynamic(pOut) );
000856    pOut->u.i = pOp->p3 - 1;
000857    pOut->flags = MEM_Int;
000858    if( pOp->p2 ) goto jump_to_p2;
000859    break;
000860  }
000861  
000862  /* Opcode:  EndCoroutine P1 * * * *
000863  **
000864  ** The instruction at the address in register P1 is a Yield.
000865  ** Jump to the P2 parameter of that Yield.
000866  ** After the jump, register P1 becomes undefined.
000867  **
000868  ** See also: InitCoroutine
000869  */
000870  case OP_EndCoroutine: {           /* in1 */
000871    VdbeOp *pCaller;
000872    pIn1 = &aMem[pOp->p1];
000873    assert( pIn1->flags==MEM_Int );
000874    assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
000875    pCaller = &aOp[pIn1->u.i];
000876    assert( pCaller->opcode==OP_Yield );
000877    assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
000878    pOp = &aOp[pCaller->p2 - 1];
000879    pIn1->flags = MEM_Undefined;
000880    break;
000881  }
000882  
000883  /* Opcode:  Yield P1 P2 * * *
000884  **
000885  ** Swap the program counter with the value in register P1.  This
000886  ** has the effect of yielding to a coroutine.
000887  **
000888  ** If the coroutine that is launched by this instruction ends with
000889  ** Yield or Return then continue to the next instruction.  But if
000890  ** the coroutine launched by this instruction ends with
000891  ** EndCoroutine, then jump to P2 rather than continuing with the
000892  ** next instruction.
000893  **
000894  ** See also: InitCoroutine
000895  */
000896  case OP_Yield: {            /* in1, jump */
000897    int pcDest;
000898    pIn1 = &aMem[pOp->p1];
000899    assert( VdbeMemDynamic(pIn1)==0 );
000900    pIn1->flags = MEM_Int;
000901    pcDest = (int)pIn1->u.i;
000902    pIn1->u.i = (int)(pOp - aOp);
000903    REGISTER_TRACE(pOp->p1, pIn1);
000904    pOp = &aOp[pcDest];
000905    break;
000906  }
000907  
000908  /* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
000909  ** Synopsis: if r[P3]=null halt
000910  **
000911  ** Check the value in register P3.  If it is NULL then Halt using
000912  ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
000913  ** value in register P3 is not NULL, then this routine is a no-op.
000914  ** The P5 parameter should be 1.
000915  */
000916  case OP_HaltIfNull: {      /* in3 */
000917    pIn3 = &aMem[pOp->p3];
000918  #ifdef SQLITE_DEBUG
000919    if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
000920  #endif
000921    if( (pIn3->flags & MEM_Null)==0 ) break;
000922    /* Fall through into OP_Halt */
000923  }
000924  
000925  /* Opcode:  Halt P1 P2 * P4 P5
000926  **
000927  ** Exit immediately.  All open cursors, etc are closed
000928  ** automatically.
000929  **
000930  ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
000931  ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
000932  ** For errors, it can be some other value.  If P1!=0 then P2 will determine
000933  ** whether or not to rollback the current transaction.  Do not rollback
000934  ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
000935  ** then back out all changes that have occurred during this execution of the
000936  ** VDBE, but do not rollback the transaction. 
000937  **
000938  ** If P4 is not null then it is an error message string.
000939  **
000940  ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
000941  **
000942  **    0:  (no change)
000943  **    1:  NOT NULL contraint failed: P4
000944  **    2:  UNIQUE constraint failed: P4
000945  **    3:  CHECK constraint failed: P4
000946  **    4:  FOREIGN KEY constraint failed: P4
000947  **
000948  ** If P5 is not zero and P4 is NULL, then everything after the ":" is
000949  ** omitted.
000950  **
000951  ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
000952  ** every program.  So a jump past the last instruction of the program
000953  ** is the same as executing Halt.
000954  */
000955  case OP_Halt: {
000956    VdbeFrame *pFrame;
000957    int pcx;
000958  
000959    pcx = (int)(pOp - aOp);
000960  #ifdef SQLITE_DEBUG
000961    if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
000962  #endif
000963    if( pOp->p1==SQLITE_OK && p->pFrame ){
000964      /* Halt the sub-program. Return control to the parent frame. */
000965      pFrame = p->pFrame;
000966      p->pFrame = pFrame->pParent;
000967      p->nFrame--;
000968      sqlite3VdbeSetChanges(db, p->nChange);
000969      pcx = sqlite3VdbeFrameRestore(pFrame);
000970      if( pOp->p2==OE_Ignore ){
000971        /* Instruction pcx is the OP_Program that invoked the sub-program 
000972        ** currently being halted. If the p2 instruction of this OP_Halt
000973        ** instruction is set to OE_Ignore, then the sub-program is throwing
000974        ** an IGNORE exception. In this case jump to the address specified
000975        ** as the p2 of the calling OP_Program.  */
000976        pcx = p->aOp[pcx].p2-1;
000977      }
000978      aOp = p->aOp;
000979      aMem = p->aMem;
000980      pOp = &aOp[pcx];
000981      break;
000982    }
000983    p->rc = pOp->p1;
000984    p->errorAction = (u8)pOp->p2;
000985    p->pc = pcx;
000986    assert( pOp->p5<=4 );
000987    if( p->rc ){
000988      if( pOp->p5 ){
000989        static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
000990                                               "FOREIGN KEY" };
000991        testcase( pOp->p5==1 );
000992        testcase( pOp->p5==2 );
000993        testcase( pOp->p5==3 );
000994        testcase( pOp->p5==4 );
000995        sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
000996        if( pOp->p4.z ){
000997          p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
000998        }
000999      }else{
001000        sqlite3VdbeError(p, "%s", pOp->p4.z);
001001      }
001002      sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
001003    }
001004    rc = sqlite3VdbeHalt(p);
001005    assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
001006    if( rc==SQLITE_BUSY ){
001007      p->rc = SQLITE_BUSY;
001008    }else{
001009      assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
001010      assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
001011      rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
001012    }
001013    goto vdbe_return;
001014  }
001015  
001016  /* Opcode: Integer P1 P2 * * *
001017  ** Synopsis: r[P2]=P1
001018  **
001019  ** The 32-bit integer value P1 is written into register P2.
001020  */
001021  case OP_Integer: {         /* out2 */
001022    pOut = out2Prerelease(p, pOp);
001023    pOut->u.i = pOp->p1;
001024    break;
001025  }
001026  
001027  /* Opcode: Int64 * P2 * P4 *
001028  ** Synopsis: r[P2]=P4
001029  **
001030  ** P4 is a pointer to a 64-bit integer value.
001031  ** Write that value into register P2.
001032  */
001033  case OP_Int64: {           /* out2 */
001034    pOut = out2Prerelease(p, pOp);
001035    assert( pOp->p4.pI64!=0 );
001036    pOut->u.i = *pOp->p4.pI64;
001037    break;
001038  }
001039  
001040  #ifndef SQLITE_OMIT_FLOATING_POINT
001041  /* Opcode: Real * P2 * P4 *
001042  ** Synopsis: r[P2]=P4
001043  **
001044  ** P4 is a pointer to a 64-bit floating point value.
001045  ** Write that value into register P2.
001046  */
001047  case OP_Real: {            /* same as TK_FLOAT, out2 */
001048    pOut = out2Prerelease(p, pOp);
001049    pOut->flags = MEM_Real;
001050    assert( !sqlite3IsNaN(*pOp->p4.pReal) );
001051    pOut->u.r = *pOp->p4.pReal;
001052    break;
001053  }
001054  #endif
001055  
001056  /* Opcode: String8 * P2 * P4 *
001057  ** Synopsis: r[P2]='P4'
001058  **
001059  ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
001060  ** into a String opcode before it is executed for the first time.  During
001061  ** this transformation, the length of string P4 is computed and stored
001062  ** as the P1 parameter.
001063  */
001064  case OP_String8: {         /* same as TK_STRING, out2 */
001065    assert( pOp->p4.z!=0 );
001066    pOut = out2Prerelease(p, pOp);
001067    pOp->opcode = OP_String;
001068    pOp->p1 = sqlite3Strlen30(pOp->p4.z);
001069  
001070  #ifndef SQLITE_OMIT_UTF16
001071    if( encoding!=SQLITE_UTF8 ){
001072      rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
001073      assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
001074      if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
001075      assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
001076      assert( VdbeMemDynamic(pOut)==0 );
001077      pOut->szMalloc = 0;
001078      pOut->flags |= MEM_Static;
001079      if( pOp->p4type==P4_DYNAMIC ){
001080        sqlite3DbFree(db, pOp->p4.z);
001081      }
001082      pOp->p4type = P4_DYNAMIC;
001083      pOp->p4.z = pOut->z;
001084      pOp->p1 = pOut->n;
001085    }
001086    testcase( rc==SQLITE_TOOBIG );
001087  #endif
001088    if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
001089      goto too_big;
001090    }
001091    assert( rc==SQLITE_OK );
001092    /* Fall through to the next case, OP_String */
001093  }
001094    
001095  /* Opcode: String P1 P2 P3 P4 P5
001096  ** Synopsis: r[P2]='P4' (len=P1)
001097  **
001098  ** The string value P4 of length P1 (bytes) is stored in register P2.
001099  **
001100  ** If P3 is not zero and the content of register P3 is equal to P5, then
001101  ** the datatype of the register P2 is converted to BLOB.  The content is
001102  ** the same sequence of bytes, it is merely interpreted as a BLOB instead
001103  ** of a string, as if it had been CAST.  In other words:
001104  **
001105  ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
001106  */
001107  case OP_String: {          /* out2 */
001108    assert( pOp->p4.z!=0 );
001109    pOut = out2Prerelease(p, pOp);
001110    pOut->flags = MEM_Str|MEM_Static|MEM_Term;
001111    pOut->z = pOp->p4.z;
001112    pOut->n = pOp->p1;
001113    pOut->enc = encoding;
001114    UPDATE_MAX_BLOBSIZE(pOut);
001115  #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
001116    if( pOp->p3>0 ){
001117      assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
001118      pIn3 = &aMem[pOp->p3];
001119      assert( pIn3->flags & MEM_Int );
001120      if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
001121    }
001122  #endif
001123    break;
001124  }
001125  
001126  /* Opcode: Null P1 P2 P3 * *
001127  ** Synopsis: r[P2..P3]=NULL
001128  **
001129  ** Write a NULL into registers P2.  If P3 greater than P2, then also write
001130  ** NULL into register P3 and every register in between P2 and P3.  If P3
001131  ** is less than P2 (typically P3 is zero) then only register P2 is
001132  ** set to NULL.
001133  **
001134  ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
001135  ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
001136  ** OP_Ne or OP_Eq.
001137  */
001138  case OP_Null: {           /* out2 */
001139    int cnt;
001140    u16 nullFlag;
001141    pOut = out2Prerelease(p, pOp);
001142    cnt = pOp->p3-pOp->p2;
001143    assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
001144    pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
001145    pOut->n = 0;
001146    while( cnt>0 ){
001147      pOut++;
001148      memAboutToChange(p, pOut);
001149      sqlite3VdbeMemSetNull(pOut);
001150      pOut->flags = nullFlag;
001151      pOut->n = 0;
001152      cnt--;
001153    }
001154    break;
001155  }
001156  
001157  /* Opcode: SoftNull P1 * * * *
001158  ** Synopsis: r[P1]=NULL
001159  **
001160  ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
001161  ** instruction, but do not free any string or blob memory associated with
001162  ** the register, so that if the value was a string or blob that was
001163  ** previously copied using OP_SCopy, the copies will continue to be valid.
001164  */
001165  case OP_SoftNull: {
001166    assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
001167    pOut = &aMem[pOp->p1];
001168    pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
001169    break;
001170  }
001171  
001172  /* Opcode: Blob P1 P2 * P4 *
001173  ** Synopsis: r[P2]=P4 (len=P1)
001174  **
001175  ** P4 points to a blob of data P1 bytes long.  Store this
001176  ** blob in register P2.
001177  */
001178  case OP_Blob: {                /* out2 */
001179    assert( pOp->p1 <= SQLITE_MAX_LENGTH );
001180    pOut = out2Prerelease(p, pOp);
001181    sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
001182    pOut->enc = encoding;
001183    UPDATE_MAX_BLOBSIZE(pOut);
001184    break;
001185  }
001186  
001187  /* Opcode: Variable P1 P2 * P4 *
001188  ** Synopsis: r[P2]=parameter(P1,P4)
001189  **
001190  ** Transfer the values of bound parameter P1 into register P2
001191  **
001192  ** If the parameter is named, then its name appears in P4.
001193  ** The P4 value is used by sqlite3_bind_parameter_name().
001194  */
001195  case OP_Variable: {            /* out2 */
001196    Mem *pVar;       /* Value being transferred */
001197  
001198    assert( pOp->p1>0 && pOp->p1<=p->nVar );
001199    assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
001200    pVar = &p->aVar[pOp->p1 - 1];
001201    if( sqlite3VdbeMemTooBig(pVar) ){
001202      goto too_big;
001203    }
001204    pOut = &aMem[pOp->p2];
001205    sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
001206    UPDATE_MAX_BLOBSIZE(pOut);
001207    break;
001208  }
001209  
001210  /* Opcode: Move P1 P2 P3 * *
001211  ** Synopsis: r[P2@P3]=r[P1@P3]
001212  **
001213  ** Move the P3 values in register P1..P1+P3-1 over into
001214  ** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
001215  ** left holding a NULL.  It is an error for register ranges
001216  ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
001217  ** for P3 to be less than 1.
001218  */
001219  case OP_Move: {
001220    int n;           /* Number of registers left to copy */
001221    int p1;          /* Register to copy from */
001222    int p2;          /* Register to copy to */
001223  
001224    n = pOp->p3;
001225    p1 = pOp->p1;
001226    p2 = pOp->p2;
001227    assert( n>0 && p1>0 && p2>0 );
001228    assert( p1+n<=p2 || p2+n<=p1 );
001229  
001230    pIn1 = &aMem[p1];
001231    pOut = &aMem[p2];
001232    do{
001233      assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
001234      assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
001235      assert( memIsValid(pIn1) );
001236      memAboutToChange(p, pOut);
001237      sqlite3VdbeMemMove(pOut, pIn1);
001238  #ifdef SQLITE_DEBUG
001239      if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
001240        pOut->pScopyFrom += pOp->p2 - p1;
001241      }
001242  #endif
001243      Deephemeralize(pOut);
001244      REGISTER_TRACE(p2++, pOut);
001245      pIn1++;
001246      pOut++;
001247    }while( --n );
001248    break;
001249  }
001250  
001251  /* Opcode: Copy P1 P2 P3 * *
001252  ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
001253  **
001254  ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
001255  **
001256  ** This instruction makes a deep copy of the value.  A duplicate
001257  ** is made of any string or blob constant.  See also OP_SCopy.
001258  */
001259  case OP_Copy: {
001260    int n;
001261  
001262    n = pOp->p3;
001263    pIn1 = &aMem[pOp->p1];
001264    pOut = &aMem[pOp->p2];
001265    assert( pOut!=pIn1 );
001266    while( 1 ){
001267      sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
001268      Deephemeralize(pOut);
001269  #ifdef SQLITE_DEBUG
001270      pOut->pScopyFrom = 0;
001271  #endif
001272      REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
001273      if( (n--)==0 ) break;
001274      pOut++;
001275      pIn1++;
001276    }
001277    break;
001278  }
001279  
001280  /* Opcode: SCopy P1 P2 * * *
001281  ** Synopsis: r[P2]=r[P1]
001282  **
001283  ** Make a shallow copy of register P1 into register P2.
001284  **
001285  ** This instruction makes a shallow copy of the value.  If the value
001286  ** is a string or blob, then the copy is only a pointer to the
001287  ** original and hence if the original changes so will the copy.
001288  ** Worse, if the original is deallocated, the copy becomes invalid.
001289  ** Thus the program must guarantee that the original will not change
001290  ** during the lifetime of the copy.  Use OP_Copy to make a complete
001291  ** copy.
001292  */
001293  case OP_SCopy: {            /* out2 */
001294    pIn1 = &aMem[pOp->p1];
001295    pOut = &aMem[pOp->p2];
001296    assert( pOut!=pIn1 );
001297    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
001298  #ifdef SQLITE_DEBUG
001299    if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
001300  #endif
001301    break;
001302  }
001303  
001304  /* Opcode: IntCopy P1 P2 * * *
001305  ** Synopsis: r[P2]=r[P1]
001306  **
001307  ** Transfer the integer value held in register P1 into register P2.
001308  **
001309  ** This is an optimized version of SCopy that works only for integer
001310  ** values.
001311  */
001312  case OP_IntCopy: {            /* out2 */
001313    pIn1 = &aMem[pOp->p1];
001314    assert( (pIn1->flags & MEM_Int)!=0 );
001315    pOut = &aMem[pOp->p2];
001316    sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
001317    break;
001318  }
001319  
001320  /* Opcode: ResultRow P1 P2 * * *
001321  ** Synopsis: output=r[P1@P2]
001322  **
001323  ** The registers P1 through P1+P2-1 contain a single row of
001324  ** results. This opcode causes the sqlite3_step() call to terminate
001325  ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
001326  ** structure to provide access to the r(P1)..r(P1+P2-1) values as
001327  ** the result row.
001328  */
001329  case OP_ResultRow: {
001330    Mem *pMem;
001331    int i;
001332    assert( p->nResColumn==pOp->p2 );
001333    assert( pOp->p1>0 );
001334    assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
001335  
001336  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
001337    /* Run the progress counter just before returning.
001338    */
001339    if( db->xProgress!=0
001340     && nVmStep>=nProgressLimit 
001341     && db->xProgress(db->pProgressArg)!=0
001342    ){
001343      rc = SQLITE_INTERRUPT;
001344      goto abort_due_to_error;
001345    }
001346  #endif
001347  
001348    /* If this statement has violated immediate foreign key constraints, do
001349    ** not return the number of rows modified. And do not RELEASE the statement
001350    ** transaction. It needs to be rolled back.  */
001351    if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
001352      assert( db->flags&SQLITE_CountRows );
001353      assert( p->usesStmtJournal );
001354      goto abort_due_to_error;
001355    }
001356  
001357    /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then 
001358    ** DML statements invoke this opcode to return the number of rows 
001359    ** modified to the user. This is the only way that a VM that
001360    ** opens a statement transaction may invoke this opcode.
001361    **
001362    ** In case this is such a statement, close any statement transaction
001363    ** opened by this VM before returning control to the user. This is to
001364    ** ensure that statement-transactions are always nested, not overlapping.
001365    ** If the open statement-transaction is not closed here, then the user
001366    ** may step another VM that opens its own statement transaction. This
001367    ** may lead to overlapping statement transactions.
001368    **
001369    ** The statement transaction is never a top-level transaction.  Hence
001370    ** the RELEASE call below can never fail.
001371    */
001372    assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
001373    rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
001374    assert( rc==SQLITE_OK );
001375  
001376    /* Invalidate all ephemeral cursor row caches */
001377    p->cacheCtr = (p->cacheCtr + 2)|1;
001378  
001379    /* Make sure the results of the current row are \000 terminated
001380    ** and have an assigned type.  The results are de-ephemeralized as
001381    ** a side effect.
001382    */
001383    pMem = p->pResultSet = &aMem[pOp->p1];
001384    for(i=0; i<pOp->p2; i++){
001385      assert( memIsValid(&pMem[i]) );
001386      Deephemeralize(&pMem[i]);
001387      assert( (pMem[i].flags & MEM_Ephem)==0
001388              || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
001389      sqlite3VdbeMemNulTerminate(&pMem[i]);
001390      REGISTER_TRACE(pOp->p1+i, &pMem[i]);
001391    }
001392    if( db->mallocFailed ) goto no_mem;
001393  
001394    if( db->mTrace & SQLITE_TRACE_ROW ){
001395      db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
001396    }
001397  
001398    /* Return SQLITE_ROW
001399    */
001400    p->pc = (int)(pOp - aOp) + 1;
001401    rc = SQLITE_ROW;
001402    goto vdbe_return;
001403  }
001404  
001405  /* Opcode: Concat P1 P2 P3 * *
001406  ** Synopsis: r[P3]=r[P2]+r[P1]
001407  **
001408  ** Add the text in register P1 onto the end of the text in
001409  ** register P2 and store the result in register P3.
001410  ** If either the P1 or P2 text are NULL then store NULL in P3.
001411  **
001412  **   P3 = P2 || P1
001413  **
001414  ** It is illegal for P1 and P3 to be the same register. Sometimes,
001415  ** if P3 is the same register as P2, the implementation is able
001416  ** to avoid a memcpy().
001417  */
001418  case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
001419    i64 nByte;
001420  
001421    pIn1 = &aMem[pOp->p1];
001422    pIn2 = &aMem[pOp->p2];
001423    pOut = &aMem[pOp->p3];
001424    assert( pIn1!=pOut );
001425    if( (pIn1->flags | pIn2->flags) & MEM_Null ){
001426      sqlite3VdbeMemSetNull(pOut);
001427      break;
001428    }
001429    if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
001430    Stringify(pIn1, encoding);
001431    Stringify(pIn2, encoding);
001432    nByte = pIn1->n + pIn2->n;
001433    if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
001434      goto too_big;
001435    }
001436    if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
001437      goto no_mem;
001438    }
001439    MemSetTypeFlag(pOut, MEM_Str);
001440    if( pOut!=pIn2 ){
001441      memcpy(pOut->z, pIn2->z, pIn2->n);
001442    }
001443    memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
001444    pOut->z[nByte]=0;
001445    pOut->z[nByte+1] = 0;
001446    pOut->flags |= MEM_Term;
001447    pOut->n = (int)nByte;
001448    pOut->enc = encoding;
001449    UPDATE_MAX_BLOBSIZE(pOut);
001450    break;
001451  }
001452  
001453  /* Opcode: Add P1 P2 P3 * *
001454  ** Synopsis: r[P3]=r[P1]+r[P2]
001455  **
001456  ** Add the value in register P1 to the value in register P2
001457  ** and store the result in register P3.
001458  ** If either input is NULL, the result is NULL.
001459  */
001460  /* Opcode: Multiply P1 P2 P3 * *
001461  ** Synopsis: r[P3]=r[P1]*r[P2]
001462  **
001463  **
001464  ** Multiply the value in register P1 by the value in register P2
001465  ** and store the result in register P3.
001466  ** If either input is NULL, the result is NULL.
001467  */
001468  /* Opcode: Subtract P1 P2 P3 * *
001469  ** Synopsis: r[P3]=r[P2]-r[P1]
001470  **
001471  ** Subtract the value in register P1 from the value in register P2
001472  ** and store the result in register P3.
001473  ** If either input is NULL, the result is NULL.
001474  */
001475  /* Opcode: Divide P1 P2 P3 * *
001476  ** Synopsis: r[P3]=r[P2]/r[P1]
001477  **
001478  ** Divide the value in register P1 by the value in register P2
001479  ** and store the result in register P3 (P3=P2/P1). If the value in 
001480  ** register P1 is zero, then the result is NULL. If either input is 
001481  ** NULL, the result is NULL.
001482  */
001483  /* Opcode: Remainder P1 P2 P3 * *
001484  ** Synopsis: r[P3]=r[P2]%r[P1]
001485  **
001486  ** Compute the remainder after integer register P2 is divided by 
001487  ** register P1 and store the result in register P3. 
001488  ** If the value in register P1 is zero the result is NULL.
001489  ** If either operand is NULL, the result is NULL.
001490  */
001491  case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
001492  case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
001493  case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
001494  case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
001495  case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
001496    char bIntint;   /* Started out as two integer operands */
001497    u16 flags;      /* Combined MEM_* flags from both inputs */
001498    u16 type1;      /* Numeric type of left operand */
001499    u16 type2;      /* Numeric type of right operand */
001500    i64 iA;         /* Integer value of left operand */
001501    i64 iB;         /* Integer value of right operand */
001502    double rA;      /* Real value of left operand */
001503    double rB;      /* Real value of right operand */
001504  
001505    pIn1 = &aMem[pOp->p1];
001506    type1 = numericType(pIn1);
001507    pIn2 = &aMem[pOp->p2];
001508    type2 = numericType(pIn2);
001509    pOut = &aMem[pOp->p3];
001510    flags = pIn1->flags | pIn2->flags;
001511    if( (type1 & type2 & MEM_Int)!=0 ){
001512      iA = pIn1->u.i;
001513      iB = pIn2->u.i;
001514      bIntint = 1;
001515      switch( pOp->opcode ){
001516        case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
001517        case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
001518        case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
001519        case OP_Divide: {
001520          if( iA==0 ) goto arithmetic_result_is_null;
001521          if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
001522          iB /= iA;
001523          break;
001524        }
001525        default: {
001526          if( iA==0 ) goto arithmetic_result_is_null;
001527          if( iA==-1 ) iA = 1;
001528          iB %= iA;
001529          break;
001530        }
001531      }
001532      pOut->u.i = iB;
001533      MemSetTypeFlag(pOut, MEM_Int);
001534    }else if( (flags & MEM_Null)!=0 ){
001535      goto arithmetic_result_is_null;
001536    }else{
001537      bIntint = 0;
001538  fp_math:
001539      rA = sqlite3VdbeRealValue(pIn1);
001540      rB = sqlite3VdbeRealValue(pIn2);
001541      switch( pOp->opcode ){
001542        case OP_Add:         rB += rA;       break;
001543        case OP_Subtract:    rB -= rA;       break;
001544        case OP_Multiply:    rB *= rA;       break;
001545        case OP_Divide: {
001546          /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
001547          if( rA==(double)0 ) goto arithmetic_result_is_null;
001548          rB /= rA;
001549          break;
001550        }
001551        default: {
001552          iA = (i64)rA;
001553          iB = (i64)rB;
001554          if( iA==0 ) goto arithmetic_result_is_null;
001555          if( iA==-1 ) iA = 1;
001556          rB = (double)(iB % iA);
001557          break;
001558        }
001559      }
001560  #ifdef SQLITE_OMIT_FLOATING_POINT
001561      pOut->u.i = rB;
001562      MemSetTypeFlag(pOut, MEM_Int);
001563  #else
001564      if( sqlite3IsNaN(rB) ){
001565        goto arithmetic_result_is_null;
001566      }
001567      pOut->u.r = rB;
001568      MemSetTypeFlag(pOut, MEM_Real);
001569      if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
001570        sqlite3VdbeIntegerAffinity(pOut);
001571      }
001572  #endif
001573    }
001574    break;
001575  
001576  arithmetic_result_is_null:
001577    sqlite3VdbeMemSetNull(pOut);
001578    break;
001579  }
001580  
001581  /* Opcode: CollSeq P1 * * P4
001582  **
001583  ** P4 is a pointer to a CollSeq object. If the next call to a user function
001584  ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
001585  ** be returned. This is used by the built-in min(), max() and nullif()
001586  ** functions.
001587  **
001588  ** If P1 is not zero, then it is a register that a subsequent min() or
001589  ** max() aggregate will set to 1 if the current row is not the minimum or
001590  ** maximum.  The P1 register is initialized to 0 by this instruction.
001591  **
001592  ** The interface used by the implementation of the aforementioned functions
001593  ** to retrieve the collation sequence set by this opcode is not available
001594  ** publicly.  Only built-in functions have access to this feature.
001595  */
001596  case OP_CollSeq: {
001597    assert( pOp->p4type==P4_COLLSEQ );
001598    if( pOp->p1 ){
001599      sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
001600    }
001601    break;
001602  }
001603  
001604  /* Opcode: BitAnd P1 P2 P3 * *
001605  ** Synopsis: r[P3]=r[P1]&r[P2]
001606  **
001607  ** Take the bit-wise AND of the values in register P1 and P2 and
001608  ** store the result in register P3.
001609  ** If either input is NULL, the result is NULL.
001610  */
001611  /* Opcode: BitOr P1 P2 P3 * *
001612  ** Synopsis: r[P3]=r[P1]|r[P2]
001613  **
001614  ** Take the bit-wise OR of the values in register P1 and P2 and
001615  ** store the result in register P3.
001616  ** If either input is NULL, the result is NULL.
001617  */
001618  /* Opcode: ShiftLeft P1 P2 P3 * *
001619  ** Synopsis: r[P3]=r[P2]<<r[P1]
001620  **
001621  ** Shift the integer value in register P2 to the left by the
001622  ** number of bits specified by the integer in register P1.
001623  ** Store the result in register P3.
001624  ** If either input is NULL, the result is NULL.
001625  */
001626  /* Opcode: ShiftRight P1 P2 P3 * *
001627  ** Synopsis: r[P3]=r[P2]>>r[P1]
001628  **
001629  ** Shift the integer value in register P2 to the right by the
001630  ** number of bits specified by the integer in register P1.
001631  ** Store the result in register P3.
001632  ** If either input is NULL, the result is NULL.
001633  */
001634  case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
001635  case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
001636  case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
001637  case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
001638    i64 iA;
001639    u64 uA;
001640    i64 iB;
001641    u8 op;
001642  
001643    pIn1 = &aMem[pOp->p1];
001644    pIn2 = &aMem[pOp->p2];
001645    pOut = &aMem[pOp->p3];
001646    if( (pIn1->flags | pIn2->flags) & MEM_Null ){
001647      sqlite3VdbeMemSetNull(pOut);
001648      break;
001649    }
001650    iA = sqlite3VdbeIntValue(pIn2);
001651    iB = sqlite3VdbeIntValue(pIn1);
001652    op = pOp->opcode;
001653    if( op==OP_BitAnd ){
001654      iA &= iB;
001655    }else if( op==OP_BitOr ){
001656      iA |= iB;
001657    }else if( iB!=0 ){
001658      assert( op==OP_ShiftRight || op==OP_ShiftLeft );
001659  
001660      /* If shifting by a negative amount, shift in the other direction */
001661      if( iB<0 ){
001662        assert( OP_ShiftRight==OP_ShiftLeft+1 );
001663        op = 2*OP_ShiftLeft + 1 - op;
001664        iB = iB>(-64) ? -iB : 64;
001665      }
001666  
001667      if( iB>=64 ){
001668        iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
001669      }else{
001670        memcpy(&uA, &iA, sizeof(uA));
001671        if( op==OP_ShiftLeft ){
001672          uA <<= iB;
001673        }else{
001674          uA >>= iB;
001675          /* Sign-extend on a right shift of a negative number */
001676          if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
001677        }
001678        memcpy(&iA, &uA, sizeof(iA));
001679      }
001680    }
001681    pOut->u.i = iA;
001682    MemSetTypeFlag(pOut, MEM_Int);
001683    break;
001684  }
001685  
001686  /* Opcode: AddImm  P1 P2 * * *
001687  ** Synopsis: r[P1]=r[P1]+P2
001688  ** 
001689  ** Add the constant P2 to the value in register P1.
001690  ** The result is always an integer.
001691  **
001692  ** To force any register to be an integer, just add 0.
001693  */
001694  case OP_AddImm: {            /* in1 */
001695    pIn1 = &aMem[pOp->p1];
001696    memAboutToChange(p, pIn1);
001697    sqlite3VdbeMemIntegerify(pIn1);
001698    pIn1->u.i += pOp->p2;
001699    break;
001700  }
001701  
001702  /* Opcode: MustBeInt P1 P2 * * *
001703  ** 
001704  ** Force the value in register P1 to be an integer.  If the value
001705  ** in P1 is not an integer and cannot be converted into an integer
001706  ** without data loss, then jump immediately to P2, or if P2==0
001707  ** raise an SQLITE_MISMATCH exception.
001708  */
001709  case OP_MustBeInt: {            /* jump, in1 */
001710    pIn1 = &aMem[pOp->p1];
001711    if( (pIn1->flags & MEM_Int)==0 ){
001712      applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
001713      VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
001714      if( (pIn1->flags & MEM_Int)==0 ){
001715        if( pOp->p2==0 ){
001716          rc = SQLITE_MISMATCH;
001717          goto abort_due_to_error;
001718        }else{
001719          goto jump_to_p2;
001720        }
001721      }
001722    }
001723    MemSetTypeFlag(pIn1, MEM_Int);
001724    break;
001725  }
001726  
001727  #ifndef SQLITE_OMIT_FLOATING_POINT
001728  /* Opcode: RealAffinity P1 * * * *
001729  **
001730  ** If register P1 holds an integer convert it to a real value.
001731  **
001732  ** This opcode is used when extracting information from a column that
001733  ** has REAL affinity.  Such column values may still be stored as
001734  ** integers, for space efficiency, but after extraction we want them
001735  ** to have only a real value.
001736  */
001737  case OP_RealAffinity: {                  /* in1 */
001738    pIn1 = &aMem[pOp->p1];
001739    if( pIn1->flags & MEM_Int ){
001740      sqlite3VdbeMemRealify(pIn1);
001741    }
001742    break;
001743  }
001744  #endif
001745  
001746  #ifndef SQLITE_OMIT_CAST
001747  /* Opcode: Cast P1 P2 * * *
001748  ** Synopsis: affinity(r[P1])
001749  **
001750  ** Force the value in register P1 to be the type defined by P2.
001751  ** 
001752  ** <ul>
001753  ** <li> P2=='A' &rarr; BLOB
001754  ** <li> P2=='B' &rarr; TEXT
001755  ** <li> P2=='C' &rarr; NUMERIC
001756  ** <li> P2=='D' &rarr; INTEGER
001757  ** <li> P2=='E' &rarr; REAL
001758  ** </ul>
001759  **
001760  ** A NULL value is not changed by this routine.  It remains NULL.
001761  */
001762  case OP_Cast: {                  /* in1 */
001763    assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
001764    testcase( pOp->p2==SQLITE_AFF_TEXT );
001765    testcase( pOp->p2==SQLITE_AFF_BLOB );
001766    testcase( pOp->p2==SQLITE_AFF_NUMERIC );
001767    testcase( pOp->p2==SQLITE_AFF_INTEGER );
001768    testcase( pOp->p2==SQLITE_AFF_REAL );
001769    pIn1 = &aMem[pOp->p1];
001770    memAboutToChange(p, pIn1);
001771    rc = ExpandBlob(pIn1);
001772    sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
001773    UPDATE_MAX_BLOBSIZE(pIn1);
001774    if( rc ) goto abort_due_to_error;
001775    break;
001776  }
001777  #endif /* SQLITE_OMIT_CAST */
001778  
001779  /* Opcode: Eq P1 P2 P3 P4 P5
001780  ** Synopsis: IF r[P3]==r[P1]
001781  **
001782  ** Compare the values in register P1 and P3.  If reg(P3)==reg(P1) then
001783  ** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5, then
001784  ** store the result of comparison in register P2.
001785  **
001786  ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
001787  ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
001788  ** to coerce both inputs according to this affinity before the
001789  ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
001790  ** affinity is used. Note that the affinity conversions are stored
001791  ** back into the input registers P1 and P3.  So this opcode can cause
001792  ** persistent changes to registers P1 and P3.
001793  **
001794  ** Once any conversions have taken place, and neither value is NULL, 
001795  ** the values are compared. If both values are blobs then memcmp() is
001796  ** used to determine the results of the comparison.  If both values
001797  ** are text, then the appropriate collating function specified in
001798  ** P4 is used to do the comparison.  If P4 is not specified then
001799  ** memcmp() is used to compare text string.  If both values are
001800  ** numeric, then a numeric comparison is used. If the two values
001801  ** are of different types, then numbers are considered less than
001802  ** strings and strings are considered less than blobs.
001803  **
001804  ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
001805  ** true or false and is never NULL.  If both operands are NULL then the result
001806  ** of comparison is true.  If either operand is NULL then the result is false.
001807  ** If neither operand is NULL the result is the same as it would be if
001808  ** the SQLITE_NULLEQ flag were omitted from P5.
001809  **
001810  ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
001811  ** content of r[P2] is only changed if the new value is NULL or 0 (false).
001812  ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
001813  */
001814  /* Opcode: Ne P1 P2 P3 P4 P5
001815  ** Synopsis: IF r[P3]!=r[P1]
001816  **
001817  ** This works just like the Eq opcode except that the jump is taken if
001818  ** the operands in registers P1 and P3 are not equal.  See the Eq opcode for
001819  ** additional information.
001820  **
001821  ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
001822  ** content of r[P2] is only changed if the new value is NULL or 1 (true).
001823  ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
001824  */
001825  /* Opcode: Lt P1 P2 P3 P4 P5
001826  ** Synopsis: IF r[P3]<r[P1]
001827  **
001828  ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
001829  ** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5 store
001830  ** the result of comparison (0 or 1 or NULL) into register P2.
001831  **
001832  ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
001833  ** reg(P3) is NULL then the take the jump.  If the SQLITE_JUMPIFNULL 
001834  ** bit is clear then fall through if either operand is NULL.
001835  **
001836  ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
001837  ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
001838  ** to coerce both inputs according to this affinity before the
001839  ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
001840  ** affinity is used. Note that the affinity conversions are stored
001841  ** back into the input registers P1 and P3.  So this opcode can cause
001842  ** persistent changes to registers P1 and P3.
001843  **
001844  ** Once any conversions have taken place, and neither value is NULL, 
001845  ** the values are compared. If both values are blobs then memcmp() is
001846  ** used to determine the results of the comparison.  If both values
001847  ** are text, then the appropriate collating function specified in
001848  ** P4 is  used to do the comparison.  If P4 is not specified then
001849  ** memcmp() is used to compare text string.  If both values are
001850  ** numeric, then a numeric comparison is used. If the two values
001851  ** are of different types, then numbers are considered less than
001852  ** strings and strings are considered less than blobs.
001853  */
001854  /* Opcode: Le P1 P2 P3 P4 P5
001855  ** Synopsis: IF r[P3]<=r[P1]
001856  **
001857  ** This works just like the Lt opcode except that the jump is taken if
001858  ** the content of register P3 is less than or equal to the content of
001859  ** register P1.  See the Lt opcode for additional information.
001860  */
001861  /* Opcode: Gt P1 P2 P3 P4 P5
001862  ** Synopsis: IF r[P3]>r[P1]
001863  **
001864  ** This works just like the Lt opcode except that the jump is taken if
001865  ** the content of register P3 is greater than the content of
001866  ** register P1.  See the Lt opcode for additional information.
001867  */
001868  /* Opcode: Ge P1 P2 P3 P4 P5
001869  ** Synopsis: IF r[P3]>=r[P1]
001870  **
001871  ** This works just like the Lt opcode except that the jump is taken if
001872  ** the content of register P3 is greater than or equal to the content of
001873  ** register P1.  See the Lt opcode for additional information.
001874  */
001875  case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
001876  case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
001877  case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
001878  case OP_Le:               /* same as TK_LE, jump, in1, in3 */
001879  case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
001880  case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
001881    int res, res2;      /* Result of the comparison of pIn1 against pIn3 */
001882    char affinity;      /* Affinity to use for comparison */
001883    u16 flags1;         /* Copy of initial value of pIn1->flags */
001884    u16 flags3;         /* Copy of initial value of pIn3->flags */
001885  
001886    pIn1 = &aMem[pOp->p1];
001887    pIn3 = &aMem[pOp->p3];
001888    flags1 = pIn1->flags;
001889    flags3 = pIn3->flags;
001890    if( (flags1 | flags3)&MEM_Null ){
001891      /* One or both operands are NULL */
001892      if( pOp->p5 & SQLITE_NULLEQ ){
001893        /* If SQLITE_NULLEQ is set (which will only happen if the operator is
001894        ** OP_Eq or OP_Ne) then take the jump or not depending on whether
001895        ** or not both operands are null.
001896        */
001897        assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
001898        assert( (flags1 & MEM_Cleared)==0 );
001899        assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
001900        if( (flags1&flags3&MEM_Null)!=0
001901         && (flags3&MEM_Cleared)==0
001902        ){
001903          res = 0;  /* Operands are equal */
001904        }else{
001905          res = 1;  /* Operands are not equal */
001906        }
001907      }else{
001908        /* SQLITE_NULLEQ is clear and at least one operand is NULL,
001909        ** then the result is always NULL.
001910        ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
001911        */
001912        if( pOp->p5 & SQLITE_STOREP2 ){
001913          pOut = &aMem[pOp->p2];
001914          iCompare = 1;    /* Operands are not equal */
001915          memAboutToChange(p, pOut);
001916          MemSetTypeFlag(pOut, MEM_Null);
001917          REGISTER_TRACE(pOp->p2, pOut);
001918        }else{
001919          VdbeBranchTaken(2,3);
001920          if( pOp->p5 & SQLITE_JUMPIFNULL ){
001921            goto jump_to_p2;
001922          }
001923        }
001924        break;
001925      }
001926    }else{
001927      /* Neither operand is NULL.  Do a comparison. */
001928      affinity = pOp->p5 & SQLITE_AFF_MASK;
001929      if( affinity>=SQLITE_AFF_NUMERIC ){
001930        if( (flags1 | flags3)&MEM_Str ){
001931          if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
001932            applyNumericAffinity(pIn1,0);
001933            testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
001934            flags3 = pIn3->flags;
001935          }
001936          if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
001937            applyNumericAffinity(pIn3,0);
001938          }
001939        }
001940        /* Handle the common case of integer comparison here, as an
001941        ** optimization, to avoid a call to sqlite3MemCompare() */
001942        if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
001943          if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
001944          if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
001945          res = 0;
001946          goto compare_op;
001947        }
001948      }else if( affinity==SQLITE_AFF_TEXT ){
001949        if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
001950          testcase( pIn1->flags & MEM_Int );
001951          testcase( pIn1->flags & MEM_Real );
001952          sqlite3VdbeMemStringify(pIn1, encoding, 1);
001953          testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
001954          flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
001955          assert( pIn1!=pIn3 );
001956        }
001957        if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
001958          testcase( pIn3->flags & MEM_Int );
001959          testcase( pIn3->flags & MEM_Real );
001960          sqlite3VdbeMemStringify(pIn3, encoding, 1);
001961          testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
001962          flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
001963        }
001964      }
001965      assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
001966      res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
001967    }
001968  compare_op:
001969    /* At this point, res is negative, zero, or positive if reg[P1] is
001970    ** less than, equal to, or greater than reg[P3], respectively.  Compute
001971    ** the answer to this operator in res2, depending on what the comparison
001972    ** operator actually is.  The next block of code depends on the fact
001973    ** that the 6 comparison operators are consecutive integers in this
001974    ** order:  NE, EQ, GT, LE, LT, GE */
001975    assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
001976    assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
001977    if( res<0 ){                        /* ne, eq, gt, le, lt, ge */
001978      static const unsigned char aLTb[] = { 1,  0,  0,  1,  1,  0 };
001979      res2 = aLTb[pOp->opcode - OP_Ne];
001980    }else if( res==0 ){
001981      static const unsigned char aEQb[] = { 0,  1,  0,  1,  0,  1 };
001982      res2 = aEQb[pOp->opcode - OP_Ne];
001983    }else{
001984      static const unsigned char aGTb[] = { 1,  0,  1,  0,  0,  1 };
001985      res2 = aGTb[pOp->opcode - OP_Ne];
001986    }
001987  
001988    /* Undo any changes made by applyAffinity() to the input registers. */
001989    assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
001990    pIn1->flags = flags1;
001991    assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
001992    pIn3->flags = flags3;
001993  
001994    if( pOp->p5 & SQLITE_STOREP2 ){
001995      pOut = &aMem[pOp->p2];
001996      iCompare = res;
001997      if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
001998        /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
001999        ** and prevents OP_Ne from overwriting NULL with 0.  This flag
002000        ** is only used in contexts where either:
002001        **   (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
002002        **   (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
002003        ** Therefore it is not necessary to check the content of r[P2] for
002004        ** NULL. */
002005        assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
002006        assert( res2==0 || res2==1 );
002007        testcase( res2==0 && pOp->opcode==OP_Eq );
002008        testcase( res2==1 && pOp->opcode==OP_Eq );
002009        testcase( res2==0 && pOp->opcode==OP_Ne );
002010        testcase( res2==1 && pOp->opcode==OP_Ne );
002011        if( (pOp->opcode==OP_Eq)==res2 ) break;
002012      }
002013      memAboutToChange(p, pOut);
002014      MemSetTypeFlag(pOut, MEM_Int);
002015      pOut->u.i = res2;
002016      REGISTER_TRACE(pOp->p2, pOut);
002017    }else{
002018      VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
002019      if( res2 ){
002020        goto jump_to_p2;
002021      }
002022    }
002023    break;
002024  }
002025  
002026  /* Opcode: ElseNotEq * P2 * * *
002027  **
002028  ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
002029  ** If result of an OP_Eq comparison on the same two operands
002030  ** would have be NULL or false (0), then then jump to P2. 
002031  ** If the result of an OP_Eq comparison on the two previous operands
002032  ** would have been true (1), then fall through.
002033  */
002034  case OP_ElseNotEq: {       /* same as TK_ESCAPE, jump */
002035    assert( pOp>aOp );
002036    assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
002037    assert( pOp[-1].p5 & SQLITE_STOREP2 );
002038    VdbeBranchTaken(iCompare!=0, 2);
002039    if( iCompare!=0 ) goto jump_to_p2;
002040    break;
002041  }
002042  
002043  
002044  /* Opcode: Permutation * * * P4 *
002045  **
002046  ** Set the permutation used by the OP_Compare operator in the next
002047  ** instruction.  The permutation is stored in the P4 operand.
002048  **
002049  ** The permutation is only valid until the next OP_Compare that has
002050  ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should 
002051  ** occur immediately prior to the OP_Compare.
002052  **
002053  ** The first integer in the P4 integer array is the length of the array
002054  ** and does not become part of the permutation.
002055  */
002056  case OP_Permutation: {
002057    assert( pOp->p4type==P4_INTARRAY );
002058    assert( pOp->p4.ai );
002059    assert( pOp[1].opcode==OP_Compare );
002060    assert( pOp[1].p5 & OPFLAG_PERMUTE );
002061    break;
002062  }
002063  
002064  /* Opcode: Compare P1 P2 P3 P4 P5
002065  ** Synopsis: r[P1@P3] <-> r[P2@P3]
002066  **
002067  ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
002068  ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
002069  ** the comparison for use by the next OP_Jump instruct.
002070  **
002071  ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
002072  ** determined by the most recent OP_Permutation operator.  If the
002073  ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
002074  ** order.
002075  **
002076  ** P4 is a KeyInfo structure that defines collating sequences and sort
002077  ** orders for the comparison.  The permutation applies to registers
002078  ** only.  The KeyInfo elements are used sequentially.
002079  **
002080  ** The comparison is a sort comparison, so NULLs compare equal,
002081  ** NULLs are less than numbers, numbers are less than strings,
002082  ** and strings are less than blobs.
002083  */
002084  case OP_Compare: {
002085    int n;
002086    int i;
002087    int p1;
002088    int p2;
002089    const KeyInfo *pKeyInfo;
002090    int idx;
002091    CollSeq *pColl;    /* Collating sequence to use on this term */
002092    int bRev;          /* True for DESCENDING sort order */
002093    int *aPermute;     /* The permutation */
002094  
002095    if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
002096      aPermute = 0;
002097    }else{
002098      assert( pOp>aOp );
002099      assert( pOp[-1].opcode==OP_Permutation );
002100      assert( pOp[-1].p4type==P4_INTARRAY );
002101      aPermute = pOp[-1].p4.ai + 1;
002102      assert( aPermute!=0 );
002103    }
002104    n = pOp->p3;
002105    pKeyInfo = pOp->p4.pKeyInfo;
002106    assert( n>0 );
002107    assert( pKeyInfo!=0 );
002108    p1 = pOp->p1;
002109    p2 = pOp->p2;
002110  #ifdef SQLITE_DEBUG
002111    if( aPermute ){
002112      int k, mx = 0;
002113      for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
002114      assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
002115      assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
002116    }else{
002117      assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
002118      assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
002119    }
002120  #endif /* SQLITE_DEBUG */
002121    for(i=0; i<n; i++){
002122      idx = aPermute ? aPermute[i] : i;
002123      assert( memIsValid(&aMem[p1+idx]) );
002124      assert( memIsValid(&aMem[p2+idx]) );
002125      REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
002126      REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
002127      assert( i<pKeyInfo->nKeyField );
002128      pColl = pKeyInfo->aColl[i];
002129      bRev = pKeyInfo->aSortOrder[i];
002130      iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
002131      if( iCompare ){
002132        if( bRev ) iCompare = -iCompare;
002133        break;
002134      }
002135    }
002136    break;
002137  }
002138  
002139  /* Opcode: Jump P1 P2 P3 * *
002140  **
002141  ** Jump to the instruction at address P1, P2, or P3 depending on whether
002142  ** in the most recent OP_Compare instruction the P1 vector was less than
002143  ** equal to, or greater than the P2 vector, respectively.
002144  */
002145  case OP_Jump: {             /* jump */
002146    if( iCompare<0 ){
002147      VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
002148    }else if( iCompare==0 ){
002149      VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
002150    }else{
002151      VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
002152    }
002153    break;
002154  }
002155  
002156  /* Opcode: And P1 P2 P3 * *
002157  ** Synopsis: r[P3]=(r[P1] && r[P2])
002158  **
002159  ** Take the logical AND of the values in registers P1 and P2 and
002160  ** write the result into register P3.
002161  **
002162  ** If either P1 or P2 is 0 (false) then the result is 0 even if
002163  ** the other input is NULL.  A NULL and true or two NULLs give
002164  ** a NULL output.
002165  */
002166  /* Opcode: Or P1 P2 P3 * *
002167  ** Synopsis: r[P3]=(r[P1] || r[P2])
002168  **
002169  ** Take the logical OR of the values in register P1 and P2 and
002170  ** store the answer in register P3.
002171  **
002172  ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
002173  ** even if the other input is NULL.  A NULL and false or two NULLs
002174  ** give a NULL output.
002175  */
002176  case OP_And:              /* same as TK_AND, in1, in2, out3 */
002177  case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
002178    int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
002179    int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
002180  
002181    v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
002182    v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
002183    if( pOp->opcode==OP_And ){
002184      static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
002185      v1 = and_logic[v1*3+v2];
002186    }else{
002187      static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
002188      v1 = or_logic[v1*3+v2];
002189    }
002190    pOut = &aMem[pOp->p3];
002191    if( v1==2 ){
002192      MemSetTypeFlag(pOut, MEM_Null);
002193    }else{
002194      pOut->u.i = v1;
002195      MemSetTypeFlag(pOut, MEM_Int);
002196    }
002197    break;
002198  }
002199  
002200  /* Opcode: IsTrue P1 P2 P3 P4 *
002201  ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
002202  **
002203  ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
002204  ** IS NOT FALSE operators.
002205  **
002206  ** Interpret the value in register P1 as a boolean value.  Store that
002207  ** boolean (a 0 or 1) in register P2.  Or if the value in register P1 is 
002208  ** NULL, then the P3 is stored in register P2.  Invert the answer if P4
002209  ** is 1.
002210  **
002211  ** The logic is summarized like this:
002212  **
002213  ** <ul> 
002214  ** <li> If P3==0 and P4==0  then  r[P2] := r[P1] IS TRUE
002215  ** <li> If P3==1 and P4==1  then  r[P2] := r[P1] IS FALSE
002216  ** <li> If P3==0 and P4==1  then  r[P2] := r[P1] IS NOT TRUE
002217  ** <li> If P3==1 and P4==0  then  r[P2] := r[P1] IS NOT FALSE
002218  ** </ul>
002219  */
002220  case OP_IsTrue: {               /* in1, out2 */
002221    assert( pOp->p4type==P4_INT32 );
002222    assert( pOp->p4.i==0 || pOp->p4.i==1 );
002223    assert( pOp->p3==0 || pOp->p3==1 );
002224    sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
002225        sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
002226    break;
002227  }
002228  
002229  /* Opcode: Not P1 P2 * * *
002230  ** Synopsis: r[P2]= !r[P1]
002231  **
002232  ** Interpret the value in register P1 as a boolean value.  Store the
002233  ** boolean complement in register P2.  If the value in register P1 is 
002234  ** NULL, then a NULL is stored in P2.
002235  */
002236  case OP_Not: {                /* same as TK_NOT, in1, out2 */
002237    pIn1 = &aMem[pOp->p1];
002238    pOut = &aMem[pOp->p2];
002239    if( (pIn1->flags & MEM_Null)==0 ){
002240      sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
002241    }else{
002242      sqlite3VdbeMemSetNull(pOut);
002243    }
002244    break;
002245  }
002246  
002247  /* Opcode: BitNot P1 P2 * * *
002248  ** Synopsis: r[P1]= ~r[P1]
002249  **
002250  ** Interpret the content of register P1 as an integer.  Store the
002251  ** ones-complement of the P1 value into register P2.  If P1 holds
002252  ** a NULL then store a NULL in P2.
002253  */
002254  case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
002255    pIn1 = &aMem[pOp->p1];
002256    pOut = &aMem[pOp->p2];
002257    sqlite3VdbeMemSetNull(pOut);
002258    if( (pIn1->flags & MEM_Null)==0 ){
002259      pOut->flags = MEM_Int;
002260      pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
002261    }
002262    break;
002263  }
002264  
002265  /* Opcode: Once P1 P2 * * *
002266  **
002267  ** Fall through to the next instruction the first time this opcode is
002268  ** encountered on each invocation of the byte-code program.  Jump to P2
002269  ** on the second and all subsequent encounters during the same invocation.
002270  **
002271  ** Top-level programs determine first invocation by comparing the P1
002272  ** operand against the P1 operand on the OP_Init opcode at the beginning
002273  ** of the program.  If the P1 values differ, then fall through and make
002274  ** the P1 of this opcode equal to the P1 of OP_Init.  If P1 values are
002275  ** the same then take the jump.
002276  **
002277  ** For subprograms, there is a bitmask in the VdbeFrame that determines
002278  ** whether or not the jump should be taken.  The bitmask is necessary
002279  ** because the self-altering code trick does not work for recursive
002280  ** triggers.
002281  */
002282  case OP_Once: {             /* jump */
002283    u32 iAddr;                /* Address of this instruction */
002284    assert( p->aOp[0].opcode==OP_Init );
002285    if( p->pFrame ){
002286      iAddr = (int)(pOp - p->aOp);
002287      if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
002288        VdbeBranchTaken(1, 2);
002289        goto jump_to_p2;
002290      }
002291      p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
002292    }else{
002293      if( p->aOp[0].p1==pOp->p1 ){
002294        VdbeBranchTaken(1, 2);
002295        goto jump_to_p2;
002296      }
002297    }
002298    VdbeBranchTaken(0, 2);
002299    pOp->p1 = p->aOp[0].p1;
002300    break;
002301  }
002302  
002303  /* Opcode: If P1 P2 P3 * *
002304  **
002305  ** Jump to P2 if the value in register P1 is true.  The value
002306  ** is considered true if it is numeric and non-zero.  If the value
002307  ** in P1 is NULL then take the jump if and only if P3 is non-zero.
002308  */
002309  case OP_If:  {               /* jump, in1 */
002310    int c;
002311    c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
002312    VdbeBranchTaken(c!=0, 2);
002313    if( c ) goto jump_to_p2;
002314    break;
002315  }
002316  
002317  /* Opcode: IfNot P1 P2 P3 * *
002318  **
002319  ** Jump to P2 if the value in register P1 is False.  The value
002320  ** is considered false if it has a numeric value of zero.  If the value
002321  ** in P1 is NULL then take the jump if and only if P3 is non-zero.
002322  */
002323  case OP_IfNot: {            /* jump, in1 */
002324    int c;
002325    c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
002326    VdbeBranchTaken(c!=0, 2);
002327    if( c ) goto jump_to_p2;
002328    break;
002329  }
002330  
002331  /* Opcode: IsNull P1 P2 * * *
002332  ** Synopsis: if r[P1]==NULL goto P2
002333  **
002334  ** Jump to P2 if the value in register P1 is NULL.
002335  */
002336  case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
002337    pIn1 = &aMem[pOp->p1];
002338    VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
002339    if( (pIn1->flags & MEM_Null)!=0 ){
002340      goto jump_to_p2;
002341    }
002342    break;
002343  }
002344  
002345  /* Opcode: NotNull P1 P2 * * *
002346  ** Synopsis: if r[P1]!=NULL goto P2
002347  **
002348  ** Jump to P2 if the value in register P1 is not NULL.  
002349  */
002350  case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
002351    pIn1 = &aMem[pOp->p1];
002352    VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
002353    if( (pIn1->flags & MEM_Null)==0 ){
002354      goto jump_to_p2;
002355    }
002356    break;
002357  }
002358  
002359  /* Opcode: IfNullRow P1 P2 P3 * *
002360  ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
002361  **
002362  ** Check the cursor P1 to see if it is currently pointing at a NULL row.
002363  ** If it is, then set register P3 to NULL and jump immediately to P2.
002364  ** If P1 is not on a NULL row, then fall through without making any
002365  ** changes.
002366  */
002367  case OP_IfNullRow: {         /* jump */
002368    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
002369    assert( p->apCsr[pOp->p1]!=0 );
002370    if( p->apCsr[pOp->p1]->nullRow ){
002371      sqlite3VdbeMemSetNull(aMem + pOp->p3);
002372      goto jump_to_p2;
002373    }
002374    break;
002375  }
002376  
002377  #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
002378  /* Opcode: Offset P1 P2 P3 * *
002379  ** Synopsis: r[P3] = sqlite_offset(P1)
002380  **
002381  ** Store in register r[P3] the byte offset into the database file that is the
002382  ** start of the payload for the record at which that cursor P1 is currently
002383  ** pointing.
002384  **
002385  ** P2 is the column number for the argument to the sqlite_offset() function.
002386  ** This opcode does not use P2 itself, but the P2 value is used by the
002387  ** code generator.  The P1, P2, and P3 operands to this opcode are the
002388  ** same as for OP_Column.
002389  **
002390  ** This opcode is only available if SQLite is compiled with the
002391  ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
002392  */
002393  case OP_Offset: {          /* out3 */
002394    VdbeCursor *pC;    /* The VDBE cursor */
002395    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
002396    pC = p->apCsr[pOp->p1];
002397    pOut = &p->aMem[pOp->p3];
002398    if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
002399      sqlite3VdbeMemSetNull(pOut);
002400    }else{
002401      sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
002402    }
002403    break;
002404  }
002405  #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
002406  
002407  /* Opcode: Column P1 P2 P3 P4 P5
002408  ** Synopsis: r[P3]=PX
002409  **
002410  ** Interpret the data that cursor P1 points to as a structure built using
002411  ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
002412  ** information about the format of the data.)  Extract the P2-th column
002413  ** from this record.  If there are less that (P2+1) 
002414  ** values in the record, extract a NULL.
002415  **
002416  ** The value extracted is stored in register P3.
002417  **
002418  ** If the record contains fewer than P2 fields, then extract a NULL.  Or,
002419  ** if the P4 argument is a P4_MEM use the value of the P4 argument as
002420  ** the result.
002421  **
002422  ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
002423  ** then the cache of the cursor is reset prior to extracting the column.
002424  ** The first OP_Column against a pseudo-table after the value of the content
002425  ** register has changed should have this bit set.
002426  **
002427  ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
002428  ** the result is guaranteed to only be used as the argument of a length()
002429  ** or typeof() function, respectively.  The loading of large blobs can be
002430  ** skipped for length() and all content loading can be skipped for typeof().
002431  */
002432  case OP_Column: {
002433    int p2;            /* column number to retrieve */
002434    VdbeCursor *pC;    /* The VDBE cursor */
002435    BtCursor *pCrsr;   /* The BTree cursor */
002436    u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
002437    int len;           /* The length of the serialized data for the column */
002438    int i;             /* Loop counter */
002439    Mem *pDest;        /* Where to write the extracted value */
002440    Mem sMem;          /* For storing the record being decoded */
002441    const u8 *zData;   /* Part of the record being decoded */
002442    const u8 *zHdr;    /* Next unparsed byte of the header */
002443    const u8 *zEndHdr; /* Pointer to first byte after the header */
002444    u64 offset64;      /* 64-bit offset */
002445    u32 t;             /* A type code from the record header */
002446    Mem *pReg;         /* PseudoTable input register */
002447  
002448    pC = p->apCsr[pOp->p1];
002449    p2 = pOp->p2;
002450  
002451    /* If the cursor cache is stale (meaning it is not currently point at
002452    ** the correct row) then bring it up-to-date by doing the necessary 
002453    ** B-Tree seek. */
002454    rc = sqlite3VdbeCursorMoveto(&pC, &p2);
002455    if( rc ) goto abort_due_to_error;
002456  
002457    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
002458    pDest = &aMem[pOp->p3];
002459    memAboutToChange(p, pDest);
002460    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
002461    assert( pC!=0 );
002462    assert( p2<pC->nField );
002463    aOffset = pC->aOffset;
002464    assert( pC->eCurType!=CURTYPE_VTAB );
002465    assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
002466    assert( pC->eCurType!=CURTYPE_SORTER );
002467  
002468    if( pC->cacheStatus!=p->cacheCtr ){                /*OPTIMIZATION-IF-FALSE*/
002469      if( pC->nullRow ){
002470        if( pC->eCurType==CURTYPE_PSEUDO ){
002471          /* For the special case of as pseudo-cursor, the seekResult field
002472          ** identifies the register that holds the record */
002473          assert( pC->seekResult>0 );
002474          pReg = &aMem[pC->seekResult];
002475          assert( pReg->flags & MEM_Blob );
002476          assert( memIsValid(pReg) );
002477          pC->payloadSize = pC->szRow = pReg->n;
002478          pC->aRow = (u8*)pReg->z;
002479        }else{
002480          sqlite3VdbeMemSetNull(pDest);
002481          goto op_column_out;
002482        }
002483      }else{
002484        pCrsr = pC->uc.pCursor;
002485        assert( pC->eCurType==CURTYPE_BTREE );
002486        assert( pCrsr );
002487        assert( sqlite3BtreeCursorIsValid(pCrsr) );
002488        pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
002489        pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
002490        assert( pC->szRow<=pC->payloadSize );
002491        assert( pC->szRow<=65536 );  /* Maximum page size is 64KiB */
002492        if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
002493          goto too_big;
002494        }
002495      }
002496      pC->cacheStatus = p->cacheCtr;
002497      pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
002498      pC->nHdrParsed = 0;
002499  
002500  
002501      if( pC->szRow<aOffset[0] ){      /*OPTIMIZATION-IF-FALSE*/
002502        /* pC->aRow does not have to hold the entire row, but it does at least
002503        ** need to cover the header of the record.  If pC->aRow does not contain
002504        ** the complete header, then set it to zero, forcing the header to be
002505        ** dynamically allocated. */
002506        pC->aRow = 0;
002507        pC->szRow = 0;
002508  
002509        /* Make sure a corrupt database has not given us an oversize header.
002510        ** Do this now to avoid an oversize memory allocation.
002511        **
002512        ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
002513        ** types use so much data space that there can only be 4096 and 32 of
002514        ** them, respectively.  So the maximum header length results from a
002515        ** 3-byte type for each of the maximum of 32768 columns plus three
002516        ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
002517        */
002518        if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
002519          goto op_column_corrupt;
002520        }
002521      }else{
002522        /* This is an optimization.  By skipping over the first few tests
002523        ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
002524        ** measurable performance gain.
002525        **
002526        ** This branch is taken even if aOffset[0]==0.  Such a record is never
002527        ** generated by SQLite, and could be considered corruption, but we
002528        ** accept it for historical reasons.  When aOffset[0]==0, the code this
002529        ** branch jumps to reads past the end of the record, but never more
002530        ** than a few bytes.  Even if the record occurs at the end of the page
002531        ** content area, the "page header" comes after the page content and so
002532        ** this overread is harmless.  Similar overreads can occur for a corrupt
002533        ** database file.
002534        */
002535        zData = pC->aRow;
002536        assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
002537        testcase( aOffset[0]==0 );
002538        goto op_column_read_header;
002539      }
002540    }
002541  
002542    /* Make sure at least the first p2+1 entries of the header have been
002543    ** parsed and valid information is in aOffset[] and pC->aType[].
002544    */
002545    if( pC->nHdrParsed<=p2 ){
002546      /* If there is more header available for parsing in the record, try
002547      ** to extract additional fields up through the p2+1-th field 
002548      */
002549      if( pC->iHdrOffset<aOffset[0] ){
002550        /* Make sure zData points to enough of the record to cover the header. */
002551        if( pC->aRow==0 ){
002552          memset(&sMem, 0, sizeof(sMem));
002553          rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
002554          if( rc!=SQLITE_OK ) goto abort_due_to_error;
002555          zData = (u8*)sMem.z;
002556        }else{
002557          zData = pC->aRow;
002558        }
002559    
002560        /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
002561      op_column_read_header:
002562        i = pC->nHdrParsed;
002563        offset64 = aOffset[i];
002564        zHdr = zData + pC->iHdrOffset;
002565        zEndHdr = zData + aOffset[0];
002566        testcase( zHdr>=zEndHdr );
002567        do{
002568          if( (t = zHdr[0])<0x80 ){
002569            zHdr++;
002570            offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
002571          }else{
002572            zHdr += sqlite3GetVarint32(zHdr, &t);
002573            offset64 += sqlite3VdbeSerialTypeLen(t);
002574          }
002575          pC->aType[i++] = t;
002576          aOffset[i] = (u32)(offset64 & 0xffffffff);
002577        }while( i<=p2 && zHdr<zEndHdr );
002578  
002579        /* The record is corrupt if any of the following are true:
002580        ** (1) the bytes of the header extend past the declared header size
002581        ** (2) the entire header was used but not all data was used
002582        ** (3) the end of the data extends beyond the end of the record.
002583        */
002584        if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
002585         || (offset64 > pC->payloadSize)
002586        ){
002587          if( aOffset[0]==0 ){
002588            i = 0;
002589            zHdr = zEndHdr;
002590          }else{
002591            if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
002592            goto op_column_corrupt;
002593          }
002594        }
002595  
002596        pC->nHdrParsed = i;
002597        pC->iHdrOffset = (u32)(zHdr - zData);
002598        if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
002599      }else{
002600        t = 0;
002601      }
002602  
002603      /* If after trying to extract new entries from the header, nHdrParsed is
002604      ** still not up to p2, that means that the record has fewer than p2
002605      ** columns.  So the result will be either the default value or a NULL.
002606      */
002607      if( pC->nHdrParsed<=p2 ){
002608        if( pOp->p4type==P4_MEM ){
002609          sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
002610        }else{
002611          sqlite3VdbeMemSetNull(pDest);
002612        }
002613        goto op_column_out;
002614      }
002615    }else{
002616      t = pC->aType[p2];
002617    }
002618  
002619    /* Extract the content for the p2+1-th column.  Control can only
002620    ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
002621    ** all valid.
002622    */
002623    assert( p2<pC->nHdrParsed );
002624    assert( rc==SQLITE_OK );
002625    assert( sqlite3VdbeCheckMemInvariants(pDest) );
002626    if( VdbeMemDynamic(pDest) ){
002627      sqlite3VdbeMemSetNull(pDest);
002628    }
002629    assert( t==pC->aType[p2] );
002630    if( pC->szRow>=aOffset[p2+1] ){
002631      /* This is the common case where the desired content fits on the original
002632      ** page - where the content is not on an overflow page */
002633      zData = pC->aRow + aOffset[p2];
002634      if( t<12 ){
002635        sqlite3VdbeSerialGet(zData, t, pDest);
002636      }else{
002637        /* If the column value is a string, we need a persistent value, not
002638        ** a MEM_Ephem value.  This branch is a fast short-cut that is equivalent
002639        ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
002640        */
002641        static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
002642        pDest->n = len = (t-12)/2;
002643        pDest->enc = encoding;
002644        if( pDest->szMalloc < len+2 ){
002645          pDest->flags = MEM_Null;
002646          if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
002647        }else{
002648          pDest->z = pDest->zMalloc;
002649        }
002650        memcpy(pDest->z, zData, len);
002651        pDest->z[len] = 0;
002652        pDest->z[len+1] = 0;
002653        pDest->flags = aFlag[t&1];
002654      }
002655    }else{
002656      pDest->enc = encoding;
002657      /* This branch happens only when content is on overflow pages */
002658      if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
002659            && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
002660       || (len = sqlite3VdbeSerialTypeLen(t))==0
002661      ){
002662        /* Content is irrelevant for
002663        **    1. the typeof() function,
002664        **    2. the length(X) function if X is a blob, and
002665        **    3. if the content length is zero.
002666        ** So we might as well use bogus content rather than reading
002667        ** content from disk. 
002668        **
002669        ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
002670        ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
002671        ** read up to 16. So 16 bytes of bogus content is supplied.
002672        */
002673        static u8 aZero[16];  /* This is the bogus content */
002674        sqlite3VdbeSerialGet(aZero, t, pDest);
002675      }else{
002676        rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
002677        if( rc!=SQLITE_OK ) goto abort_due_to_error;
002678        sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
002679        pDest->flags &= ~MEM_Ephem;
002680      }
002681    }
002682  
002683  op_column_out:
002684    UPDATE_MAX_BLOBSIZE(pDest);
002685    REGISTER_TRACE(pOp->p3, pDest);
002686    break;
002687  
002688  op_column_corrupt:
002689    if( aOp[0].p3>0 ){
002690      pOp = &aOp[aOp[0].p3-1];
002691      break;
002692    }else{
002693      rc = SQLITE_CORRUPT_BKPT;
002694      goto abort_due_to_error;
002695    }
002696  }
002697  
002698  /* Opcode: Affinity P1 P2 * P4 *
002699  ** Synopsis: affinity(r[P1@P2])
002700  **
002701  ** Apply affinities to a range of P2 registers starting with P1.
002702  **
002703  ** P4 is a string that is P2 characters long. The N-th character of the
002704  ** string indicates the column affinity that should be used for the N-th
002705  ** memory cell in the range.
002706  */
002707  case OP_Affinity: {
002708    const char *zAffinity;   /* The affinity to be applied */
002709  
002710    zAffinity = pOp->p4.z;
002711    assert( zAffinity!=0 );
002712    assert( pOp->p2>0 );
002713    assert( zAffinity[pOp->p2]==0 );
002714    pIn1 = &aMem[pOp->p1];
002715    do{
002716      assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
002717      assert( memIsValid(pIn1) );
002718      applyAffinity(pIn1, *(zAffinity++), encoding);
002719      pIn1++;
002720    }while( zAffinity[0] );
002721    break;
002722  }
002723  
002724  /* Opcode: MakeRecord P1 P2 P3 P4 *
002725  ** Synopsis: r[P3]=mkrec(r[P1@P2])
002726  **
002727  ** Convert P2 registers beginning with P1 into the [record format]
002728  ** use as a data record in a database table or as a key
002729  ** in an index.  The OP_Column opcode can decode the record later.
002730  **
002731  ** P4 may be a string that is P2 characters long.  The N-th character of the
002732  ** string indicates the column affinity that should be used for the N-th
002733  ** field of the index key.
002734  **
002735  ** The mapping from character to affinity is given by the SQLITE_AFF_
002736  ** macros defined in sqliteInt.h.
002737  **
002738  ** If P4 is NULL then all index fields have the affinity BLOB.
002739  */
002740  case OP_MakeRecord: {
002741    u8 *zNewRecord;        /* A buffer to hold the data for the new record */
002742    Mem *pRec;             /* The new record */
002743    u64 nData;             /* Number of bytes of data space */
002744    int nHdr;              /* Number of bytes of header space */
002745    i64 nByte;             /* Data space required for this record */
002746    i64 nZero;             /* Number of zero bytes at the end of the record */
002747    int nVarint;           /* Number of bytes in a varint */
002748    u32 serial_type;       /* Type field */
002749    Mem *pData0;           /* First field to be combined into the record */
002750    Mem *pLast;            /* Last field of the record */
002751    int nField;            /* Number of fields in the record */
002752    char *zAffinity;       /* The affinity string for the record */
002753    int file_format;       /* File format to use for encoding */
002754    int i;                 /* Space used in zNewRecord[] header */
002755    int j;                 /* Space used in zNewRecord[] content */
002756    u32 len;               /* Length of a field */
002757  
002758    /* Assuming the record contains N fields, the record format looks
002759    ** like this:
002760    **
002761    ** ------------------------------------------------------------------------
002762    ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
002763    ** ------------------------------------------------------------------------
002764    **
002765    ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
002766    ** and so forth.
002767    **
002768    ** Each type field is a varint representing the serial type of the 
002769    ** corresponding data element (see sqlite3VdbeSerialType()). The
002770    ** hdr-size field is also a varint which is the offset from the beginning
002771    ** of the record to data0.
002772    */
002773    nData = 0;         /* Number of bytes of data space */
002774    nHdr = 0;          /* Number of bytes of header space */
002775    nZero = 0;         /* Number of zero bytes at the end of the record */
002776    nField = pOp->p1;
002777    zAffinity = pOp->p4.z;
002778    assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
002779    pData0 = &aMem[nField];
002780    nField = pOp->p2;
002781    pLast = &pData0[nField-1];
002782    file_format = p->minWriteFileFormat;
002783  
002784    /* Identify the output register */
002785    assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
002786    pOut = &aMem[pOp->p3];
002787    memAboutToChange(p, pOut);
002788  
002789    /* Apply the requested affinity to all inputs
002790    */
002791    assert( pData0<=pLast );
002792    if( zAffinity ){
002793      pRec = pData0;
002794      do{
002795        applyAffinity(pRec++, *(zAffinity++), encoding);
002796        assert( zAffinity[0]==0 || pRec<=pLast );
002797      }while( zAffinity[0] );
002798    }
002799  
002800  #ifdef SQLITE_ENABLE_NULL_TRIM
002801    /* NULLs can be safely trimmed from the end of the record, as long as
002802    ** as the schema format is 2 or more and none of the omitted columns
002803    ** have a non-NULL default value.  Also, the record must be left with
002804    ** at least one field.  If P5>0 then it will be one more than the
002805    ** index of the right-most column with a non-NULL default value */
002806    if( pOp->p5 ){
002807      while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
002808        pLast--;
002809        nField--;
002810      }
002811    }
002812  #endif
002813  
002814    /* Loop through the elements that will make up the record to figure
002815    ** out how much space is required for the new record.
002816    */
002817    pRec = pLast;
002818    do{
002819      assert( memIsValid(pRec) );
002820      serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
002821      if( pRec->flags & MEM_Zero ){
002822        if( serial_type==0 ){
002823          /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
002824          ** table methods that never invoke sqlite3_result_xxxxx() while
002825          ** computing an unchanging column value in an UPDATE statement.
002826          ** Give such values a special internal-use-only serial-type of 10
002827          ** so that they can be passed through to xUpdate and have
002828          ** a true sqlite3_value_nochange(). */
002829          assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
002830          serial_type = 10;
002831        }else if( nData ){
002832          if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
002833        }else{
002834          nZero += pRec->u.nZero;
002835          len -= pRec->u.nZero;
002836        }
002837      }
002838      nData += len;
002839      testcase( serial_type==127 );
002840      testcase( serial_type==128 );
002841      nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
002842      pRec->uTemp = serial_type;
002843      if( pRec==pData0 ) break;
002844      pRec--;
002845    }while(1);
002846  
002847    /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
002848    ** which determines the total number of bytes in the header. The varint
002849    ** value is the size of the header in bytes including the size varint
002850    ** itself. */
002851    testcase( nHdr==126 );
002852    testcase( nHdr==127 );
002853    if( nHdr<=126 ){
002854      /* The common case */
002855      nHdr += 1;
002856    }else{
002857      /* Rare case of a really large header */
002858      nVarint = sqlite3VarintLen(nHdr);
002859      nHdr += nVarint;
002860      if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
002861    }
002862    nByte = nHdr+nData;
002863    if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
002864      goto too_big;
002865    }
002866  
002867    /* Make sure the output register has a buffer large enough to store 
002868    ** the new record. The output register (pOp->p3) is not allowed to
002869    ** be one of the input registers (because the following call to
002870    ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
002871    */
002872    if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
002873      goto no_mem;
002874    }
002875    zNewRecord = (u8 *)pOut->z;
002876  
002877    /* Write the record */
002878    i = putVarint32(zNewRecord, nHdr);
002879    j = nHdr;
002880    assert( pData0<=pLast );
002881    pRec = pData0;
002882    do{
002883      serial_type = pRec->uTemp;
002884      /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
002885      ** additional varints, one per column. */
002886      i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
002887      /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
002888      ** immediately follow the header. */
002889      j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
002890    }while( (++pRec)<=pLast );
002891    assert( i==nHdr );
002892    assert( j==nByte );
002893  
002894    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
002895    pOut->n = (int)nByte;
002896    pOut->flags = MEM_Blob;
002897    if( nZero ){
002898      pOut->u.nZero = nZero;
002899      pOut->flags |= MEM_Zero;
002900    }
002901    REGISTER_TRACE(pOp->p3, pOut);
002902    UPDATE_MAX_BLOBSIZE(pOut);
002903    break;
002904  }
002905  
002906  /* Opcode: Count P1 P2 * * *
002907  ** Synopsis: r[P2]=count()
002908  **
002909  ** Store the number of entries (an integer value) in the table or index 
002910  ** opened by cursor P1 in register P2
002911  */
002912  #ifndef SQLITE_OMIT_BTREECOUNT
002913  case OP_Count: {         /* out2 */
002914    i64 nEntry;
002915    BtCursor *pCrsr;
002916  
002917    assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
002918    pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
002919    assert( pCrsr );
002920    nEntry = 0;  /* Not needed.  Only used to silence a warning. */
002921    rc = sqlite3BtreeCount(pCrsr, &nEntry);
002922    if( rc ) goto abort_due_to_error;
002923    pOut = out2Prerelease(p, pOp);
002924    pOut->u.i = nEntry;
002925    break;
002926  }
002927  #endif
002928  
002929  /* Opcode: Savepoint P1 * * P4 *
002930  **
002931  ** Open, release or rollback the savepoint named by parameter P4, depending
002932  ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
002933  ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
002934  */
002935  case OP_Savepoint: {
002936    int p1;                         /* Value of P1 operand */
002937    char *zName;                    /* Name of savepoint */
002938    int nName;
002939    Savepoint *pNew;
002940    Savepoint *pSavepoint;
002941    Savepoint *pTmp;
002942    int iSavepoint;
002943    int ii;
002944  
002945    p1 = pOp->p1;
002946    zName = pOp->p4.z;
002947  
002948    /* Assert that the p1 parameter is valid. Also that if there is no open
002949    ** transaction, then there cannot be any savepoints. 
002950    */
002951    assert( db->pSavepoint==0 || db->autoCommit==0 );
002952    assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
002953    assert( db->pSavepoint || db->isTransactionSavepoint==0 );
002954    assert( checkSavepointCount(db) );
002955    assert( p->bIsReader );
002956  
002957    if( p1==SAVEPOINT_BEGIN ){
002958      if( db->nVdbeWrite>0 ){
002959        /* A new savepoint cannot be created if there are active write 
002960        ** statements (i.e. open read/write incremental blob handles).
002961        */
002962        sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
002963        rc = SQLITE_BUSY;
002964      }else{
002965        nName = sqlite3Strlen30(zName);
002966  
002967  #ifndef SQLITE_OMIT_VIRTUALTABLE
002968        /* This call is Ok even if this savepoint is actually a transaction
002969        ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
002970        ** If this is a transaction savepoint being opened, it is guaranteed
002971        ** that the db->aVTrans[] array is empty.  */
002972        assert( db->autoCommit==0 || db->nVTrans==0 );
002973        rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
002974                                  db->nStatement+db->nSavepoint);
002975        if( rc!=SQLITE_OK ) goto abort_due_to_error;
002976  #endif
002977  
002978        /* Create a new savepoint structure. */
002979        pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
002980        if( pNew ){
002981          pNew->zName = (char *)&pNew[1];
002982          memcpy(pNew->zName, zName, nName+1);
002983      
002984          /* If there is no open transaction, then mark this as a special
002985          ** "transaction savepoint". */
002986          if( db->autoCommit ){
002987            db->autoCommit = 0;
002988            db->isTransactionSavepoint = 1;
002989          }else{
002990            db->nSavepoint++;
002991          }
002992  
002993          /* Link the new savepoint into the database handle's list. */
002994          pNew->pNext = db->pSavepoint;
002995          db->pSavepoint = pNew;
002996          pNew->nDeferredCons = db->nDeferredCons;
002997          pNew->nDeferredImmCons = db->nDeferredImmCons;
002998        }
002999      }
003000    }else{
003001      iSavepoint = 0;
003002  
003003      /* Find the named savepoint. If there is no such savepoint, then an
003004      ** an error is returned to the user.  */
003005      for(
003006        pSavepoint = db->pSavepoint; 
003007        pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
003008        pSavepoint = pSavepoint->pNext
003009      ){
003010        iSavepoint++;
003011      }
003012      if( !pSavepoint ){
003013        sqlite3VdbeError(p, "no such savepoint: %s", zName);
003014        rc = SQLITE_ERROR;
003015      }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
003016        /* It is not possible to release (commit) a savepoint if there are 
003017        ** active write statements.
003018        */
003019        sqlite3VdbeError(p, "cannot release savepoint - "
003020                            "SQL statements in progress");
003021        rc = SQLITE_BUSY;
003022      }else{
003023  
003024        /* Determine whether or not this is a transaction savepoint. If so,
003025        ** and this is a RELEASE command, then the current transaction 
003026        ** is committed. 
003027        */
003028        int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
003029        if( isTransaction && p1==SAVEPOINT_RELEASE ){
003030          if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
003031            goto vdbe_return;
003032          }
003033          db->autoCommit = 1;
003034          if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
003035            p->pc = (int)(pOp - aOp);
003036            db->autoCommit = 0;
003037            p->rc = rc = SQLITE_BUSY;
003038            goto vdbe_return;
003039          }
003040          db->isTransactionSavepoint = 0;
003041          rc = p->rc;
003042        }else{
003043          int isSchemaChange;
003044          iSavepoint = db->nSavepoint - iSavepoint - 1;
003045          if( p1==SAVEPOINT_ROLLBACK ){
003046            isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
003047            for(ii=0; ii<db->nDb; ii++){
003048              rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
003049                                         SQLITE_ABORT_ROLLBACK,
003050                                         isSchemaChange==0);
003051              if( rc!=SQLITE_OK ) goto abort_due_to_error;
003052            }
003053          }else{
003054            isSchemaChange = 0;
003055          }
003056          for(ii=0; ii<db->nDb; ii++){
003057            rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
003058            if( rc!=SQLITE_OK ){
003059              goto abort_due_to_error;
003060            }
003061          }
003062          if( isSchemaChange ){
003063            sqlite3ExpirePreparedStatements(db);
003064            sqlite3ResetAllSchemasOfConnection(db);
003065            db->mDbFlags |= DBFLAG_SchemaChange;
003066          }
003067        }
003068    
003069        /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all 
003070        ** savepoints nested inside of the savepoint being operated on. */
003071        while( db->pSavepoint!=pSavepoint ){
003072          pTmp = db->pSavepoint;
003073          db->pSavepoint = pTmp->pNext;
003074          sqlite3DbFree(db, pTmp);
003075          db->nSavepoint--;
003076        }
003077  
003078        /* If it is a RELEASE, then destroy the savepoint being operated on 
003079        ** too. If it is a ROLLBACK TO, then set the number of deferred 
003080        ** constraint violations present in the database to the value stored
003081        ** when the savepoint was created.  */
003082        if( p1==SAVEPOINT_RELEASE ){
003083          assert( pSavepoint==db->pSavepoint );
003084          db->pSavepoint = pSavepoint->pNext;
003085          sqlite3DbFree(db, pSavepoint);
003086          if( !isTransaction ){
003087            db->nSavepoint--;
003088          }
003089        }else{
003090          db->nDeferredCons = pSavepoint->nDeferredCons;
003091          db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
003092        }
003093  
003094        if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
003095          rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
003096          if( rc!=SQLITE_OK ) goto abort_due_to_error;
003097        }
003098      }
003099    }
003100    if( rc ) goto abort_due_to_error;
003101  
003102    break;
003103  }
003104  
003105  /* Opcode: AutoCommit P1 P2 * * *
003106  **
003107  ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
003108  ** back any currently active btree transactions. If there are any active
003109  ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
003110  ** there are active writing VMs or active VMs that use shared cache.
003111  **
003112  ** This instruction causes the VM to halt.
003113  */
003114  case OP_AutoCommit: {
003115    int desiredAutoCommit;
003116    int iRollback;
003117  
003118    desiredAutoCommit = pOp->p1;
003119    iRollback = pOp->p2;
003120    assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
003121    assert( desiredAutoCommit==1 || iRollback==0 );
003122    assert( db->nVdbeActive>0 );  /* At least this one VM is active */
003123    assert( p->bIsReader );
003124  
003125    if( desiredAutoCommit!=db->autoCommit ){
003126      if( iRollback ){
003127        assert( desiredAutoCommit==1 );
003128        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
003129        db->autoCommit = 1;
003130      }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
003131        /* If this instruction implements a COMMIT and other VMs are writing
003132        ** return an error indicating that the other VMs must complete first. 
003133        */
003134        sqlite3VdbeError(p, "cannot commit transaction - "
003135                            "SQL statements in progress");
003136        rc = SQLITE_BUSY;
003137        goto abort_due_to_error;
003138      }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
003139        goto vdbe_return;
003140      }else{
003141        db->autoCommit = (u8)desiredAutoCommit;
003142      }
003143      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
003144        p->pc = (int)(pOp - aOp);
003145        db->autoCommit = (u8)(1-desiredAutoCommit);
003146        p->rc = rc = SQLITE_BUSY;
003147        goto vdbe_return;
003148      }
003149      assert( db->nStatement==0 );
003150      sqlite3CloseSavepoints(db);
003151      if( p->rc==SQLITE_OK ){
003152        rc = SQLITE_DONE;
003153      }else{
003154        rc = SQLITE_ERROR;
003155      }
003156      goto vdbe_return;
003157    }else{
003158      sqlite3VdbeError(p,
003159          (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
003160          (iRollback)?"cannot rollback - no transaction is active":
003161                     "cannot commit - no transaction is active"));
003162           
003163      rc = SQLITE_ERROR;
003164      goto abort_due_to_error;
003165    }
003166    break;
003167  }
003168  
003169  /* Opcode: Transaction P1 P2 P3 P4 P5
003170  **
003171  ** Begin a transaction on database P1 if a transaction is not already
003172  ** active.
003173  ** If P2 is non-zero, then a write-transaction is started, or if a 
003174  ** read-transaction is already active, it is upgraded to a write-transaction.
003175  ** If P2 is zero, then a read-transaction is started.
003176  **
003177  ** P1 is the index of the database file on which the transaction is
003178  ** started.  Index 0 is the main database file and index 1 is the
003179  ** file used for temporary tables.  Indices of 2 or more are used for
003180  ** attached databases.
003181  **
003182  ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
003183  ** true (this flag is set if the Vdbe may modify more than one row and may
003184  ** throw an ABORT exception), a statement transaction may also be opened.
003185  ** More specifically, a statement transaction is opened iff the database
003186  ** connection is currently not in autocommit mode, or if there are other
003187  ** active statements. A statement transaction allows the changes made by this
003188  ** VDBE to be rolled back after an error without having to roll back the
003189  ** entire transaction. If no error is encountered, the statement transaction
003190  ** will automatically commit when the VDBE halts.
003191  **
003192  ** If P5!=0 then this opcode also checks the schema cookie against P3
003193  ** and the schema generation counter against P4.
003194  ** The cookie changes its value whenever the database schema changes.
003195  ** This operation is used to detect when that the cookie has changed
003196  ** and that the current process needs to reread the schema.  If the schema
003197  ** cookie in P3 differs from the schema cookie in the database header or
003198  ** if the schema generation counter in P4 differs from the current
003199  ** generation counter, then an SQLITE_SCHEMA error is raised and execution
003200  ** halts.  The sqlite3_step() wrapper function might then reprepare the
003201  ** statement and rerun it from the beginning.
003202  */
003203  case OP_Transaction: {
003204    Btree *pBt;
003205    int iMeta;
003206    int iGen;
003207  
003208    assert( p->bIsReader );
003209    assert( p->readOnly==0 || pOp->p2==0 );
003210    assert( pOp->p1>=0 && pOp->p1<db->nDb );
003211    assert( DbMaskTest(p->btreeMask, pOp->p1) );
003212    if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
003213      rc = SQLITE_READONLY;
003214      goto abort_due_to_error;
003215    }
003216    pBt = db->aDb[pOp->p1].pBt;
003217  
003218    if( pBt ){
003219      rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
003220      testcase( rc==SQLITE_BUSY_SNAPSHOT );
003221      testcase( rc==SQLITE_BUSY_RECOVERY );
003222      if( rc!=SQLITE_OK ){
003223        if( (rc&0xff)==SQLITE_BUSY ){
003224          p->pc = (int)(pOp - aOp);
003225          p->rc = rc;
003226          goto vdbe_return;
003227        }
003228        goto abort_due_to_error;
003229      }
003230  
003231      if( pOp->p2 && p->usesStmtJournal 
003232       && (db->autoCommit==0 || db->nVdbeRead>1) 
003233      ){
003234        assert( sqlite3BtreeIsInTrans(pBt) );
003235        if( p->iStatement==0 ){
003236          assert( db->nStatement>=0 && db->nSavepoint>=0 );
003237          db->nStatement++; 
003238          p->iStatement = db->nSavepoint + db->nStatement;
003239        }
003240  
003241        rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
003242        if( rc==SQLITE_OK ){
003243          rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
003244        }
003245  
003246        /* Store the current value of the database handles deferred constraint
003247        ** counter. If the statement transaction needs to be rolled back,
003248        ** the value of this counter needs to be restored too.  */
003249        p->nStmtDefCons = db->nDeferredCons;
003250        p->nStmtDefImmCons = db->nDeferredImmCons;
003251      }
003252  
003253      /* Gather the schema version number for checking:
003254      ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
003255      ** version is checked to ensure that the schema has not changed since the
003256      ** SQL statement was prepared.
003257      */
003258      sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
003259      iGen = db->aDb[pOp->p1].pSchema->iGeneration;
003260    }else{
003261      iGen = iMeta = 0;
003262    }
003263    assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
003264    if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
003265      sqlite3DbFree(db, p->zErrMsg);
003266      p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
003267      /* If the schema-cookie from the database file matches the cookie 
003268      ** stored with the in-memory representation of the schema, do
003269      ** not reload the schema from the database file.
003270      **
003271      ** If virtual-tables are in use, this is not just an optimization.
003272      ** Often, v-tables store their data in other SQLite tables, which
003273      ** are queried from within xNext() and other v-table methods using
003274      ** prepared queries. If such a query is out-of-date, we do not want to
003275      ** discard the database schema, as the user code implementing the
003276      ** v-table would have to be ready for the sqlite3_vtab structure itself
003277      ** to be invalidated whenever sqlite3_step() is called from within 
003278      ** a v-table method.
003279      */
003280      if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
003281        sqlite3ResetOneSchema(db, pOp->p1);
003282      }
003283      p->expired = 1;
003284      rc = SQLITE_SCHEMA;
003285    }
003286    if( rc ) goto abort_due_to_error;
003287    break;
003288  }
003289  
003290  /* Opcode: ReadCookie P1 P2 P3 * *
003291  **
003292  ** Read cookie number P3 from database P1 and write it into register P2.
003293  ** P3==1 is the schema version.  P3==2 is the database format.
003294  ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
003295  ** the main database file and P1==1 is the database file used to store
003296  ** temporary tables.
003297  **
003298  ** There must be a read-lock on the database (either a transaction
003299  ** must be started or there must be an open cursor) before
003300  ** executing this instruction.
003301  */
003302  case OP_ReadCookie: {               /* out2 */
003303    int iMeta;
003304    int iDb;
003305    int iCookie;
003306  
003307    assert( p->bIsReader );
003308    iDb = pOp->p1;
003309    iCookie = pOp->p3;
003310    assert( pOp->p3<SQLITE_N_BTREE_META );
003311    assert( iDb>=0 && iDb<db->nDb );
003312    assert( db->aDb[iDb].pBt!=0 );
003313    assert( DbMaskTest(p->btreeMask, iDb) );
003314  
003315    sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
003316    pOut = out2Prerelease(p, pOp);
003317    pOut->u.i = iMeta;
003318    break;
003319  }
003320  
003321  /* Opcode: SetCookie P1 P2 P3 * *
003322  **
003323  ** Write the integer value P3 into cookie number P2 of database P1.
003324  ** P2==1 is the schema version.  P2==2 is the database format.
003325  ** P2==3 is the recommended pager cache 
003326  ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
003327  ** database file used to store temporary tables.
003328  **
003329  ** A transaction must be started before executing this opcode.
003330  */
003331  case OP_SetCookie: {
003332    Db *pDb;
003333  
003334    sqlite3VdbeIncrWriteCounter(p, 0);
003335    assert( pOp->p2<SQLITE_N_BTREE_META );
003336    assert( pOp->p1>=0 && pOp->p1<db->nDb );
003337    assert( DbMaskTest(p->btreeMask, pOp->p1) );
003338    assert( p->readOnly==0 );
003339    pDb = &db->aDb[pOp->p1];
003340    assert( pDb->pBt!=0 );
003341    assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
003342    /* See note about index shifting on OP_ReadCookie */
003343    rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
003344    if( pOp->p2==BTREE_SCHEMA_VERSION ){
003345      /* When the schema cookie changes, record the new cookie internally */
003346      pDb->pSchema->schema_cookie = pOp->p3;
003347      db->mDbFlags |= DBFLAG_SchemaChange;
003348    }else if( pOp->p2==BTREE_FILE_FORMAT ){
003349      /* Record changes in the file format */
003350      pDb->pSchema->file_format = pOp->p3;
003351    }
003352    if( pOp->p1==1 ){
003353      /* Invalidate all prepared statements whenever the TEMP database
003354      ** schema is changed.  Ticket #1644 */
003355      sqlite3ExpirePreparedStatements(db);
003356      p->expired = 0;
003357    }
003358    if( rc ) goto abort_due_to_error;
003359    break;
003360  }
003361  
003362  /* Opcode: OpenRead P1 P2 P3 P4 P5
003363  ** Synopsis: root=P2 iDb=P3
003364  **
003365  ** Open a read-only cursor for the database table whose root page is
003366  ** P2 in a database file.  The database file is determined by P3. 
003367  ** P3==0 means the main database, P3==1 means the database used for 
003368  ** temporary tables, and P3>1 means used the corresponding attached
003369  ** database.  Give the new cursor an identifier of P1.  The P1
003370  ** values need not be contiguous but all P1 values should be small integers.
003371  ** It is an error for P1 to be negative.
003372  **
003373  ** If P5!=0 then use the content of register P2 as the root page, not
003374  ** the value of P2 itself.
003375  **
003376  ** There will be a read lock on the database whenever there is an
003377  ** open cursor.  If the database was unlocked prior to this instruction
003378  ** then a read lock is acquired as part of this instruction.  A read
003379  ** lock allows other processes to read the database but prohibits
003380  ** any other process from modifying the database.  The read lock is
003381  ** released when all cursors are closed.  If this instruction attempts
003382  ** to get a read lock but fails, the script terminates with an
003383  ** SQLITE_BUSY error code.
003384  **
003385  ** The P4 value may be either an integer (P4_INT32) or a pointer to
003386  ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
003387  ** structure, then said structure defines the content and collating 
003388  ** sequence of the index being opened. Otherwise, if P4 is an integer 
003389  ** value, it is set to the number of columns in the table.
003390  **
003391  ** See also: OpenWrite, ReopenIdx
003392  */
003393  /* Opcode: ReopenIdx P1 P2 P3 P4 P5
003394  ** Synopsis: root=P2 iDb=P3
003395  **
003396  ** The ReopenIdx opcode works exactly like ReadOpen except that it first
003397  ** checks to see if the cursor on P1 is already open with a root page
003398  ** number of P2 and if it is this opcode becomes a no-op.  In other words,
003399  ** if the cursor is already open, do not reopen it.
003400  **
003401  ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
003402  ** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
003403  ** every other ReopenIdx or OpenRead for the same cursor number.
003404  **
003405  ** See the OpenRead opcode documentation for additional information.
003406  */
003407  /* Opcode: OpenWrite P1 P2 P3 P4 P5
003408  ** Synopsis: root=P2 iDb=P3
003409  **
003410  ** Open a read/write cursor named P1 on the table or index whose root
003411  ** page is P2.  Or if P5!=0 use the content of register P2 to find the
003412  ** root page.
003413  **
003414  ** The P4 value may be either an integer (P4_INT32) or a pointer to
003415  ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
003416  ** structure, then said structure defines the content and collating 
003417  ** sequence of the index being opened. Otherwise, if P4 is an integer 
003418  ** value, it is set to the number of columns in the table, or to the
003419  ** largest index of any column of the table that is actually used.
003420  **
003421  ** This instruction works just like OpenRead except that it opens the cursor
003422  ** in read/write mode.  For a given table, there can be one or more read-only
003423  ** cursors or a single read/write cursor but not both.
003424  **
003425  ** See also OpenRead.
003426  */
003427  case OP_ReopenIdx: {
003428    int nField;
003429    KeyInfo *pKeyInfo;
003430    int p2;
003431    int iDb;
003432    int wrFlag;
003433    Btree *pX;
003434    VdbeCursor *pCur;
003435    Db *pDb;
003436  
003437    assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
003438    assert( pOp->p4type==P4_KEYINFO );
003439    pCur = p->apCsr[pOp->p1];
003440    if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
003441      assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
003442      goto open_cursor_set_hints;
003443    }
003444    /* If the cursor is not currently open or is open on a different
003445    ** index, then fall through into OP_OpenRead to force a reopen */
003446  case OP_OpenRead:
003447  case OP_OpenWrite:
003448  
003449    assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
003450    assert( p->bIsReader );
003451    assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
003452            || p->readOnly==0 );
003453  
003454    if( p->expired ){
003455      rc = SQLITE_ABORT_ROLLBACK;
003456      goto abort_due_to_error;
003457    }
003458  
003459    nField = 0;
003460    pKeyInfo = 0;
003461    p2 = pOp->p2;
003462    iDb = pOp->p3;
003463    assert( iDb>=0 && iDb<db->nDb );
003464    assert( DbMaskTest(p->btreeMask, iDb) );
003465    pDb = &db->aDb[iDb];
003466    pX = pDb->pBt;
003467    assert( pX!=0 );
003468    if( pOp->opcode==OP_OpenWrite ){
003469      assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
003470      wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
003471      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
003472      if( pDb->pSchema->file_format < p->minWriteFileFormat ){
003473        p->minWriteFileFormat = pDb->pSchema->file_format;
003474      }
003475    }else{
003476      wrFlag = 0;
003477    }
003478    if( pOp->p5 & OPFLAG_P2ISREG ){
003479      assert( p2>0 );
003480      assert( p2<=(p->nMem+1 - p->nCursor) );
003481      pIn2 = &aMem[p2];
003482      assert( memIsValid(pIn2) );
003483      assert( (pIn2->flags & MEM_Int)!=0 );
003484      sqlite3VdbeMemIntegerify(pIn2);
003485      p2 = (int)pIn2->u.i;
003486      /* The p2 value always comes from a prior OP_CreateBtree opcode and
003487      ** that opcode will always set the p2 value to 2 or more or else fail.
003488      ** If there were a failure, the prepared statement would have halted
003489      ** before reaching this instruction. */
003490      assert( p2>=2 );
003491    }
003492    if( pOp->p4type==P4_KEYINFO ){
003493      pKeyInfo = pOp->p4.pKeyInfo;
003494      assert( pKeyInfo->enc==ENC(db) );
003495      assert( pKeyInfo->db==db );
003496      nField = pKeyInfo->nAllField;
003497    }else if( pOp->p4type==P4_INT32 ){
003498      nField = pOp->p4.i;
003499    }
003500    assert( pOp->p1>=0 );
003501    assert( nField>=0 );
003502    testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
003503    pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
003504    if( pCur==0 ) goto no_mem;
003505    pCur->nullRow = 1;
003506    pCur->isOrdered = 1;
003507    pCur->pgnoRoot = p2;
003508  #ifdef SQLITE_DEBUG
003509    pCur->wrFlag = wrFlag;
003510  #endif
003511    rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
003512    pCur->pKeyInfo = pKeyInfo;
003513    /* Set the VdbeCursor.isTable variable. Previous versions of
003514    ** SQLite used to check if the root-page flags were sane at this point
003515    ** and report database corruption if they were not, but this check has
003516    ** since moved into the btree layer.  */  
003517    pCur->isTable = pOp->p4type!=P4_KEYINFO;
003518  
003519  open_cursor_set_hints:
003520    assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
003521    assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
003522    testcase( pOp->p5 & OPFLAG_BULKCSR );
003523  #ifdef SQLITE_ENABLE_CURSOR_HINTS
003524    testcase( pOp->p2 & OPFLAG_SEEKEQ );
003525  #endif
003526    sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
003527                                 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
003528    if( rc ) goto abort_due_to_error;
003529    break;
003530  }
003531  
003532  /* Opcode: OpenDup P1 P2 * * *
003533  **
003534  ** Open a new cursor P1 that points to the same ephemeral table as
003535  ** cursor P2.  The P2 cursor must have been opened by a prior OP_OpenEphemeral
003536  ** opcode.  Only ephemeral cursors may be duplicated.
003537  **
003538  ** Duplicate ephemeral cursors are used for self-joins of materialized views.
003539  */
003540  case OP_OpenDup: {
003541    VdbeCursor *pOrig;    /* The original cursor to be duplicated */
003542    VdbeCursor *pCx;      /* The new cursor */
003543  
003544    pOrig = p->apCsr[pOp->p2];
003545    assert( pOrig->pBtx!=0 );  /* Only ephemeral cursors can be duplicated */
003546  
003547    pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
003548    if( pCx==0 ) goto no_mem;
003549    pCx->nullRow = 1;
003550    pCx->isEphemeral = 1;
003551    pCx->pKeyInfo = pOrig->pKeyInfo;
003552    pCx->isTable = pOrig->isTable;
003553    rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
003554                            pCx->pKeyInfo, pCx->uc.pCursor);
003555    /* The sqlite3BtreeCursor() routine can only fail for the first cursor
003556    ** opened for a database.  Since there is already an open cursor when this
003557    ** opcode is run, the sqlite3BtreeCursor() cannot fail */
003558    assert( rc==SQLITE_OK );
003559    break;
003560  }
003561  
003562  
003563  /* Opcode: OpenEphemeral P1 P2 * P4 P5
003564  ** Synopsis: nColumn=P2
003565  **
003566  ** Open a new cursor P1 to a transient table.
003567  ** The cursor is always opened read/write even if 
003568  ** the main database is read-only.  The ephemeral
003569  ** table is deleted automatically when the cursor is closed.
003570  **
003571  ** P2 is the number of columns in the ephemeral table.
003572  ** The cursor points to a BTree table if P4==0 and to a BTree index
003573  ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
003574  ** that defines the format of keys in the index.
003575  **
003576  ** The P5 parameter can be a mask of the BTREE_* flags defined
003577  ** in btree.h.  These flags control aspects of the operation of
003578  ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
003579  ** added automatically.
003580  */
003581  /* Opcode: OpenAutoindex P1 P2 * P4 *
003582  ** Synopsis: nColumn=P2
003583  **
003584  ** This opcode works the same as OP_OpenEphemeral.  It has a
003585  ** different name to distinguish its use.  Tables created using
003586  ** by this opcode will be used for automatically created transient
003587  ** indices in joins.
003588  */
003589  case OP_OpenAutoindex: 
003590  case OP_OpenEphemeral: {
003591    VdbeCursor *pCx;
003592    KeyInfo *pKeyInfo;
003593  
003594    static const int vfsFlags = 
003595        SQLITE_OPEN_READWRITE |
003596        SQLITE_OPEN_CREATE |
003597        SQLITE_OPEN_EXCLUSIVE |
003598        SQLITE_OPEN_DELETEONCLOSE |
003599        SQLITE_OPEN_TRANSIENT_DB;
003600    assert( pOp->p1>=0 );
003601    assert( pOp->p2>=0 );
003602    pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
003603    if( pCx==0 ) goto no_mem;
003604    pCx->nullRow = 1;
003605    pCx->isEphemeral = 1;
003606    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx, 
003607                          BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
003608    if( rc==SQLITE_OK ){
003609      rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
003610    }
003611    if( rc==SQLITE_OK ){
003612      /* If a transient index is required, create it by calling
003613      ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
003614      ** opening it. If a transient table is required, just use the
003615      ** automatically created table with root-page 1 (an BLOB_INTKEY table).
003616      */
003617      if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
003618        int pgno;
003619        assert( pOp->p4type==P4_KEYINFO );
003620        rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5); 
003621        if( rc==SQLITE_OK ){
003622          assert( pgno==MASTER_ROOT+1 );
003623          assert( pKeyInfo->db==db );
003624          assert( pKeyInfo->enc==ENC(db) );
003625          rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
003626                                  pKeyInfo, pCx->uc.pCursor);
003627        }
003628        pCx->isTable = 0;
003629      }else{
003630        rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
003631                                0, pCx->uc.pCursor);
003632        pCx->isTable = 1;
003633      }
003634    }
003635    if( rc ) goto abort_due_to_error;
003636    pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
003637    break;
003638  }
003639  
003640  /* Opcode: SorterOpen P1 P2 P3 P4 *
003641  **
003642  ** This opcode works like OP_OpenEphemeral except that it opens
003643  ** a transient index that is specifically designed to sort large
003644  ** tables using an external merge-sort algorithm.
003645  **
003646  ** If argument P3 is non-zero, then it indicates that the sorter may
003647  ** assume that a stable sort considering the first P3 fields of each
003648  ** key is sufficient to produce the required results.
003649  */
003650  case OP_SorterOpen: {
003651    VdbeCursor *pCx;
003652  
003653    assert( pOp->p1>=0 );
003654    assert( pOp->p2>=0 );
003655    pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
003656    if( pCx==0 ) goto no_mem;
003657    pCx->pKeyInfo = pOp->p4.pKeyInfo;
003658    assert( pCx->pKeyInfo->db==db );
003659    assert( pCx->pKeyInfo->enc==ENC(db) );
003660    rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
003661    if( rc ) goto abort_due_to_error;
003662    break;
003663  }
003664  
003665  /* Opcode: SequenceTest P1 P2 * * *
003666  ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
003667  **
003668  ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
003669  ** to P2. Regardless of whether or not the jump is taken, increment the
003670  ** the sequence value.
003671  */
003672  case OP_SequenceTest: {
003673    VdbeCursor *pC;
003674    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
003675    pC = p->apCsr[pOp->p1];
003676    assert( isSorter(pC) );
003677    if( (pC->seqCount++)==0 ){
003678      goto jump_to_p2;
003679    }
003680    break;
003681  }
003682  
003683  /* Opcode: OpenPseudo P1 P2 P3 * *
003684  ** Synopsis: P3 columns in r[P2]
003685  **
003686  ** Open a new cursor that points to a fake table that contains a single
003687  ** row of data.  The content of that one row is the content of memory
003688  ** register P2.  In other words, cursor P1 becomes an alias for the 
003689  ** MEM_Blob content contained in register P2.
003690  **
003691  ** A pseudo-table created by this opcode is used to hold a single
003692  ** row output from the sorter so that the row can be decomposed into
003693  ** individual columns using the OP_Column opcode.  The OP_Column opcode
003694  ** is the only cursor opcode that works with a pseudo-table.
003695  **
003696  ** P3 is the number of fields in the records that will be stored by
003697  ** the pseudo-table.
003698  */
003699  case OP_OpenPseudo: {
003700    VdbeCursor *pCx;
003701  
003702    assert( pOp->p1>=0 );
003703    assert( pOp->p3>=0 );
003704    pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
003705    if( pCx==0 ) goto no_mem;
003706    pCx->nullRow = 1;
003707    pCx->seekResult = pOp->p2;
003708    pCx->isTable = 1;
003709    /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
003710    ** can be safely passed to sqlite3VdbeCursorMoveto().  This avoids a test
003711    ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
003712    ** which is a performance optimization */
003713    pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
003714    assert( pOp->p5==0 );
003715    break;
003716  }
003717  
003718  /* Opcode: Close P1 * * * *
003719  **
003720  ** Close a cursor previously opened as P1.  If P1 is not
003721  ** currently open, this instruction is a no-op.
003722  */
003723  case OP_Close: {
003724    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
003725    sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
003726    p->apCsr[pOp->p1] = 0;
003727    break;
003728  }
003729  
003730  #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
003731  /* Opcode: ColumnsUsed P1 * * P4 *
003732  **
003733  ** This opcode (which only exists if SQLite was compiled with
003734  ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
003735  ** table or index for cursor P1 are used.  P4 is a 64-bit integer
003736  ** (P4_INT64) in which the first 63 bits are one for each of the
003737  ** first 63 columns of the table or index that are actually used
003738  ** by the cursor.  The high-order bit is set if any column after
003739  ** the 64th is used.
003740  */
003741  case OP_ColumnsUsed: {
003742    VdbeCursor *pC;
003743    pC = p->apCsr[pOp->p1];
003744    assert( pC->eCurType==CURTYPE_BTREE );
003745    pC->maskUsed = *(u64*)pOp->p4.pI64;
003746    break;
003747  }
003748  #endif
003749  
003750  /* Opcode: SeekGE P1 P2 P3 P4 *
003751  ** Synopsis: key=r[P3@P4]
003752  **
003753  ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
003754  ** use the value in register P3 as the key.  If cursor P1 refers 
003755  ** to an SQL index, then P3 is the first in an array of P4 registers 
003756  ** that are used as an unpacked index key. 
003757  **
003758  ** Reposition cursor P1 so that  it points to the smallest entry that 
003759  ** is greater than or equal to the key value. If there are no records 
003760  ** greater than or equal to the key and P2 is not zero, then jump to P2.
003761  **
003762  ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
003763  ** opcode will always land on a record that equally equals the key, or
003764  ** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
003765  ** opcode must be followed by an IdxLE opcode with the same arguments.
003766  ** The IdxLE opcode will be skipped if this opcode succeeds, but the
003767  ** IdxLE opcode will be used on subsequent loop iterations.
003768  **
003769  ** This opcode leaves the cursor configured to move in forward order,
003770  ** from the beginning toward the end.  In other words, the cursor is
003771  ** configured to use Next, not Prev.
003772  **
003773  ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
003774  */
003775  /* Opcode: SeekGT P1 P2 P3 P4 *
003776  ** Synopsis: key=r[P3@P4]
003777  **
003778  ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
003779  ** use the value in register P3 as a key. If cursor P1 refers 
003780  ** to an SQL index, then P3 is the first in an array of P4 registers 
003781  ** that are used as an unpacked index key. 
003782  **
003783  ** Reposition cursor P1 so that  it points to the smallest entry that 
003784  ** is greater than the key value. If there are no records greater than 
003785  ** the key and P2 is not zero, then jump to P2.
003786  **
003787  ** This opcode leaves the cursor configured to move in forward order,
003788  ** from the beginning toward the end.  In other words, the cursor is
003789  ** configured to use Next, not Prev.
003790  **
003791  ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
003792  */
003793  /* Opcode: SeekLT P1 P2 P3 P4 * 
003794  ** Synopsis: key=r[P3@P4]
003795  **
003796  ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
003797  ** use the value in register P3 as a key. If cursor P1 refers 
003798  ** to an SQL index, then P3 is the first in an array of P4 registers 
003799  ** that are used as an unpacked index key. 
003800  **
003801  ** Reposition cursor P1 so that  it points to the largest entry that 
003802  ** is less than the key value. If there are no records less than 
003803  ** the key and P2 is not zero, then jump to P2.
003804  **
003805  ** This opcode leaves the cursor configured to move in reverse order,
003806  ** from the end toward the beginning.  In other words, the cursor is
003807  ** configured to use Prev, not Next.
003808  **
003809  ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
003810  */
003811  /* Opcode: SeekLE P1 P2 P3 P4 *
003812  ** Synopsis: key=r[P3@P4]
003813  **
003814  ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
003815  ** use the value in register P3 as a key. If cursor P1 refers 
003816  ** to an SQL index, then P3 is the first in an array of P4 registers 
003817  ** that are used as an unpacked index key. 
003818  **
003819  ** Reposition cursor P1 so that it points to the largest entry that 
003820  ** is less than or equal to the key value. If there are no records 
003821  ** less than or equal to the key and P2 is not zero, then jump to P2.
003822  **
003823  ** This opcode leaves the cursor configured to move in reverse order,
003824  ** from the end toward the beginning.  In other words, the cursor is
003825  ** configured to use Prev, not Next.
003826  **
003827  ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
003828  ** opcode will always land on a record that equally equals the key, or
003829  ** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
003830  ** opcode must be followed by an IdxGE opcode with the same arguments.
003831  ** The IdxGE opcode will be skipped if this opcode succeeds, but the
003832  ** IdxGE opcode will be used on subsequent loop iterations.
003833  **
003834  ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
003835  */
003836  case OP_SeekLT:         /* jump, in3 */
003837  case OP_SeekLE:         /* jump, in3 */
003838  case OP_SeekGE:         /* jump, in3 */
003839  case OP_SeekGT: {       /* jump, in3 */
003840    int res;           /* Comparison result */
003841    int oc;            /* Opcode */
003842    VdbeCursor *pC;    /* The cursor to seek */
003843    UnpackedRecord r;  /* The key to seek for */
003844    int nField;        /* Number of columns or fields in the key */
003845    i64 iKey;          /* The rowid we are to seek to */
003846    int eqOnly;        /* Only interested in == results */
003847  
003848    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
003849    assert( pOp->p2!=0 );
003850    pC = p->apCsr[pOp->p1];
003851    assert( pC!=0 );
003852    assert( pC->eCurType==CURTYPE_BTREE );
003853    assert( OP_SeekLE == OP_SeekLT+1 );
003854    assert( OP_SeekGE == OP_SeekLT+2 );
003855    assert( OP_SeekGT == OP_SeekLT+3 );
003856    assert( pC->isOrdered );
003857    assert( pC->uc.pCursor!=0 );
003858    oc = pOp->opcode;
003859    eqOnly = 0;
003860    pC->nullRow = 0;
003861  #ifdef SQLITE_DEBUG
003862    pC->seekOp = pOp->opcode;
003863  #endif
003864  
003865    if( pC->isTable ){
003866      /* The BTREE_SEEK_EQ flag is only set on index cursors */
003867      assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
003868                || CORRUPT_DB );
003869  
003870      /* The input value in P3 might be of any type: integer, real, string,
003871      ** blob, or NULL.  But it needs to be an integer before we can do
003872      ** the seek, so convert it. */
003873      pIn3 = &aMem[pOp->p3];
003874      if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
003875        applyNumericAffinity(pIn3, 0);
003876      }
003877      iKey = sqlite3VdbeIntValue(pIn3);
003878  
003879      /* If the P3 value could not be converted into an integer without
003880      ** loss of information, then special processing is required... */
003881      if( (pIn3->flags & MEM_Int)==0 ){
003882        if( (pIn3->flags & MEM_Real)==0 ){
003883          /* If the P3 value cannot be converted into any kind of a number,
003884          ** then the seek is not possible, so jump to P2 */
003885          VdbeBranchTaken(1,2); goto jump_to_p2;
003886          break;
003887        }
003888  
003889        /* If the approximation iKey is larger than the actual real search
003890        ** term, substitute >= for > and < for <=. e.g. if the search term
003891        ** is 4.9 and the integer approximation 5:
003892        **
003893        **        (x >  4.9)    ->     (x >= 5)
003894        **        (x <= 4.9)    ->     (x <  5)
003895        */
003896        if( pIn3->u.r<(double)iKey ){
003897          assert( OP_SeekGE==(OP_SeekGT-1) );
003898          assert( OP_SeekLT==(OP_SeekLE-1) );
003899          assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
003900          if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
003901        }
003902  
003903        /* If the approximation iKey is smaller than the actual real search
003904        ** term, substitute <= for < and > for >=.  */
003905        else if( pIn3->u.r>(double)iKey ){
003906          assert( OP_SeekLE==(OP_SeekLT+1) );
003907          assert( OP_SeekGT==(OP_SeekGE+1) );
003908          assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
003909          if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
003910        }
003911      } 
003912      rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
003913      pC->movetoTarget = iKey;  /* Used by OP_Delete */
003914      if( rc!=SQLITE_OK ){
003915        goto abort_due_to_error;
003916      }
003917    }else{
003918      /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
003919      ** OP_SeekLE opcodes are allowed, and these must be immediately followed
003920      ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
003921      */
003922      if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
003923        eqOnly = 1;
003924        assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
003925        assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
003926        assert( pOp[1].p1==pOp[0].p1 );
003927        assert( pOp[1].p2==pOp[0].p2 );
003928        assert( pOp[1].p3==pOp[0].p3 );
003929        assert( pOp[1].p4.i==pOp[0].p4.i );
003930      }
003931  
003932      nField = pOp->p4.i;
003933      assert( pOp->p4type==P4_INT32 );
003934      assert( nField>0 );
003935      r.pKeyInfo = pC->pKeyInfo;
003936      r.nField = (u16)nField;
003937  
003938      /* The next line of code computes as follows, only faster:
003939      **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
003940      **     r.default_rc = -1;
003941      **   }else{
003942      **     r.default_rc = +1;
003943      **   }
003944      */
003945      r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
003946      assert( oc!=OP_SeekGT || r.default_rc==-1 );
003947      assert( oc!=OP_SeekLE || r.default_rc==-1 );
003948      assert( oc!=OP_SeekGE || r.default_rc==+1 );
003949      assert( oc!=OP_SeekLT || r.default_rc==+1 );
003950  
003951      r.aMem = &aMem[pOp->p3];
003952  #ifdef SQLITE_DEBUG
003953      { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
003954  #endif
003955      r.eqSeen = 0;
003956      rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
003957      if( rc!=SQLITE_OK ){
003958        goto abort_due_to_error;
003959      }
003960      if( eqOnly && r.eqSeen==0 ){
003961        assert( res!=0 );
003962        goto seek_not_found;
003963      }
003964    }
003965    pC->deferredMoveto = 0;
003966    pC->cacheStatus = CACHE_STALE;
003967  #ifdef SQLITE_TEST
003968    sqlite3_search_count++;
003969  #endif
003970    if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
003971      if( res<0 || (res==0 && oc==OP_SeekGT) ){
003972        res = 0;
003973        rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
003974        if( rc!=SQLITE_OK ){
003975          if( rc==SQLITE_DONE ){
003976            rc = SQLITE_OK;
003977            res = 1;
003978          }else{
003979            goto abort_due_to_error;
003980          }
003981        }
003982      }else{
003983        res = 0;
003984      }
003985    }else{
003986      assert( oc==OP_SeekLT || oc==OP_SeekLE );
003987      if( res>0 || (res==0 && oc==OP_SeekLT) ){
003988        res = 0;
003989        rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
003990        if( rc!=SQLITE_OK ){
003991          if( rc==SQLITE_DONE ){
003992            rc = SQLITE_OK;
003993            res = 1;
003994          }else{
003995            goto abort_due_to_error;
003996          }
003997        }
003998      }else{
003999        /* res might be negative because the table is empty.  Check to
004000        ** see if this is the case.
004001        */
004002        res = sqlite3BtreeEof(pC->uc.pCursor);
004003      }
004004    }
004005  seek_not_found:
004006    assert( pOp->p2>0 );
004007    VdbeBranchTaken(res!=0,2);
004008    if( res ){
004009      goto jump_to_p2;
004010    }else if( eqOnly ){
004011      assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
004012      pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
004013    }
004014    break;
004015  }
004016  
004017  /* Opcode: Found P1 P2 P3 P4 *
004018  ** Synopsis: key=r[P3@P4]
004019  **
004020  ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
004021  ** P4>0 then register P3 is the first of P4 registers that form an unpacked
004022  ** record.
004023  **
004024  ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
004025  ** is a prefix of any entry in P1 then a jump is made to P2 and
004026  ** P1 is left pointing at the matching entry.
004027  **
004028  ** This operation leaves the cursor in a state where it can be
004029  ** advanced in the forward direction.  The Next instruction will work,
004030  ** but not the Prev instruction.
004031  **
004032  ** See also: NotFound, NoConflict, NotExists. SeekGe
004033  */
004034  /* Opcode: NotFound P1 P2 P3 P4 *
004035  ** Synopsis: key=r[P3@P4]
004036  **
004037  ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
004038  ** P4>0 then register P3 is the first of P4 registers that form an unpacked
004039  ** record.
004040  ** 
004041  ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
004042  ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
004043  ** does contain an entry whose prefix matches the P3/P4 record then control
004044  ** falls through to the next instruction and P1 is left pointing at the
004045  ** matching entry.
004046  **
004047  ** This operation leaves the cursor in a state where it cannot be
004048  ** advanced in either direction.  In other words, the Next and Prev
004049  ** opcodes do not work after this operation.
004050  **
004051  ** See also: Found, NotExists, NoConflict
004052  */
004053  /* Opcode: NoConflict P1 P2 P3 P4 *
004054  ** Synopsis: key=r[P3@P4]
004055  **
004056  ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
004057  ** P4>0 then register P3 is the first of P4 registers that form an unpacked
004058  ** record.
004059  ** 
004060  ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
004061  ** contains any NULL value, jump immediately to P2.  If all terms of the
004062  ** record are not-NULL then a check is done to determine if any row in the
004063  ** P1 index btree has a matching key prefix.  If there are no matches, jump
004064  ** immediately to P2.  If there is a match, fall through and leave the P1
004065  ** cursor pointing to the matching row.
004066  **
004067  ** This opcode is similar to OP_NotFound with the exceptions that the
004068  ** branch is always taken if any part of the search key input is NULL.
004069  **
004070  ** This operation leaves the cursor in a state where it cannot be
004071  ** advanced in either direction.  In other words, the Next and Prev
004072  ** opcodes do not work after this operation.
004073  **
004074  ** See also: NotFound, Found, NotExists
004075  */
004076  case OP_NoConflict:     /* jump, in3 */
004077  case OP_NotFound:       /* jump, in3 */
004078  case OP_Found: {        /* jump, in3 */
004079    int alreadyExists;
004080    int takeJump;
004081    int ii;
004082    VdbeCursor *pC;
004083    int res;
004084    UnpackedRecord *pFree;
004085    UnpackedRecord *pIdxKey;
004086    UnpackedRecord r;
004087  
004088  #ifdef SQLITE_TEST
004089    if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
004090  #endif
004091  
004092    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
004093    assert( pOp->p4type==P4_INT32 );
004094    pC = p->apCsr[pOp->p1];
004095    assert( pC!=0 );
004096  #ifdef SQLITE_DEBUG
004097    pC->seekOp = pOp->opcode;
004098  #endif
004099    pIn3 = &aMem[pOp->p3];
004100    assert( pC->eCurType==CURTYPE_BTREE );
004101    assert( pC->uc.pCursor!=0 );
004102    assert( pC->isTable==0 );
004103    if( pOp->p4.i>0 ){
004104      r.pKeyInfo = pC->pKeyInfo;
004105      r.nField = (u16)pOp->p4.i;
004106      r.aMem = pIn3;
004107  #ifdef SQLITE_DEBUG
004108      for(ii=0; ii<r.nField; ii++){
004109        assert( memIsValid(&r.aMem[ii]) );
004110        assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
004111        if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
004112      }
004113  #endif
004114      pIdxKey = &r;
004115      pFree = 0;
004116    }else{
004117      assert( pIn3->flags & MEM_Blob );
004118      rc = ExpandBlob(pIn3);
004119      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
004120      if( rc ) goto no_mem;
004121      pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
004122      if( pIdxKey==0 ) goto no_mem;
004123      sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
004124    }
004125    pIdxKey->default_rc = 0;
004126    takeJump = 0;
004127    if( pOp->opcode==OP_NoConflict ){
004128      /* For the OP_NoConflict opcode, take the jump if any of the
004129      ** input fields are NULL, since any key with a NULL will not
004130      ** conflict */
004131      for(ii=0; ii<pIdxKey->nField; ii++){
004132        if( pIdxKey->aMem[ii].flags & MEM_Null ){
004133          takeJump = 1;
004134          break;
004135        }
004136      }
004137    }
004138    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
004139    if( pFree ) sqlite3DbFreeNN(db, pFree);
004140    if( rc!=SQLITE_OK ){
004141      goto abort_due_to_error;
004142    }
004143    pC->seekResult = res;
004144    alreadyExists = (res==0);
004145    pC->nullRow = 1-alreadyExists;
004146    pC->deferredMoveto = 0;
004147    pC->cacheStatus = CACHE_STALE;
004148    if( pOp->opcode==OP_Found ){
004149      VdbeBranchTaken(alreadyExists!=0,2);
004150      if( alreadyExists ) goto jump_to_p2;
004151    }else{
004152      VdbeBranchTaken(takeJump||alreadyExists==0,2);
004153      if( takeJump || !alreadyExists ) goto jump_to_p2;
004154    }
004155    break;
004156  }
004157  
004158  /* Opcode: SeekRowid P1 P2 P3 * *
004159  ** Synopsis: intkey=r[P3]
004160  **
004161  ** P1 is the index of a cursor open on an SQL table btree (with integer
004162  ** keys).  If register P3 does not contain an integer or if P1 does not
004163  ** contain a record with rowid P3 then jump immediately to P2.  
004164  ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
004165  ** a record with rowid P3 then 
004166  ** leave the cursor pointing at that record and fall through to the next
004167  ** instruction.
004168  **
004169  ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
004170  ** the P3 register must be guaranteed to contain an integer value.  With this
004171  ** opcode, register P3 might not contain an integer.
004172  **
004173  ** The OP_NotFound opcode performs the same operation on index btrees
004174  ** (with arbitrary multi-value keys).
004175  **
004176  ** This opcode leaves the cursor in a state where it cannot be advanced
004177  ** in either direction.  In other words, the Next and Prev opcodes will
004178  ** not work following this opcode.
004179  **
004180  ** See also: Found, NotFound, NoConflict, SeekRowid
004181  */
004182  /* Opcode: NotExists P1 P2 P3 * *
004183  ** Synopsis: intkey=r[P3]
004184  **
004185  ** P1 is the index of a cursor open on an SQL table btree (with integer
004186  ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
004187  ** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
004188  ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then 
004189  ** leave the cursor pointing at that record and fall through to the next
004190  ** instruction.
004191  **
004192  ** The OP_SeekRowid opcode performs the same operation but also allows the
004193  ** P3 register to contain a non-integer value, in which case the jump is
004194  ** always taken.  This opcode requires that P3 always contain an integer.
004195  **
004196  ** The OP_NotFound opcode performs the same operation on index btrees
004197  ** (with arbitrary multi-value keys).
004198  **
004199  ** This opcode leaves the cursor in a state where it cannot be advanced
004200  ** in either direction.  In other words, the Next and Prev opcodes will
004201  ** not work following this opcode.
004202  **
004203  ** See also: Found, NotFound, NoConflict, SeekRowid
004204  */
004205  case OP_SeekRowid: {        /* jump, in3 */
004206    VdbeCursor *pC;
004207    BtCursor *pCrsr;
004208    int res;
004209    u64 iKey;
004210  
004211    pIn3 = &aMem[pOp->p3];
004212    if( (pIn3->flags & MEM_Int)==0 ){
004213      applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
004214      if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
004215    }
004216    /* Fall through into OP_NotExists */
004217  case OP_NotExists:          /* jump, in3 */
004218    pIn3 = &aMem[pOp->p3];
004219    assert( pIn3->flags & MEM_Int );
004220    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
004221    pC = p->apCsr[pOp->p1];
004222    assert( pC!=0 );
004223  #ifdef SQLITE_DEBUG
004224    pC->seekOp = 0;
004225  #endif
004226    assert( pC->isTable );
004227    assert( pC->eCurType==CURTYPE_BTREE );
004228    pCrsr = pC->uc.pCursor;
004229    assert( pCrsr!=0 );
004230    res = 0;
004231    iKey = pIn3->u.i;
004232    rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
004233    assert( rc==SQLITE_OK || res==0 );
004234    pC->movetoTarget = iKey;  /* Used by OP_Delete */
004235    pC->nullRow = 0;
004236    pC->cacheStatus = CACHE_STALE;
004237    pC->deferredMoveto = 0;
004238    VdbeBranchTaken(res!=0,2);
004239    pC->seekResult = res;
004240    if( res!=0 ){
004241      assert( rc==SQLITE_OK );
004242      if( pOp->p2==0 ){
004243        rc = SQLITE_CORRUPT_BKPT;
004244      }else{
004245        goto jump_to_p2;
004246      }
004247    }
004248    if( rc ) goto abort_due_to_error;
004249    break;
004250  }
004251  
004252  /* Opcode: Sequence P1 P2 * * *
004253  ** Synopsis: r[P2]=cursor[P1].ctr++
004254  **
004255  ** Find the next available sequence number for cursor P1.
004256  ** Write the sequence number into register P2.
004257  ** The sequence number on the cursor is incremented after this
004258  ** instruction.  
004259  */
004260  case OP_Sequence: {           /* out2 */
004261    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
004262    assert( p->apCsr[pOp->p1]!=0 );
004263    assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
004264    pOut = out2Prerelease(p, pOp);
004265    pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
004266    break;
004267  }
004268  
004269  
004270  /* Opcode: NewRowid P1 P2 P3 * *
004271  ** Synopsis: r[P2]=rowid
004272  **
004273  ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
004274  ** The record number is not previously used as a key in the database
004275  ** table that cursor P1 points to.  The new record number is written
004276  ** written to register P2.
004277  **
004278  ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
004279  ** the largest previously generated record number. No new record numbers are
004280  ** allowed to be less than this value. When this value reaches its maximum, 
004281  ** an SQLITE_FULL error is generated. The P3 register is updated with the '
004282  ** generated record number. This P3 mechanism is used to help implement the
004283  ** AUTOINCREMENT feature.
004284  */
004285  case OP_NewRowid: {           /* out2 */
004286    i64 v;                 /* The new rowid */
004287    VdbeCursor *pC;        /* Cursor of table to get the new rowid */
004288    int res;               /* Result of an sqlite3BtreeLast() */
004289    int cnt;               /* Counter to limit the number of searches */
004290    Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
004291    VdbeFrame *pFrame;     /* Root frame of VDBE */
004292  
004293    v = 0;
004294    res = 0;
004295    pOut = out2Prerelease(p, pOp);
004296    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
004297    pC = p->apCsr[pOp->p1];
004298    assert( pC!=0 );
004299    assert( pC->isTable );
004300    assert( pC->eCurType==CURTYPE_BTREE );
004301    assert( pC->uc.pCursor!=0 );
004302    {
004303      /* The next rowid or record number (different terms for the same
004304      ** thing) is obtained in a two-step algorithm.
004305      **
004306      ** First we attempt to find the largest existing rowid and add one
004307      ** to that.  But if the largest existing rowid is already the maximum
004308      ** positive integer, we have to fall through to the second
004309      ** probabilistic algorithm
004310      **
004311      ** The second algorithm is to select a rowid at random and see if
004312      ** it already exists in the table.  If it does not exist, we have
004313      ** succeeded.  If the random rowid does exist, we select a new one
004314      ** and try again, up to 100 times.
004315      */
004316      assert( pC->isTable );
004317  
004318  #ifdef SQLITE_32BIT_ROWID
004319  #   define MAX_ROWID 0x7fffffff
004320  #else
004321      /* Some compilers complain about constants of the form 0x7fffffffffffffff.
004322      ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
004323      ** to provide the constant while making all compilers happy.
004324      */
004325  #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
004326  #endif
004327  
004328      if( !pC->useRandomRowid ){
004329        rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
004330        if( rc!=SQLITE_OK ){
004331          goto abort_due_to_error;
004332        }
004333        if( res ){
004334          v = 1;   /* IMP: R-61914-48074 */
004335        }else{
004336          assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
004337          v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
004338          if( v>=MAX_ROWID ){
004339            pC->useRandomRowid = 1;
004340          }else{
004341            v++;   /* IMP: R-29538-34987 */
004342          }
004343        }
004344      }
004345  
004346  #ifndef SQLITE_OMIT_AUTOINCREMENT
004347      if( pOp->p3 ){
004348        /* Assert that P3 is a valid memory cell. */
004349        assert( pOp->p3>0 );
004350        if( p->pFrame ){
004351          for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
004352          /* Assert that P3 is a valid memory cell. */
004353          assert( pOp->p3<=pFrame->nMem );
004354          pMem = &pFrame->aMem[pOp->p3];
004355        }else{
004356          /* Assert that P3 is a valid memory cell. */
004357          assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
004358          pMem = &aMem[pOp->p3];
004359          memAboutToChange(p, pMem);
004360        }
004361        assert( memIsValid(pMem) );
004362  
004363        REGISTER_TRACE(pOp->p3, pMem);
004364        sqlite3VdbeMemIntegerify(pMem);
004365        assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
004366        if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
004367          rc = SQLITE_FULL;   /* IMP: R-17817-00630 */
004368          goto abort_due_to_error;
004369        }
004370        if( v<pMem->u.i+1 ){
004371          v = pMem->u.i + 1;
004372        }
004373        pMem->u.i = v;
004374      }
004375  #endif
004376      if( pC->useRandomRowid ){
004377        /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
004378        ** largest possible integer (9223372036854775807) then the database
004379        ** engine starts picking positive candidate ROWIDs at random until
004380        ** it finds one that is not previously used. */
004381        assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
004382                               ** an AUTOINCREMENT table. */
004383        cnt = 0;
004384        do{
004385          sqlite3_randomness(sizeof(v), &v);
004386          v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
004387        }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
004388                                                   0, &res))==SQLITE_OK)
004389              && (res==0)
004390              && (++cnt<100));
004391        if( rc ) goto abort_due_to_error;
004392        if( res==0 ){
004393          rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
004394          goto abort_due_to_error;
004395        }
004396        assert( v>0 );  /* EV: R-40812-03570 */
004397      }
004398      pC->deferredMoveto = 0;
004399      pC->cacheStatus = CACHE_STALE;
004400    }
004401    pOut->u.i = v;
004402    break;
004403  }
004404  
004405  /* Opcode: Insert P1 P2 P3 P4 P5
004406  ** Synopsis: intkey=r[P3] data=r[P2]
004407  **
004408  ** Write an entry into the table of cursor P1.  A new entry is
004409  ** created if it doesn't already exist or the data for an existing
004410  ** entry is overwritten.  The data is the value MEM_Blob stored in register
004411  ** number P2. The key is stored in register P3. The key must
004412  ** be a MEM_Int.
004413  **
004414  ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
004415  ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
004416  ** then rowid is stored for subsequent return by the
004417  ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
004418  **
004419  ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
004420  ** run faster by avoiding an unnecessary seek on cursor P1.  However,
004421  ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
004422  ** seeks on the cursor or if the most recent seek used a key equal to P3.
004423  **
004424  ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
004425  ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
004426  ** is part of an INSERT operation.  The difference is only important to
004427  ** the update hook.
004428  **
004429  ** Parameter P4 may point to a Table structure, or may be NULL. If it is 
004430  ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked 
004431  ** following a successful insert.
004432  **
004433  ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
004434  ** allocated, then ownership of P2 is transferred to the pseudo-cursor
004435  ** and register P2 becomes ephemeral.  If the cursor is changed, the
004436  ** value of register P2 will then change.  Make sure this does not
004437  ** cause any problems.)
004438  **
004439  ** This instruction only works on tables.  The equivalent instruction
004440  ** for indices is OP_IdxInsert.
004441  */
004442  /* Opcode: InsertInt P1 P2 P3 P4 P5
004443  ** Synopsis: intkey=P3 data=r[P2]
004444  **
004445  ** This works exactly like OP_Insert except that the key is the
004446  ** integer value P3, not the value of the integer stored in register P3.
004447  */
004448  case OP_Insert: 
004449  case OP_InsertInt: {
004450    Mem *pData;       /* MEM cell holding data for the record to be inserted */
004451    Mem *pKey;        /* MEM cell holding key  for the record */
004452    VdbeCursor *pC;   /* Cursor to table into which insert is written */
004453    int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
004454    const char *zDb;  /* database name - used by the update hook */
004455    Table *pTab;      /* Table structure - used by update and pre-update hooks */
004456    BtreePayload x;   /* Payload to be inserted */
004457  
004458    pData = &aMem[pOp->p2];
004459    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
004460    assert( memIsValid(pData) );
004461    pC = p->apCsr[pOp->p1];
004462    assert( pC!=0 );
004463    assert( pC->eCurType==CURTYPE_BTREE );
004464    assert( pC->uc.pCursor!=0 );
004465    assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
004466    assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
004467    REGISTER_TRACE(pOp->p2, pData);
004468    sqlite3VdbeIncrWriteCounter(p, pC);
004469  
004470    if( pOp->opcode==OP_Insert ){
004471      pKey = &aMem[pOp->p3];
004472      assert( pKey->flags & MEM_Int );
004473      assert( memIsValid(pKey) );
004474      REGISTER_TRACE(pOp->p3, pKey);
004475      x.nKey = pKey->u.i;
004476    }else{
004477      assert( pOp->opcode==OP_InsertInt );
004478      x.nKey = pOp->p3;
004479    }
004480  
004481    if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
004482      assert( pC->iDb>=0 );
004483      zDb = db->aDb[pC->iDb].zDbSName;
004484      pTab = pOp->p4.pTab;
004485      assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
004486    }else{
004487      pTab = 0;
004488      zDb = 0;  /* Not needed.  Silence a compiler warning. */
004489    }
004490  
004491  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
004492    /* Invoke the pre-update hook, if any */
004493    if( pTab ){
004494      if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
004495        sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
004496      }
004497      if( db->xUpdateCallback==0 || pTab->aCol==0 ){
004498        /* Prevent post-update hook from running in cases when it should not */
004499        pTab = 0;
004500      }
004501    }
004502    if( pOp->p5 & OPFLAG_ISNOOP ) break;
004503  #endif
004504  
004505    if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
004506    if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
004507    assert( pData->flags & (MEM_Blob|MEM_Str) );
004508    x.pData = pData->z;
004509    x.nData = pData->n;
004510    seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
004511    if( pData->flags & MEM_Zero ){
004512      x.nZero = pData->u.nZero;
004513    }else{
004514      x.nZero = 0;
004515    }
004516    x.pKey = 0;
004517    rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
004518        (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
004519    );
004520    pC->deferredMoveto = 0;
004521    pC->cacheStatus = CACHE_STALE;
004522  
004523    /* Invoke the update-hook if required. */
004524    if( rc ) goto abort_due_to_error;
004525    if( pTab ){
004526      assert( db->xUpdateCallback!=0 );
004527      assert( pTab->aCol!=0 );
004528      db->xUpdateCallback(db->pUpdateArg,
004529             (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
004530             zDb, pTab->zName, x.nKey);
004531    }
004532    break;
004533  }
004534  
004535  /* Opcode: Delete P1 P2 P3 P4 P5
004536  **
004537  ** Delete the record at which the P1 cursor is currently pointing.
004538  **
004539  ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
004540  ** the cursor will be left pointing at  either the next or the previous
004541  ** record in the table. If it is left pointing at the next record, then
004542  ** the next Next instruction will be a no-op. As a result, in this case
004543  ** it is ok to delete a record from within a Next loop. If 
004544  ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
004545  ** left in an undefined state.
004546  **
004547  ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
004548  ** delete one of several associated with deleting a table row and all its
004549  ** associated index entries.  Exactly one of those deletes is the "primary"
004550  ** delete.  The others are all on OPFLAG_FORDELETE cursors or else are
004551  ** marked with the AUXDELETE flag.
004552  **
004553  ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
004554  ** change count is incremented (otherwise not).
004555  **
004556  ** P1 must not be pseudo-table.  It has to be a real table with
004557  ** multiple rows.
004558  **
004559  ** If P4 is not NULL then it points to a Table object. In this case either 
004560  ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
004561  ** have been positioned using OP_NotFound prior to invoking this opcode in 
004562  ** this case. Specifically, if one is configured, the pre-update hook is 
004563  ** invoked if P4 is not NULL. The update-hook is invoked if one is configured, 
004564  ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
004565  **
004566  ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
004567  ** of the memory cell that contains the value that the rowid of the row will
004568  ** be set to by the update.
004569  */
004570  case OP_Delete: {
004571    VdbeCursor *pC;
004572    const char *zDb;
004573    Table *pTab;
004574    int opflags;
004575  
004576    opflags = pOp->p2;
004577    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
004578    pC = p->apCsr[pOp->p1];
004579    assert( pC!=0 );
004580    assert( pC->eCurType==CURTYPE_BTREE );
004581    assert( pC->uc.pCursor!=0 );
004582    assert( pC->deferredMoveto==0 );
004583    sqlite3VdbeIncrWriteCounter(p, pC);
004584  
004585  #ifdef SQLITE_DEBUG
004586    if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
004587      /* If p5 is zero, the seek operation that positioned the cursor prior to
004588      ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
004589      ** the row that is being deleted */
004590      i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
004591      assert( pC->movetoTarget==iKey );
004592    }
004593  #endif
004594  
004595    /* If the update-hook or pre-update-hook will be invoked, set zDb to
004596    ** the name of the db to pass as to it. Also set local pTab to a copy
004597    ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
004598    ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set 
004599    ** VdbeCursor.movetoTarget to the current rowid.  */
004600    if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
004601      assert( pC->iDb>=0 );
004602      assert( pOp->p4.pTab!=0 );
004603      zDb = db->aDb[pC->iDb].zDbSName;
004604      pTab = pOp->p4.pTab;
004605      if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
004606        pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
004607      }
004608    }else{
004609      zDb = 0;   /* Not needed.  Silence a compiler warning. */
004610      pTab = 0;  /* Not needed.  Silence a compiler warning. */
004611    }
004612  
004613  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
004614    /* Invoke the pre-update-hook if required. */
004615    if( db->xPreUpdateCallback && pOp->p4.pTab ){
004616      assert( !(opflags & OPFLAG_ISUPDATE) 
004617           || HasRowid(pTab)==0 
004618           || (aMem[pOp->p3].flags & MEM_Int) 
004619      );
004620      sqlite3VdbePreUpdateHook(p, pC,
004621          (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE, 
004622          zDb, pTab, pC->movetoTarget,
004623          pOp->p3
004624      );
004625    }
004626    if( opflags & OPFLAG_ISNOOP ) break;
004627  #endif
004628   
004629    /* Only flags that can be set are SAVEPOISTION and AUXDELETE */ 
004630    assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
004631    assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
004632    assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
004633  
004634  #ifdef SQLITE_DEBUG
004635    if( p->pFrame==0 ){
004636      if( pC->isEphemeral==0
004637          && (pOp->p5 & OPFLAG_AUXDELETE)==0
004638          && (pC->wrFlag & OPFLAG_FORDELETE)==0
004639        ){
004640        nExtraDelete++;
004641      }
004642      if( pOp->p2 & OPFLAG_NCHANGE ){
004643        nExtraDelete--;
004644      }
004645    }
004646  #endif
004647  
004648    rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
004649    pC->cacheStatus = CACHE_STALE;
004650    pC->seekResult = 0;
004651    if( rc ) goto abort_due_to_error;
004652  
004653    /* Invoke the update-hook if required. */
004654    if( opflags & OPFLAG_NCHANGE ){
004655      p->nChange++;
004656      if( db->xUpdateCallback && HasRowid(pTab) ){
004657        db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
004658            pC->movetoTarget);
004659        assert( pC->iDb>=0 );
004660      }
004661    }
004662  
004663    break;
004664  }
004665  /* Opcode: ResetCount * * * * *
004666  **
004667  ** The value of the change counter is copied to the database handle
004668  ** change counter (returned by subsequent calls to sqlite3_changes()).
004669  ** Then the VMs internal change counter resets to 0.
004670  ** This is used by trigger programs.
004671  */
004672  case OP_ResetCount: {
004673    sqlite3VdbeSetChanges(db, p->nChange);
004674    p->nChange = 0;
004675    break;
004676  }
004677  
004678  /* Opcode: SorterCompare P1 P2 P3 P4
004679  ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
004680  **
004681  ** P1 is a sorter cursor. This instruction compares a prefix of the
004682  ** record blob in register P3 against a prefix of the entry that 
004683  ** the sorter cursor currently points to.  Only the first P4 fields
004684  ** of r[P3] and the sorter record are compared.
004685  **
004686  ** If either P3 or the sorter contains a NULL in one of their significant
004687  ** fields (not counting the P4 fields at the end which are ignored) then
004688  ** the comparison is assumed to be equal.
004689  **
004690  ** Fall through to next instruction if the two records compare equal to
004691  ** each other.  Jump to P2 if they are different.
004692  */
004693  case OP_SorterCompare: {
004694    VdbeCursor *pC;
004695    int res;
004696    int nKeyCol;
004697  
004698    pC = p->apCsr[pOp->p1];
004699    assert( isSorter(pC) );
004700    assert( pOp->p4type==P4_INT32 );
004701    pIn3 = &aMem[pOp->p3];
004702    nKeyCol = pOp->p4.i;
004703    res = 0;
004704    rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
004705    VdbeBranchTaken(res!=0,2);
004706    if( rc ) goto abort_due_to_error;
004707    if( res ) goto jump_to_p2;
004708    break;
004709  };
004710  
004711  /* Opcode: SorterData P1 P2 P3 * *
004712  ** Synopsis: r[P2]=data
004713  **
004714  ** Write into register P2 the current sorter data for sorter cursor P1.
004715  ** Then clear the column header cache on cursor P3.
004716  **
004717  ** This opcode is normally use to move a record out of the sorter and into
004718  ** a register that is the source for a pseudo-table cursor created using
004719  ** OpenPseudo.  That pseudo-table cursor is the one that is identified by
004720  ** parameter P3.  Clearing the P3 column cache as part of this opcode saves
004721  ** us from having to issue a separate NullRow instruction to clear that cache.
004722  */
004723  case OP_SorterData: {
004724    VdbeCursor *pC;
004725  
004726    pOut = &aMem[pOp->p2];
004727    pC = p->apCsr[pOp->p1];
004728    assert( isSorter(pC) );
004729    rc = sqlite3VdbeSorterRowkey(pC, pOut);
004730    assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
004731    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
004732    if( rc ) goto abort_due_to_error;
004733    p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
004734    break;
004735  }
004736  
004737  /* Opcode: RowData P1 P2 P3 * *
004738  ** Synopsis: r[P2]=data
004739  **
004740  ** Write into register P2 the complete row content for the row at 
004741  ** which cursor P1 is currently pointing.
004742  ** There is no interpretation of the data.  
004743  ** It is just copied onto the P2 register exactly as 
004744  ** it is found in the database file.
004745  **
004746  ** If cursor P1 is an index, then the content is the key of the row.
004747  ** If cursor P2 is a table, then the content extracted is the data.
004748  **
004749  ** If the P1 cursor must be pointing to a valid row (not a NULL row)
004750  ** of a real table, not a pseudo-table.
004751  **
004752  ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
004753  ** into the database page.  That means that the content of the output
004754  ** register will be invalidated as soon as the cursor moves - including
004755  ** moves caused by other cursors that "save" the current cursors
004756  ** position in order that they can write to the same table.  If P3==0
004757  ** then a copy of the data is made into memory.  P3!=0 is faster, but
004758  ** P3==0 is safer.
004759  **
004760  ** If P3!=0 then the content of the P2 register is unsuitable for use
004761  ** in OP_Result and any OP_Result will invalidate the P2 register content.
004762  ** The P2 register content is invalidated by opcodes like OP_Function or
004763  ** by any use of another cursor pointing to the same table.
004764  */
004765  case OP_RowData: {
004766    VdbeCursor *pC;
004767    BtCursor *pCrsr;
004768    u32 n;
004769  
004770    pOut = out2Prerelease(p, pOp);
004771  
004772    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
004773    pC = p->apCsr[pOp->p1];
004774    assert( pC!=0 );
004775    assert( pC->eCurType==CURTYPE_BTREE );
004776    assert( isSorter(pC)==0 );
004777    assert( pC->nullRow==0 );
004778    assert( pC->uc.pCursor!=0 );
004779    pCrsr = pC->uc.pCursor;
004780  
004781    /* The OP_RowData opcodes always follow OP_NotExists or
004782    ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
004783    ** that might invalidate the cursor.
004784    ** If this where not the case, on of the following assert()s
004785    ** would fail.  Should this ever change (because of changes in the code
004786    ** generator) then the fix would be to insert a call to
004787    ** sqlite3VdbeCursorMoveto().
004788    */
004789    assert( pC->deferredMoveto==0 );
004790    assert( sqlite3BtreeCursorIsValid(pCrsr) );
004791  #if 0  /* Not required due to the previous to assert() statements */
004792    rc = sqlite3VdbeCursorMoveto(pC);
004793    if( rc!=SQLITE_OK ) goto abort_due_to_error;
004794  #endif
004795  
004796    n = sqlite3BtreePayloadSize(pCrsr);
004797    if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
004798      goto too_big;
004799    }
004800    testcase( n==0 );
004801    rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
004802    if( rc ) goto abort_due_to_error;
004803    if( !pOp->p3 ) Deephemeralize(pOut);
004804    UPDATE_MAX_BLOBSIZE(pOut);
004805    REGISTER_TRACE(pOp->p2, pOut);
004806    break;
004807  }
004808  
004809  /* Opcode: Rowid P1 P2 * * *
004810  ** Synopsis: r[P2]=rowid
004811  **
004812  ** Store in register P2 an integer which is the key of the table entry that
004813  ** P1 is currently point to.
004814  **
004815  ** P1 can be either an ordinary table or a virtual table.  There used to
004816  ** be a separate OP_VRowid opcode for use with virtual tables, but this
004817  ** one opcode now works for both table types.
004818  */
004819  case OP_Rowid: {                 /* out2 */
004820    VdbeCursor *pC;
004821    i64 v;
004822    sqlite3_vtab *pVtab;
004823    const sqlite3_module *pModule;
004824  
004825    pOut = out2Prerelease(p, pOp);
004826    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
004827    pC = p->apCsr[pOp->p1];
004828    assert( pC!=0 );
004829    assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
004830    if( pC->nullRow ){
004831      pOut->flags = MEM_Null;
004832      break;
004833    }else if( pC->deferredMoveto ){
004834      v = pC->movetoTarget;
004835  #ifndef SQLITE_OMIT_VIRTUALTABLE
004836    }else if( pC->eCurType==CURTYPE_VTAB ){
004837      assert( pC->uc.pVCur!=0 );
004838      pVtab = pC->uc.pVCur->pVtab;
004839      pModule = pVtab->pModule;
004840      assert( pModule->xRowid );
004841      rc = pModule->xRowid(pC->uc.pVCur, &v);
004842      sqlite3VtabImportErrmsg(p, pVtab);
004843      if( rc ) goto abort_due_to_error;
004844  #endif /* SQLITE_OMIT_VIRTUALTABLE */
004845    }else{
004846      assert( pC->eCurType==CURTYPE_BTREE );
004847      assert( pC->uc.pCursor!=0 );
004848      rc = sqlite3VdbeCursorRestore(pC);
004849      if( rc ) goto abort_due_to_error;
004850      if( pC->nullRow ){
004851        pOut->flags = MEM_Null;
004852        break;
004853      }
004854      v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
004855    }
004856    pOut->u.i = v;
004857    break;
004858  }
004859  
004860  /* Opcode: NullRow P1 * * * *
004861  **
004862  ** Move the cursor P1 to a null row.  Any OP_Column operations
004863  ** that occur while the cursor is on the null row will always
004864  ** write a NULL.
004865  */
004866  case OP_NullRow: {
004867    VdbeCursor *pC;
004868  
004869    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
004870    pC = p->apCsr[pOp->p1];
004871    assert( pC!=0 );
004872    pC->nullRow = 1;
004873    pC->cacheStatus = CACHE_STALE;
004874    if( pC->eCurType==CURTYPE_BTREE ){
004875      assert( pC->uc.pCursor!=0 );
004876      sqlite3BtreeClearCursor(pC->uc.pCursor);
004877    }
004878    break;
004879  }
004880  
004881  /* Opcode: SeekEnd P1 * * * *
004882  **
004883  ** Position cursor P1 at the end of the btree for the purpose of
004884  ** appending a new entry onto the btree.
004885  **
004886  ** It is assumed that the cursor is used only for appending and so
004887  ** if the cursor is valid, then the cursor must already be pointing
004888  ** at the end of the btree and so no changes are made to
004889  ** the cursor.
004890  */
004891  /* Opcode: Last P1 P2 * * *
004892  **
004893  ** The next use of the Rowid or Column or Prev instruction for P1 
004894  ** will refer to the last entry in the database table or index.
004895  ** If the table or index is empty and P2>0, then jump immediately to P2.
004896  ** If P2 is 0 or if the table or index is not empty, fall through
004897  ** to the following instruction.
004898  **
004899  ** This opcode leaves the cursor configured to move in reverse order,
004900  ** from the end toward the beginning.  In other words, the cursor is
004901  ** configured to use Prev, not Next.
004902  */
004903  case OP_SeekEnd:
004904  case OP_Last: {        /* jump */
004905    VdbeCursor *pC;
004906    BtCursor *pCrsr;
004907    int res;
004908  
004909    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
004910    pC = p->apCsr[pOp->p1];
004911    assert( pC!=0 );
004912    assert( pC->eCurType==CURTYPE_BTREE );
004913    pCrsr = pC->uc.pCursor;
004914    res = 0;
004915    assert( pCrsr!=0 );
004916  #ifdef SQLITE_DEBUG
004917    pC->seekOp = pOp->opcode;
004918  #endif
004919    if( pOp->opcode==OP_SeekEnd ){
004920      assert( pOp->p2==0 );
004921      pC->seekResult = -1;
004922      if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
004923        break;
004924      }
004925    }
004926    rc = sqlite3BtreeLast(pCrsr, &res);
004927    pC->nullRow = (u8)res;
004928    pC->deferredMoveto = 0;
004929    pC->cacheStatus = CACHE_STALE;
004930    if( rc ) goto abort_due_to_error;
004931    if( pOp->p2>0 ){
004932      VdbeBranchTaken(res!=0,2);
004933      if( res ) goto jump_to_p2;
004934    }
004935    break;
004936  }
004937  
004938  /* Opcode: IfSmaller P1 P2 P3 * *
004939  **
004940  ** Estimate the number of rows in the table P1.  Jump to P2 if that
004941  ** estimate is less than approximately 2**(0.1*P3).
004942  */
004943  case OP_IfSmaller: {        /* jump */
004944    VdbeCursor *pC;
004945    BtCursor *pCrsr;
004946    int res;
004947    i64 sz;
004948  
004949    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
004950    pC = p->apCsr[pOp->p1];
004951    assert( pC!=0 );
004952    pCrsr = pC->uc.pCursor;
004953    assert( pCrsr );
004954    rc = sqlite3BtreeFirst(pCrsr, &res);
004955    if( rc ) goto abort_due_to_error;
004956    if( res==0 ){
004957      sz = sqlite3BtreeRowCountEst(pCrsr);
004958      if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
004959    }
004960    VdbeBranchTaken(res!=0,2);
004961    if( res ) goto jump_to_p2;
004962    break;
004963  }
004964  
004965  
004966  /* Opcode: SorterSort P1 P2 * * *
004967  **
004968  ** After all records have been inserted into the Sorter object
004969  ** identified by P1, invoke this opcode to actually do the sorting.
004970  ** Jump to P2 if there are no records to be sorted.
004971  **
004972  ** This opcode is an alias for OP_Sort and OP_Rewind that is used
004973  ** for Sorter objects.
004974  */
004975  /* Opcode: Sort P1 P2 * * *
004976  **
004977  ** This opcode does exactly the same thing as OP_Rewind except that
004978  ** it increments an undocumented global variable used for testing.
004979  **
004980  ** Sorting is accomplished by writing records into a sorting index,
004981  ** then rewinding that index and playing it back from beginning to
004982  ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
004983  ** rewinding so that the global variable will be incremented and
004984  ** regression tests can determine whether or not the optimizer is
004985  ** correctly optimizing out sorts.
004986  */
004987  case OP_SorterSort:    /* jump */
004988  case OP_Sort: {        /* jump */
004989  #ifdef SQLITE_TEST
004990    sqlite3_sort_count++;
004991    sqlite3_search_count--;
004992  #endif
004993    p->aCounter[SQLITE_STMTSTATUS_SORT]++;
004994    /* Fall through into OP_Rewind */
004995  }
004996  /* Opcode: Rewind P1 P2 * * *
004997  **
004998  ** The next use of the Rowid or Column or Next instruction for P1 
004999  ** will refer to the first entry in the database table or index.
005000  ** If the table or index is empty, jump immediately to P2.
005001  ** If the table or index is not empty, fall through to the following 
005002  ** instruction.
005003  **
005004  ** This opcode leaves the cursor configured to move in forward order,
005005  ** from the beginning toward the end.  In other words, the cursor is
005006  ** configured to use Next, not Prev.
005007  */
005008  case OP_Rewind: {        /* jump */
005009    VdbeCursor *pC;
005010    BtCursor *pCrsr;
005011    int res;
005012  
005013    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
005014    pC = p->apCsr[pOp->p1];
005015    assert( pC!=0 );
005016    assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
005017    res = 1;
005018  #ifdef SQLITE_DEBUG
005019    pC->seekOp = OP_Rewind;
005020  #endif
005021    if( isSorter(pC) ){
005022      rc = sqlite3VdbeSorterRewind(pC, &res);
005023    }else{
005024      assert( pC->eCurType==CURTYPE_BTREE );
005025      pCrsr = pC->uc.pCursor;
005026      assert( pCrsr );
005027      rc = sqlite3BtreeFirst(pCrsr, &res);
005028      pC->deferredMoveto = 0;
005029      pC->cacheStatus = CACHE_STALE;
005030    }
005031    if( rc ) goto abort_due_to_error;
005032    pC->nullRow = (u8)res;
005033    assert( pOp->p2>0 && pOp->p2<p->nOp );
005034    VdbeBranchTaken(res!=0,2);
005035    if( res ) goto jump_to_p2;
005036    break;
005037  }
005038  
005039  /* Opcode: Next P1 P2 P3 P4 P5
005040  **
005041  ** Advance cursor P1 so that it points to the next key/data pair in its
005042  ** table or index.  If there are no more key/value pairs then fall through
005043  ** to the following instruction.  But if the cursor advance was successful,
005044  ** jump immediately to P2.
005045  **
005046  ** The Next opcode is only valid following an SeekGT, SeekGE, or
005047  ** OP_Rewind opcode used to position the cursor.  Next is not allowed
005048  ** to follow SeekLT, SeekLE, or OP_Last.
005049  **
005050  ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
005051  ** been opened prior to this opcode or the program will segfault.
005052  **
005053  ** The P3 value is a hint to the btree implementation. If P3==1, that
005054  ** means P1 is an SQL index and that this instruction could have been
005055  ** omitted if that index had been unique.  P3 is usually 0.  P3 is
005056  ** always either 0 or 1.
005057  **
005058  ** P4 is always of type P4_ADVANCE. The function pointer points to
005059  ** sqlite3BtreeNext().
005060  **
005061  ** If P5 is positive and the jump is taken, then event counter
005062  ** number P5-1 in the prepared statement is incremented.
005063  **
005064  ** See also: Prev, NextIfOpen
005065  */
005066  /* Opcode: NextIfOpen P1 P2 P3 P4 P5
005067  **
005068  ** This opcode works just like Next except that if cursor P1 is not
005069  ** open it behaves a no-op.
005070  */
005071  /* Opcode: Prev P1 P2 P3 P4 P5
005072  **
005073  ** Back up cursor P1 so that it points to the previous key/data pair in its
005074  ** table or index.  If there is no previous key/value pairs then fall through
005075  ** to the following instruction.  But if the cursor backup was successful,
005076  ** jump immediately to P2.
005077  **
005078  **
005079  ** The Prev opcode is only valid following an SeekLT, SeekLE, or
005080  ** OP_Last opcode used to position the cursor.  Prev is not allowed
005081  ** to follow SeekGT, SeekGE, or OP_Rewind.
005082  **
005083  ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
005084  ** not open then the behavior is undefined.
005085  **
005086  ** The P3 value is a hint to the btree implementation. If P3==1, that
005087  ** means P1 is an SQL index and that this instruction could have been
005088  ** omitted if that index had been unique.  P3 is usually 0.  P3 is
005089  ** always either 0 or 1.
005090  **
005091  ** P4 is always of type P4_ADVANCE. The function pointer points to
005092  ** sqlite3BtreePrevious().
005093  **
005094  ** If P5 is positive and the jump is taken, then event counter
005095  ** number P5-1 in the prepared statement is incremented.
005096  */
005097  /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
005098  **
005099  ** This opcode works just like Prev except that if cursor P1 is not
005100  ** open it behaves a no-op.
005101  */
005102  /* Opcode: SorterNext P1 P2 * * P5
005103  **
005104  ** This opcode works just like OP_Next except that P1 must be a
005105  ** sorter object for which the OP_SorterSort opcode has been
005106  ** invoked.  This opcode advances the cursor to the next sorted
005107  ** record, or jumps to P2 if there are no more sorted records.
005108  */
005109  case OP_SorterNext: {  /* jump */
005110    VdbeCursor *pC;
005111  
005112    pC = p->apCsr[pOp->p1];
005113    assert( isSorter(pC) );
005114    rc = sqlite3VdbeSorterNext(db, pC);
005115    goto next_tail;
005116  case OP_PrevIfOpen:    /* jump */
005117  case OP_NextIfOpen:    /* jump */
005118    if( p->apCsr[pOp->p1]==0 ) break;
005119    /* Fall through */
005120  case OP_Prev:          /* jump */
005121  case OP_Next:          /* jump */
005122    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
005123    assert( pOp->p5<ArraySize(p->aCounter) );
005124    pC = p->apCsr[pOp->p1];
005125    assert( pC!=0 );
005126    assert( pC->deferredMoveto==0 );
005127    assert( pC->eCurType==CURTYPE_BTREE );
005128    assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
005129    assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
005130    assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
005131    assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
005132  
005133    /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
005134    ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
005135    assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
005136         || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
005137         || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
005138    assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
005139         || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
005140         || pC->seekOp==OP_Last );
005141  
005142    rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
005143  next_tail:
005144    pC->cacheStatus = CACHE_STALE;
005145    VdbeBranchTaken(rc==SQLITE_OK,2);
005146    if( rc==SQLITE_OK ){
005147      pC->nullRow = 0;
005148      p->aCounter[pOp->p5]++;
005149  #ifdef SQLITE_TEST
005150      sqlite3_search_count++;
005151  #endif
005152      goto jump_to_p2_and_check_for_interrupt;
005153    }
005154    if( rc!=SQLITE_DONE ) goto abort_due_to_error;
005155    rc = SQLITE_OK;
005156    pC->nullRow = 1;
005157    goto check_for_interrupt;
005158  }
005159  
005160  /* Opcode: IdxInsert P1 P2 P3 P4 P5
005161  ** Synopsis: key=r[P2]
005162  **
005163  ** Register P2 holds an SQL index key made using the
005164  ** MakeRecord instructions.  This opcode writes that key
005165  ** into the index P1.  Data for the entry is nil.
005166  **
005167  ** If P4 is not zero, then it is the number of values in the unpacked
005168  ** key of reg(P2).  In that case, P3 is the index of the first register
005169  ** for the unpacked key.  The availability of the unpacked key can sometimes
005170  ** be an optimization.
005171  **
005172  ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
005173  ** that this insert is likely to be an append.
005174  **
005175  ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
005176  ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
005177  ** then the change counter is unchanged.
005178  **
005179  ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
005180  ** run faster by avoiding an unnecessary seek on cursor P1.  However,
005181  ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
005182  ** seeks on the cursor or if the most recent seek used a key equivalent
005183  ** to P2. 
005184  **
005185  ** This instruction only works for indices.  The equivalent instruction
005186  ** for tables is OP_Insert.
005187  */
005188  /* Opcode: SorterInsert P1 P2 * * *
005189  ** Synopsis: key=r[P2]
005190  **
005191  ** Register P2 holds an SQL index key made using the
005192  ** MakeRecord instructions.  This opcode writes that key
005193  ** into the sorter P1.  Data for the entry is nil.
005194  */
005195  case OP_SorterInsert:       /* in2 */
005196  case OP_IdxInsert: {        /* in2 */
005197    VdbeCursor *pC;
005198    BtreePayload x;
005199  
005200    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
005201    pC = p->apCsr[pOp->p1];
005202    sqlite3VdbeIncrWriteCounter(p, pC);
005203    assert( pC!=0 );
005204    assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
005205    pIn2 = &aMem[pOp->p2];
005206    assert( pIn2->flags & MEM_Blob );
005207    if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
005208    assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
005209    assert( pC->isTable==0 );
005210    rc = ExpandBlob(pIn2);
005211    if( rc ) goto abort_due_to_error;
005212    if( pOp->opcode==OP_SorterInsert ){
005213      rc = sqlite3VdbeSorterWrite(pC, pIn2);
005214    }else{
005215      x.nKey = pIn2->n;
005216      x.pKey = pIn2->z;
005217      x.aMem = aMem + pOp->p3;
005218      x.nMem = (u16)pOp->p4.i;
005219      rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
005220           (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), 
005221          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
005222          );
005223      assert( pC->deferredMoveto==0 );
005224      pC->cacheStatus = CACHE_STALE;
005225    }
005226    if( rc) goto abort_due_to_error;
005227    break;
005228  }
005229  
005230  /* Opcode: IdxDelete P1 P2 P3 * *
005231  ** Synopsis: key=r[P2@P3]
005232  **
005233  ** The content of P3 registers starting at register P2 form
005234  ** an unpacked index key. This opcode removes that entry from the 
005235  ** index opened by cursor P1.
005236  */
005237  case OP_IdxDelete: {
005238    VdbeCursor *pC;
005239    BtCursor *pCrsr;
005240    int res;
005241    UnpackedRecord r;
005242  
005243    assert( pOp->p3>0 );
005244    assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
005245    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
005246    pC = p->apCsr[pOp->p1];
005247    assert( pC!=0 );
005248    assert( pC->eCurType==CURTYPE_BTREE );
005249    sqlite3VdbeIncrWriteCounter(p, pC);
005250    pCrsr = pC->uc.pCursor;
005251    assert( pCrsr!=0 );
005252    assert( pOp->p5==0 );
005253    r.pKeyInfo = pC->pKeyInfo;
005254    r.nField = (u16)pOp->p3;
005255    r.default_rc = 0;
005256    r.aMem = &aMem[pOp->p2];
005257    rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
005258    if( rc ) goto abort_due_to_error;
005259    if( res==0 ){
005260      rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
005261      if( rc ) goto abort_due_to_error;
005262    }
005263    assert( pC->deferredMoveto==0 );
005264    pC->cacheStatus = CACHE_STALE;
005265    pC->seekResult = 0;
005266    break;
005267  }
005268  
005269  /* Opcode: DeferredSeek P1 * P3 P4 *
005270  ** Synopsis: Move P3 to P1.rowid if needed
005271  **
005272  ** P1 is an open index cursor and P3 is a cursor on the corresponding
005273  ** table.  This opcode does a deferred seek of the P3 table cursor
005274  ** to the row that corresponds to the current row of P1.
005275  **
005276  ** This is a deferred seek.  Nothing actually happens until
005277  ** the cursor is used to read a record.  That way, if no reads
005278  ** occur, no unnecessary I/O happens.
005279  **
005280  ** P4 may be an array of integers (type P4_INTARRAY) containing
005281  ** one entry for each column in the P3 table.  If array entry a(i)
005282  ** is non-zero, then reading column a(i)-1 from cursor P3 is 
005283  ** equivalent to performing the deferred seek and then reading column i 
005284  ** from P1.  This information is stored in P3 and used to redirect
005285  ** reads against P3 over to P1, thus possibly avoiding the need to
005286  ** seek and read cursor P3.
005287  */
005288  /* Opcode: IdxRowid P1 P2 * * *
005289  ** Synopsis: r[P2]=rowid
005290  **
005291  ** Write into register P2 an integer which is the last entry in the record at
005292  ** the end of the index key pointed to by cursor P1.  This integer should be
005293  ** the rowid of the table entry to which this index entry points.
005294  **
005295  ** See also: Rowid, MakeRecord.
005296  */
005297  case OP_DeferredSeek:
005298  case OP_IdxRowid: {           /* out2 */
005299    VdbeCursor *pC;             /* The P1 index cursor */
005300    VdbeCursor *pTabCur;        /* The P2 table cursor (OP_DeferredSeek only) */
005301    i64 rowid;                  /* Rowid that P1 current points to */
005302  
005303    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
005304    pC = p->apCsr[pOp->p1];
005305    assert( pC!=0 );
005306    assert( pC->eCurType==CURTYPE_BTREE );
005307    assert( pC->uc.pCursor!=0 );
005308    assert( pC->isTable==0 );
005309    assert( pC->deferredMoveto==0 );
005310    assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
005311  
005312    /* The IdxRowid and Seek opcodes are combined because of the commonality
005313    ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
005314    rc = sqlite3VdbeCursorRestore(pC);
005315  
005316    /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
005317    ** out from under the cursor.  That will never happens for an IdxRowid
005318    ** or Seek opcode */
005319    if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
005320  
005321    if( !pC->nullRow ){
005322      rowid = 0;  /* Not needed.  Only used to silence a warning. */
005323      rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
005324      if( rc!=SQLITE_OK ){
005325        goto abort_due_to_error;
005326      }
005327      if( pOp->opcode==OP_DeferredSeek ){
005328        assert( pOp->p3>=0 && pOp->p3<p->nCursor );
005329        pTabCur = p->apCsr[pOp->p3];
005330        assert( pTabCur!=0 );
005331        assert( pTabCur->eCurType==CURTYPE_BTREE );
005332        assert( pTabCur->uc.pCursor!=0 );
005333        assert( pTabCur->isTable );
005334        pTabCur->nullRow = 0;
005335        pTabCur->movetoTarget = rowid;
005336        pTabCur->deferredMoveto = 1;
005337        assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
005338        pTabCur->aAltMap = pOp->p4.ai;
005339        pTabCur->pAltCursor = pC;
005340      }else{
005341        pOut = out2Prerelease(p, pOp);
005342        pOut->u.i = rowid;
005343      }
005344    }else{
005345      assert( pOp->opcode==OP_IdxRowid );
005346      sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
005347    }
005348    break;
005349  }
005350  
005351  /* Opcode: IdxGE P1 P2 P3 P4 P5
005352  ** Synopsis: key=r[P3@P4]
005353  **
005354  ** The P4 register values beginning with P3 form an unpacked index 
005355  ** key that omits the PRIMARY KEY.  Compare this key value against the index 
005356  ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
005357  ** fields at the end.
005358  **
005359  ** If the P1 index entry is greater than or equal to the key value
005360  ** then jump to P2.  Otherwise fall through to the next instruction.
005361  */
005362  /* Opcode: IdxGT P1 P2 P3 P4 P5
005363  ** Synopsis: key=r[P3@P4]
005364  **
005365  ** The P4 register values beginning with P3 form an unpacked index 
005366  ** key that omits the PRIMARY KEY.  Compare this key value against the index 
005367  ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
005368  ** fields at the end.
005369  **
005370  ** If the P1 index entry is greater than the key value
005371  ** then jump to P2.  Otherwise fall through to the next instruction.
005372  */
005373  /* Opcode: IdxLT P1 P2 P3 P4 P5
005374  ** Synopsis: key=r[P3@P4]
005375  **
005376  ** The P4 register values beginning with P3 form an unpacked index 
005377  ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
005378  ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
005379  ** ROWID on the P1 index.
005380  **
005381  ** If the P1 index entry is less than the key value then jump to P2.
005382  ** Otherwise fall through to the next instruction.
005383  */
005384  /* Opcode: IdxLE P1 P2 P3 P4 P5
005385  ** Synopsis: key=r[P3@P4]
005386  **
005387  ** The P4 register values beginning with P3 form an unpacked index 
005388  ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
005389  ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
005390  ** ROWID on the P1 index.
005391  **
005392  ** If the P1 index entry is less than or equal to the key value then jump
005393  ** to P2. Otherwise fall through to the next instruction.
005394  */
005395  case OP_IdxLE:          /* jump */
005396  case OP_IdxGT:          /* jump */
005397  case OP_IdxLT:          /* jump */
005398  case OP_IdxGE:  {       /* jump */
005399    VdbeCursor *pC;
005400    int res;
005401    UnpackedRecord r;
005402  
005403    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
005404    pC = p->apCsr[pOp->p1];
005405    assert( pC!=0 );
005406    assert( pC->isOrdered );
005407    assert( pC->eCurType==CURTYPE_BTREE );
005408    assert( pC->uc.pCursor!=0);
005409    assert( pC->deferredMoveto==0 );
005410    assert( pOp->p5==0 || pOp->p5==1 );
005411    assert( pOp->p4type==P4_INT32 );
005412    r.pKeyInfo = pC->pKeyInfo;
005413    r.nField = (u16)pOp->p4.i;
005414    if( pOp->opcode<OP_IdxLT ){
005415      assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
005416      r.default_rc = -1;
005417    }else{
005418      assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
005419      r.default_rc = 0;
005420    }
005421    r.aMem = &aMem[pOp->p3];
005422  #ifdef SQLITE_DEBUG
005423    { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
005424  #endif
005425    res = 0;  /* Not needed.  Only used to silence a warning. */
005426    rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
005427    assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
005428    if( (pOp->opcode&1)==(OP_IdxLT&1) ){
005429      assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
005430      res = -res;
005431    }else{
005432      assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
005433      res++;
005434    }
005435    VdbeBranchTaken(res>0,2);
005436    if( rc ) goto abort_due_to_error;
005437    if( res>0 ) goto jump_to_p2;
005438    break;
005439  }
005440  
005441  /* Opcode: Destroy P1 P2 P3 * *
005442  **
005443  ** Delete an entire database table or index whose root page in the database
005444  ** file is given by P1.
005445  **
005446  ** The table being destroyed is in the main database file if P3==0.  If
005447  ** P3==1 then the table to be clear is in the auxiliary database file
005448  ** that is used to store tables create using CREATE TEMPORARY TABLE.
005449  **
005450  ** If AUTOVACUUM is enabled then it is possible that another root page
005451  ** might be moved into the newly deleted root page in order to keep all
005452  ** root pages contiguous at the beginning of the database.  The former
005453  ** value of the root page that moved - its value before the move occurred -
005454  ** is stored in register P2. If no page movement was required (because the
005455  ** table being dropped was already the last one in the database) then a 
005456  ** zero is stored in register P2.  If AUTOVACUUM is disabled then a zero 
005457  ** is stored in register P2.
005458  **
005459  ** This opcode throws an error if there are any active reader VMs when
005460  ** it is invoked. This is done to avoid the difficulty associated with 
005461  ** updating existing cursors when a root page is moved in an AUTOVACUUM 
005462  ** database. This error is thrown even if the database is not an AUTOVACUUM 
005463  ** db in order to avoid introducing an incompatibility between autovacuum 
005464  ** and non-autovacuum modes.
005465  **
005466  ** See also: Clear
005467  */
005468  case OP_Destroy: {     /* out2 */
005469    int iMoved;
005470    int iDb;
005471  
005472    sqlite3VdbeIncrWriteCounter(p, 0);
005473    assert( p->readOnly==0 );
005474    assert( pOp->p1>1 );
005475    pOut = out2Prerelease(p, pOp);
005476    pOut->flags = MEM_Null;
005477    if( db->nVdbeRead > db->nVDestroy+1 ){
005478      rc = SQLITE_LOCKED;
005479      p->errorAction = OE_Abort;
005480      goto abort_due_to_error;
005481    }else{
005482      iDb = pOp->p3;
005483      assert( DbMaskTest(p->btreeMask, iDb) );
005484      iMoved = 0;  /* Not needed.  Only to silence a warning. */
005485      rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
005486      pOut->flags = MEM_Int;
005487      pOut->u.i = iMoved;
005488      if( rc ) goto abort_due_to_error;
005489  #ifndef SQLITE_OMIT_AUTOVACUUM
005490      if( iMoved!=0 ){
005491        sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
005492        /* All OP_Destroy operations occur on the same btree */
005493        assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
005494        resetSchemaOnFault = iDb+1;
005495      }
005496  #endif
005497    }
005498    break;
005499  }
005500  
005501  /* Opcode: Clear P1 P2 P3
005502  **
005503  ** Delete all contents of the database table or index whose root page
005504  ** in the database file is given by P1.  But, unlike Destroy, do not
005505  ** remove the table or index from the database file.
005506  **
005507  ** The table being clear is in the main database file if P2==0.  If
005508  ** P2==1 then the table to be clear is in the auxiliary database file
005509  ** that is used to store tables create using CREATE TEMPORARY TABLE.
005510  **
005511  ** If the P3 value is non-zero, then the table referred to must be an
005512  ** intkey table (an SQL table, not an index). In this case the row change 
005513  ** count is incremented by the number of rows in the table being cleared. 
005514  ** If P3 is greater than zero, then the value stored in register P3 is
005515  ** also incremented by the number of rows in the table being cleared.
005516  **
005517  ** See also: Destroy
005518  */
005519  case OP_Clear: {
005520    int nChange;
005521   
005522    sqlite3VdbeIncrWriteCounter(p, 0);
005523    nChange = 0;
005524    assert( p->readOnly==0 );
005525    assert( DbMaskTest(p->btreeMask, pOp->p2) );
005526    rc = sqlite3BtreeClearTable(
005527        db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
005528    );
005529    if( pOp->p3 ){
005530      p->nChange += nChange;
005531      if( pOp->p3>0 ){
005532        assert( memIsValid(&aMem[pOp->p3]) );
005533        memAboutToChange(p, &aMem[pOp->p3]);
005534        aMem[pOp->p3].u.i += nChange;
005535      }
005536    }
005537    if( rc ) goto abort_due_to_error;
005538    break;
005539  }
005540  
005541  /* Opcode: ResetSorter P1 * * * *
005542  **
005543  ** Delete all contents from the ephemeral table or sorter
005544  ** that is open on cursor P1.
005545  **
005546  ** This opcode only works for cursors used for sorting and
005547  ** opened with OP_OpenEphemeral or OP_SorterOpen.
005548  */
005549  case OP_ResetSorter: {
005550    VdbeCursor *pC;
005551   
005552    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
005553    pC = p->apCsr[pOp->p1];
005554    assert( pC!=0 );
005555    if( isSorter(pC) ){
005556      sqlite3VdbeSorterReset(db, pC->uc.pSorter);
005557    }else{
005558      assert( pC->eCurType==CURTYPE_BTREE );
005559      assert( pC->isEphemeral );
005560      rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
005561      if( rc ) goto abort_due_to_error;
005562    }
005563    break;
005564  }
005565  
005566  /* Opcode: CreateBtree P1 P2 P3 * *
005567  ** Synopsis: r[P2]=root iDb=P1 flags=P3
005568  **
005569  ** Allocate a new b-tree in the main database file if P1==0 or in the
005570  ** TEMP database file if P1==1 or in an attached database if
005571  ** P1>1.  The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
005572  ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
005573  ** The root page number of the new b-tree is stored in register P2.
005574  */
005575  case OP_CreateBtree: {          /* out2 */
005576    int pgno;
005577    Db *pDb;
005578  
005579    sqlite3VdbeIncrWriteCounter(p, 0);
005580    pOut = out2Prerelease(p, pOp);
005581    pgno = 0;
005582    assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
005583    assert( pOp->p1>=0 && pOp->p1<db->nDb );
005584    assert( DbMaskTest(p->btreeMask, pOp->p1) );
005585    assert( p->readOnly==0 );
005586    pDb = &db->aDb[pOp->p1];
005587    assert( pDb->pBt!=0 );
005588    rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
005589    if( rc ) goto abort_due_to_error;
005590    pOut->u.i = pgno;
005591    break;
005592  }
005593  
005594  /* Opcode: SqlExec * * * P4 *
005595  **
005596  ** Run the SQL statement or statements specified in the P4 string.
005597  */
005598  case OP_SqlExec: {
005599    sqlite3VdbeIncrWriteCounter(p, 0);
005600    db->nSqlExec++;
005601    rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
005602    db->nSqlExec--;
005603    if( rc ) goto abort_due_to_error;
005604    break;
005605  }
005606  
005607  /* Opcode: ParseSchema P1 * * P4 *
005608  **
005609  ** Read and parse all entries from the SQLITE_MASTER table of database P1
005610  ** that match the WHERE clause P4. 
005611  **
005612  ** This opcode invokes the parser to create a new virtual machine,
005613  ** then runs the new virtual machine.  It is thus a re-entrant opcode.
005614  */
005615  case OP_ParseSchema: {
005616    int iDb;
005617    const char *zMaster;
005618    char *zSql;
005619    InitData initData;
005620  
005621    /* Any prepared statement that invokes this opcode will hold mutexes
005622    ** on every btree.  This is a prerequisite for invoking 
005623    ** sqlite3InitCallback().
005624    */
005625  #ifdef SQLITE_DEBUG
005626    for(iDb=0; iDb<db->nDb; iDb++){
005627      assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
005628    }
005629  #endif
005630  
005631    iDb = pOp->p1;
005632    assert( iDb>=0 && iDb<db->nDb );
005633    assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
005634    /* Used to be a conditional */ {
005635      zMaster = MASTER_NAME;
005636      initData.db = db;
005637      initData.iDb = pOp->p1;
005638      initData.pzErrMsg = &p->zErrMsg;
005639      zSql = sqlite3MPrintf(db,
005640         "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
005641         db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
005642      if( zSql==0 ){
005643        rc = SQLITE_NOMEM_BKPT;
005644      }else{
005645        assert( db->init.busy==0 );
005646        db->init.busy = 1;
005647        initData.rc = SQLITE_OK;
005648        assert( !db->mallocFailed );
005649        rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
005650        if( rc==SQLITE_OK ) rc = initData.rc;
005651        sqlite3DbFreeNN(db, zSql);
005652        db->init.busy = 0;
005653      }
005654    }
005655    if( rc ){
005656      sqlite3ResetAllSchemasOfConnection(db);
005657      if( rc==SQLITE_NOMEM ){
005658        goto no_mem;
005659      }
005660      goto abort_due_to_error;
005661    }
005662    break;  
005663  }
005664  
005665  #if !defined(SQLITE_OMIT_ANALYZE)
005666  /* Opcode: LoadAnalysis P1 * * * *
005667  **
005668  ** Read the sqlite_stat1 table for database P1 and load the content
005669  ** of that table into the internal index hash table.  This will cause
005670  ** the analysis to be used when preparing all subsequent queries.
005671  */
005672  case OP_LoadAnalysis: {
005673    assert( pOp->p1>=0 && pOp->p1<db->nDb );
005674    rc = sqlite3AnalysisLoad(db, pOp->p1);
005675    if( rc ) goto abort_due_to_error;
005676    break;  
005677  }
005678  #endif /* !defined(SQLITE_OMIT_ANALYZE) */
005679  
005680  /* Opcode: DropTable P1 * * P4 *
005681  **
005682  ** Remove the internal (in-memory) data structures that describe
005683  ** the table named P4 in database P1.  This is called after a table
005684  ** is dropped from disk (using the Destroy opcode) in order to keep 
005685  ** the internal representation of the
005686  ** schema consistent with what is on disk.
005687  */
005688  case OP_DropTable: {
005689    sqlite3VdbeIncrWriteCounter(p, 0);
005690    sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
005691    break;
005692  }
005693  
005694  /* Opcode: DropIndex P1 * * P4 *
005695  **
005696  ** Remove the internal (in-memory) data structures that describe
005697  ** the index named P4 in database P1.  This is called after an index
005698  ** is dropped from disk (using the Destroy opcode)
005699  ** in order to keep the internal representation of the
005700  ** schema consistent with what is on disk.
005701  */
005702  case OP_DropIndex: {
005703    sqlite3VdbeIncrWriteCounter(p, 0);
005704    sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
005705    break;
005706  }
005707  
005708  /* Opcode: DropTrigger P1 * * P4 *
005709  **
005710  ** Remove the internal (in-memory) data structures that describe
005711  ** the trigger named P4 in database P1.  This is called after a trigger
005712  ** is dropped from disk (using the Destroy opcode) in order to keep 
005713  ** the internal representation of the
005714  ** schema consistent with what is on disk.
005715  */
005716  case OP_DropTrigger: {
005717    sqlite3VdbeIncrWriteCounter(p, 0);
005718    sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
005719    break;
005720  }
005721  
005722  
005723  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
005724  /* Opcode: IntegrityCk P1 P2 P3 P4 P5
005725  **
005726  ** Do an analysis of the currently open database.  Store in
005727  ** register P1 the text of an error message describing any problems.
005728  ** If no problems are found, store a NULL in register P1.
005729  **
005730  ** The register P3 contains one less than the maximum number of allowed errors.
005731  ** At most reg(P3) errors will be reported.
005732  ** In other words, the analysis stops as soon as reg(P1) errors are 
005733  ** seen.  Reg(P1) is updated with the number of errors remaining.
005734  **
005735  ** The root page numbers of all tables in the database are integers
005736  ** stored in P4_INTARRAY argument.
005737  **
005738  ** If P5 is not zero, the check is done on the auxiliary database
005739  ** file, not the main database file.
005740  **
005741  ** This opcode is used to implement the integrity_check pragma.
005742  */
005743  case OP_IntegrityCk: {
005744    int nRoot;      /* Number of tables to check.  (Number of root pages.) */
005745    int *aRoot;     /* Array of rootpage numbers for tables to be checked */
005746    int nErr;       /* Number of errors reported */
005747    char *z;        /* Text of the error report */
005748    Mem *pnErr;     /* Register keeping track of errors remaining */
005749  
005750    assert( p->bIsReader );
005751    nRoot = pOp->p2;
005752    aRoot = pOp->p4.ai;
005753    assert( nRoot>0 );
005754    assert( aRoot[0]==nRoot );
005755    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
005756    pnErr = &aMem[pOp->p3];
005757    assert( (pnErr->flags & MEM_Int)!=0 );
005758    assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
005759    pIn1 = &aMem[pOp->p1];
005760    assert( pOp->p5<db->nDb );
005761    assert( DbMaskTest(p->btreeMask, pOp->p5) );
005762    z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
005763                                   (int)pnErr->u.i+1, &nErr);
005764    sqlite3VdbeMemSetNull(pIn1);
005765    if( nErr==0 ){
005766      assert( z==0 );
005767    }else if( z==0 ){
005768      goto no_mem;
005769    }else{
005770      pnErr->u.i -= nErr-1;
005771      sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
005772    }
005773    UPDATE_MAX_BLOBSIZE(pIn1);
005774    sqlite3VdbeChangeEncoding(pIn1, encoding);
005775    break;
005776  }
005777  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
005778  
005779  /* Opcode: RowSetAdd P1 P2 * * *
005780  ** Synopsis: rowset(P1)=r[P2]
005781  **
005782  ** Insert the integer value held by register P2 into a RowSet object
005783  ** held in register P1.
005784  **
005785  ** An assertion fails if P2 is not an integer.
005786  */
005787  case OP_RowSetAdd: {       /* in1, in2 */
005788    pIn1 = &aMem[pOp->p1];
005789    pIn2 = &aMem[pOp->p2];
005790    assert( (pIn2->flags & MEM_Int)!=0 );
005791    if( (pIn1->flags & MEM_RowSet)==0 ){
005792      sqlite3VdbeMemSetRowSet(pIn1);
005793      if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
005794    }
005795    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
005796    break;
005797  }
005798  
005799  /* Opcode: RowSetRead P1 P2 P3 * *
005800  ** Synopsis: r[P3]=rowset(P1)
005801  **
005802  ** Extract the smallest value from the RowSet object in P1
005803  ** and put that value into register P3.
005804  ** Or, if RowSet object P1 is initially empty, leave P3
005805  ** unchanged and jump to instruction P2.
005806  */
005807  case OP_RowSetRead: {       /* jump, in1, out3 */
005808    i64 val;
005809  
005810    pIn1 = &aMem[pOp->p1];
005811    if( (pIn1->flags & MEM_RowSet)==0 
005812     || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
005813    ){
005814      /* The boolean index is empty */
005815      sqlite3VdbeMemSetNull(pIn1);
005816      VdbeBranchTaken(1,2);
005817      goto jump_to_p2_and_check_for_interrupt;
005818    }else{
005819      /* A value was pulled from the index */
005820      VdbeBranchTaken(0,2);
005821      sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
005822    }
005823    goto check_for_interrupt;
005824  }
005825  
005826  /* Opcode: RowSetTest P1 P2 P3 P4
005827  ** Synopsis: if r[P3] in rowset(P1) goto P2
005828  **
005829  ** Register P3 is assumed to hold a 64-bit integer value. If register P1
005830  ** contains a RowSet object and that RowSet object contains
005831  ** the value held in P3, jump to register P2. Otherwise, insert the
005832  ** integer in P3 into the RowSet and continue on to the
005833  ** next opcode.
005834  **
005835  ** The RowSet object is optimized for the case where sets of integers
005836  ** are inserted in distinct phases, which each set contains no duplicates.
005837  ** Each set is identified by a unique P4 value. The first set
005838  ** must have P4==0, the final set must have P4==-1, and for all other sets
005839  ** must have P4>0.
005840  **
005841  ** This allows optimizations: (a) when P4==0 there is no need to test
005842  ** the RowSet object for P3, as it is guaranteed not to contain it,
005843  ** (b) when P4==-1 there is no need to insert the value, as it will
005844  ** never be tested for, and (c) when a value that is part of set X is
005845  ** inserted, there is no need to search to see if the same value was
005846  ** previously inserted as part of set X (only if it was previously
005847  ** inserted as part of some other set).
005848  */
005849  case OP_RowSetTest: {                     /* jump, in1, in3 */
005850    int iSet;
005851    int exists;
005852  
005853    pIn1 = &aMem[pOp->p1];
005854    pIn3 = &aMem[pOp->p3];
005855    iSet = pOp->p4.i;
005856    assert( pIn3->flags&MEM_Int );
005857  
005858    /* If there is anything other than a rowset object in memory cell P1,
005859    ** delete it now and initialize P1 with an empty rowset
005860    */
005861    if( (pIn1->flags & MEM_RowSet)==0 ){
005862      sqlite3VdbeMemSetRowSet(pIn1);
005863      if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
005864    }
005865  
005866    assert( pOp->p4type==P4_INT32 );
005867    assert( iSet==-1 || iSet>=0 );
005868    if( iSet ){
005869      exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
005870      VdbeBranchTaken(exists!=0,2);
005871      if( exists ) goto jump_to_p2;
005872    }
005873    if( iSet>=0 ){
005874      sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
005875    }
005876    break;
005877  }
005878  
005879  
005880  #ifndef SQLITE_OMIT_TRIGGER
005881  
005882  /* Opcode: Program P1 P2 P3 P4 P5
005883  **
005884  ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
005885  **
005886  ** P1 contains the address of the memory cell that contains the first memory 
005887  ** cell in an array of values used as arguments to the sub-program. P2 
005888  ** contains the address to jump to if the sub-program throws an IGNORE 
005889  ** exception using the RAISE() function. Register P3 contains the address 
005890  ** of a memory cell in this (the parent) VM that is used to allocate the 
005891  ** memory required by the sub-vdbe at runtime.
005892  **
005893  ** P4 is a pointer to the VM containing the trigger program.
005894  **
005895  ** If P5 is non-zero, then recursive program invocation is enabled.
005896  */
005897  case OP_Program: {        /* jump */
005898    int nMem;               /* Number of memory registers for sub-program */
005899    int nByte;              /* Bytes of runtime space required for sub-program */
005900    Mem *pRt;               /* Register to allocate runtime space */
005901    Mem *pMem;              /* Used to iterate through memory cells */
005902    Mem *pEnd;              /* Last memory cell in new array */
005903    VdbeFrame *pFrame;      /* New vdbe frame to execute in */
005904    SubProgram *pProgram;   /* Sub-program to execute */
005905    void *t;                /* Token identifying trigger */
005906  
005907    pProgram = pOp->p4.pProgram;
005908    pRt = &aMem[pOp->p3];
005909    assert( pProgram->nOp>0 );
005910    
005911    /* If the p5 flag is clear, then recursive invocation of triggers is 
005912    ** disabled for backwards compatibility (p5 is set if this sub-program
005913    ** is really a trigger, not a foreign key action, and the flag set
005914    ** and cleared by the "PRAGMA recursive_triggers" command is clear).
005915    ** 
005916    ** It is recursive invocation of triggers, at the SQL level, that is 
005917    ** disabled. In some cases a single trigger may generate more than one 
005918    ** SubProgram (if the trigger may be executed with more than one different 
005919    ** ON CONFLICT algorithm). SubProgram structures associated with a
005920    ** single trigger all have the same value for the SubProgram.token 
005921    ** variable.  */
005922    if( pOp->p5 ){
005923      t = pProgram->token;
005924      for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
005925      if( pFrame ) break;
005926    }
005927  
005928    if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
005929      rc = SQLITE_ERROR;
005930      sqlite3VdbeError(p, "too many levels of trigger recursion");
005931      goto abort_due_to_error;
005932    }
005933  
005934    /* Register pRt is used to store the memory required to save the state
005935    ** of the current program, and the memory required at runtime to execute
005936    ** the trigger program. If this trigger has been fired before, then pRt 
005937    ** is already allocated. Otherwise, it must be initialized.  */
005938    if( (pRt->flags&MEM_Frame)==0 ){
005939      /* SubProgram.nMem is set to the number of memory cells used by the 
005940      ** program stored in SubProgram.aOp. As well as these, one memory
005941      ** cell is required for each cursor used by the program. Set local
005942      ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
005943      */
005944      nMem = pProgram->nMem + pProgram->nCsr;
005945      assert( nMem>0 );
005946      if( pProgram->nCsr==0 ) nMem++;
005947      nByte = ROUND8(sizeof(VdbeFrame))
005948                + nMem * sizeof(Mem)
005949                + pProgram->nCsr * sizeof(VdbeCursor*)
005950                + (pProgram->nOp + 7)/8;
005951      pFrame = sqlite3DbMallocZero(db, nByte);
005952      if( !pFrame ){
005953        goto no_mem;
005954      }
005955      sqlite3VdbeMemRelease(pRt);
005956      pRt->flags = MEM_Frame;
005957      pRt->u.pFrame = pFrame;
005958  
005959      pFrame->v = p;
005960      pFrame->nChildMem = nMem;
005961      pFrame->nChildCsr = pProgram->nCsr;
005962      pFrame->pc = (int)(pOp - aOp);
005963      pFrame->aMem = p->aMem;
005964      pFrame->nMem = p->nMem;
005965      pFrame->apCsr = p->apCsr;
005966      pFrame->nCursor = p->nCursor;
005967      pFrame->aOp = p->aOp;
005968      pFrame->nOp = p->nOp;
005969      pFrame->token = pProgram->token;
005970  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
005971      pFrame->anExec = p->anExec;
005972  #endif
005973  
005974      pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
005975      for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
005976        pMem->flags = MEM_Undefined;
005977        pMem->db = db;
005978      }
005979    }else{
005980      pFrame = pRt->u.pFrame;
005981      assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem 
005982          || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
005983      assert( pProgram->nCsr==pFrame->nChildCsr );
005984      assert( (int)(pOp - aOp)==pFrame->pc );
005985    }
005986  
005987    p->nFrame++;
005988    pFrame->pParent = p->pFrame;
005989    pFrame->lastRowid = db->lastRowid;
005990    pFrame->nChange = p->nChange;
005991    pFrame->nDbChange = p->db->nChange;
005992    assert( pFrame->pAuxData==0 );
005993    pFrame->pAuxData = p->pAuxData;
005994    p->pAuxData = 0;
005995    p->nChange = 0;
005996    p->pFrame = pFrame;
005997    p->aMem = aMem = VdbeFrameMem(pFrame);
005998    p->nMem = pFrame->nChildMem;
005999    p->nCursor = (u16)pFrame->nChildCsr;
006000    p->apCsr = (VdbeCursor **)&aMem[p->nMem];
006001    pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
006002    memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
006003    p->aOp = aOp = pProgram->aOp;
006004    p->nOp = pProgram->nOp;
006005  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
006006    p->anExec = 0;
006007  #endif
006008    pOp = &aOp[-1];
006009  
006010    break;
006011  }
006012  
006013  /* Opcode: Param P1 P2 * * *
006014  **
006015  ** This opcode is only ever present in sub-programs called via the 
006016  ** OP_Program instruction. Copy a value currently stored in a memory 
006017  ** cell of the calling (parent) frame to cell P2 in the current frames 
006018  ** address space. This is used by trigger programs to access the new.* 
006019  ** and old.* values.
006020  **
006021  ** The address of the cell in the parent frame is determined by adding
006022  ** the value of the P1 argument to the value of the P1 argument to the
006023  ** calling OP_Program instruction.
006024  */
006025  case OP_Param: {           /* out2 */
006026    VdbeFrame *pFrame;
006027    Mem *pIn;
006028    pOut = out2Prerelease(p, pOp);
006029    pFrame = p->pFrame;
006030    pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];   
006031    sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
006032    break;
006033  }
006034  
006035  #endif /* #ifndef SQLITE_OMIT_TRIGGER */
006036  
006037  #ifndef SQLITE_OMIT_FOREIGN_KEY
006038  /* Opcode: FkCounter P1 P2 * * *
006039  ** Synopsis: fkctr[P1]+=P2
006040  **
006041  ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
006042  ** If P1 is non-zero, the database constraint counter is incremented 
006043  ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
006044  ** statement counter is incremented (immediate foreign key constraints).
006045  */
006046  case OP_FkCounter: {
006047    if( db->flags & SQLITE_DeferFKs ){
006048      db->nDeferredImmCons += pOp->p2;
006049    }else if( pOp->p1 ){
006050      db->nDeferredCons += pOp->p2;
006051    }else{
006052      p->nFkConstraint += pOp->p2;
006053    }
006054    break;
006055  }
006056  
006057  /* Opcode: FkIfZero P1 P2 * * *
006058  ** Synopsis: if fkctr[P1]==0 goto P2
006059  **
006060  ** This opcode tests if a foreign key constraint-counter is currently zero.
006061  ** If so, jump to instruction P2. Otherwise, fall through to the next 
006062  ** instruction.
006063  **
006064  ** If P1 is non-zero, then the jump is taken if the database constraint-counter
006065  ** is zero (the one that counts deferred constraint violations). If P1 is
006066  ** zero, the jump is taken if the statement constraint-counter is zero
006067  ** (immediate foreign key constraint violations).
006068  */
006069  case OP_FkIfZero: {         /* jump */
006070    if( pOp->p1 ){
006071      VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
006072      if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
006073    }else{
006074      VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
006075      if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
006076    }
006077    break;
006078  }
006079  #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
006080  
006081  #ifndef SQLITE_OMIT_AUTOINCREMENT
006082  /* Opcode: MemMax P1 P2 * * *
006083  ** Synopsis: r[P1]=max(r[P1],r[P2])
006084  **
006085  ** P1 is a register in the root frame of this VM (the root frame is
006086  ** different from the current frame if this instruction is being executed
006087  ** within a sub-program). Set the value of register P1 to the maximum of 
006088  ** its current value and the value in register P2.
006089  **
006090  ** This instruction throws an error if the memory cell is not initially
006091  ** an integer.
006092  */
006093  case OP_MemMax: {        /* in2 */
006094    VdbeFrame *pFrame;
006095    if( p->pFrame ){
006096      for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
006097      pIn1 = &pFrame->aMem[pOp->p1];
006098    }else{
006099      pIn1 = &aMem[pOp->p1];
006100    }
006101    assert( memIsValid(pIn1) );
006102    sqlite3VdbeMemIntegerify(pIn1);
006103    pIn2 = &aMem[pOp->p2];
006104    sqlite3VdbeMemIntegerify(pIn2);
006105    if( pIn1->u.i<pIn2->u.i){
006106      pIn1->u.i = pIn2->u.i;
006107    }
006108    break;
006109  }
006110  #endif /* SQLITE_OMIT_AUTOINCREMENT */
006111  
006112  /* Opcode: IfPos P1 P2 P3 * *
006113  ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
006114  **
006115  ** Register P1 must contain an integer.
006116  ** If the value of register P1 is 1 or greater, subtract P3 from the
006117  ** value in P1 and jump to P2.
006118  **
006119  ** If the initial value of register P1 is less than 1, then the
006120  ** value is unchanged and control passes through to the next instruction.
006121  */
006122  case OP_IfPos: {        /* jump, in1 */
006123    pIn1 = &aMem[pOp->p1];
006124    assert( pIn1->flags&MEM_Int );
006125    VdbeBranchTaken( pIn1->u.i>0, 2);
006126    if( pIn1->u.i>0 ){
006127      pIn1->u.i -= pOp->p3;
006128      goto jump_to_p2;
006129    }
006130    break;
006131  }
006132  
006133  /* Opcode: OffsetLimit P1 P2 P3 * *
006134  ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
006135  **
006136  ** This opcode performs a commonly used computation associated with
006137  ** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]
006138  ** holds the offset counter.  The opcode computes the combined value
006139  ** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
006140  ** value computed is the total number of rows that will need to be
006141  ** visited in order to complete the query.
006142  **
006143  ** If r[P3] is zero or negative, that means there is no OFFSET
006144  ** and r[P2] is set to be the value of the LIMIT, r[P1].
006145  **
006146  ** if r[P1] is zero or negative, that means there is no LIMIT
006147  ** and r[P2] is set to -1. 
006148  **
006149  ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
006150  */
006151  case OP_OffsetLimit: {    /* in1, out2, in3 */
006152    i64 x;
006153    pIn1 = &aMem[pOp->p1];
006154    pIn3 = &aMem[pOp->p3];
006155    pOut = out2Prerelease(p, pOp);
006156    assert( pIn1->flags & MEM_Int );
006157    assert( pIn3->flags & MEM_Int );
006158    x = pIn1->u.i;
006159    if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
006160      /* If the LIMIT is less than or equal to zero, loop forever.  This
006161      ** is documented.  But also, if the LIMIT+OFFSET exceeds 2^63 then
006162      ** also loop forever.  This is undocumented.  In fact, one could argue
006163      ** that the loop should terminate.  But assuming 1 billion iterations
006164      ** per second (far exceeding the capabilities of any current hardware)
006165      ** it would take nearly 300 years to actually reach the limit.  So
006166      ** looping forever is a reasonable approximation. */
006167      pOut->u.i = -1;
006168    }else{
006169      pOut->u.i = x;
006170    }
006171    break;
006172  }
006173  
006174  /* Opcode: IfNotZero P1 P2 * * *
006175  ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
006176  **
006177  ** Register P1 must contain an integer.  If the content of register P1 is
006178  ** initially greater than zero, then decrement the value in register P1.
006179  ** If it is non-zero (negative or positive) and then also jump to P2.  
006180  ** If register P1 is initially zero, leave it unchanged and fall through.
006181  */
006182  case OP_IfNotZero: {        /* jump, in1 */
006183    pIn1 = &aMem[pOp->p1];
006184    assert( pIn1->flags&MEM_Int );
006185    VdbeBranchTaken(pIn1->u.i<0, 2);
006186    if( pIn1->u.i ){
006187       if( pIn1->u.i>0 ) pIn1->u.i--;
006188       goto jump_to_p2;
006189    }
006190    break;
006191  }
006192  
006193  /* Opcode: DecrJumpZero P1 P2 * * *
006194  ** Synopsis: if (--r[P1])==0 goto P2
006195  **
006196  ** Register P1 must hold an integer.  Decrement the value in P1
006197  ** and jump to P2 if the new value is exactly zero.
006198  */
006199  case OP_DecrJumpZero: {      /* jump, in1 */
006200    pIn1 = &aMem[pOp->p1];
006201    assert( pIn1->flags&MEM_Int );
006202    if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
006203    VdbeBranchTaken(pIn1->u.i==0, 2);
006204    if( pIn1->u.i==0 ) goto jump_to_p2;
006205    break;
006206  }
006207  
006208  
006209  /* Opcode: AggStep0 * P2 P3 P4 P5
006210  ** Synopsis: accum=r[P3] step(r[P2@P5])
006211  **
006212  ** Execute the step function for an aggregate.  The
006213  ** function has P5 arguments.   P4 is a pointer to the FuncDef
006214  ** structure that specifies the function.  Register P3 is the
006215  ** accumulator.
006216  **
006217  ** The P5 arguments are taken from register P2 and its
006218  ** successors.
006219  */
006220  /* Opcode: AggStep * P2 P3 P4 P5
006221  ** Synopsis: accum=r[P3] step(r[P2@P5])
006222  **
006223  ** Execute the step function for an aggregate.  The
006224  ** function has P5 arguments.   P4 is a pointer to an sqlite3_context
006225  ** object that is used to run the function.  Register P3 is
006226  ** as the accumulator.
006227  **
006228  ** The P5 arguments are taken from register P2 and its
006229  ** successors.
006230  **
006231  ** This opcode is initially coded as OP_AggStep0.  On first evaluation,
006232  ** the FuncDef stored in P4 is converted into an sqlite3_context and
006233  ** the opcode is changed.  In this way, the initialization of the
006234  ** sqlite3_context only happens once, instead of on each call to the
006235  ** step function.
006236  */
006237  case OP_AggStep0: {
006238    int n;
006239    sqlite3_context *pCtx;
006240  
006241    assert( pOp->p4type==P4_FUNCDEF );
006242    n = pOp->p5;
006243    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
006244    assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
006245    assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
006246    pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
006247                 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
006248    if( pCtx==0 ) goto no_mem;
006249    pCtx->pMem = 0;
006250    pCtx->pOut = (Mem*)&(pCtx->argv[n]);
006251    sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
006252    pCtx->pFunc = pOp->p4.pFunc;
006253    pCtx->iOp = (int)(pOp - aOp);
006254    pCtx->pVdbe = p;
006255    pCtx->skipFlag = 0;
006256    pCtx->isError = 0;
006257    pCtx->argc = n;
006258    pOp->p4type = P4_FUNCCTX;
006259    pOp->p4.pCtx = pCtx;
006260    pOp->opcode = OP_AggStep;
006261    /* Fall through into OP_AggStep */
006262  }
006263  case OP_AggStep: {
006264    int i;
006265    sqlite3_context *pCtx;
006266    Mem *pMem;
006267  
006268    assert( pOp->p4type==P4_FUNCCTX );
006269    pCtx = pOp->p4.pCtx;
006270    pMem = &aMem[pOp->p3];
006271  
006272    /* If this function is inside of a trigger, the register array in aMem[]
006273    ** might change from one evaluation to the next.  The next block of code
006274    ** checks to see if the register array has changed, and if so it
006275    ** reinitializes the relavant parts of the sqlite3_context object */
006276    if( pCtx->pMem != pMem ){
006277      pCtx->pMem = pMem;
006278      for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
006279    }
006280  
006281  #ifdef SQLITE_DEBUG
006282    for(i=0; i<pCtx->argc; i++){
006283      assert( memIsValid(pCtx->argv[i]) );
006284      REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
006285    }
006286  #endif
006287  
006288    pMem->n++;
006289    assert( pCtx->pOut->flags==MEM_Null );
006290    assert( pCtx->isError==0 );
006291    assert( pCtx->skipFlag==0 );
006292    (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
006293    if( pCtx->isError ){
006294      if( pCtx->isError>0 ){
006295        sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
006296        rc = pCtx->isError;
006297      }
006298      if( pCtx->skipFlag ){
006299        assert( pOp[-1].opcode==OP_CollSeq );
006300        i = pOp[-1].p1;
006301        if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
006302        pCtx->skipFlag = 0;
006303      }
006304      sqlite3VdbeMemRelease(pCtx->pOut);
006305      pCtx->pOut->flags = MEM_Null;
006306      pCtx->isError = 0;
006307      if( rc ) goto abort_due_to_error;
006308    }
006309    assert( pCtx->pOut->flags==MEM_Null );
006310    assert( pCtx->skipFlag==0 );
006311    break;
006312  }
006313  
006314  /* Opcode: AggFinal P1 P2 * P4 *
006315  ** Synopsis: accum=r[P1] N=P2
006316  **
006317  ** Execute the finalizer function for an aggregate.  P1 is
006318  ** the memory location that is the accumulator for the aggregate.
006319  **
006320  ** P2 is the number of arguments that the step function takes and
006321  ** P4 is a pointer to the FuncDef for this function.  The P2
006322  ** argument is not used by this opcode.  It is only there to disambiguate
006323  ** functions that can take varying numbers of arguments.  The
006324  ** P4 argument is only needed for the degenerate case where
006325  ** the step function was not previously called.
006326  */
006327  case OP_AggFinal: {
006328    Mem *pMem;
006329    assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
006330    pMem = &aMem[pOp->p1];
006331    assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
006332    rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
006333    if( rc ){
006334      sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
006335      goto abort_due_to_error;
006336    }
006337    sqlite3VdbeChangeEncoding(pMem, encoding);
006338    UPDATE_MAX_BLOBSIZE(pMem);
006339    if( sqlite3VdbeMemTooBig(pMem) ){
006340      goto too_big;
006341    }
006342    break;
006343  }
006344  
006345  #ifndef SQLITE_OMIT_WAL
006346  /* Opcode: Checkpoint P1 P2 P3 * *
006347  **
006348  ** Checkpoint database P1. This is a no-op if P1 is not currently in
006349  ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
006350  ** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
006351  ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
006352  ** WAL after the checkpoint into mem[P3+1] and the number of pages
006353  ** in the WAL that have been checkpointed after the checkpoint
006354  ** completes into mem[P3+2].  However on an error, mem[P3+1] and
006355  ** mem[P3+2] are initialized to -1.
006356  */
006357  case OP_Checkpoint: {
006358    int i;                          /* Loop counter */
006359    int aRes[3];                    /* Results */
006360    Mem *pMem;                      /* Write results here */
006361  
006362    assert( p->readOnly==0 );
006363    aRes[0] = 0;
006364    aRes[1] = aRes[2] = -1;
006365    assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
006366         || pOp->p2==SQLITE_CHECKPOINT_FULL
006367         || pOp->p2==SQLITE_CHECKPOINT_RESTART
006368         || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
006369    );
006370    rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
006371    if( rc ){
006372      if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
006373      rc = SQLITE_OK;
006374      aRes[0] = 1;
006375    }
006376    for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
006377      sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
006378    }    
006379    break;
006380  };  
006381  #endif
006382  
006383  #ifndef SQLITE_OMIT_PRAGMA
006384  /* Opcode: JournalMode P1 P2 P3 * *
006385  **
006386  ** Change the journal mode of database P1 to P3. P3 must be one of the
006387  ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
006388  ** modes (delete, truncate, persist, off and memory), this is a simple
006389  ** operation. No IO is required.
006390  **
006391  ** If changing into or out of WAL mode the procedure is more complicated.
006392  **
006393  ** Write a string containing the final journal-mode to register P2.
006394  */
006395  case OP_JournalMode: {    /* out2 */
006396    Btree *pBt;                     /* Btree to change journal mode of */
006397    Pager *pPager;                  /* Pager associated with pBt */
006398    int eNew;                       /* New journal mode */
006399    int eOld;                       /* The old journal mode */
006400  #ifndef SQLITE_OMIT_WAL
006401    const char *zFilename;          /* Name of database file for pPager */
006402  #endif
006403  
006404    pOut = out2Prerelease(p, pOp);
006405    eNew = pOp->p3;
006406    assert( eNew==PAGER_JOURNALMODE_DELETE 
006407         || eNew==PAGER_JOURNALMODE_TRUNCATE 
006408         || eNew==PAGER_JOURNALMODE_PERSIST 
006409         || eNew==PAGER_JOURNALMODE_OFF
006410         || eNew==PAGER_JOURNALMODE_MEMORY
006411         || eNew==PAGER_JOURNALMODE_WAL
006412         || eNew==PAGER_JOURNALMODE_QUERY
006413    );
006414    assert( pOp->p1>=0 && pOp->p1<db->nDb );
006415    assert( p->readOnly==0 );
006416  
006417    pBt = db->aDb[pOp->p1].pBt;
006418    pPager = sqlite3BtreePager(pBt);
006419    eOld = sqlite3PagerGetJournalMode(pPager);
006420    if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
006421    if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
006422  
006423  #ifndef SQLITE_OMIT_WAL
006424    zFilename = sqlite3PagerFilename(pPager, 1);
006425  
006426    /* Do not allow a transition to journal_mode=WAL for a database
006427    ** in temporary storage or if the VFS does not support shared memory 
006428    */
006429    if( eNew==PAGER_JOURNALMODE_WAL
006430     && (sqlite3Strlen30(zFilename)==0           /* Temp file */
006431         || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
006432    ){
006433      eNew = eOld;
006434    }
006435  
006436    if( (eNew!=eOld)
006437     && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
006438    ){
006439      if( !db->autoCommit || db->nVdbeRead>1 ){
006440        rc = SQLITE_ERROR;
006441        sqlite3VdbeError(p,
006442            "cannot change %s wal mode from within a transaction",
006443            (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
006444        );
006445        goto abort_due_to_error;
006446      }else{
006447   
006448        if( eOld==PAGER_JOURNALMODE_WAL ){
006449          /* If leaving WAL mode, close the log file. If successful, the call
006450          ** to PagerCloseWal() checkpoints and deletes the write-ahead-log 
006451          ** file. An EXCLUSIVE lock may still be held on the database file 
006452          ** after a successful return. 
006453          */
006454          rc = sqlite3PagerCloseWal(pPager, db);
006455          if( rc==SQLITE_OK ){
006456            sqlite3PagerSetJournalMode(pPager, eNew);
006457          }
006458        }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
006459          /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
006460          ** as an intermediate */
006461          sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
006462        }
006463    
006464        /* Open a transaction on the database file. Regardless of the journal
006465        ** mode, this transaction always uses a rollback journal.
006466        */
006467        assert( sqlite3BtreeIsInTrans(pBt)==0 );
006468        if( rc==SQLITE_OK ){
006469          rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
006470        }
006471      }
006472    }
006473  #endif /* ifndef SQLITE_OMIT_WAL */
006474  
006475    if( rc ) eNew = eOld;
006476    eNew = sqlite3PagerSetJournalMode(pPager, eNew);
006477  
006478    pOut->flags = MEM_Str|MEM_Static|MEM_Term;
006479    pOut->z = (char *)sqlite3JournalModename(eNew);
006480    pOut->n = sqlite3Strlen30(pOut->z);
006481    pOut->enc = SQLITE_UTF8;
006482    sqlite3VdbeChangeEncoding(pOut, encoding);
006483    if( rc ) goto abort_due_to_error;
006484    break;
006485  };
006486  #endif /* SQLITE_OMIT_PRAGMA */
006487  
006488  #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
006489  /* Opcode: Vacuum P1 * * * *
006490  **
006491  ** Vacuum the entire database P1.  P1 is 0 for "main", and 2 or more
006492  ** for an attached database.  The "temp" database may not be vacuumed.
006493  */
006494  case OP_Vacuum: {
006495    assert( p->readOnly==0 );
006496    rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
006497    if( rc ) goto abort_due_to_error;
006498    break;
006499  }
006500  #endif
006501  
006502  #if !defined(SQLITE_OMIT_AUTOVACUUM)
006503  /* Opcode: IncrVacuum P1 P2 * * *
006504  **
006505  ** Perform a single step of the incremental vacuum procedure on
006506  ** the P1 database. If the vacuum has finished, jump to instruction
006507  ** P2. Otherwise, fall through to the next instruction.
006508  */
006509  case OP_IncrVacuum: {        /* jump */
006510    Btree *pBt;
006511  
006512    assert( pOp->p1>=0 && pOp->p1<db->nDb );
006513    assert( DbMaskTest(p->btreeMask, pOp->p1) );
006514    assert( p->readOnly==0 );
006515    pBt = db->aDb[pOp->p1].pBt;
006516    rc = sqlite3BtreeIncrVacuum(pBt);
006517    VdbeBranchTaken(rc==SQLITE_DONE,2);
006518    if( rc ){
006519      if( rc!=SQLITE_DONE ) goto abort_due_to_error;
006520      rc = SQLITE_OK;
006521      goto jump_to_p2;
006522    }
006523    break;
006524  }
006525  #endif
006526  
006527  /* Opcode: Expire P1 * * * *
006528  **
006529  ** Cause precompiled statements to expire.  When an expired statement
006530  ** is executed using sqlite3_step() it will either automatically
006531  ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
006532  ** or it will fail with SQLITE_SCHEMA.
006533  ** 
006534  ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
006535  ** then only the currently executing statement is expired.
006536  */
006537  case OP_Expire: {
006538    if( !pOp->p1 ){
006539      sqlite3ExpirePreparedStatements(db);
006540    }else{
006541      p->expired = 1;
006542    }
006543    break;
006544  }
006545  
006546  #ifndef SQLITE_OMIT_SHARED_CACHE
006547  /* Opcode: TableLock P1 P2 P3 P4 *
006548  ** Synopsis: iDb=P1 root=P2 write=P3
006549  **
006550  ** Obtain a lock on a particular table. This instruction is only used when
006551  ** the shared-cache feature is enabled. 
006552  **
006553  ** P1 is the index of the database in sqlite3.aDb[] of the database
006554  ** on which the lock is acquired.  A readlock is obtained if P3==0 or
006555  ** a write lock if P3==1.
006556  **
006557  ** P2 contains the root-page of the table to lock.
006558  **
006559  ** P4 contains a pointer to the name of the table being locked. This is only
006560  ** used to generate an error message if the lock cannot be obtained.
006561  */
006562  case OP_TableLock: {
006563    u8 isWriteLock = (u8)pOp->p3;
006564    if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
006565      int p1 = pOp->p1; 
006566      assert( p1>=0 && p1<db->nDb );
006567      assert( DbMaskTest(p->btreeMask, p1) );
006568      assert( isWriteLock==0 || isWriteLock==1 );
006569      rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
006570      if( rc ){
006571        if( (rc&0xFF)==SQLITE_LOCKED ){
006572          const char *z = pOp->p4.z;
006573          sqlite3VdbeError(p, "database table is locked: %s", z);
006574        }
006575        goto abort_due_to_error;
006576      }
006577    }
006578    break;
006579  }
006580  #endif /* SQLITE_OMIT_SHARED_CACHE */
006581  
006582  #ifndef SQLITE_OMIT_VIRTUALTABLE
006583  /* Opcode: VBegin * * * P4 *
006584  **
006585  ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
006586  ** xBegin method for that table.
006587  **
006588  ** Also, whether or not P4 is set, check that this is not being called from
006589  ** within a callback to a virtual table xSync() method. If it is, the error
006590  ** code will be set to SQLITE_LOCKED.
006591  */
006592  case OP_VBegin: {
006593    VTable *pVTab;
006594    pVTab = pOp->p4.pVtab;
006595    rc = sqlite3VtabBegin(db, pVTab);
006596    if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
006597    if( rc ) goto abort_due_to_error;
006598    break;
006599  }
006600  #endif /* SQLITE_OMIT_VIRTUALTABLE */
006601  
006602  #ifndef SQLITE_OMIT_VIRTUALTABLE
006603  /* Opcode: VCreate P1 P2 * * *
006604  **
006605  ** P2 is a register that holds the name of a virtual table in database 
006606  ** P1. Call the xCreate method for that table.
006607  */
006608  case OP_VCreate: {
006609    Mem sMem;          /* For storing the record being decoded */
006610    const char *zTab;  /* Name of the virtual table */
006611  
006612    memset(&sMem, 0, sizeof(sMem));
006613    sMem.db = db;
006614    /* Because P2 is always a static string, it is impossible for the
006615    ** sqlite3VdbeMemCopy() to fail */
006616    assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
006617    assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
006618    rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
006619    assert( rc==SQLITE_OK );
006620    zTab = (const char*)sqlite3_value_text(&sMem);
006621    assert( zTab || db->mallocFailed );
006622    if( zTab ){
006623      rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
006624    }
006625    sqlite3VdbeMemRelease(&sMem);
006626    if( rc ) goto abort_due_to_error;
006627    break;
006628  }
006629  #endif /* SQLITE_OMIT_VIRTUALTABLE */
006630  
006631  #ifndef SQLITE_OMIT_VIRTUALTABLE
006632  /* Opcode: VDestroy P1 * * P4 *
006633  **
006634  ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
006635  ** of that table.
006636  */
006637  case OP_VDestroy: {
006638    db->nVDestroy++;
006639    rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
006640    db->nVDestroy--;
006641    if( rc ) goto abort_due_to_error;
006642    break;
006643  }
006644  #endif /* SQLITE_OMIT_VIRTUALTABLE */
006645  
006646  #ifndef SQLITE_OMIT_VIRTUALTABLE
006647  /* Opcode: VOpen P1 * * P4 *
006648  **
006649  ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
006650  ** P1 is a cursor number.  This opcode opens a cursor to the virtual
006651  ** table and stores that cursor in P1.
006652  */
006653  case OP_VOpen: {
006654    VdbeCursor *pCur;
006655    sqlite3_vtab_cursor *pVCur;
006656    sqlite3_vtab *pVtab;
006657    const sqlite3_module *pModule;
006658  
006659    assert( p->bIsReader );
006660    pCur = 0;
006661    pVCur = 0;
006662    pVtab = pOp->p4.pVtab->pVtab;
006663    if( pVtab==0 || NEVER(pVtab->pModule==0) ){
006664      rc = SQLITE_LOCKED;
006665      goto abort_due_to_error;
006666    }
006667    pModule = pVtab->pModule;
006668    rc = pModule->xOpen(pVtab, &pVCur);
006669    sqlite3VtabImportErrmsg(p, pVtab);
006670    if( rc ) goto abort_due_to_error;
006671  
006672    /* Initialize sqlite3_vtab_cursor base class */
006673    pVCur->pVtab = pVtab;
006674  
006675    /* Initialize vdbe cursor object */
006676    pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
006677    if( pCur ){
006678      pCur->uc.pVCur = pVCur;
006679      pVtab->nRef++;
006680    }else{
006681      assert( db->mallocFailed );
006682      pModule->xClose(pVCur);
006683      goto no_mem;
006684    }
006685    break;
006686  }
006687  #endif /* SQLITE_OMIT_VIRTUALTABLE */
006688  
006689  #ifndef SQLITE_OMIT_VIRTUALTABLE
006690  /* Opcode: VFilter P1 P2 P3 P4 *
006691  ** Synopsis: iplan=r[P3] zplan='P4'
006692  **
006693  ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
006694  ** the filtered result set is empty.
006695  **
006696  ** P4 is either NULL or a string that was generated by the xBestIndex
006697  ** method of the module.  The interpretation of the P4 string is left
006698  ** to the module implementation.
006699  **
006700  ** This opcode invokes the xFilter method on the virtual table specified
006701  ** by P1.  The integer query plan parameter to xFilter is stored in register
006702  ** P3. Register P3+1 stores the argc parameter to be passed to the
006703  ** xFilter method. Registers P3+2..P3+1+argc are the argc
006704  ** additional parameters which are passed to
006705  ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
006706  **
006707  ** A jump is made to P2 if the result set after filtering would be empty.
006708  */
006709  case OP_VFilter: {   /* jump */
006710    int nArg;
006711    int iQuery;
006712    const sqlite3_module *pModule;
006713    Mem *pQuery;
006714    Mem *pArgc;
006715    sqlite3_vtab_cursor *pVCur;
006716    sqlite3_vtab *pVtab;
006717    VdbeCursor *pCur;
006718    int res;
006719    int i;
006720    Mem **apArg;
006721  
006722    pQuery = &aMem[pOp->p3];
006723    pArgc = &pQuery[1];
006724    pCur = p->apCsr[pOp->p1];
006725    assert( memIsValid(pQuery) );
006726    REGISTER_TRACE(pOp->p3, pQuery);
006727    assert( pCur->eCurType==CURTYPE_VTAB );
006728    pVCur = pCur->uc.pVCur;
006729    pVtab = pVCur->pVtab;
006730    pModule = pVtab->pModule;
006731  
006732    /* Grab the index number and argc parameters */
006733    assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
006734    nArg = (int)pArgc->u.i;
006735    iQuery = (int)pQuery->u.i;
006736  
006737    /* Invoke the xFilter method */
006738    res = 0;
006739    apArg = p->apArg;
006740    for(i = 0; i<nArg; i++){
006741      apArg[i] = &pArgc[i+1];
006742    }
006743    rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
006744    sqlite3VtabImportErrmsg(p, pVtab);
006745    if( rc ) goto abort_due_to_error;
006746    res = pModule->xEof(pVCur);
006747    pCur->nullRow = 0;
006748    VdbeBranchTaken(res!=0,2);
006749    if( res ) goto jump_to_p2;
006750    break;
006751  }
006752  #endif /* SQLITE_OMIT_VIRTUALTABLE */
006753  
006754  #ifndef SQLITE_OMIT_VIRTUALTABLE
006755  /* Opcode: VColumn P1 P2 P3 * P5
006756  ** Synopsis: r[P3]=vcolumn(P2)
006757  **
006758  ** Store in register P3 the value of the P2-th column of
006759  ** the current row of the virtual-table of cursor P1.
006760  **
006761  ** If the VColumn opcode is being used to fetch the value of
006762  ** an unchanging column during an UPDATE operation, then the P5
006763  ** value is 1.  Otherwise, P5 is 0.  The P5 value is returned
006764  ** by sqlite3_vtab_nochange() routine and can be used
006765  ** by virtual table implementations to return special "no-change"
006766  ** marks which can be more efficient, depending on the virtual table.
006767  */
006768  case OP_VColumn: {
006769    sqlite3_vtab *pVtab;
006770    const sqlite3_module *pModule;
006771    Mem *pDest;
006772    sqlite3_context sContext;
006773  
006774    VdbeCursor *pCur = p->apCsr[pOp->p1];
006775    assert( pCur->eCurType==CURTYPE_VTAB );
006776    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
006777    pDest = &aMem[pOp->p3];
006778    memAboutToChange(p, pDest);
006779    if( pCur->nullRow ){
006780      sqlite3VdbeMemSetNull(pDest);
006781      break;
006782    }
006783    pVtab = pCur->uc.pVCur->pVtab;
006784    pModule = pVtab->pModule;
006785    assert( pModule->xColumn );
006786    memset(&sContext, 0, sizeof(sContext));
006787    sContext.pOut = pDest;
006788    if( pOp->p5 ){
006789      sqlite3VdbeMemSetNull(pDest);
006790      pDest->flags = MEM_Null|MEM_Zero;
006791      pDest->u.nZero = 0;
006792    }else{
006793      MemSetTypeFlag(pDest, MEM_Null);
006794    }
006795    rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
006796    sqlite3VtabImportErrmsg(p, pVtab);
006797    if( sContext.isError>0 ){
006798      sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
006799      rc = sContext.isError;
006800    }
006801    sqlite3VdbeChangeEncoding(pDest, encoding);
006802    REGISTER_TRACE(pOp->p3, pDest);
006803    UPDATE_MAX_BLOBSIZE(pDest);
006804  
006805    if( sqlite3VdbeMemTooBig(pDest) ){
006806      goto too_big;
006807    }
006808    if( rc ) goto abort_due_to_error;
006809    break;
006810  }
006811  #endif /* SQLITE_OMIT_VIRTUALTABLE */
006812  
006813  #ifndef SQLITE_OMIT_VIRTUALTABLE
006814  /* Opcode: VNext P1 P2 * * *
006815  **
006816  ** Advance virtual table P1 to the next row in its result set and
006817  ** jump to instruction P2.  Or, if the virtual table has reached
006818  ** the end of its result set, then fall through to the next instruction.
006819  */
006820  case OP_VNext: {   /* jump */
006821    sqlite3_vtab *pVtab;
006822    const sqlite3_module *pModule;
006823    int res;
006824    VdbeCursor *pCur;
006825  
006826    res = 0;
006827    pCur = p->apCsr[pOp->p1];
006828    assert( pCur->eCurType==CURTYPE_VTAB );
006829    if( pCur->nullRow ){
006830      break;
006831    }
006832    pVtab = pCur->uc.pVCur->pVtab;
006833    pModule = pVtab->pModule;
006834    assert( pModule->xNext );
006835  
006836    /* Invoke the xNext() method of the module. There is no way for the
006837    ** underlying implementation to return an error if one occurs during
006838    ** xNext(). Instead, if an error occurs, true is returned (indicating that 
006839    ** data is available) and the error code returned when xColumn or
006840    ** some other method is next invoked on the save virtual table cursor.
006841    */
006842    rc = pModule->xNext(pCur->uc.pVCur);
006843    sqlite3VtabImportErrmsg(p, pVtab);
006844    if( rc ) goto abort_due_to_error;
006845    res = pModule->xEof(pCur->uc.pVCur);
006846    VdbeBranchTaken(!res,2);
006847    if( !res ){
006848      /* If there is data, jump to P2 */
006849      goto jump_to_p2_and_check_for_interrupt;
006850    }
006851    goto check_for_interrupt;
006852  }
006853  #endif /* SQLITE_OMIT_VIRTUALTABLE */
006854  
006855  #ifndef SQLITE_OMIT_VIRTUALTABLE
006856  /* Opcode: VRename P1 * * P4 *
006857  **
006858  ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
006859  ** This opcode invokes the corresponding xRename method. The value
006860  ** in register P1 is passed as the zName argument to the xRename method.
006861  */
006862  case OP_VRename: {
006863    sqlite3_vtab *pVtab;
006864    Mem *pName;
006865  
006866    pVtab = pOp->p4.pVtab->pVtab;
006867    pName = &aMem[pOp->p1];
006868    assert( pVtab->pModule->xRename );
006869    assert( memIsValid(pName) );
006870    assert( p->readOnly==0 );
006871    REGISTER_TRACE(pOp->p1, pName);
006872    assert( pName->flags & MEM_Str );
006873    testcase( pName->enc==SQLITE_UTF8 );
006874    testcase( pName->enc==SQLITE_UTF16BE );
006875    testcase( pName->enc==SQLITE_UTF16LE );
006876    rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
006877    if( rc ) goto abort_due_to_error;
006878    rc = pVtab->pModule->xRename(pVtab, pName->z);
006879    sqlite3VtabImportErrmsg(p, pVtab);
006880    p->expired = 0;
006881    if( rc ) goto abort_due_to_error;
006882    break;
006883  }
006884  #endif
006885  
006886  #ifndef SQLITE_OMIT_VIRTUALTABLE
006887  /* Opcode: VUpdate P1 P2 P3 P4 P5
006888  ** Synopsis: data=r[P3@P2]
006889  **
006890  ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
006891  ** This opcode invokes the corresponding xUpdate method. P2 values
006892  ** are contiguous memory cells starting at P3 to pass to the xUpdate 
006893  ** invocation. The value in register (P3+P2-1) corresponds to the 
006894  ** p2th element of the argv array passed to xUpdate.
006895  **
006896  ** The xUpdate method will do a DELETE or an INSERT or both.
006897  ** The argv[0] element (which corresponds to memory cell P3)
006898  ** is the rowid of a row to delete.  If argv[0] is NULL then no 
006899  ** deletion occurs.  The argv[1] element is the rowid of the new 
006900  ** row.  This can be NULL to have the virtual table select the new 
006901  ** rowid for itself.  The subsequent elements in the array are 
006902  ** the values of columns in the new row.
006903  **
006904  ** If P2==1 then no insert is performed.  argv[0] is the rowid of
006905  ** a row to delete.
006906  **
006907  ** P1 is a boolean flag. If it is set to true and the xUpdate call
006908  ** is successful, then the value returned by sqlite3_last_insert_rowid() 
006909  ** is set to the value of the rowid for the row just inserted.
006910  **
006911  ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
006912  ** apply in the case of a constraint failure on an insert or update.
006913  */
006914  case OP_VUpdate: {
006915    sqlite3_vtab *pVtab;
006916    const sqlite3_module *pModule;
006917    int nArg;
006918    int i;
006919    sqlite_int64 rowid;
006920    Mem **apArg;
006921    Mem *pX;
006922  
006923    assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback 
006924         || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
006925    );
006926    assert( p->readOnly==0 );
006927    sqlite3VdbeIncrWriteCounter(p, 0);
006928    pVtab = pOp->p4.pVtab->pVtab;
006929    if( pVtab==0 || NEVER(pVtab->pModule==0) ){
006930      rc = SQLITE_LOCKED;
006931      goto abort_due_to_error;
006932    }
006933    pModule = pVtab->pModule;
006934    nArg = pOp->p2;
006935    assert( pOp->p4type==P4_VTAB );
006936    if( ALWAYS(pModule->xUpdate) ){
006937      u8 vtabOnConflict = db->vtabOnConflict;
006938      apArg = p->apArg;
006939      pX = &aMem[pOp->p3];
006940      for(i=0; i<nArg; i++){
006941        assert( memIsValid(pX) );
006942        memAboutToChange(p, pX);
006943        apArg[i] = pX;
006944        pX++;
006945      }
006946      db->vtabOnConflict = pOp->p5;
006947      rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
006948      db->vtabOnConflict = vtabOnConflict;
006949      sqlite3VtabImportErrmsg(p, pVtab);
006950      if( rc==SQLITE_OK && pOp->p1 ){
006951        assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
006952        db->lastRowid = rowid;
006953      }
006954      if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
006955        if( pOp->p5==OE_Ignore ){
006956          rc = SQLITE_OK;
006957        }else{
006958          p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
006959        }
006960      }else{
006961        p->nChange++;
006962      }
006963      if( rc ) goto abort_due_to_error;
006964    }
006965    break;
006966  }
006967  #endif /* SQLITE_OMIT_VIRTUALTABLE */
006968  
006969  #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
006970  /* Opcode: Pagecount P1 P2 * * *
006971  **
006972  ** Write the current number of pages in database P1 to memory cell P2.
006973  */
006974  case OP_Pagecount: {            /* out2 */
006975    pOut = out2Prerelease(p, pOp);
006976    pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
006977    break;
006978  }
006979  #endif
006980  
006981  
006982  #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
006983  /* Opcode: MaxPgcnt P1 P2 P3 * *
006984  **
006985  ** Try to set the maximum page count for database P1 to the value in P3.
006986  ** Do not let the maximum page count fall below the current page count and
006987  ** do not change the maximum page count value if P3==0.
006988  **
006989  ** Store the maximum page count after the change in register P2.
006990  */
006991  case OP_MaxPgcnt: {            /* out2 */
006992    unsigned int newMax;
006993    Btree *pBt;
006994  
006995    pOut = out2Prerelease(p, pOp);
006996    pBt = db->aDb[pOp->p1].pBt;
006997    newMax = 0;
006998    if( pOp->p3 ){
006999      newMax = sqlite3BtreeLastPage(pBt);
007000      if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
007001    }
007002    pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
007003    break;
007004  }
007005  #endif
007006  
007007  /* Opcode: Function0 P1 P2 P3 P4 P5
007008  ** Synopsis: r[P3]=func(r[P2@P5])
007009  **
007010  ** Invoke a user function (P4 is a pointer to a FuncDef object that
007011  ** defines the function) with P5 arguments taken from register P2 and
007012  ** successors.  The result of the function is stored in register P3.
007013  ** Register P3 must not be one of the function inputs.
007014  **
007015  ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
007016  ** function was determined to be constant at compile time. If the first
007017  ** argument was constant then bit 0 of P1 is set. This is used to determine
007018  ** whether meta data associated with a user function argument using the
007019  ** sqlite3_set_auxdata() API may be safely retained until the next
007020  ** invocation of this opcode.
007021  **
007022  ** See also: Function, AggStep, AggFinal
007023  */
007024  /* Opcode: Function P1 P2 P3 P4 P5
007025  ** Synopsis: r[P3]=func(r[P2@P5])
007026  **
007027  ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
007028  ** contains a pointer to the function to be run) with P5 arguments taken
007029  ** from register P2 and successors.  The result of the function is stored
007030  ** in register P3.  Register P3 must not be one of the function inputs.
007031  **
007032  ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
007033  ** function was determined to be constant at compile time. If the first
007034  ** argument was constant then bit 0 of P1 is set. This is used to determine
007035  ** whether meta data associated with a user function argument using the
007036  ** sqlite3_set_auxdata() API may be safely retained until the next
007037  ** invocation of this opcode.
007038  **
007039  ** SQL functions are initially coded as OP_Function0 with P4 pointing
007040  ** to a FuncDef object.  But on first evaluation, the P4 operand is
007041  ** automatically converted into an sqlite3_context object and the operation
007042  ** changed to this OP_Function opcode.  In this way, the initialization of
007043  ** the sqlite3_context object occurs only once, rather than once for each
007044  ** evaluation of the function.
007045  **
007046  ** See also: Function0, AggStep, AggFinal
007047  */
007048  case OP_PureFunc0:
007049  case OP_Function0: {
007050    int n;
007051    sqlite3_context *pCtx;
007052  
007053    assert( pOp->p4type==P4_FUNCDEF );
007054    n = pOp->p5;
007055    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
007056    assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
007057    assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
007058    pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
007059    if( pCtx==0 ) goto no_mem;
007060    pCtx->pOut = 0;
007061    pCtx->pFunc = pOp->p4.pFunc;
007062    pCtx->iOp = (int)(pOp - aOp);
007063    pCtx->pVdbe = p;
007064    pCtx->isError = 0;
007065    pCtx->argc = n;
007066    pOp->p4type = P4_FUNCCTX;
007067    pOp->p4.pCtx = pCtx;
007068    assert( OP_PureFunc == OP_PureFunc0+2 );
007069    assert( OP_Function == OP_Function0+2 );
007070    pOp->opcode += 2;
007071    /* Fall through into OP_Function */
007072  }
007073  case OP_PureFunc:
007074  case OP_Function: {
007075    int i;
007076    sqlite3_context *pCtx;
007077  
007078    assert( pOp->p4type==P4_FUNCCTX );
007079    pCtx = pOp->p4.pCtx;
007080  
007081    /* If this function is inside of a trigger, the register array in aMem[]
007082    ** might change from one evaluation to the next.  The next block of code
007083    ** checks to see if the register array has changed, and if so it
007084    ** reinitializes the relavant parts of the sqlite3_context object */
007085    pOut = &aMem[pOp->p3];
007086    if( pCtx->pOut != pOut ){
007087      pCtx->pOut = pOut;
007088      for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
007089    }
007090  
007091    memAboutToChange(p, pOut);
007092  #ifdef SQLITE_DEBUG
007093    for(i=0; i<pCtx->argc; i++){
007094      assert( memIsValid(pCtx->argv[i]) );
007095      REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
007096    }
007097  #endif
007098    MemSetTypeFlag(pOut, MEM_Null);
007099    assert( pCtx->isError==0 );
007100    (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
007101  
007102    /* If the function returned an error, throw an exception */
007103    if( pCtx->isError ){
007104      if( pCtx->isError>0 ){
007105        sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
007106        rc = pCtx->isError;
007107      }
007108      sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
007109      pCtx->isError = 0;
007110      if( rc ) goto abort_due_to_error;
007111    }
007112  
007113    /* Copy the result of the function into register P3 */
007114    if( pOut->flags & (MEM_Str|MEM_Blob) ){
007115      sqlite3VdbeChangeEncoding(pOut, encoding);
007116      if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
007117    }
007118  
007119    REGISTER_TRACE(pOp->p3, pOut);
007120    UPDATE_MAX_BLOBSIZE(pOut);
007121    break;
007122  }
007123  
007124  /* Opcode: Trace P1 P2 * P4 *
007125  **
007126  ** Write P4 on the statement trace output if statement tracing is
007127  ** enabled.
007128  **
007129  ** Operand P1 must be 0x7fffffff and P2 must positive.
007130  */
007131  /* Opcode: Init P1 P2 P3 P4 *
007132  ** Synopsis: Start at P2
007133  **
007134  ** Programs contain a single instance of this opcode as the very first
007135  ** opcode.
007136  **
007137  ** If tracing is enabled (by the sqlite3_trace()) interface, then
007138  ** the UTF-8 string contained in P4 is emitted on the trace callback.
007139  ** Or if P4 is blank, use the string returned by sqlite3_sql().
007140  **
007141  ** If P2 is not zero, jump to instruction P2.
007142  **
007143  ** Increment the value of P1 so that OP_Once opcodes will jump the
007144  ** first time they are evaluated for this run.
007145  **
007146  ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
007147  ** error is encountered.
007148  */
007149  case OP_Trace:
007150  case OP_Init: {          /* jump */
007151    int i;
007152  #ifndef SQLITE_OMIT_TRACE
007153    char *zTrace;
007154  #endif
007155  
007156    /* If the P4 argument is not NULL, then it must be an SQL comment string.
007157    ** The "--" string is broken up to prevent false-positives with srcck1.c.
007158    **
007159    ** This assert() provides evidence for:
007160    ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
007161    ** would have been returned by the legacy sqlite3_trace() interface by
007162    ** using the X argument when X begins with "--" and invoking
007163    ** sqlite3_expanded_sql(P) otherwise.
007164    */
007165    assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
007166  
007167    /* OP_Init is always instruction 0 */
007168    assert( pOp==p->aOp || pOp->opcode==OP_Trace );
007169  
007170  #ifndef SQLITE_OMIT_TRACE
007171    if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
007172     && !p->doingRerun
007173     && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
007174    ){
007175  #ifndef SQLITE_OMIT_DEPRECATED
007176      if( db->mTrace & SQLITE_TRACE_LEGACY ){
007177        void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
007178        char *z = sqlite3VdbeExpandSql(p, zTrace);
007179        x(db->pTraceArg, z);
007180        sqlite3_free(z);
007181      }else
007182  #endif
007183      if( db->nVdbeExec>1 ){
007184        char *z = sqlite3MPrintf(db, "-- %s", zTrace);
007185        (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
007186        sqlite3DbFree(db, z);
007187      }else{
007188        (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
007189      }
007190    }
007191  #ifdef SQLITE_USE_FCNTL_TRACE
007192    zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
007193    if( zTrace ){
007194      int j;
007195      for(j=0; j<db->nDb; j++){
007196        if( DbMaskTest(p->btreeMask, j)==0 ) continue;
007197        sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
007198      }
007199    }
007200  #endif /* SQLITE_USE_FCNTL_TRACE */
007201  #ifdef SQLITE_DEBUG
007202    if( (db->flags & SQLITE_SqlTrace)!=0
007203     && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
007204    ){
007205      sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
007206    }
007207  #endif /* SQLITE_DEBUG */
007208  #endif /* SQLITE_OMIT_TRACE */
007209    assert( pOp->p2>0 );
007210    if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
007211      if( pOp->opcode==OP_Trace ) break;
007212      for(i=1; i<p->nOp; i++){
007213        if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
007214      }
007215      pOp->p1 = 0;
007216    }
007217    pOp->p1++;
007218    p->aCounter[SQLITE_STMTSTATUS_RUN]++;
007219    goto jump_to_p2;
007220  }
007221  
007222  #ifdef SQLITE_ENABLE_CURSOR_HINTS
007223  /* Opcode: CursorHint P1 * * P4 *
007224  **
007225  ** Provide a hint to cursor P1 that it only needs to return rows that
007226  ** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
007227  ** to values currently held in registers.  TK_COLUMN terms in the P4
007228  ** expression refer to columns in the b-tree to which cursor P1 is pointing.
007229  */
007230  case OP_CursorHint: {
007231    VdbeCursor *pC;
007232  
007233    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
007234    assert( pOp->p4type==P4_EXPR );
007235    pC = p->apCsr[pOp->p1];
007236    if( pC ){
007237      assert( pC->eCurType==CURTYPE_BTREE );
007238      sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
007239                             pOp->p4.pExpr, aMem);
007240    }
007241    break;
007242  }
007243  #endif /* SQLITE_ENABLE_CURSOR_HINTS */
007244  
007245  #ifdef SQLITE_DEBUG
007246  /* Opcode:  Abortable   * * * * *
007247  **
007248  ** Verify that an Abort can happen.  Assert if an Abort at this point
007249  ** might cause database corruption.  This opcode only appears in debugging
007250  ** builds.
007251  **
007252  ** An Abort is safe if either there have been no writes, or if there is
007253  ** an active statement journal.
007254  */
007255  case OP_Abortable: {
007256    sqlite3VdbeAssertAbortable(p);
007257    break;
007258  }
007259  #endif
007260  
007261  /* Opcode: Noop * * * * *
007262  **
007263  ** Do nothing.  This instruction is often useful as a jump
007264  ** destination.
007265  */
007266  /*
007267  ** The magic Explain opcode are only inserted when explain==2 (which
007268  ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
007269  ** This opcode records information from the optimizer.  It is the
007270  ** the same as a no-op.  This opcodesnever appears in a real VM program.
007271  */
007272  default: {          /* This is really OP_Noop, OP_Explain */
007273    assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
007274  
007275    break;
007276  }
007277  
007278  /*****************************************************************************
007279  ** The cases of the switch statement above this line should all be indented
007280  ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
007281  ** readability.  From this point on down, the normal indentation rules are
007282  ** restored.
007283  *****************************************************************************/
007284      }
007285  
007286  #ifdef VDBE_PROFILE
007287      {
007288        u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
007289        if( endTime>start ) pOrigOp->cycles += endTime - start;
007290        pOrigOp->cnt++;
007291      }
007292  #endif
007293  
007294      /* The following code adds nothing to the actual functionality
007295      ** of the program.  It is only here for testing and debugging.
007296      ** On the other hand, it does burn CPU cycles every time through
007297      ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
007298      */
007299  #ifndef NDEBUG
007300      assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
007301  
007302  #ifdef SQLITE_DEBUG
007303      if( db->flags & SQLITE_VdbeTrace ){
007304        u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
007305        if( rc!=0 ) printf("rc=%d\n",rc);
007306        if( opProperty & (OPFLG_OUT2) ){
007307          registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
007308        }
007309        if( opProperty & OPFLG_OUT3 ){
007310          registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
007311        }
007312      }
007313  #endif  /* SQLITE_DEBUG */
007314  #endif  /* NDEBUG */
007315    }  /* The end of the for(;;) loop the loops through opcodes */
007316  
007317    /* If we reach this point, it means that execution is finished with
007318    ** an error of some kind.
007319    */
007320  abort_due_to_error:
007321    if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
007322    assert( rc );
007323    if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
007324      sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
007325    }
007326    p->rc = rc;
007327    sqlite3SystemError(db, rc);
007328    testcase( sqlite3GlobalConfig.xLog!=0 );
007329    sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
007330                     (int)(pOp - aOp), p->zSql, p->zErrMsg);
007331    sqlite3VdbeHalt(p);
007332    if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
007333    rc = SQLITE_ERROR;
007334    if( resetSchemaOnFault>0 ){
007335      sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
007336    }
007337  
007338    /* This is the only way out of this procedure.  We have to
007339    ** release the mutexes on btrees that were acquired at the
007340    ** top. */
007341  vdbe_return:
007342    testcase( nVmStep>0 );
007343    p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
007344    sqlite3VdbeLeave(p);
007345    assert( rc!=SQLITE_OK || nExtraDelete==0 
007346         || sqlite3_strlike("DELETE%",p->zSql,0)!=0 
007347    );
007348    return rc;
007349  
007350    /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
007351    ** is encountered.
007352    */
007353  too_big:
007354    sqlite3VdbeError(p, "string or blob too big");
007355    rc = SQLITE_TOOBIG;
007356    goto abort_due_to_error;
007357  
007358    /* Jump to here if a malloc() fails.
007359    */
007360  no_mem:
007361    sqlite3OomFault(db);
007362    sqlite3VdbeError(p, "out of memory");
007363    rc = SQLITE_NOMEM_BKPT;
007364    goto abort_due_to_error;
007365  
007366    /* Jump to here if the sqlite3_interrupt() API sets the interrupt
007367    ** flag.
007368    */
007369  abort_due_to_interrupt:
007370    assert( db->u1.isInterrupted );
007371    rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
007372    p->rc = rc;
007373    sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
007374    goto abort_due_to_error;
007375  }