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