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