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