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