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