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