1 /* 2 ** 2001 September 15 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** The code in this file implements the function that runs the 13 ** bytecode of a prepared statement. 14 ** 15 ** Various scripts scan this source file in order to generate HTML 16 ** documentation, headers files, or other derived files. The formatting 17 ** of the code in this file is, therefore, important. See other comments 18 ** in this file for details. If in doubt, do not deviate from existing 19 ** commenting and indentation practices when changing or adding code. 20 */ 21 #include "sqliteInt.h" 22 #include "vdbeInt.h" 23 24 /* 25 ** Invoke this macro on memory cells just prior to changing the 26 ** value of the cell. This macro verifies that shallow copies are 27 ** not misused. A shallow copy of a string or blob just copies a 28 ** pointer to the string or blob, not the content. If the original 29 ** is changed while the copy is still in use, the string or blob might 30 ** be changed out from under the copy. This macro verifies that nothing 31 ** like that ever happens. 32 */ 33 #ifdef SQLITE_DEBUG 34 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M) 35 #else 36 # define memAboutToChange(P,M) 37 #endif 38 39 /* 40 ** The following global variable is incremented every time a cursor 41 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test 42 ** procedures use this information to make sure that indices are 43 ** working correctly. This variable has no function other than to 44 ** help verify the correct operation of the library. 45 */ 46 #ifdef SQLITE_TEST 47 int sqlite3_search_count = 0; 48 #endif 49 50 /* 51 ** When this global variable is positive, it gets decremented once before 52 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted 53 ** field of the sqlite3 structure is set in order to simulate an interrupt. 54 ** 55 ** This facility is used for testing purposes only. It does not function 56 ** in an ordinary build. 57 */ 58 #ifdef SQLITE_TEST 59 int sqlite3_interrupt_count = 0; 60 #endif 61 62 /* 63 ** The next global variable is incremented each type the OP_Sort opcode 64 ** is executed. The test procedures use this information to make sure that 65 ** sorting is occurring or not occurring at appropriate times. This variable 66 ** has no function other than to help verify the correct operation of the 67 ** library. 68 */ 69 #ifdef SQLITE_TEST 70 int sqlite3_sort_count = 0; 71 #endif 72 73 /* 74 ** The next global variable records the size of the largest MEM_Blob 75 ** or MEM_Str that has been used by a VDBE opcode. The test procedures 76 ** use this information to make sure that the zero-blob functionality 77 ** is working correctly. This variable has no function other than to 78 ** help verify the correct operation of the library. 79 */ 80 #ifdef SQLITE_TEST 81 int sqlite3_max_blobsize = 0; 82 static void updateMaxBlobsize(Mem *p){ 83 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){ 84 sqlite3_max_blobsize = p->n; 85 } 86 } 87 #endif 88 89 /* 90 ** This macro evaluates to true if either the update hook or the preupdate 91 ** hook are enabled for database connect DB. 92 */ 93 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 94 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback) 95 #else 96 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback) 97 #endif 98 99 /* 100 ** The next global variable is incremented each time the OP_Found opcode 101 ** is executed. This is used to test whether or not the foreign key 102 ** operation implemented using OP_FkIsZero is working. This variable 103 ** has no function other than to help verify the correct operation of the 104 ** library. 105 */ 106 #ifdef SQLITE_TEST 107 int sqlite3_found_count = 0; 108 #endif 109 110 /* 111 ** Test a register to see if it exceeds the current maximum blob size. 112 ** If it does, record the new maximum blob size. 113 */ 114 #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE) 115 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P) 116 #else 117 # define UPDATE_MAX_BLOBSIZE(P) 118 #endif 119 120 #ifdef SQLITE_DEBUG 121 /* This routine provides a convenient place to set a breakpoint during 122 ** tracing with PRAGMA vdbe_trace=on. The breakpoint fires right after 123 ** each opcode is printed. Variables "pc" (program counter) and pOp are 124 ** available to add conditionals to the breakpoint. GDB example: 125 ** 126 ** break test_trace_breakpoint if pc=22 127 ** 128 ** Other useful labels for breakpoints include: 129 ** test_addop_breakpoint(pc,pOp) 130 ** sqlite3CorruptError(lineno) 131 ** sqlite3MisuseError(lineno) 132 ** sqlite3CantopenError(lineno) 133 */ 134 static void test_trace_breakpoint(int pc, Op *pOp, Vdbe *v){ 135 static int n = 0; 136 n++; 137 } 138 #endif 139 140 /* 141 ** Invoke the VDBE coverage callback, if that callback is defined. This 142 ** feature is used for test suite validation only and does not appear an 143 ** production builds. 144 ** 145 ** M is the type of branch. I is the direction taken for this instance of 146 ** the branch. 147 ** 148 ** M: 2 - two-way branch (I=0: fall-thru 1: jump ) 149 ** 3 - two-way + NULL (I=0: fall-thru 1: jump 2: NULL ) 150 ** 4 - OP_Jump (I=0: jump p1 1: jump p2 2: jump p3) 151 ** 152 ** In other words, if M is 2, then I is either 0 (for fall-through) or 153 ** 1 (for when the branch is taken). If M is 3, the I is 0 for an 154 ** ordinary fall-through, I is 1 if the branch was taken, and I is 2 155 ** if the result of comparison is NULL. For M=3, I=2 the jump may or 156 ** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5. 157 ** When M is 4, that means that an OP_Jump is being run. I is 0, 1, or 2 158 ** depending on if the operands are less than, equal, or greater than. 159 ** 160 ** iSrcLine is the source code line (from the __LINE__ macro) that 161 ** generated the VDBE instruction combined with flag bits. The source 162 ** code line number is in the lower 24 bits of iSrcLine and the upper 163 ** 8 bytes are flags. The lower three bits of the flags indicate 164 ** values for I that should never occur. For example, if the branch is 165 ** always taken, the flags should be 0x05 since the fall-through and 166 ** alternate branch are never taken. If a branch is never taken then 167 ** flags should be 0x06 since only the fall-through approach is allowed. 168 ** 169 ** Bit 0x08 of the flags indicates an OP_Jump opcode that is only 170 ** interested in equal or not-equal. In other words, I==0 and I==2 171 ** should be treated as equivalent 172 ** 173 ** Since only a line number is retained, not the filename, this macro 174 ** only works for amalgamation builds. But that is ok, since these macros 175 ** should be no-ops except for special builds used to measure test coverage. 176 */ 177 #if !defined(SQLITE_VDBE_COVERAGE) 178 # define VdbeBranchTaken(I,M) 179 #else 180 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M) 181 static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){ 182 u8 mNever; 183 assert( I<=2 ); /* 0: fall through, 1: taken, 2: alternate taken */ 184 assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */ 185 assert( I<M ); /* I can only be 2 if M is 3 or 4 */ 186 /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */ 187 I = 1<<I; 188 /* The upper 8 bits of iSrcLine are flags. The lower three bits of 189 ** the flags indicate directions that the branch can never go. If 190 ** a branch really does go in one of those directions, assert right 191 ** away. */ 192 mNever = iSrcLine >> 24; 193 assert( (I & mNever)==0 ); 194 if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/ 195 /* Invoke the branch coverage callback with three arguments: 196 ** iSrcLine - the line number of the VdbeCoverage() macro, with 197 ** flags removed. 198 ** I - Mask of bits 0x07 indicating which cases are are 199 ** fulfilled by this instance of the jump. 0x01 means 200 ** fall-thru, 0x02 means taken, 0x04 means NULL. Any 201 ** impossible cases (ex: if the comparison is never NULL) 202 ** are filled in automatically so that the coverage 203 ** measurement logic does not flag those impossible cases 204 ** as missed coverage. 205 ** M - Type of jump. Same as M argument above 206 */ 207 I |= mNever; 208 if( M==2 ) I |= 0x04; 209 if( M==4 ){ 210 I |= 0x08; 211 if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/ 212 } 213 sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg, 214 iSrcLine&0xffffff, I, M); 215 } 216 #endif 217 218 /* 219 ** An ephemeral string value (signified by the MEM_Ephem flag) contains 220 ** a pointer to a dynamically allocated string where some other entity 221 ** is responsible for deallocating that string. Because the register 222 ** does not control the string, it might be deleted without the register 223 ** knowing it. 224 ** 225 ** This routine converts an ephemeral string into a dynamically allocated 226 ** string that the register itself controls. In other words, it 227 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc. 228 */ 229 #define Deephemeralize(P) \ 230 if( ((P)->flags&MEM_Ephem)!=0 \ 231 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;} 232 233 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */ 234 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER) 235 236 /* 237 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL 238 ** if we run out of memory. 239 */ 240 static VdbeCursor *allocateCursor( 241 Vdbe *p, /* The virtual machine */ 242 int iCur, /* Index of the new VdbeCursor */ 243 int nField, /* Number of fields in the table or index */ 244 int iDb, /* Database the cursor belongs to, or -1 */ 245 u8 eCurType /* Type of the new cursor */ 246 ){ 247 /* Find the memory cell that will be used to store the blob of memory 248 ** required for this VdbeCursor structure. It is convenient to use a 249 ** vdbe memory cell to manage the memory allocation required for a 250 ** VdbeCursor structure for the following reasons: 251 ** 252 ** * Sometimes cursor numbers are used for a couple of different 253 ** purposes in a vdbe program. The different uses might require 254 ** different sized allocations. Memory cells provide growable 255 ** allocations. 256 ** 257 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can 258 ** be freed lazily via the sqlite3_release_memory() API. This 259 ** minimizes the number of malloc calls made by the system. 260 ** 261 ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from 262 ** the top of the register space. Cursor 1 is at Mem[p->nMem-1]. 263 ** Cursor 2 is at Mem[p->nMem-2]. And so forth. 264 */ 265 Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem; 266 267 int nByte; 268 VdbeCursor *pCx = 0; 269 nByte = 270 ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + 271 (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0); 272 273 assert( iCur>=0 && iCur<p->nCursor ); 274 if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/ 275 /* Before calling sqlite3VdbeFreeCursor(), ensure the isEphemeral flag 276 ** is clear. Otherwise, if this is an ephemeral cursor created by 277 ** OP_OpenDup, the cursor will not be closed and will still be part 278 ** of a BtShared.pCursor list. */ 279 if( p->apCsr[iCur]->pBtx==0 ) p->apCsr[iCur]->isEphemeral = 0; 280 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]); 281 p->apCsr[iCur] = 0; 282 } 283 if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){ 284 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z; 285 memset(pCx, 0, offsetof(VdbeCursor,pAltCursor)); 286 pCx->eCurType = eCurType; 287 pCx->iDb = iDb; 288 pCx->nField = nField; 289 pCx->aOffset = &pCx->aType[nField]; 290 if( eCurType==CURTYPE_BTREE ){ 291 pCx->uc.pCursor = (BtCursor*) 292 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField]; 293 sqlite3BtreeCursorZero(pCx->uc.pCursor); 294 } 295 } 296 return pCx; 297 } 298 299 /* 300 ** The string in pRec is known to look like an integer and to have a 301 ** floating point value of rValue. Return true and set *piValue to the 302 ** integer value if the string is in range to be an integer. Otherwise, 303 ** return false. 304 */ 305 static int alsoAnInt(Mem *pRec, double rValue, i64 *piValue){ 306 i64 iValue = (double)rValue; 307 if( sqlite3RealSameAsInt(rValue,iValue) ){ 308 *piValue = iValue; 309 return 1; 310 } 311 return 0==sqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc); 312 } 313 314 /* 315 ** Try to convert a value into a numeric representation if we can 316 ** do so without loss of information. In other words, if the string 317 ** looks like a number, convert it into a number. If it does not 318 ** look like a number, leave it alone. 319 ** 320 ** If the bTryForInt flag is true, then extra effort is made to give 321 ** an integer representation. Strings that look like floating point 322 ** values but which have no fractional component (example: '48.00') 323 ** will have a MEM_Int representation when bTryForInt is true. 324 ** 325 ** If bTryForInt is false, then if the input string contains a decimal 326 ** point or exponential notation, the result is only MEM_Real, even 327 ** if there is an exact integer representation of the quantity. 328 */ 329 static void applyNumericAffinity(Mem *pRec, int bTryForInt){ 330 double rValue; 331 u8 enc = pRec->enc; 332 int rc; 333 assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str ); 334 rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc); 335 if( rc<=0 ) return; 336 if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){ 337 pRec->flags |= MEM_Int; 338 }else{ 339 pRec->u.r = rValue; 340 pRec->flags |= MEM_Real; 341 if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec); 342 } 343 /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the 344 ** string representation after computing a numeric equivalent, because the 345 ** string representation might not be the canonical representation for the 346 ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */ 347 pRec->flags &= ~MEM_Str; 348 } 349 350 /* 351 ** Processing is determine by the affinity parameter: 352 ** 353 ** SQLITE_AFF_INTEGER: 354 ** SQLITE_AFF_REAL: 355 ** SQLITE_AFF_NUMERIC: 356 ** Try to convert pRec to an integer representation or a 357 ** floating-point representation if an integer representation 358 ** is not possible. Note that the integer representation is 359 ** always preferred, even if the affinity is REAL, because 360 ** an integer representation is more space efficient on disk. 361 ** 362 ** SQLITE_AFF_TEXT: 363 ** Convert pRec to a text representation. 364 ** 365 ** SQLITE_AFF_BLOB: 366 ** SQLITE_AFF_NONE: 367 ** No-op. pRec is unchanged. 368 */ 369 static void applyAffinity( 370 Mem *pRec, /* The value to apply affinity to */ 371 char affinity, /* The affinity to be applied */ 372 u8 enc /* Use this text encoding */ 373 ){ 374 if( affinity>=SQLITE_AFF_NUMERIC ){ 375 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL 376 || affinity==SQLITE_AFF_NUMERIC ); 377 if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/ 378 if( (pRec->flags & MEM_Real)==0 ){ 379 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1); 380 }else{ 381 sqlite3VdbeIntegerAffinity(pRec); 382 } 383 } 384 }else if( affinity==SQLITE_AFF_TEXT ){ 385 /* Only attempt the conversion to TEXT if there is an integer or real 386 ** representation (blob and NULL do not get converted) but no string 387 ** representation. It would be harmless to repeat the conversion if 388 ** there is already a string rep, but it is pointless to waste those 389 ** CPU cycles. */ 390 if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/ 391 if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){ 392 testcase( pRec->flags & MEM_Int ); 393 testcase( pRec->flags & MEM_Real ); 394 testcase( pRec->flags & MEM_IntReal ); 395 sqlite3VdbeMemStringify(pRec, enc, 1); 396 } 397 } 398 pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal); 399 } 400 } 401 402 /* 403 ** Try to convert the type of a function argument or a result column 404 ** into a numeric representation. Use either INTEGER or REAL whichever 405 ** is appropriate. But only do the conversion if it is possible without 406 ** loss of information and return the revised type of the argument. 407 */ 408 int sqlite3_value_numeric_type(sqlite3_value *pVal){ 409 int eType = sqlite3_value_type(pVal); 410 if( eType==SQLITE_TEXT ){ 411 Mem *pMem = (Mem*)pVal; 412 applyNumericAffinity(pMem, 0); 413 eType = sqlite3_value_type(pVal); 414 } 415 return eType; 416 } 417 418 /* 419 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 420 ** not the internal Mem* type. 421 */ 422 void sqlite3ValueApplyAffinity( 423 sqlite3_value *pVal, 424 u8 affinity, 425 u8 enc 426 ){ 427 applyAffinity((Mem *)pVal, affinity, enc); 428 } 429 430 /* 431 ** pMem currently only holds a string type (or maybe a BLOB that we can 432 ** interpret as a string if we want to). Compute its corresponding 433 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields 434 ** accordingly. 435 */ 436 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){ 437 int rc; 438 sqlite3_int64 ix; 439 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ); 440 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ); 441 ExpandBlob(pMem); 442 rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc); 443 if( rc<=0 ){ 444 if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){ 445 pMem->u.i = ix; 446 return MEM_Int; 447 }else{ 448 return MEM_Real; 449 } 450 }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){ 451 pMem->u.i = ix; 452 return MEM_Int; 453 } 454 return MEM_Real; 455 } 456 457 /* 458 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or 459 ** none. 460 ** 461 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags. 462 ** But it does set pMem->u.r and pMem->u.i appropriately. 463 */ 464 static u16 numericType(Mem *pMem){ 465 if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal) ){ 466 testcase( pMem->flags & MEM_Int ); 467 testcase( pMem->flags & MEM_Real ); 468 testcase( pMem->flags & MEM_IntReal ); 469 return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal); 470 } 471 if( pMem->flags & (MEM_Str|MEM_Blob) ){ 472 testcase( pMem->flags & MEM_Str ); 473 testcase( pMem->flags & MEM_Blob ); 474 return computeNumericType(pMem); 475 } 476 return 0; 477 } 478 479 #ifdef SQLITE_DEBUG 480 /* 481 ** Write a nice string representation of the contents of cell pMem 482 ** into buffer zBuf, length nBuf. 483 */ 484 void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr){ 485 int f = pMem->flags; 486 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"}; 487 if( f&MEM_Blob ){ 488 int i; 489 char c; 490 if( f & MEM_Dyn ){ 491 c = 'z'; 492 assert( (f & (MEM_Static|MEM_Ephem))==0 ); 493 }else if( f & MEM_Static ){ 494 c = 't'; 495 assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); 496 }else if( f & MEM_Ephem ){ 497 c = 'e'; 498 assert( (f & (MEM_Static|MEM_Dyn))==0 ); 499 }else{ 500 c = 's'; 501 } 502 sqlite3_str_appendf(pStr, "%cx[", c); 503 for(i=0; i<25 && i<pMem->n; i++){ 504 sqlite3_str_appendf(pStr, "%02X", ((int)pMem->z[i] & 0xFF)); 505 } 506 sqlite3_str_appendf(pStr, "|"); 507 for(i=0; i<25 && i<pMem->n; i++){ 508 char z = pMem->z[i]; 509 sqlite3_str_appendchar(pStr, 1, (z<32||z>126)?'.':z); 510 } 511 sqlite3_str_appendf(pStr,"]"); 512 if( f & MEM_Zero ){ 513 sqlite3_str_appendf(pStr, "+%dz",pMem->u.nZero); 514 } 515 }else if( f & MEM_Str ){ 516 int j; 517 int c; 518 if( f & MEM_Dyn ){ 519 c = 'z'; 520 assert( (f & (MEM_Static|MEM_Ephem))==0 ); 521 }else if( f & MEM_Static ){ 522 c = 't'; 523 assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); 524 }else if( f & MEM_Ephem ){ 525 c = 'e'; 526 assert( (f & (MEM_Static|MEM_Dyn))==0 ); 527 }else{ 528 c = 's'; 529 } 530 sqlite3_str_appendf(pStr, " %c%d[", c, pMem->n); 531 for(j=0; j<25 && j<pMem->n; j++){ 532 u8 c = pMem->z[j]; 533 sqlite3_str_appendchar(pStr, 1, (c>=0x20&&c<=0x7f) ? c : '.'); 534 } 535 sqlite3_str_appendf(pStr, "]%s", encnames[pMem->enc]); 536 } 537 } 538 #endif 539 540 #ifdef SQLITE_DEBUG 541 /* 542 ** Print the value of a register for tracing purposes: 543 */ 544 static void memTracePrint(Mem *p){ 545 if( p->flags & MEM_Undefined ){ 546 printf(" undefined"); 547 }else if( p->flags & MEM_Null ){ 548 printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL"); 549 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){ 550 printf(" si:%lld", p->u.i); 551 }else if( (p->flags & (MEM_IntReal))!=0 ){ 552 printf(" ir:%lld", p->u.i); 553 }else if( p->flags & MEM_Int ){ 554 printf(" i:%lld", p->u.i); 555 #ifndef SQLITE_OMIT_FLOATING_POINT 556 }else if( p->flags & MEM_Real ){ 557 printf(" r:%.17g", p->u.r); 558 #endif 559 }else if( sqlite3VdbeMemIsRowSet(p) ){ 560 printf(" (rowset)"); 561 }else{ 562 StrAccum acc; 563 char zBuf[1000]; 564 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); 565 sqlite3VdbeMemPrettyPrint(p, &acc); 566 printf(" %s", sqlite3StrAccumFinish(&acc)); 567 } 568 if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype); 569 } 570 static void registerTrace(int iReg, Mem *p){ 571 printf("R[%d] = ", iReg); 572 memTracePrint(p); 573 if( p->pScopyFrom ){ 574 printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg])); 575 } 576 printf("\n"); 577 sqlite3VdbeCheckMemInvariants(p); 578 } 579 #endif 580 581 #ifdef SQLITE_DEBUG 582 /* 583 ** Show the values of all registers in the virtual machine. Used for 584 ** interactive debugging. 585 */ 586 void sqlite3VdbeRegisterDump(Vdbe *v){ 587 int i; 588 for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i); 589 } 590 #endif /* SQLITE_DEBUG */ 591 592 593 #ifdef SQLITE_DEBUG 594 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M) 595 #else 596 # define REGISTER_TRACE(R,M) 597 #endif 598 599 600 #ifdef VDBE_PROFILE 601 602 /* 603 ** hwtime.h contains inline assembler code for implementing 604 ** high-performance timing routines. 605 */ 606 #include "hwtime.h" 607 608 #endif 609 610 #ifndef NDEBUG 611 /* 612 ** This function is only called from within an assert() expression. It 613 ** checks that the sqlite3.nTransaction variable is correctly set to 614 ** the number of non-transaction savepoints currently in the 615 ** linked list starting at sqlite3.pSavepoint. 616 ** 617 ** Usage: 618 ** 619 ** assert( checkSavepointCount(db) ); 620 */ 621 static int checkSavepointCount(sqlite3 *db){ 622 int n = 0; 623 Savepoint *p; 624 for(p=db->pSavepoint; p; p=p->pNext) n++; 625 assert( n==(db->nSavepoint + db->isTransactionSavepoint) ); 626 return 1; 627 } 628 #endif 629 630 /* 631 ** Return the register of pOp->p2 after first preparing it to be 632 ** overwritten with an integer value. 633 */ 634 static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){ 635 sqlite3VdbeMemSetNull(pOut); 636 pOut->flags = MEM_Int; 637 return pOut; 638 } 639 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){ 640 Mem *pOut; 641 assert( pOp->p2>0 ); 642 assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); 643 pOut = &p->aMem[pOp->p2]; 644 memAboutToChange(p, pOut); 645 if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/ 646 return out2PrereleaseWithClear(pOut); 647 }else{ 648 pOut->flags = MEM_Int; 649 return pOut; 650 } 651 } 652 653 654 /* 655 ** Execute as much of a VDBE program as we can. 656 ** This is the core of sqlite3_step(). 657 */ 658 int sqlite3VdbeExec( 659 Vdbe *p /* The VDBE */ 660 ){ 661 Op *aOp = p->aOp; /* Copy of p->aOp */ 662 Op *pOp = aOp; /* Current operation */ 663 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) 664 Op *pOrigOp; /* Value of pOp at the top of the loop */ 665 #endif 666 #ifdef SQLITE_DEBUG 667 int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */ 668 #endif 669 int rc = SQLITE_OK; /* Value to return */ 670 sqlite3 *db = p->db; /* The database */ 671 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */ 672 u8 encoding = ENC(db); /* The database encoding */ 673 int iCompare = 0; /* Result of last comparison */ 674 unsigned nVmStep = 0; /* Number of virtual machine steps */ 675 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 676 unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */ 677 #endif 678 Mem *aMem = p->aMem; /* Copy of p->aMem */ 679 Mem *pIn1 = 0; /* 1st input operand */ 680 Mem *pIn2 = 0; /* 2nd input operand */ 681 Mem *pIn3 = 0; /* 3rd input operand */ 682 Mem *pOut = 0; /* Output operand */ 683 #ifdef VDBE_PROFILE 684 u64 start; /* CPU clock count at start of opcode */ 685 #endif 686 /*** INSERT STACK UNION HERE ***/ 687 688 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */ 689 sqlite3VdbeEnter(p); 690 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 691 if( db->xProgress ){ 692 u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP]; 693 assert( 0 < db->nProgressOps ); 694 nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps); 695 }else{ 696 nProgressLimit = 0xffffffff; 697 } 698 #endif 699 if( p->rc==SQLITE_NOMEM ){ 700 /* This happens if a malloc() inside a call to sqlite3_column_text() or 701 ** sqlite3_column_text16() failed. */ 702 goto no_mem; 703 } 704 assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY ); 705 assert( p->bIsReader || p->readOnly!=0 ); 706 p->iCurrentTime = 0; 707 assert( p->explain==0 ); 708 p->pResultSet = 0; 709 db->busyHandler.nBusy = 0; 710 if( db->u1.isInterrupted ) goto abort_due_to_interrupt; 711 sqlite3VdbeIOTraceSql(p); 712 #ifdef SQLITE_DEBUG 713 sqlite3BeginBenignMalloc(); 714 if( p->pc==0 715 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0 716 ){ 717 int i; 718 int once = 1; 719 sqlite3VdbePrintSql(p); 720 if( p->db->flags & SQLITE_VdbeListing ){ 721 printf("VDBE Program Listing:\n"); 722 for(i=0; i<p->nOp; i++){ 723 sqlite3VdbePrintOp(stdout, i, &aOp[i]); 724 } 725 } 726 if( p->db->flags & SQLITE_VdbeEQP ){ 727 for(i=0; i<p->nOp; i++){ 728 if( aOp[i].opcode==OP_Explain ){ 729 if( once ) printf("VDBE Query Plan:\n"); 730 printf("%s\n", aOp[i].p4.z); 731 once = 0; 732 } 733 } 734 } 735 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n"); 736 } 737 sqlite3EndBenignMalloc(); 738 #endif 739 for(pOp=&aOp[p->pc]; 1; pOp++){ 740 /* Errors are detected by individual opcodes, with an immediate 741 ** jumps to abort_due_to_error. */ 742 assert( rc==SQLITE_OK ); 743 744 assert( pOp>=aOp && pOp<&aOp[p->nOp]); 745 #ifdef VDBE_PROFILE 746 start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime(); 747 #endif 748 nVmStep++; 749 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 750 if( p->anExec ) p->anExec[(int)(pOp-aOp)]++; 751 #endif 752 753 /* Only allow tracing if SQLITE_DEBUG is defined. 754 */ 755 #ifdef SQLITE_DEBUG 756 if( db->flags & SQLITE_VdbeTrace ){ 757 sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp); 758 test_trace_breakpoint((int)(pOp - aOp),pOp,p); 759 } 760 #endif 761 762 763 /* Check to see if we need to simulate an interrupt. This only happens 764 ** if we have a special test build. 765 */ 766 #ifdef SQLITE_TEST 767 if( sqlite3_interrupt_count>0 ){ 768 sqlite3_interrupt_count--; 769 if( sqlite3_interrupt_count==0 ){ 770 sqlite3_interrupt(db); 771 } 772 } 773 #endif 774 775 /* Sanity checking on other operands */ 776 #ifdef SQLITE_DEBUG 777 { 778 u8 opProperty = sqlite3OpcodeProperty[pOp->opcode]; 779 if( (opProperty & OPFLG_IN1)!=0 ){ 780 assert( pOp->p1>0 ); 781 assert( pOp->p1<=(p->nMem+1 - p->nCursor) ); 782 assert( memIsValid(&aMem[pOp->p1]) ); 783 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) ); 784 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]); 785 } 786 if( (opProperty & OPFLG_IN2)!=0 ){ 787 assert( pOp->p2>0 ); 788 assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); 789 assert( memIsValid(&aMem[pOp->p2]) ); 790 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) ); 791 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]); 792 } 793 if( (opProperty & OPFLG_IN3)!=0 ){ 794 assert( pOp->p3>0 ); 795 assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); 796 assert( memIsValid(&aMem[pOp->p3]) ); 797 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) ); 798 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]); 799 } 800 if( (opProperty & OPFLG_OUT2)!=0 ){ 801 assert( pOp->p2>0 ); 802 assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); 803 memAboutToChange(p, &aMem[pOp->p2]); 804 } 805 if( (opProperty & OPFLG_OUT3)!=0 ){ 806 assert( pOp->p3>0 ); 807 assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); 808 memAboutToChange(p, &aMem[pOp->p3]); 809 } 810 } 811 #endif 812 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) 813 pOrigOp = pOp; 814 #endif 815 816 switch( pOp->opcode ){ 817 818 /***************************************************************************** 819 ** What follows is a massive switch statement where each case implements a 820 ** separate instruction in the virtual machine. If we follow the usual 821 ** indentation conventions, each case should be indented by 6 spaces. But 822 ** that is a lot of wasted space on the left margin. So the code within 823 ** the switch statement will break with convention and be flush-left. Another 824 ** big comment (similar to this one) will mark the point in the code where 825 ** we transition back to normal indentation. 826 ** 827 ** The formatting of each case is important. The makefile for SQLite 828 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this 829 ** file looking for lines that begin with "case OP_". The opcodes.h files 830 ** will be filled with #defines that give unique integer values to each 831 ** opcode and the opcodes.c file is filled with an array of strings where 832 ** each string is the symbolic name for the corresponding opcode. If the 833 ** case statement is followed by a comment of the form "/# same as ... #/" 834 ** that comment is used to determine the particular value of the opcode. 835 ** 836 ** Other keywords in the comment that follows each case are used to 837 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[]. 838 ** Keywords include: in1, in2, in3, out2, out3. See 839 ** the mkopcodeh.awk script for additional information. 840 ** 841 ** Documentation about VDBE opcodes is generated by scanning this file 842 ** for lines of that contain "Opcode:". That line and all subsequent 843 ** comment lines are used in the generation of the opcode.html documentation 844 ** file. 845 ** 846 ** SUMMARY: 847 ** 848 ** Formatting is important to scripts that scan this file. 849 ** Do not deviate from the formatting style currently in use. 850 ** 851 *****************************************************************************/ 852 853 /* Opcode: Goto * P2 * * * 854 ** 855 ** An unconditional jump to address P2. 856 ** The next instruction executed will be 857 ** the one at index P2 from the beginning of 858 ** the program. 859 ** 860 ** The P1 parameter is not actually used by this opcode. However, it 861 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell 862 ** that this Goto is the bottom of a loop and that the lines from P2 down 863 ** to the current line should be indented for EXPLAIN output. 864 */ 865 case OP_Goto: { /* jump */ 866 867 #ifdef SQLITE_DEBUG 868 /* In debuggging mode, when the p5 flags is set on an OP_Goto, that 869 ** means we should really jump back to the preceeding OP_ReleaseReg 870 ** instruction. */ 871 if( pOp->p5 ){ 872 assert( pOp->p2 < (int)(pOp - aOp) ); 873 assert( pOp->p2 > 1 ); 874 pOp = &aOp[pOp->p2 - 2]; 875 assert( pOp[1].opcode==OP_ReleaseReg ); 876 goto check_for_interrupt; 877 } 878 #endif 879 880 jump_to_p2_and_check_for_interrupt: 881 pOp = &aOp[pOp->p2 - 1]; 882 883 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev, 884 ** OP_VNext, or OP_SorterNext) all jump here upon 885 ** completion. Check to see if sqlite3_interrupt() has been called 886 ** or if the progress callback needs to be invoked. 887 ** 888 ** This code uses unstructured "goto" statements and does not look clean. 889 ** But that is not due to sloppy coding habits. The code is written this 890 ** way for performance, to avoid having to run the interrupt and progress 891 ** checks on every opcode. This helps sqlite3_step() to run about 1.5% 892 ** faster according to "valgrind --tool=cachegrind" */ 893 check_for_interrupt: 894 if( db->u1.isInterrupted ) goto abort_due_to_interrupt; 895 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 896 /* Call the progress callback if it is configured and the required number 897 ** of VDBE ops have been executed (either since this invocation of 898 ** sqlite3VdbeExec() or since last time the progress callback was called). 899 ** If the progress callback returns non-zero, exit the virtual machine with 900 ** a return code SQLITE_ABORT. 901 */ 902 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){ 903 assert( db->nProgressOps!=0 ); 904 nProgressLimit += db->nProgressOps; 905 if( db->xProgress(db->pProgressArg) ){ 906 nProgressLimit = 0xffffffff; 907 rc = SQLITE_INTERRUPT; 908 goto abort_due_to_error; 909 } 910 } 911 #endif 912 913 break; 914 } 915 916 /* Opcode: Gosub P1 P2 * * * 917 ** 918 ** Write the current address onto register P1 919 ** and then jump to address P2. 920 */ 921 case OP_Gosub: { /* jump */ 922 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); 923 pIn1 = &aMem[pOp->p1]; 924 assert( VdbeMemDynamic(pIn1)==0 ); 925 memAboutToChange(p, pIn1); 926 pIn1->flags = MEM_Int; 927 pIn1->u.i = (int)(pOp-aOp); 928 REGISTER_TRACE(pOp->p1, pIn1); 929 930 /* Most jump operations do a goto to this spot in order to update 931 ** the pOp pointer. */ 932 jump_to_p2: 933 pOp = &aOp[pOp->p2 - 1]; 934 break; 935 } 936 937 /* Opcode: Return P1 * * * * 938 ** 939 ** Jump to the next instruction after the address in register P1. After 940 ** the jump, register P1 becomes undefined. 941 */ 942 case OP_Return: { /* in1 */ 943 pIn1 = &aMem[pOp->p1]; 944 assert( pIn1->flags==MEM_Int ); 945 pOp = &aOp[pIn1->u.i]; 946 pIn1->flags = MEM_Undefined; 947 break; 948 } 949 950 /* Opcode: InitCoroutine P1 P2 P3 * * 951 ** 952 ** Set up register P1 so that it will Yield to the coroutine 953 ** located at address P3. 954 ** 955 ** If P2!=0 then the coroutine implementation immediately follows 956 ** this opcode. So jump over the coroutine implementation to 957 ** address P2. 958 ** 959 ** See also: EndCoroutine 960 */ 961 case OP_InitCoroutine: { /* jump */ 962 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); 963 assert( pOp->p2>=0 && pOp->p2<p->nOp ); 964 assert( pOp->p3>=0 && pOp->p3<p->nOp ); 965 pOut = &aMem[pOp->p1]; 966 assert( !VdbeMemDynamic(pOut) ); 967 pOut->u.i = pOp->p3 - 1; 968 pOut->flags = MEM_Int; 969 if( pOp->p2 ) goto jump_to_p2; 970 break; 971 } 972 973 /* Opcode: EndCoroutine P1 * * * * 974 ** 975 ** The instruction at the address in register P1 is a Yield. 976 ** Jump to the P2 parameter of that Yield. 977 ** After the jump, register P1 becomes undefined. 978 ** 979 ** See also: InitCoroutine 980 */ 981 case OP_EndCoroutine: { /* in1 */ 982 VdbeOp *pCaller; 983 pIn1 = &aMem[pOp->p1]; 984 assert( pIn1->flags==MEM_Int ); 985 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp ); 986 pCaller = &aOp[pIn1->u.i]; 987 assert( pCaller->opcode==OP_Yield ); 988 assert( pCaller->p2>=0 && pCaller->p2<p->nOp ); 989 pOp = &aOp[pCaller->p2 - 1]; 990 pIn1->flags = MEM_Undefined; 991 break; 992 } 993 994 /* Opcode: Yield P1 P2 * * * 995 ** 996 ** Swap the program counter with the value in register P1. This 997 ** has the effect of yielding to a coroutine. 998 ** 999 ** If the coroutine that is launched by this instruction ends with 1000 ** Yield or Return then continue to the next instruction. But if 1001 ** the coroutine launched by this instruction ends with 1002 ** EndCoroutine, then jump to P2 rather than continuing with the 1003 ** next instruction. 1004 ** 1005 ** See also: InitCoroutine 1006 */ 1007 case OP_Yield: { /* in1, jump */ 1008 int pcDest; 1009 pIn1 = &aMem[pOp->p1]; 1010 assert( VdbeMemDynamic(pIn1)==0 ); 1011 pIn1->flags = MEM_Int; 1012 pcDest = (int)pIn1->u.i; 1013 pIn1->u.i = (int)(pOp - aOp); 1014 REGISTER_TRACE(pOp->p1, pIn1); 1015 pOp = &aOp[pcDest]; 1016 break; 1017 } 1018 1019 /* Opcode: HaltIfNull P1 P2 P3 P4 P5 1020 ** Synopsis: if r[P3]=null halt 1021 ** 1022 ** Check the value in register P3. If it is NULL then Halt using 1023 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the 1024 ** value in register P3 is not NULL, then this routine is a no-op. 1025 ** The P5 parameter should be 1. 1026 */ 1027 case OP_HaltIfNull: { /* in3 */ 1028 pIn3 = &aMem[pOp->p3]; 1029 #ifdef SQLITE_DEBUG 1030 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); } 1031 #endif 1032 if( (pIn3->flags & MEM_Null)==0 ) break; 1033 /* Fall through into OP_Halt */ 1034 } 1035 1036 /* Opcode: Halt P1 P2 * P4 P5 1037 ** 1038 ** Exit immediately. All open cursors, etc are closed 1039 ** automatically. 1040 ** 1041 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(), 1042 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0). 1043 ** For errors, it can be some other value. If P1!=0 then P2 will determine 1044 ** whether or not to rollback the current transaction. Do not rollback 1045 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort, 1046 ** then back out all changes that have occurred during this execution of the 1047 ** VDBE, but do not rollback the transaction. 1048 ** 1049 ** If P4 is not null then it is an error message string. 1050 ** 1051 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string. 1052 ** 1053 ** 0: (no change) 1054 ** 1: NOT NULL contraint failed: P4 1055 ** 2: UNIQUE constraint failed: P4 1056 ** 3: CHECK constraint failed: P4 1057 ** 4: FOREIGN KEY constraint failed: P4 1058 ** 1059 ** If P5 is not zero and P4 is NULL, then everything after the ":" is 1060 ** omitted. 1061 ** 1062 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of 1063 ** every program. So a jump past the last instruction of the program 1064 ** is the same as executing Halt. 1065 */ 1066 case OP_Halt: { 1067 VdbeFrame *pFrame; 1068 int pcx; 1069 1070 pcx = (int)(pOp - aOp); 1071 #ifdef SQLITE_DEBUG 1072 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); } 1073 #endif 1074 if( pOp->p1==SQLITE_OK && p->pFrame ){ 1075 /* Halt the sub-program. Return control to the parent frame. */ 1076 pFrame = p->pFrame; 1077 p->pFrame = pFrame->pParent; 1078 p->nFrame--; 1079 sqlite3VdbeSetChanges(db, p->nChange); 1080 pcx = sqlite3VdbeFrameRestore(pFrame); 1081 if( pOp->p2==OE_Ignore ){ 1082 /* Instruction pcx is the OP_Program that invoked the sub-program 1083 ** currently being halted. If the p2 instruction of this OP_Halt 1084 ** instruction is set to OE_Ignore, then the sub-program is throwing 1085 ** an IGNORE exception. In this case jump to the address specified 1086 ** as the p2 of the calling OP_Program. */ 1087 pcx = p->aOp[pcx].p2-1; 1088 } 1089 aOp = p->aOp; 1090 aMem = p->aMem; 1091 pOp = &aOp[pcx]; 1092 break; 1093 } 1094 p->rc = pOp->p1; 1095 p->errorAction = (u8)pOp->p2; 1096 p->pc = pcx; 1097 assert( pOp->p5<=4 ); 1098 if( p->rc ){ 1099 if( pOp->p5 ){ 1100 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK", 1101 "FOREIGN KEY" }; 1102 testcase( pOp->p5==1 ); 1103 testcase( pOp->p5==2 ); 1104 testcase( pOp->p5==3 ); 1105 testcase( pOp->p5==4 ); 1106 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]); 1107 if( pOp->p4.z ){ 1108 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z); 1109 } 1110 }else{ 1111 sqlite3VdbeError(p, "%s", pOp->p4.z); 1112 } 1113 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg); 1114 } 1115 rc = sqlite3VdbeHalt(p); 1116 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR ); 1117 if( rc==SQLITE_BUSY ){ 1118 p->rc = SQLITE_BUSY; 1119 }else{ 1120 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ); 1121 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 ); 1122 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE; 1123 } 1124 goto vdbe_return; 1125 } 1126 1127 /* Opcode: Integer P1 P2 * * * 1128 ** Synopsis: r[P2]=P1 1129 ** 1130 ** The 32-bit integer value P1 is written into register P2. 1131 */ 1132 case OP_Integer: { /* out2 */ 1133 pOut = out2Prerelease(p, pOp); 1134 pOut->u.i = pOp->p1; 1135 break; 1136 } 1137 1138 /* Opcode: Int64 * P2 * P4 * 1139 ** Synopsis: r[P2]=P4 1140 ** 1141 ** P4 is a pointer to a 64-bit integer value. 1142 ** Write that value into register P2. 1143 */ 1144 case OP_Int64: { /* out2 */ 1145 pOut = out2Prerelease(p, pOp); 1146 assert( pOp->p4.pI64!=0 ); 1147 pOut->u.i = *pOp->p4.pI64; 1148 break; 1149 } 1150 1151 #ifndef SQLITE_OMIT_FLOATING_POINT 1152 /* Opcode: Real * P2 * P4 * 1153 ** Synopsis: r[P2]=P4 1154 ** 1155 ** P4 is a pointer to a 64-bit floating point value. 1156 ** Write that value into register P2. 1157 */ 1158 case OP_Real: { /* same as TK_FLOAT, out2 */ 1159 pOut = out2Prerelease(p, pOp); 1160 pOut->flags = MEM_Real; 1161 assert( !sqlite3IsNaN(*pOp->p4.pReal) ); 1162 pOut->u.r = *pOp->p4.pReal; 1163 break; 1164 } 1165 #endif 1166 1167 /* Opcode: String8 * P2 * P4 * 1168 ** Synopsis: r[P2]='P4' 1169 ** 1170 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 1171 ** into a String opcode before it is executed for the first time. During 1172 ** this transformation, the length of string P4 is computed and stored 1173 ** as the P1 parameter. 1174 */ 1175 case OP_String8: { /* same as TK_STRING, out2 */ 1176 assert( pOp->p4.z!=0 ); 1177 pOut = out2Prerelease(p, pOp); 1178 pOp->p1 = sqlite3Strlen30(pOp->p4.z); 1179 1180 #ifndef SQLITE_OMIT_UTF16 1181 if( encoding!=SQLITE_UTF8 ){ 1182 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC); 1183 assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG ); 1184 if( rc ) goto too_big; 1185 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem; 1186 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z ); 1187 assert( VdbeMemDynamic(pOut)==0 ); 1188 pOut->szMalloc = 0; 1189 pOut->flags |= MEM_Static; 1190 if( pOp->p4type==P4_DYNAMIC ){ 1191 sqlite3DbFree(db, pOp->p4.z); 1192 } 1193 pOp->p4type = P4_DYNAMIC; 1194 pOp->p4.z = pOut->z; 1195 pOp->p1 = pOut->n; 1196 } 1197 #endif 1198 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 1199 goto too_big; 1200 } 1201 pOp->opcode = OP_String; 1202 assert( rc==SQLITE_OK ); 1203 /* Fall through to the next case, OP_String */ 1204 } 1205 1206 /* Opcode: String P1 P2 P3 P4 P5 1207 ** Synopsis: r[P2]='P4' (len=P1) 1208 ** 1209 ** The string value P4 of length P1 (bytes) is stored in register P2. 1210 ** 1211 ** If P3 is not zero and the content of register P3 is equal to P5, then 1212 ** the datatype of the register P2 is converted to BLOB. The content is 1213 ** the same sequence of bytes, it is merely interpreted as a BLOB instead 1214 ** of a string, as if it had been CAST. In other words: 1215 ** 1216 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB) 1217 */ 1218 case OP_String: { /* out2 */ 1219 assert( pOp->p4.z!=0 ); 1220 pOut = out2Prerelease(p, pOp); 1221 pOut->flags = MEM_Str|MEM_Static|MEM_Term; 1222 pOut->z = pOp->p4.z; 1223 pOut->n = pOp->p1; 1224 pOut->enc = encoding; 1225 UPDATE_MAX_BLOBSIZE(pOut); 1226 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS 1227 if( pOp->p3>0 ){ 1228 assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); 1229 pIn3 = &aMem[pOp->p3]; 1230 assert( pIn3->flags & MEM_Int ); 1231 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term; 1232 } 1233 #endif 1234 break; 1235 } 1236 1237 /* Opcode: Null P1 P2 P3 * * 1238 ** Synopsis: r[P2..P3]=NULL 1239 ** 1240 ** Write a NULL into registers P2. If P3 greater than P2, then also write 1241 ** NULL into register P3 and every register in between P2 and P3. If P3 1242 ** is less than P2 (typically P3 is zero) then only register P2 is 1243 ** set to NULL. 1244 ** 1245 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that 1246 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on 1247 ** OP_Ne or OP_Eq. 1248 */ 1249 case OP_Null: { /* out2 */ 1250 int cnt; 1251 u16 nullFlag; 1252 pOut = out2Prerelease(p, pOp); 1253 cnt = pOp->p3-pOp->p2; 1254 assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); 1255 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null; 1256 pOut->n = 0; 1257 #ifdef SQLITE_DEBUG 1258 pOut->uTemp = 0; 1259 #endif 1260 while( cnt>0 ){ 1261 pOut++; 1262 memAboutToChange(p, pOut); 1263 sqlite3VdbeMemSetNull(pOut); 1264 pOut->flags = nullFlag; 1265 pOut->n = 0; 1266 cnt--; 1267 } 1268 break; 1269 } 1270 1271 /* Opcode: SoftNull P1 * * * * 1272 ** Synopsis: r[P1]=NULL 1273 ** 1274 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord 1275 ** instruction, but do not free any string or blob memory associated with 1276 ** the register, so that if the value was a string or blob that was 1277 ** previously copied using OP_SCopy, the copies will continue to be valid. 1278 */ 1279 case OP_SoftNull: { 1280 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); 1281 pOut = &aMem[pOp->p1]; 1282 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null; 1283 break; 1284 } 1285 1286 /* Opcode: Blob P1 P2 * P4 * 1287 ** Synopsis: r[P2]=P4 (len=P1) 1288 ** 1289 ** P4 points to a blob of data P1 bytes long. Store this 1290 ** blob in register P2. 1291 */ 1292 case OP_Blob: { /* out2 */ 1293 assert( pOp->p1 <= SQLITE_MAX_LENGTH ); 1294 pOut = out2Prerelease(p, pOp); 1295 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0); 1296 pOut->enc = encoding; 1297 UPDATE_MAX_BLOBSIZE(pOut); 1298 break; 1299 } 1300 1301 /* Opcode: Variable P1 P2 * P4 * 1302 ** Synopsis: r[P2]=parameter(P1,P4) 1303 ** 1304 ** Transfer the values of bound parameter P1 into register P2 1305 ** 1306 ** If the parameter is named, then its name appears in P4. 1307 ** The P4 value is used by sqlite3_bind_parameter_name(). 1308 */ 1309 case OP_Variable: { /* out2 */ 1310 Mem *pVar; /* Value being transferred */ 1311 1312 assert( pOp->p1>0 && pOp->p1<=p->nVar ); 1313 assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) ); 1314 pVar = &p->aVar[pOp->p1 - 1]; 1315 if( sqlite3VdbeMemTooBig(pVar) ){ 1316 goto too_big; 1317 } 1318 pOut = &aMem[pOp->p2]; 1319 if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut); 1320 memcpy(pOut, pVar, MEMCELLSIZE); 1321 pOut->flags &= ~(MEM_Dyn|MEM_Ephem); 1322 pOut->flags |= MEM_Static|MEM_FromBind; 1323 UPDATE_MAX_BLOBSIZE(pOut); 1324 break; 1325 } 1326 1327 /* Opcode: Move P1 P2 P3 * * 1328 ** Synopsis: r[P2@P3]=r[P1@P3] 1329 ** 1330 ** Move the P3 values in register P1..P1+P3-1 over into 1331 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are 1332 ** left holding a NULL. It is an error for register ranges 1333 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error 1334 ** for P3 to be less than 1. 1335 */ 1336 case OP_Move: { 1337 int n; /* Number of registers left to copy */ 1338 int p1; /* Register to copy from */ 1339 int p2; /* Register to copy to */ 1340 1341 n = pOp->p3; 1342 p1 = pOp->p1; 1343 p2 = pOp->p2; 1344 assert( n>0 && p1>0 && p2>0 ); 1345 assert( p1+n<=p2 || p2+n<=p1 ); 1346 1347 pIn1 = &aMem[p1]; 1348 pOut = &aMem[p2]; 1349 do{ 1350 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] ); 1351 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] ); 1352 assert( memIsValid(pIn1) ); 1353 memAboutToChange(p, pOut); 1354 sqlite3VdbeMemMove(pOut, pIn1); 1355 #ifdef SQLITE_DEBUG 1356 pIn1->pScopyFrom = 0; 1357 { int i; 1358 for(i=1; i<p->nMem; i++){ 1359 if( aMem[i].pScopyFrom==pIn1 ){ 1360 aMem[i].pScopyFrom = pOut; 1361 } 1362 } 1363 } 1364 #endif 1365 Deephemeralize(pOut); 1366 REGISTER_TRACE(p2++, pOut); 1367 pIn1++; 1368 pOut++; 1369 }while( --n ); 1370 break; 1371 } 1372 1373 /* Opcode: Copy P1 P2 P3 * * 1374 ** Synopsis: r[P2@P3+1]=r[P1@P3+1] 1375 ** 1376 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3. 1377 ** 1378 ** This instruction makes a deep copy of the value. A duplicate 1379 ** is made of any string or blob constant. See also OP_SCopy. 1380 */ 1381 case OP_Copy: { 1382 int n; 1383 1384 n = pOp->p3; 1385 pIn1 = &aMem[pOp->p1]; 1386 pOut = &aMem[pOp->p2]; 1387 assert( pOut!=pIn1 ); 1388 while( 1 ){ 1389 memAboutToChange(p, pOut); 1390 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); 1391 Deephemeralize(pOut); 1392 #ifdef SQLITE_DEBUG 1393 pOut->pScopyFrom = 0; 1394 #endif 1395 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut); 1396 if( (n--)==0 ) break; 1397 pOut++; 1398 pIn1++; 1399 } 1400 break; 1401 } 1402 1403 /* Opcode: SCopy P1 P2 * * * 1404 ** Synopsis: r[P2]=r[P1] 1405 ** 1406 ** Make a shallow copy of register P1 into register P2. 1407 ** 1408 ** This instruction makes a shallow copy of the value. If the value 1409 ** is a string or blob, then the copy is only a pointer to the 1410 ** original and hence if the original changes so will the copy. 1411 ** Worse, if the original is deallocated, the copy becomes invalid. 1412 ** Thus the program must guarantee that the original will not change 1413 ** during the lifetime of the copy. Use OP_Copy to make a complete 1414 ** copy. 1415 */ 1416 case OP_SCopy: { /* out2 */ 1417 pIn1 = &aMem[pOp->p1]; 1418 pOut = &aMem[pOp->p2]; 1419 assert( pOut!=pIn1 ); 1420 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); 1421 #ifdef SQLITE_DEBUG 1422 pOut->pScopyFrom = pIn1; 1423 pOut->mScopyFlags = pIn1->flags; 1424 #endif 1425 break; 1426 } 1427 1428 /* Opcode: IntCopy P1 P2 * * * 1429 ** Synopsis: r[P2]=r[P1] 1430 ** 1431 ** Transfer the integer value held in register P1 into register P2. 1432 ** 1433 ** This is an optimized version of SCopy that works only for integer 1434 ** values. 1435 */ 1436 case OP_IntCopy: { /* out2 */ 1437 pIn1 = &aMem[pOp->p1]; 1438 assert( (pIn1->flags & MEM_Int)!=0 ); 1439 pOut = &aMem[pOp->p2]; 1440 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i); 1441 break; 1442 } 1443 1444 /* Opcode: ResultRow P1 P2 * * * 1445 ** Synopsis: output=r[P1@P2] 1446 ** 1447 ** The registers P1 through P1+P2-1 contain a single row of 1448 ** results. This opcode causes the sqlite3_step() call to terminate 1449 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt 1450 ** structure to provide access to the r(P1)..r(P1+P2-1) values as 1451 ** the result row. 1452 */ 1453 case OP_ResultRow: { 1454 Mem *pMem; 1455 int i; 1456 assert( p->nResColumn==pOp->p2 ); 1457 assert( pOp->p1>0 ); 1458 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 ); 1459 1460 /* If this statement has violated immediate foreign key constraints, do 1461 ** not return the number of rows modified. And do not RELEASE the statement 1462 ** transaction. It needs to be rolled back. */ 1463 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){ 1464 assert( db->flags&SQLITE_CountRows ); 1465 assert( p->usesStmtJournal ); 1466 goto abort_due_to_error; 1467 } 1468 1469 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then 1470 ** DML statements invoke this opcode to return the number of rows 1471 ** modified to the user. This is the only way that a VM that 1472 ** opens a statement transaction may invoke this opcode. 1473 ** 1474 ** In case this is such a statement, close any statement transaction 1475 ** opened by this VM before returning control to the user. This is to 1476 ** ensure that statement-transactions are always nested, not overlapping. 1477 ** If the open statement-transaction is not closed here, then the user 1478 ** may step another VM that opens its own statement transaction. This 1479 ** may lead to overlapping statement transactions. 1480 ** 1481 ** The statement transaction is never a top-level transaction. Hence 1482 ** the RELEASE call below can never fail. 1483 */ 1484 assert( p->iStatement==0 || db->flags&SQLITE_CountRows ); 1485 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE); 1486 assert( rc==SQLITE_OK ); 1487 1488 /* Invalidate all ephemeral cursor row caches */ 1489 p->cacheCtr = (p->cacheCtr + 2)|1; 1490 1491 /* Make sure the results of the current row are \000 terminated 1492 ** and have an assigned type. The results are de-ephemeralized as 1493 ** a side effect. 1494 */ 1495 pMem = p->pResultSet = &aMem[pOp->p1]; 1496 for(i=0; i<pOp->p2; i++){ 1497 assert( memIsValid(&pMem[i]) ); 1498 Deephemeralize(&pMem[i]); 1499 assert( (pMem[i].flags & MEM_Ephem)==0 1500 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 ); 1501 sqlite3VdbeMemNulTerminate(&pMem[i]); 1502 REGISTER_TRACE(pOp->p1+i, &pMem[i]); 1503 #ifdef SQLITE_DEBUG 1504 /* The registers in the result will not be used again when the 1505 ** prepared statement restarts. This is because sqlite3_column() 1506 ** APIs might have caused type conversions of made other changes to 1507 ** the register values. Therefore, we can go ahead and break any 1508 ** OP_SCopy dependencies. */ 1509 pMem[i].pScopyFrom = 0; 1510 #endif 1511 } 1512 if( db->mallocFailed ) goto no_mem; 1513 1514 if( db->mTrace & SQLITE_TRACE_ROW ){ 1515 db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0); 1516 } 1517 1518 1519 /* Return SQLITE_ROW 1520 */ 1521 p->pc = (int)(pOp - aOp) + 1; 1522 rc = SQLITE_ROW; 1523 goto vdbe_return; 1524 } 1525 1526 /* Opcode: Concat P1 P2 P3 * * 1527 ** Synopsis: r[P3]=r[P2]+r[P1] 1528 ** 1529 ** Add the text in register P1 onto the end of the text in 1530 ** register P2 and store the result in register P3. 1531 ** If either the P1 or P2 text are NULL then store NULL in P3. 1532 ** 1533 ** P3 = P2 || P1 1534 ** 1535 ** It is illegal for P1 and P3 to be the same register. Sometimes, 1536 ** if P3 is the same register as P2, the implementation is able 1537 ** to avoid a memcpy(). 1538 */ 1539 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ 1540 i64 nByte; /* Total size of the output string or blob */ 1541 u16 flags1; /* Initial flags for P1 */ 1542 u16 flags2; /* Initial flags for P2 */ 1543 1544 pIn1 = &aMem[pOp->p1]; 1545 pIn2 = &aMem[pOp->p2]; 1546 pOut = &aMem[pOp->p3]; 1547 testcase( pIn1==pIn2 ); 1548 testcase( pOut==pIn2 ); 1549 assert( pIn1!=pOut ); 1550 flags1 = pIn1->flags; 1551 testcase( flags1 & MEM_Null ); 1552 testcase( pIn2->flags & MEM_Null ); 1553 if( (flags1 | pIn2->flags) & MEM_Null ){ 1554 sqlite3VdbeMemSetNull(pOut); 1555 break; 1556 } 1557 if( (flags1 & (MEM_Str|MEM_Blob))==0 ){ 1558 if( sqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem; 1559 flags1 = pIn1->flags & ~MEM_Str; 1560 }else if( (flags1 & MEM_Zero)!=0 ){ 1561 if( sqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem; 1562 flags1 = pIn1->flags & ~MEM_Str; 1563 } 1564 flags2 = pIn2->flags; 1565 if( (flags2 & (MEM_Str|MEM_Blob))==0 ){ 1566 if( sqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem; 1567 flags2 = pIn2->flags & ~MEM_Str; 1568 }else if( (flags2 & MEM_Zero)!=0 ){ 1569 if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem; 1570 flags2 = pIn2->flags & ~MEM_Str; 1571 } 1572 nByte = pIn1->n + pIn2->n; 1573 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 1574 goto too_big; 1575 } 1576 if( sqlite3VdbeMemGrow(pOut, (int)nByte+3, pOut==pIn2) ){ 1577 goto no_mem; 1578 } 1579 MemSetTypeFlag(pOut, MEM_Str); 1580 if( pOut!=pIn2 ){ 1581 memcpy(pOut->z, pIn2->z, pIn2->n); 1582 assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) ); 1583 pIn2->flags = flags2; 1584 } 1585 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n); 1586 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) ); 1587 pIn1->flags = flags1; 1588 pOut->z[nByte]=0; 1589 pOut->z[nByte+1] = 0; 1590 pOut->z[nByte+2] = 0; 1591 pOut->flags |= MEM_Term; 1592 pOut->n = (int)nByte; 1593 pOut->enc = encoding; 1594 UPDATE_MAX_BLOBSIZE(pOut); 1595 break; 1596 } 1597 1598 /* Opcode: Add P1 P2 P3 * * 1599 ** Synopsis: r[P3]=r[P1]+r[P2] 1600 ** 1601 ** Add the value in register P1 to the value in register P2 1602 ** and store the result in register P3. 1603 ** If either input is NULL, the result is NULL. 1604 */ 1605 /* Opcode: Multiply P1 P2 P3 * * 1606 ** Synopsis: r[P3]=r[P1]*r[P2] 1607 ** 1608 ** 1609 ** Multiply the value in register P1 by the value in register P2 1610 ** and store the result in register P3. 1611 ** If either input is NULL, the result is NULL. 1612 */ 1613 /* Opcode: Subtract P1 P2 P3 * * 1614 ** Synopsis: r[P3]=r[P2]-r[P1] 1615 ** 1616 ** Subtract the value in register P1 from the value in register P2 1617 ** and store the result in register P3. 1618 ** If either input is NULL, the result is NULL. 1619 */ 1620 /* Opcode: Divide P1 P2 P3 * * 1621 ** Synopsis: r[P3]=r[P2]/r[P1] 1622 ** 1623 ** Divide the value in register P1 by the value in register P2 1624 ** and store the result in register P3 (P3=P2/P1). If the value in 1625 ** register P1 is zero, then the result is NULL. If either input is 1626 ** NULL, the result is NULL. 1627 */ 1628 /* Opcode: Remainder P1 P2 P3 * * 1629 ** Synopsis: r[P3]=r[P2]%r[P1] 1630 ** 1631 ** Compute the remainder after integer register P2 is divided by 1632 ** register P1 and store the result in register P3. 1633 ** If the value in register P1 is zero the result is NULL. 1634 ** If either operand is NULL, the result is NULL. 1635 */ 1636 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */ 1637 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */ 1638 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */ 1639 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */ 1640 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */ 1641 u16 flags; /* Combined MEM_* flags from both inputs */ 1642 u16 type1; /* Numeric type of left operand */ 1643 u16 type2; /* Numeric type of right operand */ 1644 i64 iA; /* Integer value of left operand */ 1645 i64 iB; /* Integer value of right operand */ 1646 double rA; /* Real value of left operand */ 1647 double rB; /* Real value of right operand */ 1648 1649 pIn1 = &aMem[pOp->p1]; 1650 type1 = numericType(pIn1); 1651 pIn2 = &aMem[pOp->p2]; 1652 type2 = numericType(pIn2); 1653 pOut = &aMem[pOp->p3]; 1654 flags = pIn1->flags | pIn2->flags; 1655 if( (type1 & type2 & MEM_Int)!=0 ){ 1656 iA = pIn1->u.i; 1657 iB = pIn2->u.i; 1658 switch( pOp->opcode ){ 1659 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break; 1660 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break; 1661 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break; 1662 case OP_Divide: { 1663 if( iA==0 ) goto arithmetic_result_is_null; 1664 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math; 1665 iB /= iA; 1666 break; 1667 } 1668 default: { 1669 if( iA==0 ) goto arithmetic_result_is_null; 1670 if( iA==-1 ) iA = 1; 1671 iB %= iA; 1672 break; 1673 } 1674 } 1675 pOut->u.i = iB; 1676 MemSetTypeFlag(pOut, MEM_Int); 1677 }else if( (flags & MEM_Null)!=0 ){ 1678 goto arithmetic_result_is_null; 1679 }else{ 1680 fp_math: 1681 rA = sqlite3VdbeRealValue(pIn1); 1682 rB = sqlite3VdbeRealValue(pIn2); 1683 switch( pOp->opcode ){ 1684 case OP_Add: rB += rA; break; 1685 case OP_Subtract: rB -= rA; break; 1686 case OP_Multiply: rB *= rA; break; 1687 case OP_Divide: { 1688 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ 1689 if( rA==(double)0 ) goto arithmetic_result_is_null; 1690 rB /= rA; 1691 break; 1692 } 1693 default: { 1694 iA = sqlite3VdbeIntValue(pIn1); 1695 iB = sqlite3VdbeIntValue(pIn2); 1696 if( iA==0 ) goto arithmetic_result_is_null; 1697 if( iA==-1 ) iA = 1; 1698 rB = (double)(iB % iA); 1699 break; 1700 } 1701 } 1702 #ifdef SQLITE_OMIT_FLOATING_POINT 1703 pOut->u.i = rB; 1704 MemSetTypeFlag(pOut, MEM_Int); 1705 #else 1706 if( sqlite3IsNaN(rB) ){ 1707 goto arithmetic_result_is_null; 1708 } 1709 pOut->u.r = rB; 1710 MemSetTypeFlag(pOut, MEM_Real); 1711 #endif 1712 } 1713 break; 1714 1715 arithmetic_result_is_null: 1716 sqlite3VdbeMemSetNull(pOut); 1717 break; 1718 } 1719 1720 /* Opcode: CollSeq P1 * * P4 1721 ** 1722 ** P4 is a pointer to a CollSeq object. If the next call to a user function 1723 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will 1724 ** be returned. This is used by the built-in min(), max() and nullif() 1725 ** functions. 1726 ** 1727 ** If P1 is not zero, then it is a register that a subsequent min() or 1728 ** max() aggregate will set to 1 if the current row is not the minimum or 1729 ** maximum. The P1 register is initialized to 0 by this instruction. 1730 ** 1731 ** The interface used by the implementation of the aforementioned functions 1732 ** to retrieve the collation sequence set by this opcode is not available 1733 ** publicly. Only built-in functions have access to this feature. 1734 */ 1735 case OP_CollSeq: { 1736 assert( pOp->p4type==P4_COLLSEQ ); 1737 if( pOp->p1 ){ 1738 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0); 1739 } 1740 break; 1741 } 1742 1743 /* Opcode: BitAnd P1 P2 P3 * * 1744 ** Synopsis: r[P3]=r[P1]&r[P2] 1745 ** 1746 ** Take the bit-wise AND of the values in register P1 and P2 and 1747 ** store the result in register P3. 1748 ** If either input is NULL, the result is NULL. 1749 */ 1750 /* Opcode: BitOr P1 P2 P3 * * 1751 ** Synopsis: r[P3]=r[P1]|r[P2] 1752 ** 1753 ** Take the bit-wise OR of the values in register P1 and P2 and 1754 ** store the result in register P3. 1755 ** If either input is NULL, the result is NULL. 1756 */ 1757 /* Opcode: ShiftLeft P1 P2 P3 * * 1758 ** Synopsis: r[P3]=r[P2]<<r[P1] 1759 ** 1760 ** Shift the integer value in register P2 to the left by the 1761 ** number of bits specified by the integer in register P1. 1762 ** Store the result in register P3. 1763 ** If either input is NULL, the result is NULL. 1764 */ 1765 /* Opcode: ShiftRight P1 P2 P3 * * 1766 ** Synopsis: r[P3]=r[P2]>>r[P1] 1767 ** 1768 ** Shift the integer value in register P2 to the right by the 1769 ** number of bits specified by the integer in register P1. 1770 ** Store the result in register P3. 1771 ** If either input is NULL, the result is NULL. 1772 */ 1773 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */ 1774 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */ 1775 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */ 1776 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ 1777 i64 iA; 1778 u64 uA; 1779 i64 iB; 1780 u8 op; 1781 1782 pIn1 = &aMem[pOp->p1]; 1783 pIn2 = &aMem[pOp->p2]; 1784 pOut = &aMem[pOp->p3]; 1785 if( (pIn1->flags | pIn2->flags) & MEM_Null ){ 1786 sqlite3VdbeMemSetNull(pOut); 1787 break; 1788 } 1789 iA = sqlite3VdbeIntValue(pIn2); 1790 iB = sqlite3VdbeIntValue(pIn1); 1791 op = pOp->opcode; 1792 if( op==OP_BitAnd ){ 1793 iA &= iB; 1794 }else if( op==OP_BitOr ){ 1795 iA |= iB; 1796 }else if( iB!=0 ){ 1797 assert( op==OP_ShiftRight || op==OP_ShiftLeft ); 1798 1799 /* If shifting by a negative amount, shift in the other direction */ 1800 if( iB<0 ){ 1801 assert( OP_ShiftRight==OP_ShiftLeft+1 ); 1802 op = 2*OP_ShiftLeft + 1 - op; 1803 iB = iB>(-64) ? -iB : 64; 1804 } 1805 1806 if( iB>=64 ){ 1807 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1; 1808 }else{ 1809 memcpy(&uA, &iA, sizeof(uA)); 1810 if( op==OP_ShiftLeft ){ 1811 uA <<= iB; 1812 }else{ 1813 uA >>= iB; 1814 /* Sign-extend on a right shift of a negative number */ 1815 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB); 1816 } 1817 memcpy(&iA, &uA, sizeof(iA)); 1818 } 1819 } 1820 pOut->u.i = iA; 1821 MemSetTypeFlag(pOut, MEM_Int); 1822 break; 1823 } 1824 1825 /* Opcode: AddImm P1 P2 * * * 1826 ** Synopsis: r[P1]=r[P1]+P2 1827 ** 1828 ** Add the constant P2 to the value in register P1. 1829 ** The result is always an integer. 1830 ** 1831 ** To force any register to be an integer, just add 0. 1832 */ 1833 case OP_AddImm: { /* in1 */ 1834 pIn1 = &aMem[pOp->p1]; 1835 memAboutToChange(p, pIn1); 1836 sqlite3VdbeMemIntegerify(pIn1); 1837 pIn1->u.i += pOp->p2; 1838 break; 1839 } 1840 1841 /* Opcode: MustBeInt P1 P2 * * * 1842 ** 1843 ** Force the value in register P1 to be an integer. If the value 1844 ** in P1 is not an integer and cannot be converted into an integer 1845 ** without data loss, then jump immediately to P2, or if P2==0 1846 ** raise an SQLITE_MISMATCH exception. 1847 */ 1848 case OP_MustBeInt: { /* jump, in1 */ 1849 pIn1 = &aMem[pOp->p1]; 1850 if( (pIn1->flags & MEM_Int)==0 ){ 1851 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding); 1852 if( (pIn1->flags & MEM_Int)==0 ){ 1853 VdbeBranchTaken(1, 2); 1854 if( pOp->p2==0 ){ 1855 rc = SQLITE_MISMATCH; 1856 goto abort_due_to_error; 1857 }else{ 1858 goto jump_to_p2; 1859 } 1860 } 1861 } 1862 VdbeBranchTaken(0, 2); 1863 MemSetTypeFlag(pIn1, MEM_Int); 1864 break; 1865 } 1866 1867 #ifndef SQLITE_OMIT_FLOATING_POINT 1868 /* Opcode: RealAffinity P1 * * * * 1869 ** 1870 ** If register P1 holds an integer convert it to a real value. 1871 ** 1872 ** This opcode is used when extracting information from a column that 1873 ** has REAL affinity. Such column values may still be stored as 1874 ** integers, for space efficiency, but after extraction we want them 1875 ** to have only a real value. 1876 */ 1877 case OP_RealAffinity: { /* in1 */ 1878 pIn1 = &aMem[pOp->p1]; 1879 if( pIn1->flags & (MEM_Int|MEM_IntReal) ){ 1880 testcase( pIn1->flags & MEM_Int ); 1881 testcase( pIn1->flags & MEM_IntReal ); 1882 sqlite3VdbeMemRealify(pIn1); 1883 REGISTER_TRACE(pOp->p1, pIn1); 1884 } 1885 break; 1886 } 1887 #endif 1888 1889 #ifndef SQLITE_OMIT_CAST 1890 /* Opcode: Cast P1 P2 * * * 1891 ** Synopsis: affinity(r[P1]) 1892 ** 1893 ** Force the value in register P1 to be the type defined by P2. 1894 ** 1895 ** <ul> 1896 ** <li> P2=='A' → BLOB 1897 ** <li> P2=='B' → TEXT 1898 ** <li> P2=='C' → NUMERIC 1899 ** <li> P2=='D' → INTEGER 1900 ** <li> P2=='E' → REAL 1901 ** </ul> 1902 ** 1903 ** A NULL value is not changed by this routine. It remains NULL. 1904 */ 1905 case OP_Cast: { /* in1 */ 1906 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL ); 1907 testcase( pOp->p2==SQLITE_AFF_TEXT ); 1908 testcase( pOp->p2==SQLITE_AFF_BLOB ); 1909 testcase( pOp->p2==SQLITE_AFF_NUMERIC ); 1910 testcase( pOp->p2==SQLITE_AFF_INTEGER ); 1911 testcase( pOp->p2==SQLITE_AFF_REAL ); 1912 pIn1 = &aMem[pOp->p1]; 1913 memAboutToChange(p, pIn1); 1914 rc = ExpandBlob(pIn1); 1915 if( rc ) goto abort_due_to_error; 1916 rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding); 1917 if( rc ) goto abort_due_to_error; 1918 UPDATE_MAX_BLOBSIZE(pIn1); 1919 REGISTER_TRACE(pOp->p1, pIn1); 1920 break; 1921 } 1922 #endif /* SQLITE_OMIT_CAST */ 1923 1924 /* Opcode: Eq P1 P2 P3 P4 P5 1925 ** Synopsis: IF r[P3]==r[P1] 1926 ** 1927 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then 1928 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then 1929 ** store the result of comparison in register P2. 1930 ** 1931 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character - 1932 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 1933 ** to coerce both inputs according to this affinity before the 1934 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric 1935 ** affinity is used. Note that the affinity conversions are stored 1936 ** back into the input registers P1 and P3. So this opcode can cause 1937 ** persistent changes to registers P1 and P3. 1938 ** 1939 ** Once any conversions have taken place, and neither value is NULL, 1940 ** the values are compared. If both values are blobs then memcmp() is 1941 ** used to determine the results of the comparison. If both values 1942 ** are text, then the appropriate collating function specified in 1943 ** P4 is used to do the comparison. If P4 is not specified then 1944 ** memcmp() is used to compare text string. If both values are 1945 ** numeric, then a numeric comparison is used. If the two values 1946 ** are of different types, then numbers are considered less than 1947 ** strings and strings are considered less than blobs. 1948 ** 1949 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either 1950 ** true or false and is never NULL. If both operands are NULL then the result 1951 ** of comparison is true. If either operand is NULL then the result is false. 1952 ** If neither operand is NULL the result is the same as it would be if 1953 ** the SQLITE_NULLEQ flag were omitted from P5. 1954 ** 1955 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the 1956 ** content of r[P2] is only changed if the new value is NULL or 0 (false). 1957 ** In other words, a prior r[P2] value will not be overwritten by 1 (true). 1958 */ 1959 /* Opcode: Ne P1 P2 P3 P4 P5 1960 ** Synopsis: IF r[P3]!=r[P1] 1961 ** 1962 ** This works just like the Eq opcode except that the jump is taken if 1963 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for 1964 ** additional information. 1965 ** 1966 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the 1967 ** content of r[P2] is only changed if the new value is NULL or 1 (true). 1968 ** In other words, a prior r[P2] value will not be overwritten by 0 (false). 1969 */ 1970 /* Opcode: Lt P1 P2 P3 P4 P5 1971 ** Synopsis: IF r[P3]<r[P1] 1972 ** 1973 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then 1974 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store 1975 ** the result of comparison (0 or 1 or NULL) into register P2. 1976 ** 1977 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or 1978 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL 1979 ** bit is clear then fall through if either operand is NULL. 1980 ** 1981 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character - 1982 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 1983 ** to coerce both inputs according to this affinity before the 1984 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric 1985 ** affinity is used. Note that the affinity conversions are stored 1986 ** back into the input registers P1 and P3. So this opcode can cause 1987 ** persistent changes to registers P1 and P3. 1988 ** 1989 ** Once any conversions have taken place, and neither value is NULL, 1990 ** the values are compared. If both values are blobs then memcmp() is 1991 ** used to determine the results of the comparison. If both values 1992 ** are text, then the appropriate collating function specified in 1993 ** P4 is used to do the comparison. If P4 is not specified then 1994 ** memcmp() is used to compare text string. If both values are 1995 ** numeric, then a numeric comparison is used. If the two values 1996 ** are of different types, then numbers are considered less than 1997 ** strings and strings are considered less than blobs. 1998 */ 1999 /* Opcode: Le P1 P2 P3 P4 P5 2000 ** Synopsis: IF r[P3]<=r[P1] 2001 ** 2002 ** This works just like the Lt opcode except that the jump is taken if 2003 ** the content of register P3 is less than or equal to the content of 2004 ** register P1. See the Lt opcode for additional information. 2005 */ 2006 /* Opcode: Gt P1 P2 P3 P4 P5 2007 ** Synopsis: IF r[P3]>r[P1] 2008 ** 2009 ** This works just like the Lt opcode except that the jump is taken if 2010 ** the content of register P3 is greater than the content of 2011 ** register P1. See the Lt opcode for additional information. 2012 */ 2013 /* Opcode: Ge P1 P2 P3 P4 P5 2014 ** Synopsis: IF r[P3]>=r[P1] 2015 ** 2016 ** This works just like the Lt opcode except that the jump is taken if 2017 ** the content of register P3 is greater than or equal to the content of 2018 ** register P1. See the Lt opcode for additional information. 2019 */ 2020 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */ 2021 case OP_Ne: /* same as TK_NE, jump, in1, in3 */ 2022 case OP_Lt: /* same as TK_LT, jump, in1, in3 */ 2023 case OP_Le: /* same as TK_LE, jump, in1, in3 */ 2024 case OP_Gt: /* same as TK_GT, jump, in1, in3 */ 2025 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */ 2026 int res, res2; /* Result of the comparison of pIn1 against pIn3 */ 2027 char affinity; /* Affinity to use for comparison */ 2028 u16 flags1; /* Copy of initial value of pIn1->flags */ 2029 u16 flags3; /* Copy of initial value of pIn3->flags */ 2030 2031 pIn1 = &aMem[pOp->p1]; 2032 pIn3 = &aMem[pOp->p3]; 2033 flags1 = pIn1->flags; 2034 flags3 = pIn3->flags; 2035 if( (flags1 | flags3)&MEM_Null ){ 2036 /* One or both operands are NULL */ 2037 if( pOp->p5 & SQLITE_NULLEQ ){ 2038 /* If SQLITE_NULLEQ is set (which will only happen if the operator is 2039 ** OP_Eq or OP_Ne) then take the jump or not depending on whether 2040 ** or not both operands are null. 2041 */ 2042 assert( (flags1 & MEM_Cleared)==0 ); 2043 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB ); 2044 testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 ); 2045 if( (flags1&flags3&MEM_Null)!=0 2046 && (flags3&MEM_Cleared)==0 2047 ){ 2048 res = 0; /* Operands are equal */ 2049 }else{ 2050 res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */ 2051 } 2052 }else{ 2053 /* SQLITE_NULLEQ is clear and at least one operand is NULL, 2054 ** then the result is always NULL. 2055 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set. 2056 */ 2057 if( pOp->p5 & SQLITE_STOREP2 ){ 2058 pOut = &aMem[pOp->p2]; 2059 iCompare = 1; /* Operands are not equal */ 2060 memAboutToChange(p, pOut); 2061 MemSetTypeFlag(pOut, MEM_Null); 2062 REGISTER_TRACE(pOp->p2, pOut); 2063 }else{ 2064 VdbeBranchTaken(2,3); 2065 if( pOp->p5 & SQLITE_JUMPIFNULL ){ 2066 goto jump_to_p2; 2067 } 2068 } 2069 break; 2070 } 2071 }else{ 2072 /* Neither operand is NULL. Do a comparison. */ 2073 affinity = pOp->p5 & SQLITE_AFF_MASK; 2074 if( affinity>=SQLITE_AFF_NUMERIC ){ 2075 if( (flags1 | flags3)&MEM_Str ){ 2076 if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){ 2077 applyNumericAffinity(pIn1,0); 2078 testcase( flags3!=pIn3->flags ); 2079 flags3 = pIn3->flags; 2080 } 2081 if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){ 2082 applyNumericAffinity(pIn3,0); 2083 } 2084 } 2085 /* Handle the common case of integer comparison here, as an 2086 ** optimization, to avoid a call to sqlite3MemCompare() */ 2087 if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){ 2088 if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; } 2089 if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; } 2090 res = 0; 2091 goto compare_op; 2092 } 2093 }else if( affinity==SQLITE_AFF_TEXT ){ 2094 if( (flags1 & MEM_Str)==0 && (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){ 2095 testcase( pIn1->flags & MEM_Int ); 2096 testcase( pIn1->flags & MEM_Real ); 2097 testcase( pIn1->flags & MEM_IntReal ); 2098 sqlite3VdbeMemStringify(pIn1, encoding, 1); 2099 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) ); 2100 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask); 2101 if( pIn1==pIn3 ) flags3 = flags1 | MEM_Str; 2102 } 2103 if( (flags3 & MEM_Str)==0 && (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){ 2104 testcase( pIn3->flags & MEM_Int ); 2105 testcase( pIn3->flags & MEM_Real ); 2106 testcase( pIn3->flags & MEM_IntReal ); 2107 sqlite3VdbeMemStringify(pIn3, encoding, 1); 2108 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) ); 2109 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask); 2110 } 2111 } 2112 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 ); 2113 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl); 2114 } 2115 compare_op: 2116 /* At this point, res is negative, zero, or positive if reg[P1] is 2117 ** less than, equal to, or greater than reg[P3], respectively. Compute 2118 ** the answer to this operator in res2, depending on what the comparison 2119 ** operator actually is. The next block of code depends on the fact 2120 ** that the 6 comparison operators are consecutive integers in this 2121 ** order: NE, EQ, GT, LE, LT, GE */ 2122 assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 ); 2123 assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 ); 2124 if( res<0 ){ /* ne, eq, gt, le, lt, ge */ 2125 static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 }; 2126 res2 = aLTb[pOp->opcode - OP_Ne]; 2127 }else if( res==0 ){ 2128 static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 }; 2129 res2 = aEQb[pOp->opcode - OP_Ne]; 2130 }else{ 2131 static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 }; 2132 res2 = aGTb[pOp->opcode - OP_Ne]; 2133 } 2134 2135 /* Undo any changes made by applyAffinity() to the input registers. */ 2136 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) ); 2137 pIn3->flags = flags3; 2138 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) ); 2139 pIn1->flags = flags1; 2140 2141 if( pOp->p5 & SQLITE_STOREP2 ){ 2142 pOut = &aMem[pOp->p2]; 2143 iCompare = res; 2144 if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){ 2145 /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1 2146 ** and prevents OP_Ne from overwriting NULL with 0. This flag 2147 ** is only used in contexts where either: 2148 ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0) 2149 ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1) 2150 ** Therefore it is not necessary to check the content of r[P2] for 2151 ** NULL. */ 2152 assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq ); 2153 assert( res2==0 || res2==1 ); 2154 testcase( res2==0 && pOp->opcode==OP_Eq ); 2155 testcase( res2==1 && pOp->opcode==OP_Eq ); 2156 testcase( res2==0 && pOp->opcode==OP_Ne ); 2157 testcase( res2==1 && pOp->opcode==OP_Ne ); 2158 if( (pOp->opcode==OP_Eq)==res2 ) break; 2159 } 2160 memAboutToChange(p, pOut); 2161 MemSetTypeFlag(pOut, MEM_Int); 2162 pOut->u.i = res2; 2163 REGISTER_TRACE(pOp->p2, pOut); 2164 }else{ 2165 VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3); 2166 if( res2 ){ 2167 goto jump_to_p2; 2168 } 2169 } 2170 break; 2171 } 2172 2173 /* Opcode: ElseNotEq * P2 * * * 2174 ** 2175 ** This opcode must follow an OP_Lt or OP_Gt comparison operator. There 2176 ** can be zero or more OP_ReleaseReg opcodes intervening, but no other 2177 ** opcodes are allowed to occur between this instruction and the previous 2178 ** OP_Lt or OP_Gt. Furthermore, the prior OP_Lt or OP_Gt must have the 2179 ** SQLITE_STOREP2 bit set in the P5 field. 2180 ** 2181 ** If result of an OP_Eq comparison on the same two operands as the 2182 ** prior OP_Lt or OP_Gt would have been NULL or false (0), then then 2183 ** jump to P2. If the result of an OP_Eq comparison on the two previous 2184 ** operands would have been true (1), then fall through. 2185 */ 2186 case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */ 2187 2188 #ifdef SQLITE_DEBUG 2189 /* Verify the preconditions of this opcode - that it follows an OP_Lt or 2190 ** OP_Gt with the SQLITE_STOREP2 flag set, with zero or more intervening 2191 ** OP_ReleaseReg opcodes */ 2192 int iAddr; 2193 for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){ 2194 if( aOp[iAddr].opcode==OP_ReleaseReg ) continue; 2195 assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt ); 2196 assert( aOp[iAddr].p5 & SQLITE_STOREP2 ); 2197 break; 2198 } 2199 #endif /* SQLITE_DEBUG */ 2200 VdbeBranchTaken(iCompare!=0, 2); 2201 if( iCompare!=0 ) goto jump_to_p2; 2202 break; 2203 } 2204 2205 2206 /* Opcode: Permutation * * * P4 * 2207 ** 2208 ** Set the permutation used by the OP_Compare operator in the next 2209 ** instruction. The permutation is stored in the P4 operand. 2210 ** 2211 ** The permutation is only valid until the next OP_Compare that has 2212 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should 2213 ** occur immediately prior to the OP_Compare. 2214 ** 2215 ** The first integer in the P4 integer array is the length of the array 2216 ** and does not become part of the permutation. 2217 */ 2218 case OP_Permutation: { 2219 assert( pOp->p4type==P4_INTARRAY ); 2220 assert( pOp->p4.ai ); 2221 assert( pOp[1].opcode==OP_Compare ); 2222 assert( pOp[1].p5 & OPFLAG_PERMUTE ); 2223 break; 2224 } 2225 2226 /* Opcode: Compare P1 P2 P3 P4 P5 2227 ** Synopsis: r[P1@P3] <-> r[P2@P3] 2228 ** 2229 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this 2230 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of 2231 ** the comparison for use by the next OP_Jump instruct. 2232 ** 2233 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is 2234 ** determined by the most recent OP_Permutation operator. If the 2235 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential 2236 ** order. 2237 ** 2238 ** P4 is a KeyInfo structure that defines collating sequences and sort 2239 ** orders for the comparison. The permutation applies to registers 2240 ** only. The KeyInfo elements are used sequentially. 2241 ** 2242 ** The comparison is a sort comparison, so NULLs compare equal, 2243 ** NULLs are less than numbers, numbers are less than strings, 2244 ** and strings are less than blobs. 2245 */ 2246 case OP_Compare: { 2247 int n; 2248 int i; 2249 int p1; 2250 int p2; 2251 const KeyInfo *pKeyInfo; 2252 int idx; 2253 CollSeq *pColl; /* Collating sequence to use on this term */ 2254 int bRev; /* True for DESCENDING sort order */ 2255 int *aPermute; /* The permutation */ 2256 2257 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){ 2258 aPermute = 0; 2259 }else{ 2260 assert( pOp>aOp ); 2261 assert( pOp[-1].opcode==OP_Permutation ); 2262 assert( pOp[-1].p4type==P4_INTARRAY ); 2263 aPermute = pOp[-1].p4.ai + 1; 2264 assert( aPermute!=0 ); 2265 } 2266 n = pOp->p3; 2267 pKeyInfo = pOp->p4.pKeyInfo; 2268 assert( n>0 ); 2269 assert( pKeyInfo!=0 ); 2270 p1 = pOp->p1; 2271 p2 = pOp->p2; 2272 #ifdef SQLITE_DEBUG 2273 if( aPermute ){ 2274 int k, mx = 0; 2275 for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k]; 2276 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 ); 2277 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 ); 2278 }else{ 2279 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 ); 2280 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 ); 2281 } 2282 #endif /* SQLITE_DEBUG */ 2283 for(i=0; i<n; i++){ 2284 idx = aPermute ? aPermute[i] : i; 2285 assert( memIsValid(&aMem[p1+idx]) ); 2286 assert( memIsValid(&aMem[p2+idx]) ); 2287 REGISTER_TRACE(p1+idx, &aMem[p1+idx]); 2288 REGISTER_TRACE(p2+idx, &aMem[p2+idx]); 2289 assert( i<pKeyInfo->nKeyField ); 2290 pColl = pKeyInfo->aColl[i]; 2291 bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC); 2292 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl); 2293 if( iCompare ){ 2294 if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) 2295 && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null)) 2296 ){ 2297 iCompare = -iCompare; 2298 } 2299 if( bRev ) iCompare = -iCompare; 2300 break; 2301 } 2302 } 2303 break; 2304 } 2305 2306 /* Opcode: Jump P1 P2 P3 * * 2307 ** 2308 ** Jump to the instruction at address P1, P2, or P3 depending on whether 2309 ** in the most recent OP_Compare instruction the P1 vector was less than 2310 ** equal to, or greater than the P2 vector, respectively. 2311 */ 2312 case OP_Jump: { /* jump */ 2313 if( iCompare<0 ){ 2314 VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1]; 2315 }else if( iCompare==0 ){ 2316 VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1]; 2317 }else{ 2318 VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1]; 2319 } 2320 break; 2321 } 2322 2323 /* Opcode: And P1 P2 P3 * * 2324 ** Synopsis: r[P3]=(r[P1] && r[P2]) 2325 ** 2326 ** Take the logical AND of the values in registers P1 and P2 and 2327 ** write the result into register P3. 2328 ** 2329 ** If either P1 or P2 is 0 (false) then the result is 0 even if 2330 ** the other input is NULL. A NULL and true or two NULLs give 2331 ** a NULL output. 2332 */ 2333 /* Opcode: Or P1 P2 P3 * * 2334 ** Synopsis: r[P3]=(r[P1] || r[P2]) 2335 ** 2336 ** Take the logical OR of the values in register P1 and P2 and 2337 ** store the answer in register P3. 2338 ** 2339 ** If either P1 or P2 is nonzero (true) then the result is 1 (true) 2340 ** even if the other input is NULL. A NULL and false or two NULLs 2341 ** give a NULL output. 2342 */ 2343 case OP_And: /* same as TK_AND, in1, in2, out3 */ 2344 case OP_Or: { /* same as TK_OR, in1, in2, out3 */ 2345 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ 2346 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ 2347 2348 v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2); 2349 v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2); 2350 if( pOp->opcode==OP_And ){ 2351 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 }; 2352 v1 = and_logic[v1*3+v2]; 2353 }else{ 2354 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 }; 2355 v1 = or_logic[v1*3+v2]; 2356 } 2357 pOut = &aMem[pOp->p3]; 2358 if( v1==2 ){ 2359 MemSetTypeFlag(pOut, MEM_Null); 2360 }else{ 2361 pOut->u.i = v1; 2362 MemSetTypeFlag(pOut, MEM_Int); 2363 } 2364 break; 2365 } 2366 2367 /* Opcode: IsTrue P1 P2 P3 P4 * 2368 ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 2369 ** 2370 ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and 2371 ** IS NOT FALSE operators. 2372 ** 2373 ** Interpret the value in register P1 as a boolean value. Store that 2374 ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is 2375 ** NULL, then the P3 is stored in register P2. Invert the answer if P4 2376 ** is 1. 2377 ** 2378 ** The logic is summarized like this: 2379 ** 2380 ** <ul> 2381 ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE 2382 ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE 2383 ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE 2384 ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE 2385 ** </ul> 2386 */ 2387 case OP_IsTrue: { /* in1, out2 */ 2388 assert( pOp->p4type==P4_INT32 ); 2389 assert( pOp->p4.i==0 || pOp->p4.i==1 ); 2390 assert( pOp->p3==0 || pOp->p3==1 ); 2391 sqlite3VdbeMemSetInt64(&aMem[pOp->p2], 2392 sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i); 2393 break; 2394 } 2395 2396 /* Opcode: Not P1 P2 * * * 2397 ** Synopsis: r[P2]= !r[P1] 2398 ** 2399 ** Interpret the value in register P1 as a boolean value. Store the 2400 ** boolean complement in register P2. If the value in register P1 is 2401 ** NULL, then a NULL is stored in P2. 2402 */ 2403 case OP_Not: { /* same as TK_NOT, in1, out2 */ 2404 pIn1 = &aMem[pOp->p1]; 2405 pOut = &aMem[pOp->p2]; 2406 if( (pIn1->flags & MEM_Null)==0 ){ 2407 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0)); 2408 }else{ 2409 sqlite3VdbeMemSetNull(pOut); 2410 } 2411 break; 2412 } 2413 2414 /* Opcode: BitNot P1 P2 * * * 2415 ** Synopsis: r[P2]= ~r[P1] 2416 ** 2417 ** Interpret the content of register P1 as an integer. Store the 2418 ** ones-complement of the P1 value into register P2. If P1 holds 2419 ** a NULL then store a NULL in P2. 2420 */ 2421 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */ 2422 pIn1 = &aMem[pOp->p1]; 2423 pOut = &aMem[pOp->p2]; 2424 sqlite3VdbeMemSetNull(pOut); 2425 if( (pIn1->flags & MEM_Null)==0 ){ 2426 pOut->flags = MEM_Int; 2427 pOut->u.i = ~sqlite3VdbeIntValue(pIn1); 2428 } 2429 break; 2430 } 2431 2432 /* Opcode: Once P1 P2 * * * 2433 ** 2434 ** Fall through to the next instruction the first time this opcode is 2435 ** encountered on each invocation of the byte-code program. Jump to P2 2436 ** on the second and all subsequent encounters during the same invocation. 2437 ** 2438 ** Top-level programs determine first invocation by comparing the P1 2439 ** operand against the P1 operand on the OP_Init opcode at the beginning 2440 ** of the program. If the P1 values differ, then fall through and make 2441 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are 2442 ** the same then take the jump. 2443 ** 2444 ** For subprograms, there is a bitmask in the VdbeFrame that determines 2445 ** whether or not the jump should be taken. The bitmask is necessary 2446 ** because the self-altering code trick does not work for recursive 2447 ** triggers. 2448 */ 2449 case OP_Once: { /* jump */ 2450 u32 iAddr; /* Address of this instruction */ 2451 assert( p->aOp[0].opcode==OP_Init ); 2452 if( p->pFrame ){ 2453 iAddr = (int)(pOp - p->aOp); 2454 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){ 2455 VdbeBranchTaken(1, 2); 2456 goto jump_to_p2; 2457 } 2458 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7); 2459 }else{ 2460 if( p->aOp[0].p1==pOp->p1 ){ 2461 VdbeBranchTaken(1, 2); 2462 goto jump_to_p2; 2463 } 2464 } 2465 VdbeBranchTaken(0, 2); 2466 pOp->p1 = p->aOp[0].p1; 2467 break; 2468 } 2469 2470 /* Opcode: If P1 P2 P3 * * 2471 ** 2472 ** Jump to P2 if the value in register P1 is true. The value 2473 ** is considered true if it is numeric and non-zero. If the value 2474 ** in P1 is NULL then take the jump if and only if P3 is non-zero. 2475 */ 2476 case OP_If: { /* jump, in1 */ 2477 int c; 2478 c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3); 2479 VdbeBranchTaken(c!=0, 2); 2480 if( c ) goto jump_to_p2; 2481 break; 2482 } 2483 2484 /* Opcode: IfNot P1 P2 P3 * * 2485 ** 2486 ** Jump to P2 if the value in register P1 is False. The value 2487 ** is considered false if it has a numeric value of zero. If the value 2488 ** in P1 is NULL then take the jump if and only if P3 is non-zero. 2489 */ 2490 case OP_IfNot: { /* jump, in1 */ 2491 int c; 2492 c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3); 2493 VdbeBranchTaken(c!=0, 2); 2494 if( c ) goto jump_to_p2; 2495 break; 2496 } 2497 2498 /* Opcode: IsNull P1 P2 * * * 2499 ** Synopsis: if r[P1]==NULL goto P2 2500 ** 2501 ** Jump to P2 if the value in register P1 is NULL. 2502 */ 2503 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */ 2504 pIn1 = &aMem[pOp->p1]; 2505 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2); 2506 if( (pIn1->flags & MEM_Null)!=0 ){ 2507 goto jump_to_p2; 2508 } 2509 break; 2510 } 2511 2512 /* Opcode: NotNull P1 P2 * * * 2513 ** Synopsis: if r[P1]!=NULL goto P2 2514 ** 2515 ** Jump to P2 if the value in register P1 is not NULL. 2516 */ 2517 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */ 2518 pIn1 = &aMem[pOp->p1]; 2519 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2); 2520 if( (pIn1->flags & MEM_Null)==0 ){ 2521 goto jump_to_p2; 2522 } 2523 break; 2524 } 2525 2526 /* Opcode: IfNullRow P1 P2 P3 * * 2527 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2 2528 ** 2529 ** Check the cursor P1 to see if it is currently pointing at a NULL row. 2530 ** If it is, then set register P3 to NULL and jump immediately to P2. 2531 ** If P1 is not on a NULL row, then fall through without making any 2532 ** changes. 2533 */ 2534 case OP_IfNullRow: { /* jump */ 2535 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 2536 assert( p->apCsr[pOp->p1]!=0 ); 2537 if( p->apCsr[pOp->p1]->nullRow ){ 2538 sqlite3VdbeMemSetNull(aMem + pOp->p3); 2539 goto jump_to_p2; 2540 } 2541 break; 2542 } 2543 2544 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 2545 /* Opcode: Offset P1 P2 P3 * * 2546 ** Synopsis: r[P3] = sqlite_offset(P1) 2547 ** 2548 ** Store in register r[P3] the byte offset into the database file that is the 2549 ** start of the payload for the record at which that cursor P1 is currently 2550 ** pointing. 2551 ** 2552 ** P2 is the column number for the argument to the sqlite_offset() function. 2553 ** This opcode does not use P2 itself, but the P2 value is used by the 2554 ** code generator. The P1, P2, and P3 operands to this opcode are the 2555 ** same as for OP_Column. 2556 ** 2557 ** This opcode is only available if SQLite is compiled with the 2558 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option. 2559 */ 2560 case OP_Offset: { /* out3 */ 2561 VdbeCursor *pC; /* The VDBE cursor */ 2562 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 2563 pC = p->apCsr[pOp->p1]; 2564 pOut = &p->aMem[pOp->p3]; 2565 if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){ 2566 sqlite3VdbeMemSetNull(pOut); 2567 }else{ 2568 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor)); 2569 } 2570 break; 2571 } 2572 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */ 2573 2574 /* Opcode: Column P1 P2 P3 P4 P5 2575 ** Synopsis: r[P3]=PX 2576 ** 2577 ** Interpret the data that cursor P1 points to as a structure built using 2578 ** the MakeRecord instruction. (See the MakeRecord opcode for additional 2579 ** information about the format of the data.) Extract the P2-th column 2580 ** from this record. If there are less that (P2+1) 2581 ** values in the record, extract a NULL. 2582 ** 2583 ** The value extracted is stored in register P3. 2584 ** 2585 ** If the record contains fewer than P2 fields, then extract a NULL. Or, 2586 ** if the P4 argument is a P4_MEM use the value of the P4 argument as 2587 ** the result. 2588 ** 2589 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then 2590 ** the result is guaranteed to only be used as the argument of a length() 2591 ** or typeof() function, respectively. The loading of large blobs can be 2592 ** skipped for length() and all content loading can be skipped for typeof(). 2593 */ 2594 case OP_Column: { 2595 int p2; /* column number to retrieve */ 2596 VdbeCursor *pC; /* The VDBE cursor */ 2597 BtCursor *pCrsr; /* The BTree cursor */ 2598 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */ 2599 int len; /* The length of the serialized data for the column */ 2600 int i; /* Loop counter */ 2601 Mem *pDest; /* Where to write the extracted value */ 2602 Mem sMem; /* For storing the record being decoded */ 2603 const u8 *zData; /* Part of the record being decoded */ 2604 const u8 *zHdr; /* Next unparsed byte of the header */ 2605 const u8 *zEndHdr; /* Pointer to first byte after the header */ 2606 u64 offset64; /* 64-bit offset */ 2607 u32 t; /* A type code from the record header */ 2608 Mem *pReg; /* PseudoTable input register */ 2609 2610 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 2611 pC = p->apCsr[pOp->p1]; 2612 assert( pC!=0 ); 2613 p2 = pOp->p2; 2614 2615 /* If the cursor cache is stale (meaning it is not currently point at 2616 ** the correct row) then bring it up-to-date by doing the necessary 2617 ** B-Tree seek. */ 2618 rc = sqlite3VdbeCursorMoveto(&pC, &p2); 2619 if( rc ) goto abort_due_to_error; 2620 2621 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); 2622 pDest = &aMem[pOp->p3]; 2623 memAboutToChange(p, pDest); 2624 assert( pC!=0 ); 2625 assert( p2<pC->nField ); 2626 aOffset = pC->aOffset; 2627 assert( pC->eCurType!=CURTYPE_VTAB ); 2628 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow ); 2629 assert( pC->eCurType!=CURTYPE_SORTER ); 2630 2631 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/ 2632 if( pC->nullRow ){ 2633 if( pC->eCurType==CURTYPE_PSEUDO ){ 2634 /* For the special case of as pseudo-cursor, the seekResult field 2635 ** identifies the register that holds the record */ 2636 assert( pC->seekResult>0 ); 2637 pReg = &aMem[pC->seekResult]; 2638 assert( pReg->flags & MEM_Blob ); 2639 assert( memIsValid(pReg) ); 2640 pC->payloadSize = pC->szRow = pReg->n; 2641 pC->aRow = (u8*)pReg->z; 2642 }else{ 2643 sqlite3VdbeMemSetNull(pDest); 2644 goto op_column_out; 2645 } 2646 }else{ 2647 pCrsr = pC->uc.pCursor; 2648 assert( pC->eCurType==CURTYPE_BTREE ); 2649 assert( pCrsr ); 2650 assert( sqlite3BtreeCursorIsValid(pCrsr) ); 2651 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr); 2652 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow); 2653 assert( pC->szRow<=pC->payloadSize ); 2654 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */ 2655 if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ 2656 goto too_big; 2657 } 2658 } 2659 pC->cacheStatus = p->cacheCtr; 2660 pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]); 2661 pC->nHdrParsed = 0; 2662 2663 2664 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/ 2665 /* pC->aRow does not have to hold the entire row, but it does at least 2666 ** need to cover the header of the record. If pC->aRow does not contain 2667 ** the complete header, then set it to zero, forcing the header to be 2668 ** dynamically allocated. */ 2669 pC->aRow = 0; 2670 pC->szRow = 0; 2671 2672 /* Make sure a corrupt database has not given us an oversize header. 2673 ** Do this now to avoid an oversize memory allocation. 2674 ** 2675 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte 2676 ** types use so much data space that there can only be 4096 and 32 of 2677 ** them, respectively. So the maximum header length results from a 2678 ** 3-byte type for each of the maximum of 32768 columns plus three 2679 ** extra bytes for the header length itself. 32768*3 + 3 = 98307. 2680 */ 2681 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){ 2682 goto op_column_corrupt; 2683 } 2684 }else{ 2685 /* This is an optimization. By skipping over the first few tests 2686 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a 2687 ** measurable performance gain. 2688 ** 2689 ** This branch is taken even if aOffset[0]==0. Such a record is never 2690 ** generated by SQLite, and could be considered corruption, but we 2691 ** accept it for historical reasons. When aOffset[0]==0, the code this 2692 ** branch jumps to reads past the end of the record, but never more 2693 ** than a few bytes. Even if the record occurs at the end of the page 2694 ** content area, the "page header" comes after the page content and so 2695 ** this overread is harmless. Similar overreads can occur for a corrupt 2696 ** database file. 2697 */ 2698 zData = pC->aRow; 2699 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */ 2700 testcase( aOffset[0]==0 ); 2701 goto op_column_read_header; 2702 } 2703 } 2704 2705 /* Make sure at least the first p2+1 entries of the header have been 2706 ** parsed and valid information is in aOffset[] and pC->aType[]. 2707 */ 2708 if( pC->nHdrParsed<=p2 ){ 2709 /* If there is more header available for parsing in the record, try 2710 ** to extract additional fields up through the p2+1-th field 2711 */ 2712 if( pC->iHdrOffset<aOffset[0] ){ 2713 /* Make sure zData points to enough of the record to cover the header. */ 2714 if( pC->aRow==0 ){ 2715 memset(&sMem, 0, sizeof(sMem)); 2716 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem); 2717 if( rc!=SQLITE_OK ) goto abort_due_to_error; 2718 zData = (u8*)sMem.z; 2719 }else{ 2720 zData = pC->aRow; 2721 } 2722 2723 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */ 2724 op_column_read_header: 2725 i = pC->nHdrParsed; 2726 offset64 = aOffset[i]; 2727 zHdr = zData + pC->iHdrOffset; 2728 zEndHdr = zData + aOffset[0]; 2729 testcase( zHdr>=zEndHdr ); 2730 do{ 2731 if( (pC->aType[i] = t = zHdr[0])<0x80 ){ 2732 zHdr++; 2733 offset64 += sqlite3VdbeOneByteSerialTypeLen(t); 2734 }else{ 2735 zHdr += sqlite3GetVarint32(zHdr, &t); 2736 pC->aType[i] = t; 2737 offset64 += sqlite3VdbeSerialTypeLen(t); 2738 } 2739 aOffset[++i] = (u32)(offset64 & 0xffffffff); 2740 }while( i<=p2 && zHdr<zEndHdr ); 2741 2742 /* The record is corrupt if any of the following are true: 2743 ** (1) the bytes of the header extend past the declared header size 2744 ** (2) the entire header was used but not all data was used 2745 ** (3) the end of the data extends beyond the end of the record. 2746 */ 2747 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize)) 2748 || (offset64 > pC->payloadSize) 2749 ){ 2750 if( aOffset[0]==0 ){ 2751 i = 0; 2752 zHdr = zEndHdr; 2753 }else{ 2754 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem); 2755 goto op_column_corrupt; 2756 } 2757 } 2758 2759 pC->nHdrParsed = i; 2760 pC->iHdrOffset = (u32)(zHdr - zData); 2761 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem); 2762 }else{ 2763 t = 0; 2764 } 2765 2766 /* If after trying to extract new entries from the header, nHdrParsed is 2767 ** still not up to p2, that means that the record has fewer than p2 2768 ** columns. So the result will be either the default value or a NULL. 2769 */ 2770 if( pC->nHdrParsed<=p2 ){ 2771 if( pOp->p4type==P4_MEM ){ 2772 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static); 2773 }else{ 2774 sqlite3VdbeMemSetNull(pDest); 2775 } 2776 goto op_column_out; 2777 } 2778 }else{ 2779 t = pC->aType[p2]; 2780 } 2781 2782 /* Extract the content for the p2+1-th column. Control can only 2783 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are 2784 ** all valid. 2785 */ 2786 assert( p2<pC->nHdrParsed ); 2787 assert( rc==SQLITE_OK ); 2788 assert( sqlite3VdbeCheckMemInvariants(pDest) ); 2789 if( VdbeMemDynamic(pDest) ){ 2790 sqlite3VdbeMemSetNull(pDest); 2791 } 2792 assert( t==pC->aType[p2] ); 2793 if( pC->szRow>=aOffset[p2+1] ){ 2794 /* This is the common case where the desired content fits on the original 2795 ** page - where the content is not on an overflow page */ 2796 zData = pC->aRow + aOffset[p2]; 2797 if( t<12 ){ 2798 sqlite3VdbeSerialGet(zData, t, pDest); 2799 }else{ 2800 /* If the column value is a string, we need a persistent value, not 2801 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent 2802 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize(). 2803 */ 2804 static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term }; 2805 pDest->n = len = (t-12)/2; 2806 pDest->enc = encoding; 2807 if( pDest->szMalloc < len+2 ){ 2808 pDest->flags = MEM_Null; 2809 if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem; 2810 }else{ 2811 pDest->z = pDest->zMalloc; 2812 } 2813 memcpy(pDest->z, zData, len); 2814 pDest->z[len] = 0; 2815 pDest->z[len+1] = 0; 2816 pDest->flags = aFlag[t&1]; 2817 } 2818 }else{ 2819 pDest->enc = encoding; 2820 /* This branch happens only when content is on overflow pages */ 2821 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0 2822 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)) 2823 || (len = sqlite3VdbeSerialTypeLen(t))==0 2824 ){ 2825 /* Content is irrelevant for 2826 ** 1. the typeof() function, 2827 ** 2. the length(X) function if X is a blob, and 2828 ** 3. if the content length is zero. 2829 ** So we might as well use bogus content rather than reading 2830 ** content from disk. 2831 ** 2832 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the 2833 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may 2834 ** read more. Use the global constant sqlite3CtypeMap[] as the array, 2835 ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint()) 2836 ** and it begins with a bunch of zeros. 2837 */ 2838 sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest); 2839 }else{ 2840 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest); 2841 if( rc!=SQLITE_OK ) goto abort_due_to_error; 2842 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest); 2843 pDest->flags &= ~MEM_Ephem; 2844 } 2845 } 2846 2847 op_column_out: 2848 UPDATE_MAX_BLOBSIZE(pDest); 2849 REGISTER_TRACE(pOp->p3, pDest); 2850 break; 2851 2852 op_column_corrupt: 2853 if( aOp[0].p3>0 ){ 2854 pOp = &aOp[aOp[0].p3-1]; 2855 break; 2856 }else{ 2857 rc = SQLITE_CORRUPT_BKPT; 2858 goto abort_due_to_error; 2859 } 2860 } 2861 2862 /* Opcode: Affinity P1 P2 * P4 * 2863 ** Synopsis: affinity(r[P1@P2]) 2864 ** 2865 ** Apply affinities to a range of P2 registers starting with P1. 2866 ** 2867 ** P4 is a string that is P2 characters long. The N-th character of the 2868 ** string indicates the column affinity that should be used for the N-th 2869 ** memory cell in the range. 2870 */ 2871 case OP_Affinity: { 2872 const char *zAffinity; /* The affinity to be applied */ 2873 2874 zAffinity = pOp->p4.z; 2875 assert( zAffinity!=0 ); 2876 assert( pOp->p2>0 ); 2877 assert( zAffinity[pOp->p2]==0 ); 2878 pIn1 = &aMem[pOp->p1]; 2879 while( 1 /*exit-by-break*/ ){ 2880 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] ); 2881 assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) ); 2882 applyAffinity(pIn1, zAffinity[0], encoding); 2883 if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){ 2884 /* When applying REAL affinity, if the result is still an MEM_Int 2885 ** that will fit in 6 bytes, then change the type to MEM_IntReal 2886 ** so that we keep the high-resolution integer value but know that 2887 ** the type really wants to be REAL. */ 2888 testcase( pIn1->u.i==140737488355328LL ); 2889 testcase( pIn1->u.i==140737488355327LL ); 2890 testcase( pIn1->u.i==-140737488355328LL ); 2891 testcase( pIn1->u.i==-140737488355329LL ); 2892 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){ 2893 pIn1->flags |= MEM_IntReal; 2894 pIn1->flags &= ~MEM_Int; 2895 }else{ 2896 pIn1->u.r = (double)pIn1->u.i; 2897 pIn1->flags |= MEM_Real; 2898 pIn1->flags &= ~MEM_Int; 2899 } 2900 } 2901 REGISTER_TRACE((int)(pIn1-aMem), pIn1); 2902 zAffinity++; 2903 if( zAffinity[0]==0 ) break; 2904 pIn1++; 2905 } 2906 break; 2907 } 2908 2909 /* Opcode: MakeRecord P1 P2 P3 P4 * 2910 ** Synopsis: r[P3]=mkrec(r[P1@P2]) 2911 ** 2912 ** Convert P2 registers beginning with P1 into the [record format] 2913 ** use as a data record in a database table or as a key 2914 ** in an index. The OP_Column opcode can decode the record later. 2915 ** 2916 ** P4 may be a string that is P2 characters long. The N-th character of the 2917 ** string indicates the column affinity that should be used for the N-th 2918 ** field of the index key. 2919 ** 2920 ** The mapping from character to affinity is given by the SQLITE_AFF_ 2921 ** macros defined in sqliteInt.h. 2922 ** 2923 ** If P4 is NULL then all index fields have the affinity BLOB. 2924 */ 2925 case OP_MakeRecord: { 2926 Mem *pRec; /* The new record */ 2927 u64 nData; /* Number of bytes of data space */ 2928 int nHdr; /* Number of bytes of header space */ 2929 i64 nByte; /* Data space required for this record */ 2930 i64 nZero; /* Number of zero bytes at the end of the record */ 2931 int nVarint; /* Number of bytes in a varint */ 2932 u32 serial_type; /* Type field */ 2933 Mem *pData0; /* First field to be combined into the record */ 2934 Mem *pLast; /* Last field of the record */ 2935 int nField; /* Number of fields in the record */ 2936 char *zAffinity; /* The affinity string for the record */ 2937 int file_format; /* File format to use for encoding */ 2938 u32 len; /* Length of a field */ 2939 u8 *zHdr; /* Where to write next byte of the header */ 2940 u8 *zPayload; /* Where to write next byte of the payload */ 2941 2942 /* Assuming the record contains N fields, the record format looks 2943 ** like this: 2944 ** 2945 ** ------------------------------------------------------------------------ 2946 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 2947 ** ------------------------------------------------------------------------ 2948 ** 2949 ** Data(0) is taken from register P1. Data(1) comes from register P1+1 2950 ** and so forth. 2951 ** 2952 ** Each type field is a varint representing the serial type of the 2953 ** corresponding data element (see sqlite3VdbeSerialType()). The 2954 ** hdr-size field is also a varint which is the offset from the beginning 2955 ** of the record to data0. 2956 */ 2957 nData = 0; /* Number of bytes of data space */ 2958 nHdr = 0; /* Number of bytes of header space */ 2959 nZero = 0; /* Number of zero bytes at the end of the record */ 2960 nField = pOp->p1; 2961 zAffinity = pOp->p4.z; 2962 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 ); 2963 pData0 = &aMem[nField]; 2964 nField = pOp->p2; 2965 pLast = &pData0[nField-1]; 2966 file_format = p->minWriteFileFormat; 2967 2968 /* Identify the output register */ 2969 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 ); 2970 pOut = &aMem[pOp->p3]; 2971 memAboutToChange(p, pOut); 2972 2973 /* Apply the requested affinity to all inputs 2974 */ 2975 assert( pData0<=pLast ); 2976 if( zAffinity ){ 2977 pRec = pData0; 2978 do{ 2979 applyAffinity(pRec, zAffinity[0], encoding); 2980 if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){ 2981 pRec->flags |= MEM_IntReal; 2982 pRec->flags &= ~(MEM_Int); 2983 } 2984 REGISTER_TRACE((int)(pRec-aMem), pRec); 2985 zAffinity++; 2986 pRec++; 2987 assert( zAffinity[0]==0 || pRec<=pLast ); 2988 }while( zAffinity[0] ); 2989 } 2990 2991 #ifdef SQLITE_ENABLE_NULL_TRIM 2992 /* NULLs can be safely trimmed from the end of the record, as long as 2993 ** as the schema format is 2 or more and none of the omitted columns 2994 ** have a non-NULL default value. Also, the record must be left with 2995 ** at least one field. If P5>0 then it will be one more than the 2996 ** index of the right-most column with a non-NULL default value */ 2997 if( pOp->p5 ){ 2998 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){ 2999 pLast--; 3000 nField--; 3001 } 3002 } 3003 #endif 3004 3005 /* Loop through the elements that will make up the record to figure 3006 ** out how much space is required for the new record. After this loop, 3007 ** the Mem.uTemp field of each term should hold the serial-type that will 3008 ** be used for that term in the generated record: 3009 ** 3010 ** Mem.uTemp value type 3011 ** --------------- --------------- 3012 ** 0 NULL 3013 ** 1 1-byte signed integer 3014 ** 2 2-byte signed integer 3015 ** 3 3-byte signed integer 3016 ** 4 4-byte signed integer 3017 ** 5 6-byte signed integer 3018 ** 6 8-byte signed integer 3019 ** 7 IEEE float 3020 ** 8 Integer constant 0 3021 ** 9 Integer constant 1 3022 ** 10,11 reserved for expansion 3023 ** N>=12 and even BLOB 3024 ** N>=13 and odd text 3025 ** 3026 ** The following additional values are computed: 3027 ** nHdr Number of bytes needed for the record header 3028 ** nData Number of bytes of data space needed for the record 3029 ** nZero Zero bytes at the end of the record 3030 */ 3031 pRec = pLast; 3032 do{ 3033 assert( memIsValid(pRec) ); 3034 if( pRec->flags & MEM_Null ){ 3035 if( pRec->flags & MEM_Zero ){ 3036 /* Values with MEM_Null and MEM_Zero are created by xColumn virtual 3037 ** table methods that never invoke sqlite3_result_xxxxx() while 3038 ** computing an unchanging column value in an UPDATE statement. 3039 ** Give such values a special internal-use-only serial-type of 10 3040 ** so that they can be passed through to xUpdate and have 3041 ** a true sqlite3_value_nochange(). */ 3042 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB ); 3043 pRec->uTemp = 10; 3044 }else{ 3045 pRec->uTemp = 0; 3046 } 3047 nHdr++; 3048 }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){ 3049 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */ 3050 i64 i = pRec->u.i; 3051 u64 uu; 3052 testcase( pRec->flags & MEM_Int ); 3053 testcase( pRec->flags & MEM_IntReal ); 3054 if( i<0 ){ 3055 uu = ~i; 3056 }else{ 3057 uu = i; 3058 } 3059 nHdr++; 3060 testcase( uu==127 ); testcase( uu==128 ); 3061 testcase( uu==32767 ); testcase( uu==32768 ); 3062 testcase( uu==8388607 ); testcase( uu==8388608 ); 3063 testcase( uu==2147483647 ); testcase( uu==2147483648 ); 3064 testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL ); 3065 if( uu<=127 ){ 3066 if( (i&1)==i && file_format>=4 ){ 3067 pRec->uTemp = 8+(u32)uu; 3068 }else{ 3069 nData++; 3070 pRec->uTemp = 1; 3071 } 3072 }else if( uu<=32767 ){ 3073 nData += 2; 3074 pRec->uTemp = 2; 3075 }else if( uu<=8388607 ){ 3076 nData += 3; 3077 pRec->uTemp = 3; 3078 }else if( uu<=2147483647 ){ 3079 nData += 4; 3080 pRec->uTemp = 4; 3081 }else if( uu<=140737488355327LL ){ 3082 nData += 6; 3083 pRec->uTemp = 5; 3084 }else{ 3085 nData += 8; 3086 if( pRec->flags & MEM_IntReal ){ 3087 /* If the value is IntReal and is going to take up 8 bytes to store 3088 ** as an integer, then we might as well make it an 8-byte floating 3089 ** point value */ 3090 pRec->u.r = (double)pRec->u.i; 3091 pRec->flags &= ~MEM_IntReal; 3092 pRec->flags |= MEM_Real; 3093 pRec->uTemp = 7; 3094 }else{ 3095 pRec->uTemp = 6; 3096 } 3097 } 3098 }else if( pRec->flags & MEM_Real ){ 3099 nHdr++; 3100 nData += 8; 3101 pRec->uTemp = 7; 3102 }else{ 3103 assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) ); 3104 assert( pRec->n>=0 ); 3105 len = (u32)pRec->n; 3106 serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0); 3107 if( pRec->flags & MEM_Zero ){ 3108 serial_type += pRec->u.nZero*2; 3109 if( nData ){ 3110 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem; 3111 len += pRec->u.nZero; 3112 }else{ 3113 nZero += pRec->u.nZero; 3114 } 3115 } 3116 nData += len; 3117 nHdr += sqlite3VarintLen(serial_type); 3118 pRec->uTemp = serial_type; 3119 } 3120 if( pRec==pData0 ) break; 3121 pRec--; 3122 }while(1); 3123 3124 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint 3125 ** which determines the total number of bytes in the header. The varint 3126 ** value is the size of the header in bytes including the size varint 3127 ** itself. */ 3128 testcase( nHdr==126 ); 3129 testcase( nHdr==127 ); 3130 if( nHdr<=126 ){ 3131 /* The common case */ 3132 nHdr += 1; 3133 }else{ 3134 /* Rare case of a really large header */ 3135 nVarint = sqlite3VarintLen(nHdr); 3136 nHdr += nVarint; 3137 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++; 3138 } 3139 nByte = nHdr+nData; 3140 3141 /* Make sure the output register has a buffer large enough to store 3142 ** the new record. The output register (pOp->p3) is not allowed to 3143 ** be one of the input registers (because the following call to 3144 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used). 3145 */ 3146 if( nByte+nZero<=pOut->szMalloc ){ 3147 /* The output register is already large enough to hold the record. 3148 ** No error checks or buffer enlargement is required */ 3149 pOut->z = pOut->zMalloc; 3150 }else{ 3151 /* Need to make sure that the output is not too big and then enlarge 3152 ** the output register to hold the full result */ 3153 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 3154 goto too_big; 3155 } 3156 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){ 3157 goto no_mem; 3158 } 3159 } 3160 pOut->n = (int)nByte; 3161 pOut->flags = MEM_Blob; 3162 if( nZero ){ 3163 pOut->u.nZero = nZero; 3164 pOut->flags |= MEM_Zero; 3165 } 3166 UPDATE_MAX_BLOBSIZE(pOut); 3167 zHdr = (u8 *)pOut->z; 3168 zPayload = zHdr + nHdr; 3169 3170 /* Write the record */ 3171 zHdr += putVarint32(zHdr, nHdr); 3172 assert( pData0<=pLast ); 3173 pRec = pData0; 3174 do{ 3175 serial_type = pRec->uTemp; 3176 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more 3177 ** additional varints, one per column. */ 3178 zHdr += putVarint32(zHdr, serial_type); /* serial type */ 3179 /* EVIDENCE-OF: R-64536-51728 The values for each column in the record 3180 ** immediately follow the header. */ 3181 zPayload += sqlite3VdbeSerialPut(zPayload, pRec, serial_type); /* content */ 3182 }while( (++pRec)<=pLast ); 3183 assert( nHdr==(int)(zHdr - (u8*)pOut->z) ); 3184 assert( nByte==(int)(zPayload - (u8*)pOut->z) ); 3185 3186 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); 3187 REGISTER_TRACE(pOp->p3, pOut); 3188 break; 3189 } 3190 3191 /* Opcode: Count P1 P2 * * * 3192 ** Synopsis: r[P2]=count() 3193 ** 3194 ** Store the number of entries (an integer value) in the table or index 3195 ** opened by cursor P1 in register P2 3196 */ 3197 #ifndef SQLITE_OMIT_BTREECOUNT 3198 case OP_Count: { /* out2 */ 3199 i64 nEntry; 3200 BtCursor *pCrsr; 3201 3202 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE ); 3203 pCrsr = p->apCsr[pOp->p1]->uc.pCursor; 3204 assert( pCrsr ); 3205 nEntry = 0; /* Not needed. Only used to silence a warning. */ 3206 rc = sqlite3BtreeCount(db, pCrsr, &nEntry); 3207 if( rc ) goto abort_due_to_error; 3208 pOut = out2Prerelease(p, pOp); 3209 pOut->u.i = nEntry; 3210 goto check_for_interrupt; 3211 } 3212 #endif 3213 3214 /* Opcode: Savepoint P1 * * P4 * 3215 ** 3216 ** Open, release or rollback the savepoint named by parameter P4, depending 3217 ** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN). 3218 ** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE). 3219 ** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK). 3220 */ 3221 case OP_Savepoint: { 3222 int p1; /* Value of P1 operand */ 3223 char *zName; /* Name of savepoint */ 3224 int nName; 3225 Savepoint *pNew; 3226 Savepoint *pSavepoint; 3227 Savepoint *pTmp; 3228 int iSavepoint; 3229 int ii; 3230 3231 p1 = pOp->p1; 3232 zName = pOp->p4.z; 3233 3234 /* Assert that the p1 parameter is valid. Also that if there is no open 3235 ** transaction, then there cannot be any savepoints. 3236 */ 3237 assert( db->pSavepoint==0 || db->autoCommit==0 ); 3238 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK ); 3239 assert( db->pSavepoint || db->isTransactionSavepoint==0 ); 3240 assert( checkSavepointCount(db) ); 3241 assert( p->bIsReader ); 3242 3243 if( p1==SAVEPOINT_BEGIN ){ 3244 if( db->nVdbeWrite>0 ){ 3245 /* A new savepoint cannot be created if there are active write 3246 ** statements (i.e. open read/write incremental blob handles). 3247 */ 3248 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress"); 3249 rc = SQLITE_BUSY; 3250 }else{ 3251 nName = sqlite3Strlen30(zName); 3252 3253 #ifndef SQLITE_OMIT_VIRTUALTABLE 3254 /* This call is Ok even if this savepoint is actually a transaction 3255 ** savepoint (and therefore should not prompt xSavepoint()) callbacks. 3256 ** If this is a transaction savepoint being opened, it is guaranteed 3257 ** that the db->aVTrans[] array is empty. */ 3258 assert( db->autoCommit==0 || db->nVTrans==0 ); 3259 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, 3260 db->nStatement+db->nSavepoint); 3261 if( rc!=SQLITE_OK ) goto abort_due_to_error; 3262 #endif 3263 3264 /* Create a new savepoint structure. */ 3265 pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1); 3266 if( pNew ){ 3267 pNew->zName = (char *)&pNew[1]; 3268 memcpy(pNew->zName, zName, nName+1); 3269 3270 /* If there is no open transaction, then mark this as a special 3271 ** "transaction savepoint". */ 3272 if( db->autoCommit ){ 3273 db->autoCommit = 0; 3274 db->isTransactionSavepoint = 1; 3275 }else{ 3276 db->nSavepoint++; 3277 } 3278 3279 /* Link the new savepoint into the database handle's list. */ 3280 pNew->pNext = db->pSavepoint; 3281 db->pSavepoint = pNew; 3282 pNew->nDeferredCons = db->nDeferredCons; 3283 pNew->nDeferredImmCons = db->nDeferredImmCons; 3284 } 3285 } 3286 }else{ 3287 assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK ); 3288 iSavepoint = 0; 3289 3290 /* Find the named savepoint. If there is no such savepoint, then an 3291 ** an error is returned to the user. */ 3292 for( 3293 pSavepoint = db->pSavepoint; 3294 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName); 3295 pSavepoint = pSavepoint->pNext 3296 ){ 3297 iSavepoint++; 3298 } 3299 if( !pSavepoint ){ 3300 sqlite3VdbeError(p, "no such savepoint: %s", zName); 3301 rc = SQLITE_ERROR; 3302 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){ 3303 /* It is not possible to release (commit) a savepoint if there are 3304 ** active write statements. 3305 */ 3306 sqlite3VdbeError(p, "cannot release savepoint - " 3307 "SQL statements in progress"); 3308 rc = SQLITE_BUSY; 3309 }else{ 3310 3311 /* Determine whether or not this is a transaction savepoint. If so, 3312 ** and this is a RELEASE command, then the current transaction 3313 ** is committed. 3314 */ 3315 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint; 3316 if( isTransaction && p1==SAVEPOINT_RELEASE ){ 3317 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ 3318 goto vdbe_return; 3319 } 3320 db->autoCommit = 1; 3321 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ 3322 p->pc = (int)(pOp - aOp); 3323 db->autoCommit = 0; 3324 p->rc = rc = SQLITE_BUSY; 3325 goto vdbe_return; 3326 } 3327 rc = p->rc; 3328 if( rc ){ 3329 db->autoCommit = 0; 3330 }else{ 3331 db->isTransactionSavepoint = 0; 3332 } 3333 }else{ 3334 int isSchemaChange; 3335 iSavepoint = db->nSavepoint - iSavepoint - 1; 3336 if( p1==SAVEPOINT_ROLLBACK ){ 3337 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0; 3338 for(ii=0; ii<db->nDb; ii++){ 3339 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, 3340 SQLITE_ABORT_ROLLBACK, 3341 isSchemaChange==0); 3342 if( rc!=SQLITE_OK ) goto abort_due_to_error; 3343 } 3344 }else{ 3345 assert( p1==SAVEPOINT_RELEASE ); 3346 isSchemaChange = 0; 3347 } 3348 for(ii=0; ii<db->nDb; ii++){ 3349 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint); 3350 if( rc!=SQLITE_OK ){ 3351 goto abort_due_to_error; 3352 } 3353 } 3354 if( isSchemaChange ){ 3355 sqlite3ExpirePreparedStatements(db, 0); 3356 sqlite3ResetAllSchemasOfConnection(db); 3357 db->mDbFlags |= DBFLAG_SchemaChange; 3358 } 3359 } 3360 if( rc ) goto abort_due_to_error; 3361 3362 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all 3363 ** savepoints nested inside of the savepoint being operated on. */ 3364 while( db->pSavepoint!=pSavepoint ){ 3365 pTmp = db->pSavepoint; 3366 db->pSavepoint = pTmp->pNext; 3367 sqlite3DbFree(db, pTmp); 3368 db->nSavepoint--; 3369 } 3370 3371 /* If it is a RELEASE, then destroy the savepoint being operated on 3372 ** too. If it is a ROLLBACK TO, then set the number of deferred 3373 ** constraint violations present in the database to the value stored 3374 ** when the savepoint was created. */ 3375 if( p1==SAVEPOINT_RELEASE ){ 3376 assert( pSavepoint==db->pSavepoint ); 3377 db->pSavepoint = pSavepoint->pNext; 3378 sqlite3DbFree(db, pSavepoint); 3379 if( !isTransaction ){ 3380 db->nSavepoint--; 3381 } 3382 }else{ 3383 assert( p1==SAVEPOINT_ROLLBACK ); 3384 db->nDeferredCons = pSavepoint->nDeferredCons; 3385 db->nDeferredImmCons = pSavepoint->nDeferredImmCons; 3386 } 3387 3388 if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){ 3389 rc = sqlite3VtabSavepoint(db, p1, iSavepoint); 3390 if( rc!=SQLITE_OK ) goto abort_due_to_error; 3391 } 3392 } 3393 } 3394 if( rc ) goto abort_due_to_error; 3395 3396 break; 3397 } 3398 3399 /* Opcode: AutoCommit P1 P2 * * * 3400 ** 3401 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll 3402 ** back any currently active btree transactions. If there are any active 3403 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if 3404 ** there are active writing VMs or active VMs that use shared cache. 3405 ** 3406 ** This instruction causes the VM to halt. 3407 */ 3408 case OP_AutoCommit: { 3409 int desiredAutoCommit; 3410 int iRollback; 3411 3412 desiredAutoCommit = pOp->p1; 3413 iRollback = pOp->p2; 3414 assert( desiredAutoCommit==1 || desiredAutoCommit==0 ); 3415 assert( desiredAutoCommit==1 || iRollback==0 ); 3416 assert( db->nVdbeActive>0 ); /* At least this one VM is active */ 3417 assert( p->bIsReader ); 3418 3419 if( desiredAutoCommit!=db->autoCommit ){ 3420 if( iRollback ){ 3421 assert( desiredAutoCommit==1 ); 3422 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); 3423 db->autoCommit = 1; 3424 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){ 3425 /* If this instruction implements a COMMIT and other VMs are writing 3426 ** return an error indicating that the other VMs must complete first. 3427 */ 3428 sqlite3VdbeError(p, "cannot commit transaction - " 3429 "SQL statements in progress"); 3430 rc = SQLITE_BUSY; 3431 goto abort_due_to_error; 3432 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ 3433 goto vdbe_return; 3434 }else{ 3435 db->autoCommit = (u8)desiredAutoCommit; 3436 } 3437 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ 3438 p->pc = (int)(pOp - aOp); 3439 db->autoCommit = (u8)(1-desiredAutoCommit); 3440 p->rc = rc = SQLITE_BUSY; 3441 goto vdbe_return; 3442 } 3443 sqlite3CloseSavepoints(db); 3444 if( p->rc==SQLITE_OK ){ 3445 rc = SQLITE_DONE; 3446 }else{ 3447 rc = SQLITE_ERROR; 3448 } 3449 goto vdbe_return; 3450 }else{ 3451 sqlite3VdbeError(p, 3452 (!desiredAutoCommit)?"cannot start a transaction within a transaction":( 3453 (iRollback)?"cannot rollback - no transaction is active": 3454 "cannot commit - no transaction is active")); 3455 3456 rc = SQLITE_ERROR; 3457 goto abort_due_to_error; 3458 } 3459 /*NOTREACHED*/ assert(0); 3460 } 3461 3462 /* Opcode: Transaction P1 P2 P3 P4 P5 3463 ** 3464 ** Begin a transaction on database P1 if a transaction is not already 3465 ** active. 3466 ** If P2 is non-zero, then a write-transaction is started, or if a 3467 ** read-transaction is already active, it is upgraded to a write-transaction. 3468 ** If P2 is zero, then a read-transaction is started. 3469 ** 3470 ** P1 is the index of the database file on which the transaction is 3471 ** started. Index 0 is the main database file and index 1 is the 3472 ** file used for temporary tables. Indices of 2 or more are used for 3473 ** attached databases. 3474 ** 3475 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is 3476 ** true (this flag is set if the Vdbe may modify more than one row and may 3477 ** throw an ABORT exception), a statement transaction may also be opened. 3478 ** More specifically, a statement transaction is opened iff the database 3479 ** connection is currently not in autocommit mode, or if there are other 3480 ** active statements. A statement transaction allows the changes made by this 3481 ** VDBE to be rolled back after an error without having to roll back the 3482 ** entire transaction. If no error is encountered, the statement transaction 3483 ** will automatically commit when the VDBE halts. 3484 ** 3485 ** If P5!=0 then this opcode also checks the schema cookie against P3 3486 ** and the schema generation counter against P4. 3487 ** The cookie changes its value whenever the database schema changes. 3488 ** This operation is used to detect when that the cookie has changed 3489 ** and that the current process needs to reread the schema. If the schema 3490 ** cookie in P3 differs from the schema cookie in the database header or 3491 ** if the schema generation counter in P4 differs from the current 3492 ** generation counter, then an SQLITE_SCHEMA error is raised and execution 3493 ** halts. The sqlite3_step() wrapper function might then reprepare the 3494 ** statement and rerun it from the beginning. 3495 */ 3496 case OP_Transaction: { 3497 Btree *pBt; 3498 int iMeta = 0; 3499 3500 assert( p->bIsReader ); 3501 assert( p->readOnly==0 || pOp->p2==0 ); 3502 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 3503 assert( DbMaskTest(p->btreeMask, pOp->p1) ); 3504 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){ 3505 rc = SQLITE_READONLY; 3506 goto abort_due_to_error; 3507 } 3508 pBt = db->aDb[pOp->p1].pBt; 3509 3510 if( pBt ){ 3511 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta); 3512 testcase( rc==SQLITE_BUSY_SNAPSHOT ); 3513 testcase( rc==SQLITE_BUSY_RECOVERY ); 3514 if( rc!=SQLITE_OK ){ 3515 if( (rc&0xff)==SQLITE_BUSY ){ 3516 p->pc = (int)(pOp - aOp); 3517 p->rc = rc; 3518 goto vdbe_return; 3519 } 3520 goto abort_due_to_error; 3521 } 3522 3523 if( p->usesStmtJournal 3524 && pOp->p2 3525 && (db->autoCommit==0 || db->nVdbeRead>1) 3526 ){ 3527 assert( sqlite3BtreeIsInTrans(pBt) ); 3528 if( p->iStatement==0 ){ 3529 assert( db->nStatement>=0 && db->nSavepoint>=0 ); 3530 db->nStatement++; 3531 p->iStatement = db->nSavepoint + db->nStatement; 3532 } 3533 3534 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1); 3535 if( rc==SQLITE_OK ){ 3536 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement); 3537 } 3538 3539 /* Store the current value of the database handles deferred constraint 3540 ** counter. If the statement transaction needs to be rolled back, 3541 ** the value of this counter needs to be restored too. */ 3542 p->nStmtDefCons = db->nDeferredCons; 3543 p->nStmtDefImmCons = db->nDeferredImmCons; 3544 } 3545 } 3546 assert( pOp->p5==0 || pOp->p4type==P4_INT32 ); 3547 if( pOp->p5 3548 && (iMeta!=pOp->p3 3549 || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i) 3550 ){ 3551 /* 3552 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema 3553 ** version is checked to ensure that the schema has not changed since the 3554 ** SQL statement was prepared. 3555 */ 3556 sqlite3DbFree(db, p->zErrMsg); 3557 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed"); 3558 /* If the schema-cookie from the database file matches the cookie 3559 ** stored with the in-memory representation of the schema, do 3560 ** not reload the schema from the database file. 3561 ** 3562 ** If virtual-tables are in use, this is not just an optimization. 3563 ** Often, v-tables store their data in other SQLite tables, which 3564 ** are queried from within xNext() and other v-table methods using 3565 ** prepared queries. If such a query is out-of-date, we do not want to 3566 ** discard the database schema, as the user code implementing the 3567 ** v-table would have to be ready for the sqlite3_vtab structure itself 3568 ** to be invalidated whenever sqlite3_step() is called from within 3569 ** a v-table method. 3570 */ 3571 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){ 3572 sqlite3ResetOneSchema(db, pOp->p1); 3573 } 3574 p->expired = 1; 3575 rc = SQLITE_SCHEMA; 3576 } 3577 if( rc ) goto abort_due_to_error; 3578 break; 3579 } 3580 3581 /* Opcode: ReadCookie P1 P2 P3 * * 3582 ** 3583 ** Read cookie number P3 from database P1 and write it into register P2. 3584 ** P3==1 is the schema version. P3==2 is the database format. 3585 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is 3586 ** the main database file and P1==1 is the database file used to store 3587 ** temporary tables. 3588 ** 3589 ** There must be a read-lock on the database (either a transaction 3590 ** must be started or there must be an open cursor) before 3591 ** executing this instruction. 3592 */ 3593 case OP_ReadCookie: { /* out2 */ 3594 int iMeta; 3595 int iDb; 3596 int iCookie; 3597 3598 assert( p->bIsReader ); 3599 iDb = pOp->p1; 3600 iCookie = pOp->p3; 3601 assert( pOp->p3<SQLITE_N_BTREE_META ); 3602 assert( iDb>=0 && iDb<db->nDb ); 3603 assert( db->aDb[iDb].pBt!=0 ); 3604 assert( DbMaskTest(p->btreeMask, iDb) ); 3605 3606 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta); 3607 pOut = out2Prerelease(p, pOp); 3608 pOut->u.i = iMeta; 3609 break; 3610 } 3611 3612 /* Opcode: SetCookie P1 P2 P3 * * 3613 ** 3614 ** Write the integer value P3 into cookie number P2 of database P1. 3615 ** P2==1 is the schema version. P2==2 is the database format. 3616 ** P2==3 is the recommended pager cache 3617 ** size, and so forth. P1==0 is the main database file and P1==1 is the 3618 ** database file used to store temporary tables. 3619 ** 3620 ** A transaction must be started before executing this opcode. 3621 */ 3622 case OP_SetCookie: { 3623 Db *pDb; 3624 3625 sqlite3VdbeIncrWriteCounter(p, 0); 3626 assert( pOp->p2<SQLITE_N_BTREE_META ); 3627 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 3628 assert( DbMaskTest(p->btreeMask, pOp->p1) ); 3629 assert( p->readOnly==0 ); 3630 pDb = &db->aDb[pOp->p1]; 3631 assert( pDb->pBt!=0 ); 3632 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) ); 3633 /* See note about index shifting on OP_ReadCookie */ 3634 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3); 3635 if( pOp->p2==BTREE_SCHEMA_VERSION ){ 3636 /* When the schema cookie changes, record the new cookie internally */ 3637 pDb->pSchema->schema_cookie = pOp->p3; 3638 db->mDbFlags |= DBFLAG_SchemaChange; 3639 }else if( pOp->p2==BTREE_FILE_FORMAT ){ 3640 /* Record changes in the file format */ 3641 pDb->pSchema->file_format = pOp->p3; 3642 } 3643 if( pOp->p1==1 ){ 3644 /* Invalidate all prepared statements whenever the TEMP database 3645 ** schema is changed. Ticket #1644 */ 3646 sqlite3ExpirePreparedStatements(db, 0); 3647 p->expired = 0; 3648 } 3649 if( rc ) goto abort_due_to_error; 3650 break; 3651 } 3652 3653 /* Opcode: OpenRead P1 P2 P3 P4 P5 3654 ** Synopsis: root=P2 iDb=P3 3655 ** 3656 ** Open a read-only cursor for the database table whose root page is 3657 ** P2 in a database file. The database file is determined by P3. 3658 ** P3==0 means the main database, P3==1 means the database used for 3659 ** temporary tables, and P3>1 means used the corresponding attached 3660 ** database. Give the new cursor an identifier of P1. The P1 3661 ** values need not be contiguous but all P1 values should be small integers. 3662 ** It is an error for P1 to be negative. 3663 ** 3664 ** Allowed P5 bits: 3665 ** <ul> 3666 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for 3667 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT 3668 ** of OP_SeekLE/OP_IdxGT) 3669 ** </ul> 3670 ** 3671 ** The P4 value may be either an integer (P4_INT32) or a pointer to 3672 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 3673 ** object, then table being opened must be an [index b-tree] where the 3674 ** KeyInfo object defines the content and collating 3675 ** sequence of that index b-tree. Otherwise, if P4 is an integer 3676 ** value, then the table being opened must be a [table b-tree] with a 3677 ** number of columns no less than the value of P4. 3678 ** 3679 ** See also: OpenWrite, ReopenIdx 3680 */ 3681 /* Opcode: ReopenIdx P1 P2 P3 P4 P5 3682 ** Synopsis: root=P2 iDb=P3 3683 ** 3684 ** The ReopenIdx opcode works like OP_OpenRead except that it first 3685 ** checks to see if the cursor on P1 is already open on the same 3686 ** b-tree and if it is this opcode becomes a no-op. In other words, 3687 ** if the cursor is already open, do not reopen it. 3688 ** 3689 ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ 3690 ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must 3691 ** be the same as every other ReopenIdx or OpenRead for the same cursor 3692 ** number. 3693 ** 3694 ** Allowed P5 bits: 3695 ** <ul> 3696 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for 3697 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT 3698 ** of OP_SeekLE/OP_IdxGT) 3699 ** </ul> 3700 ** 3701 ** See also: OP_OpenRead, OP_OpenWrite 3702 */ 3703 /* Opcode: OpenWrite P1 P2 P3 P4 P5 3704 ** Synopsis: root=P2 iDb=P3 3705 ** 3706 ** Open a read/write cursor named P1 on the table or index whose root 3707 ** page is P2 (or whose root page is held in register P2 if the 3708 ** OPFLAG_P2ISREG bit is set in P5 - see below). 3709 ** 3710 ** The P4 value may be either an integer (P4_INT32) or a pointer to 3711 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 3712 ** object, then table being opened must be an [index b-tree] where the 3713 ** KeyInfo object defines the content and collating 3714 ** sequence of that index b-tree. Otherwise, if P4 is an integer 3715 ** value, then the table being opened must be a [table b-tree] with a 3716 ** number of columns no less than the value of P4. 3717 ** 3718 ** Allowed P5 bits: 3719 ** <ul> 3720 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for 3721 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT 3722 ** of OP_SeekLE/OP_IdxGT) 3723 ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek 3724 ** and subsequently delete entries in an index btree. This is a 3725 ** hint to the storage engine that the storage engine is allowed to 3726 ** ignore. The hint is not used by the official SQLite b*tree storage 3727 ** engine, but is used by COMDB2. 3728 ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2 3729 ** as the root page, not the value of P2 itself. 3730 ** </ul> 3731 ** 3732 ** This instruction works like OpenRead except that it opens the cursor 3733 ** in read/write mode. 3734 ** 3735 ** See also: OP_OpenRead, OP_ReopenIdx 3736 */ 3737 case OP_ReopenIdx: { 3738 int nField; 3739 KeyInfo *pKeyInfo; 3740 int p2; 3741 int iDb; 3742 int wrFlag; 3743 Btree *pX; 3744 VdbeCursor *pCur; 3745 Db *pDb; 3746 3747 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ ); 3748 assert( pOp->p4type==P4_KEYINFO ); 3749 pCur = p->apCsr[pOp->p1]; 3750 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){ 3751 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */ 3752 goto open_cursor_set_hints; 3753 } 3754 /* If the cursor is not currently open or is open on a different 3755 ** index, then fall through into OP_OpenRead to force a reopen */ 3756 case OP_OpenRead: 3757 case OP_OpenWrite: 3758 3759 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ ); 3760 assert( p->bIsReader ); 3761 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx 3762 || p->readOnly==0 ); 3763 3764 if( p->expired==1 ){ 3765 rc = SQLITE_ABORT_ROLLBACK; 3766 goto abort_due_to_error; 3767 } 3768 3769 nField = 0; 3770 pKeyInfo = 0; 3771 p2 = pOp->p2; 3772 iDb = pOp->p3; 3773 assert( iDb>=0 && iDb<db->nDb ); 3774 assert( DbMaskTest(p->btreeMask, iDb) ); 3775 pDb = &db->aDb[iDb]; 3776 pX = pDb->pBt; 3777 assert( pX!=0 ); 3778 if( pOp->opcode==OP_OpenWrite ){ 3779 assert( OPFLAG_FORDELETE==BTREE_FORDELETE ); 3780 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE); 3781 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 3782 if( pDb->pSchema->file_format < p->minWriteFileFormat ){ 3783 p->minWriteFileFormat = pDb->pSchema->file_format; 3784 } 3785 }else{ 3786 wrFlag = 0; 3787 } 3788 if( pOp->p5 & OPFLAG_P2ISREG ){ 3789 assert( p2>0 ); 3790 assert( p2<=(p->nMem+1 - p->nCursor) ); 3791 assert( pOp->opcode==OP_OpenWrite ); 3792 pIn2 = &aMem[p2]; 3793 assert( memIsValid(pIn2) ); 3794 assert( (pIn2->flags & MEM_Int)!=0 ); 3795 sqlite3VdbeMemIntegerify(pIn2); 3796 p2 = (int)pIn2->u.i; 3797 /* The p2 value always comes from a prior OP_CreateBtree opcode and 3798 ** that opcode will always set the p2 value to 2 or more or else fail. 3799 ** If there were a failure, the prepared statement would have halted 3800 ** before reaching this instruction. */ 3801 assert( p2>=2 ); 3802 } 3803 if( pOp->p4type==P4_KEYINFO ){ 3804 pKeyInfo = pOp->p4.pKeyInfo; 3805 assert( pKeyInfo->enc==ENC(db) ); 3806 assert( pKeyInfo->db==db ); 3807 nField = pKeyInfo->nAllField; 3808 }else if( pOp->p4type==P4_INT32 ){ 3809 nField = pOp->p4.i; 3810 } 3811 assert( pOp->p1>=0 ); 3812 assert( nField>=0 ); 3813 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */ 3814 pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE); 3815 if( pCur==0 ) goto no_mem; 3816 pCur->nullRow = 1; 3817 pCur->isOrdered = 1; 3818 pCur->pgnoRoot = p2; 3819 #ifdef SQLITE_DEBUG 3820 pCur->wrFlag = wrFlag; 3821 #endif 3822 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor); 3823 pCur->pKeyInfo = pKeyInfo; 3824 /* Set the VdbeCursor.isTable variable. Previous versions of 3825 ** SQLite used to check if the root-page flags were sane at this point 3826 ** and report database corruption if they were not, but this check has 3827 ** since moved into the btree layer. */ 3828 pCur->isTable = pOp->p4type!=P4_KEYINFO; 3829 3830 open_cursor_set_hints: 3831 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD ); 3832 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ ); 3833 testcase( pOp->p5 & OPFLAG_BULKCSR ); 3834 #ifdef SQLITE_ENABLE_CURSOR_HINTS 3835 testcase( pOp->p2 & OPFLAG_SEEKEQ ); 3836 #endif 3837 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor, 3838 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ))); 3839 if( rc ) goto abort_due_to_error; 3840 break; 3841 } 3842 3843 /* Opcode: OpenDup P1 P2 * * * 3844 ** 3845 ** Open a new cursor P1 that points to the same ephemeral table as 3846 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral 3847 ** opcode. Only ephemeral cursors may be duplicated. 3848 ** 3849 ** Duplicate ephemeral cursors are used for self-joins of materialized views. 3850 */ 3851 case OP_OpenDup: { 3852 VdbeCursor *pOrig; /* The original cursor to be duplicated */ 3853 VdbeCursor *pCx; /* The new cursor */ 3854 3855 pOrig = p->apCsr[pOp->p2]; 3856 assert( pOrig ); 3857 assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */ 3858 3859 pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE); 3860 if( pCx==0 ) goto no_mem; 3861 pCx->nullRow = 1; 3862 pCx->isEphemeral = 1; 3863 pCx->pKeyInfo = pOrig->pKeyInfo; 3864 pCx->isTable = pOrig->isTable; 3865 pCx->pgnoRoot = pOrig->pgnoRoot; 3866 pCx->isOrdered = pOrig->isOrdered; 3867 rc = sqlite3BtreeCursor(pOrig->pBtx, pCx->pgnoRoot, BTREE_WRCSR, 3868 pCx->pKeyInfo, pCx->uc.pCursor); 3869 /* The sqlite3BtreeCursor() routine can only fail for the first cursor 3870 ** opened for a database. Since there is already an open cursor when this 3871 ** opcode is run, the sqlite3BtreeCursor() cannot fail */ 3872 assert( rc==SQLITE_OK ); 3873 break; 3874 } 3875 3876 3877 /* Opcode: OpenEphemeral P1 P2 * P4 P5 3878 ** Synopsis: nColumn=P2 3879 ** 3880 ** Open a new cursor P1 to a transient table. 3881 ** The cursor is always opened read/write even if 3882 ** the main database is read-only. The ephemeral 3883 ** table is deleted automatically when the cursor is closed. 3884 ** 3885 ** If the cursor P1 is already opened on an ephemeral table, the table 3886 ** is cleared (all content is erased). 3887 ** 3888 ** P2 is the number of columns in the ephemeral table. 3889 ** The cursor points to a BTree table if P4==0 and to a BTree index 3890 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure 3891 ** that defines the format of keys in the index. 3892 ** 3893 ** The P5 parameter can be a mask of the BTREE_* flags defined 3894 ** in btree.h. These flags control aspects of the operation of 3895 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are 3896 ** added automatically. 3897 */ 3898 /* Opcode: OpenAutoindex P1 P2 * P4 * 3899 ** Synopsis: nColumn=P2 3900 ** 3901 ** This opcode works the same as OP_OpenEphemeral. It has a 3902 ** different name to distinguish its use. Tables created using 3903 ** by this opcode will be used for automatically created transient 3904 ** indices in joins. 3905 */ 3906 case OP_OpenAutoindex: 3907 case OP_OpenEphemeral: { 3908 VdbeCursor *pCx; 3909 KeyInfo *pKeyInfo; 3910 3911 static const int vfsFlags = 3912 SQLITE_OPEN_READWRITE | 3913 SQLITE_OPEN_CREATE | 3914 SQLITE_OPEN_EXCLUSIVE | 3915 SQLITE_OPEN_DELETEONCLOSE | 3916 SQLITE_OPEN_TRANSIENT_DB; 3917 assert( pOp->p1>=0 ); 3918 assert( pOp->p2>=0 ); 3919 pCx = p->apCsr[pOp->p1]; 3920 if( pCx ){ 3921 /* If the ephermeral table is already open, erase all existing content 3922 ** so that the table is empty again, rather than creating a new table. */ 3923 assert( pCx->isEphemeral ); 3924 pCx->seqCount = 0; 3925 pCx->cacheStatus = CACHE_STALE; 3926 if( pCx->pBtx ){ 3927 rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0); 3928 } 3929 }else{ 3930 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE); 3931 if( pCx==0 ) goto no_mem; 3932 pCx->isEphemeral = 1; 3933 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx, 3934 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, 3935 vfsFlags); 3936 if( rc==SQLITE_OK ){ 3937 rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0); 3938 } 3939 if( rc==SQLITE_OK ){ 3940 /* If a transient index is required, create it by calling 3941 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before 3942 ** opening it. If a transient table is required, just use the 3943 ** automatically created table with root-page 1 (an BLOB_INTKEY table). 3944 */ 3945 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){ 3946 assert( pOp->p4type==P4_KEYINFO ); 3947 rc = sqlite3BtreeCreateTable(pCx->pBtx, (int*)&pCx->pgnoRoot, 3948 BTREE_BLOBKEY | pOp->p5); 3949 if( rc==SQLITE_OK ){ 3950 assert( pCx->pgnoRoot==MASTER_ROOT+1 ); 3951 assert( pKeyInfo->db==db ); 3952 assert( pKeyInfo->enc==ENC(db) ); 3953 rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR, 3954 pKeyInfo, pCx->uc.pCursor); 3955 } 3956 pCx->isTable = 0; 3957 }else{ 3958 pCx->pgnoRoot = MASTER_ROOT; 3959 rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR, 3960 0, pCx->uc.pCursor); 3961 pCx->isTable = 1; 3962 } 3963 } 3964 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED); 3965 } 3966 if( rc ) goto abort_due_to_error; 3967 pCx->nullRow = 1; 3968 break; 3969 } 3970 3971 /* Opcode: SorterOpen P1 P2 P3 P4 * 3972 ** 3973 ** This opcode works like OP_OpenEphemeral except that it opens 3974 ** a transient index that is specifically designed to sort large 3975 ** tables using an external merge-sort algorithm. 3976 ** 3977 ** If argument P3 is non-zero, then it indicates that the sorter may 3978 ** assume that a stable sort considering the first P3 fields of each 3979 ** key is sufficient to produce the required results. 3980 */ 3981 case OP_SorterOpen: { 3982 VdbeCursor *pCx; 3983 3984 assert( pOp->p1>=0 ); 3985 assert( pOp->p2>=0 ); 3986 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER); 3987 if( pCx==0 ) goto no_mem; 3988 pCx->pKeyInfo = pOp->p4.pKeyInfo; 3989 assert( pCx->pKeyInfo->db==db ); 3990 assert( pCx->pKeyInfo->enc==ENC(db) ); 3991 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx); 3992 if( rc ) goto abort_due_to_error; 3993 break; 3994 } 3995 3996 /* Opcode: SequenceTest P1 P2 * * * 3997 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2 3998 ** 3999 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump 4000 ** to P2. Regardless of whether or not the jump is taken, increment the 4001 ** the sequence value. 4002 */ 4003 case OP_SequenceTest: { 4004 VdbeCursor *pC; 4005 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4006 pC = p->apCsr[pOp->p1]; 4007 assert( isSorter(pC) ); 4008 if( (pC->seqCount++)==0 ){ 4009 goto jump_to_p2; 4010 } 4011 break; 4012 } 4013 4014 /* Opcode: OpenPseudo P1 P2 P3 * * 4015 ** Synopsis: P3 columns in r[P2] 4016 ** 4017 ** Open a new cursor that points to a fake table that contains a single 4018 ** row of data. The content of that one row is the content of memory 4019 ** register P2. In other words, cursor P1 becomes an alias for the 4020 ** MEM_Blob content contained in register P2. 4021 ** 4022 ** A pseudo-table created by this opcode is used to hold a single 4023 ** row output from the sorter so that the row can be decomposed into 4024 ** individual columns using the OP_Column opcode. The OP_Column opcode 4025 ** is the only cursor opcode that works with a pseudo-table. 4026 ** 4027 ** P3 is the number of fields in the records that will be stored by 4028 ** the pseudo-table. 4029 */ 4030 case OP_OpenPseudo: { 4031 VdbeCursor *pCx; 4032 4033 assert( pOp->p1>=0 ); 4034 assert( pOp->p3>=0 ); 4035 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO); 4036 if( pCx==0 ) goto no_mem; 4037 pCx->nullRow = 1; 4038 pCx->seekResult = pOp->p2; 4039 pCx->isTable = 1; 4040 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx 4041 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test 4042 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto() 4043 ** which is a performance optimization */ 4044 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor(); 4045 assert( pOp->p5==0 ); 4046 break; 4047 } 4048 4049 /* Opcode: Close P1 * * * * 4050 ** 4051 ** Close a cursor previously opened as P1. If P1 is not 4052 ** currently open, this instruction is a no-op. 4053 */ 4054 case OP_Close: { 4055 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4056 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]); 4057 p->apCsr[pOp->p1] = 0; 4058 break; 4059 } 4060 4061 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK 4062 /* Opcode: ColumnsUsed P1 * * P4 * 4063 ** 4064 ** This opcode (which only exists if SQLite was compiled with 4065 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the 4066 ** table or index for cursor P1 are used. P4 is a 64-bit integer 4067 ** (P4_INT64) in which the first 63 bits are one for each of the 4068 ** first 63 columns of the table or index that are actually used 4069 ** by the cursor. The high-order bit is set if any column after 4070 ** the 64th is used. 4071 */ 4072 case OP_ColumnsUsed: { 4073 VdbeCursor *pC; 4074 pC = p->apCsr[pOp->p1]; 4075 assert( pC->eCurType==CURTYPE_BTREE ); 4076 pC->maskUsed = *(u64*)pOp->p4.pI64; 4077 break; 4078 } 4079 #endif 4080 4081 /* Opcode: SeekGE P1 P2 P3 P4 * 4082 ** Synopsis: key=r[P3@P4] 4083 ** 4084 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 4085 ** use the value in register P3 as the key. If cursor P1 refers 4086 ** to an SQL index, then P3 is the first in an array of P4 registers 4087 ** that are used as an unpacked index key. 4088 ** 4089 ** Reposition cursor P1 so that it points to the smallest entry that 4090 ** is greater than or equal to the key value. If there are no records 4091 ** greater than or equal to the key and P2 is not zero, then jump to P2. 4092 ** 4093 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this 4094 ** opcode will always land on a record that equally equals the key, or 4095 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this 4096 ** opcode must be followed by an IdxLE opcode with the same arguments. 4097 ** The IdxLE opcode will be skipped if this opcode succeeds, but the 4098 ** IdxLE opcode will be used on subsequent loop iterations. 4099 ** 4100 ** This opcode leaves the cursor configured to move in forward order, 4101 ** from the beginning toward the end. In other words, the cursor is 4102 ** configured to use Next, not Prev. 4103 ** 4104 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe 4105 */ 4106 /* Opcode: SeekGT P1 P2 P3 P4 * 4107 ** Synopsis: key=r[P3@P4] 4108 ** 4109 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 4110 ** use the value in register P3 as a key. If cursor P1 refers 4111 ** to an SQL index, then P3 is the first in an array of P4 registers 4112 ** that are used as an unpacked index key. 4113 ** 4114 ** Reposition cursor P1 so that it points to the smallest entry that 4115 ** is greater than the key value. If there are no records greater than 4116 ** the key and P2 is not zero, then jump to P2. 4117 ** 4118 ** This opcode leaves the cursor configured to move in forward order, 4119 ** from the beginning toward the end. In other words, the cursor is 4120 ** configured to use Next, not Prev. 4121 ** 4122 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe 4123 */ 4124 /* Opcode: SeekLT P1 P2 P3 P4 * 4125 ** Synopsis: key=r[P3@P4] 4126 ** 4127 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 4128 ** use the value in register P3 as a key. If cursor P1 refers 4129 ** to an SQL index, then P3 is the first in an array of P4 registers 4130 ** that are used as an unpacked index key. 4131 ** 4132 ** Reposition cursor P1 so that it points to the largest entry that 4133 ** is less than the key value. If there are no records less than 4134 ** the key and P2 is not zero, then jump to P2. 4135 ** 4136 ** This opcode leaves the cursor configured to move in reverse order, 4137 ** from the end toward the beginning. In other words, the cursor is 4138 ** configured to use Prev, not Next. 4139 ** 4140 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe 4141 */ 4142 /* Opcode: SeekLE P1 P2 P3 P4 * 4143 ** Synopsis: key=r[P3@P4] 4144 ** 4145 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 4146 ** use the value in register P3 as a key. If cursor P1 refers 4147 ** to an SQL index, then P3 is the first in an array of P4 registers 4148 ** that are used as an unpacked index key. 4149 ** 4150 ** Reposition cursor P1 so that it points to the largest entry that 4151 ** is less than or equal to the key value. If there are no records 4152 ** less than or equal to the key and P2 is not zero, then jump to P2. 4153 ** 4154 ** This opcode leaves the cursor configured to move in reverse order, 4155 ** from the end toward the beginning. In other words, the cursor is 4156 ** configured to use Prev, not Next. 4157 ** 4158 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this 4159 ** opcode will always land on a record that equally equals the key, or 4160 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this 4161 ** opcode must be followed by an IdxGE opcode with the same arguments. 4162 ** The IdxGE opcode will be skipped if this opcode succeeds, but the 4163 ** IdxGE opcode will be used on subsequent loop iterations. 4164 ** 4165 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt 4166 */ 4167 case OP_SeekLT: /* jump, in3, group */ 4168 case OP_SeekLE: /* jump, in3, group */ 4169 case OP_SeekGE: /* jump, in3, group */ 4170 case OP_SeekGT: { /* jump, in3, group */ 4171 int res; /* Comparison result */ 4172 int oc; /* Opcode */ 4173 VdbeCursor *pC; /* The cursor to seek */ 4174 UnpackedRecord r; /* The key to seek for */ 4175 int nField; /* Number of columns or fields in the key */ 4176 i64 iKey; /* The rowid we are to seek to */ 4177 int eqOnly; /* Only interested in == results */ 4178 4179 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4180 assert( pOp->p2!=0 ); 4181 pC = p->apCsr[pOp->p1]; 4182 assert( pC!=0 ); 4183 assert( pC->eCurType==CURTYPE_BTREE ); 4184 assert( OP_SeekLE == OP_SeekLT+1 ); 4185 assert( OP_SeekGE == OP_SeekLT+2 ); 4186 assert( OP_SeekGT == OP_SeekLT+3 ); 4187 assert( pC->isOrdered ); 4188 assert( pC->uc.pCursor!=0 ); 4189 oc = pOp->opcode; 4190 eqOnly = 0; 4191 pC->nullRow = 0; 4192 #ifdef SQLITE_DEBUG 4193 pC->seekOp = pOp->opcode; 4194 #endif 4195 4196 pC->deferredMoveto = 0; 4197 pC->cacheStatus = CACHE_STALE; 4198 if( pC->isTable ){ 4199 u16 flags3, newType; 4200 /* The BTREE_SEEK_EQ flag is only set on index cursors */ 4201 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 4202 || CORRUPT_DB ); 4203 4204 /* The input value in P3 might be of any type: integer, real, string, 4205 ** blob, or NULL. But it needs to be an integer before we can do 4206 ** the seek, so convert it. */ 4207 pIn3 = &aMem[pOp->p3]; 4208 flags3 = pIn3->flags; 4209 if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){ 4210 applyNumericAffinity(pIn3, 0); 4211 } 4212 iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */ 4213 newType = pIn3->flags; /* Record the type after applying numeric affinity */ 4214 pIn3->flags = flags3; /* But convert the type back to its original */ 4215 4216 /* If the P3 value could not be converted into an integer without 4217 ** loss of information, then special processing is required... */ 4218 if( (newType & (MEM_Int|MEM_IntReal))==0 ){ 4219 if( (newType & MEM_Real)==0 ){ 4220 if( (newType & MEM_Null) || oc>=OP_SeekGE ){ 4221 VdbeBranchTaken(1,2); 4222 goto jump_to_p2; 4223 }else{ 4224 rc = sqlite3BtreeLast(pC->uc.pCursor, &res); 4225 if( rc!=SQLITE_OK ) goto abort_due_to_error; 4226 goto seek_not_found; 4227 } 4228 }else 4229 4230 /* If the approximation iKey is larger than the actual real search 4231 ** term, substitute >= for > and < for <=. e.g. if the search term 4232 ** is 4.9 and the integer approximation 5: 4233 ** 4234 ** (x > 4.9) -> (x >= 5) 4235 ** (x <= 4.9) -> (x < 5) 4236 */ 4237 if( pIn3->u.r<(double)iKey ){ 4238 assert( OP_SeekGE==(OP_SeekGT-1) ); 4239 assert( OP_SeekLT==(OP_SeekLE-1) ); 4240 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) ); 4241 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--; 4242 } 4243 4244 /* If the approximation iKey is smaller than the actual real search 4245 ** term, substitute <= for < and > for >=. */ 4246 else if( pIn3->u.r>(double)iKey ){ 4247 assert( OP_SeekLE==(OP_SeekLT+1) ); 4248 assert( OP_SeekGT==(OP_SeekGE+1) ); 4249 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) ); 4250 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++; 4251 } 4252 } 4253 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res); 4254 pC->movetoTarget = iKey; /* Used by OP_Delete */ 4255 if( rc!=SQLITE_OK ){ 4256 goto abort_due_to_error; 4257 } 4258 }else{ 4259 /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and 4260 ** OP_SeekLE opcodes are allowed, and these must be immediately followed 4261 ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key. 4262 */ 4263 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){ 4264 eqOnly = 1; 4265 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE ); 4266 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT ); 4267 assert( pOp[1].p1==pOp[0].p1 ); 4268 assert( pOp[1].p2==pOp[0].p2 ); 4269 assert( pOp[1].p3==pOp[0].p3 ); 4270 assert( pOp[1].p4.i==pOp[0].p4.i ); 4271 } 4272 4273 nField = pOp->p4.i; 4274 assert( pOp->p4type==P4_INT32 ); 4275 assert( nField>0 ); 4276 r.pKeyInfo = pC->pKeyInfo; 4277 r.nField = (u16)nField; 4278 4279 /* The next line of code computes as follows, only faster: 4280 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){ 4281 ** r.default_rc = -1; 4282 ** }else{ 4283 ** r.default_rc = +1; 4284 ** } 4285 */ 4286 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1); 4287 assert( oc!=OP_SeekGT || r.default_rc==-1 ); 4288 assert( oc!=OP_SeekLE || r.default_rc==-1 ); 4289 assert( oc!=OP_SeekGE || r.default_rc==+1 ); 4290 assert( oc!=OP_SeekLT || r.default_rc==+1 ); 4291 4292 r.aMem = &aMem[pOp->p3]; 4293 #ifdef SQLITE_DEBUG 4294 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); } 4295 #endif 4296 r.eqSeen = 0; 4297 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res); 4298 if( rc!=SQLITE_OK ){ 4299 goto abort_due_to_error; 4300 } 4301 if( eqOnly && r.eqSeen==0 ){ 4302 assert( res!=0 ); 4303 goto seek_not_found; 4304 } 4305 } 4306 #ifdef SQLITE_TEST 4307 sqlite3_search_count++; 4308 #endif 4309 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT ); 4310 if( res<0 || (res==0 && oc==OP_SeekGT) ){ 4311 res = 0; 4312 rc = sqlite3BtreeNext(pC->uc.pCursor, 0); 4313 if( rc!=SQLITE_OK ){ 4314 if( rc==SQLITE_DONE ){ 4315 rc = SQLITE_OK; 4316 res = 1; 4317 }else{ 4318 goto abort_due_to_error; 4319 } 4320 } 4321 }else{ 4322 res = 0; 4323 } 4324 }else{ 4325 assert( oc==OP_SeekLT || oc==OP_SeekLE ); 4326 if( res>0 || (res==0 && oc==OP_SeekLT) ){ 4327 res = 0; 4328 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0); 4329 if( rc!=SQLITE_OK ){ 4330 if( rc==SQLITE_DONE ){ 4331 rc = SQLITE_OK; 4332 res = 1; 4333 }else{ 4334 goto abort_due_to_error; 4335 } 4336 } 4337 }else{ 4338 /* res might be negative because the table is empty. Check to 4339 ** see if this is the case. 4340 */ 4341 res = sqlite3BtreeEof(pC->uc.pCursor); 4342 } 4343 } 4344 seek_not_found: 4345 assert( pOp->p2>0 ); 4346 VdbeBranchTaken(res!=0,2); 4347 if( res ){ 4348 goto jump_to_p2; 4349 }else if( eqOnly ){ 4350 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT ); 4351 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */ 4352 } 4353 break; 4354 } 4355 4356 /* Opcode: SeekHit P1 P2 * * * 4357 ** Synopsis: seekHit=P2 4358 ** 4359 ** Set the seekHit flag on cursor P1 to the value in P2. 4360 * The seekHit flag is used by the IfNoHope opcode. 4361 ** 4362 ** P1 must be a valid b-tree cursor. P2 must be a boolean value, 4363 ** either 0 or 1. 4364 */ 4365 case OP_SeekHit: { 4366 VdbeCursor *pC; 4367 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4368 pC = p->apCsr[pOp->p1]; 4369 assert( pC!=0 ); 4370 assert( pOp->p2==0 || pOp->p2==1 ); 4371 pC->seekHit = pOp->p2 & 1; 4372 break; 4373 } 4374 4375 /* Opcode: IfNotOpen P1 P2 * * * 4376 ** Synopsis: if( !csr[P1] ) goto P2 4377 ** 4378 ** If cursor P1 is not open, jump to instruction P2. Otherwise, fall through. 4379 */ 4380 case OP_IfNotOpen: { /* jump */ 4381 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4382 VdbeBranchTaken(p->apCsr[pOp->p1]==0, 2); 4383 if( !p->apCsr[pOp->p1] ){ 4384 goto jump_to_p2_and_check_for_interrupt; 4385 } 4386 break; 4387 } 4388 4389 /* Opcode: Found P1 P2 P3 P4 * 4390 ** Synopsis: key=r[P3@P4] 4391 ** 4392 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If 4393 ** P4>0 then register P3 is the first of P4 registers that form an unpacked 4394 ** record. 4395 ** 4396 ** Cursor P1 is on an index btree. If the record identified by P3 and P4 4397 ** is a prefix of any entry in P1 then a jump is made to P2 and 4398 ** P1 is left pointing at the matching entry. 4399 ** 4400 ** This operation leaves the cursor in a state where it can be 4401 ** advanced in the forward direction. The Next instruction will work, 4402 ** but not the Prev instruction. 4403 ** 4404 ** See also: NotFound, NoConflict, NotExists. SeekGe 4405 */ 4406 /* Opcode: NotFound P1 P2 P3 P4 * 4407 ** Synopsis: key=r[P3@P4] 4408 ** 4409 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If 4410 ** P4>0 then register P3 is the first of P4 registers that form an unpacked 4411 ** record. 4412 ** 4413 ** Cursor P1 is on an index btree. If the record identified by P3 and P4 4414 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1 4415 ** does contain an entry whose prefix matches the P3/P4 record then control 4416 ** falls through to the next instruction and P1 is left pointing at the 4417 ** matching entry. 4418 ** 4419 ** This operation leaves the cursor in a state where it cannot be 4420 ** advanced in either direction. In other words, the Next and Prev 4421 ** opcodes do not work after this operation. 4422 ** 4423 ** See also: Found, NotExists, NoConflict, IfNoHope 4424 */ 4425 /* Opcode: IfNoHope P1 P2 P3 P4 * 4426 ** Synopsis: key=r[P3@P4] 4427 ** 4428 ** Register P3 is the first of P4 registers that form an unpacked 4429 ** record. 4430 ** 4431 ** Cursor P1 is on an index btree. If the seekHit flag is set on P1, then 4432 ** this opcode is a no-op. But if the seekHit flag of P1 is clear, then 4433 ** check to see if there is any entry in P1 that matches the 4434 ** prefix identified by P3 and P4. If no entry matches the prefix, 4435 ** jump to P2. Otherwise fall through. 4436 ** 4437 ** This opcode behaves like OP_NotFound if the seekHit 4438 ** flag is clear and it behaves like OP_Noop if the seekHit flag is set. 4439 ** 4440 ** This opcode is used in IN clause processing for a multi-column key. 4441 ** If an IN clause is attached to an element of the key other than the 4442 ** left-most element, and if there are no matches on the most recent 4443 ** seek over the whole key, then it might be that one of the key element 4444 ** to the left is prohibiting a match, and hence there is "no hope" of 4445 ** any match regardless of how many IN clause elements are checked. 4446 ** In such a case, we abandon the IN clause search early, using this 4447 ** opcode. The opcode name comes from the fact that the 4448 ** jump is taken if there is "no hope" of achieving a match. 4449 ** 4450 ** See also: NotFound, SeekHit 4451 */ 4452 /* Opcode: NoConflict P1 P2 P3 P4 * 4453 ** Synopsis: key=r[P3@P4] 4454 ** 4455 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If 4456 ** P4>0 then register P3 is the first of P4 registers that form an unpacked 4457 ** record. 4458 ** 4459 ** Cursor P1 is on an index btree. If the record identified by P3 and P4 4460 ** contains any NULL value, jump immediately to P2. If all terms of the 4461 ** record are not-NULL then a check is done to determine if any row in the 4462 ** P1 index btree has a matching key prefix. If there are no matches, jump 4463 ** immediately to P2. If there is a match, fall through and leave the P1 4464 ** cursor pointing to the matching row. 4465 ** 4466 ** This opcode is similar to OP_NotFound with the exceptions that the 4467 ** branch is always taken if any part of the search key input is NULL. 4468 ** 4469 ** This operation leaves the cursor in a state where it cannot be 4470 ** advanced in either direction. In other words, the Next and Prev 4471 ** opcodes do not work after this operation. 4472 ** 4473 ** See also: NotFound, Found, NotExists 4474 */ 4475 case OP_IfNoHope: { /* jump, in3 */ 4476 VdbeCursor *pC; 4477 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4478 pC = p->apCsr[pOp->p1]; 4479 assert( pC!=0 ); 4480 if( pC->seekHit ) break; 4481 /* Fall through into OP_NotFound */ 4482 } 4483 case OP_NoConflict: /* jump, in3 */ 4484 case OP_NotFound: /* jump, in3 */ 4485 case OP_Found: { /* jump, in3 */ 4486 int alreadyExists; 4487 int takeJump; 4488 int ii; 4489 VdbeCursor *pC; 4490 int res; 4491 UnpackedRecord *pFree; 4492 UnpackedRecord *pIdxKey; 4493 UnpackedRecord r; 4494 4495 #ifdef SQLITE_TEST 4496 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++; 4497 #endif 4498 4499 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4500 assert( pOp->p4type==P4_INT32 ); 4501 pC = p->apCsr[pOp->p1]; 4502 assert( pC!=0 ); 4503 #ifdef SQLITE_DEBUG 4504 pC->seekOp = pOp->opcode; 4505 #endif 4506 pIn3 = &aMem[pOp->p3]; 4507 assert( pC->eCurType==CURTYPE_BTREE ); 4508 assert( pC->uc.pCursor!=0 ); 4509 assert( pC->isTable==0 ); 4510 if( pOp->p4.i>0 ){ 4511 r.pKeyInfo = pC->pKeyInfo; 4512 r.nField = (u16)pOp->p4.i; 4513 r.aMem = pIn3; 4514 #ifdef SQLITE_DEBUG 4515 for(ii=0; ii<r.nField; ii++){ 4516 assert( memIsValid(&r.aMem[ii]) ); 4517 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 ); 4518 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]); 4519 } 4520 #endif 4521 pIdxKey = &r; 4522 pFree = 0; 4523 }else{ 4524 assert( pIn3->flags & MEM_Blob ); 4525 rc = ExpandBlob(pIn3); 4526 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); 4527 if( rc ) goto no_mem; 4528 pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo); 4529 if( pIdxKey==0 ) goto no_mem; 4530 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey); 4531 } 4532 pIdxKey->default_rc = 0; 4533 takeJump = 0; 4534 if( pOp->opcode==OP_NoConflict ){ 4535 /* For the OP_NoConflict opcode, take the jump if any of the 4536 ** input fields are NULL, since any key with a NULL will not 4537 ** conflict */ 4538 for(ii=0; ii<pIdxKey->nField; ii++){ 4539 if( pIdxKey->aMem[ii].flags & MEM_Null ){ 4540 takeJump = 1; 4541 break; 4542 } 4543 } 4544 } 4545 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res); 4546 if( pFree ) sqlite3DbFreeNN(db, pFree); 4547 if( rc!=SQLITE_OK ){ 4548 goto abort_due_to_error; 4549 } 4550 pC->seekResult = res; 4551 alreadyExists = (res==0); 4552 pC->nullRow = 1-alreadyExists; 4553 pC->deferredMoveto = 0; 4554 pC->cacheStatus = CACHE_STALE; 4555 if( pOp->opcode==OP_Found ){ 4556 VdbeBranchTaken(alreadyExists!=0,2); 4557 if( alreadyExists ) goto jump_to_p2; 4558 }else{ 4559 VdbeBranchTaken(takeJump||alreadyExists==0,2); 4560 if( takeJump || !alreadyExists ) goto jump_to_p2; 4561 } 4562 break; 4563 } 4564 4565 /* Opcode: SeekRowid P1 P2 P3 * * 4566 ** Synopsis: intkey=r[P3] 4567 ** 4568 ** P1 is the index of a cursor open on an SQL table btree (with integer 4569 ** keys). If register P3 does not contain an integer or if P1 does not 4570 ** contain a record with rowid P3 then jump immediately to P2. 4571 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain 4572 ** a record with rowid P3 then 4573 ** leave the cursor pointing at that record and fall through to the next 4574 ** instruction. 4575 ** 4576 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists 4577 ** the P3 register must be guaranteed to contain an integer value. With this 4578 ** opcode, register P3 might not contain an integer. 4579 ** 4580 ** The OP_NotFound opcode performs the same operation on index btrees 4581 ** (with arbitrary multi-value keys). 4582 ** 4583 ** This opcode leaves the cursor in a state where it cannot be advanced 4584 ** in either direction. In other words, the Next and Prev opcodes will 4585 ** not work following this opcode. 4586 ** 4587 ** See also: Found, NotFound, NoConflict, SeekRowid 4588 */ 4589 /* Opcode: NotExists P1 P2 P3 * * 4590 ** Synopsis: intkey=r[P3] 4591 ** 4592 ** P1 is the index of a cursor open on an SQL table btree (with integer 4593 ** keys). P3 is an integer rowid. If P1 does not contain a record with 4594 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an 4595 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then 4596 ** leave the cursor pointing at that record and fall through to the next 4597 ** instruction. 4598 ** 4599 ** The OP_SeekRowid opcode performs the same operation but also allows the 4600 ** P3 register to contain a non-integer value, in which case the jump is 4601 ** always taken. This opcode requires that P3 always contain an integer. 4602 ** 4603 ** The OP_NotFound opcode performs the same operation on index btrees 4604 ** (with arbitrary multi-value keys). 4605 ** 4606 ** This opcode leaves the cursor in a state where it cannot be advanced 4607 ** in either direction. In other words, the Next and Prev opcodes will 4608 ** not work following this opcode. 4609 ** 4610 ** See also: Found, NotFound, NoConflict, SeekRowid 4611 */ 4612 case OP_SeekRowid: { /* jump, in3 */ 4613 VdbeCursor *pC; 4614 BtCursor *pCrsr; 4615 int res; 4616 u64 iKey; 4617 4618 pIn3 = &aMem[pOp->p3]; 4619 testcase( pIn3->flags & MEM_Int ); 4620 testcase( pIn3->flags & MEM_IntReal ); 4621 testcase( pIn3->flags & MEM_Real ); 4622 testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str ); 4623 if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){ 4624 /* If pIn3->u.i does not contain an integer, compute iKey as the 4625 ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted 4626 ** into an integer without loss of information. Take care to avoid 4627 ** changing the datatype of pIn3, however, as it is used by other 4628 ** parts of the prepared statement. */ 4629 Mem x = pIn3[0]; 4630 applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding); 4631 if( (x.flags & MEM_Int)==0 ) goto jump_to_p2; 4632 iKey = x.u.i; 4633 goto notExistsWithKey; 4634 } 4635 /* Fall through into OP_NotExists */ 4636 case OP_NotExists: /* jump, in3 */ 4637 pIn3 = &aMem[pOp->p3]; 4638 assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid ); 4639 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4640 iKey = pIn3->u.i; 4641 notExistsWithKey: 4642 pC = p->apCsr[pOp->p1]; 4643 assert( pC!=0 ); 4644 #ifdef SQLITE_DEBUG 4645 if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid; 4646 #endif 4647 assert( pC->isTable ); 4648 assert( pC->eCurType==CURTYPE_BTREE ); 4649 pCrsr = pC->uc.pCursor; 4650 assert( pCrsr!=0 ); 4651 res = 0; 4652 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res); 4653 assert( rc==SQLITE_OK || res==0 ); 4654 pC->movetoTarget = iKey; /* Used by OP_Delete */ 4655 pC->nullRow = 0; 4656 pC->cacheStatus = CACHE_STALE; 4657 pC->deferredMoveto = 0; 4658 VdbeBranchTaken(res!=0,2); 4659 pC->seekResult = res; 4660 if( res!=0 ){ 4661 assert( rc==SQLITE_OK ); 4662 if( pOp->p2==0 ){ 4663 rc = SQLITE_CORRUPT_BKPT; 4664 }else{ 4665 goto jump_to_p2; 4666 } 4667 } 4668 if( rc ) goto abort_due_to_error; 4669 break; 4670 } 4671 4672 /* Opcode: Sequence P1 P2 * * * 4673 ** Synopsis: r[P2]=cursor[P1].ctr++ 4674 ** 4675 ** Find the next available sequence number for cursor P1. 4676 ** Write the sequence number into register P2. 4677 ** The sequence number on the cursor is incremented after this 4678 ** instruction. 4679 */ 4680 case OP_Sequence: { /* out2 */ 4681 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4682 assert( p->apCsr[pOp->p1]!=0 ); 4683 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB ); 4684 pOut = out2Prerelease(p, pOp); 4685 pOut->u.i = p->apCsr[pOp->p1]->seqCount++; 4686 break; 4687 } 4688 4689 4690 /* Opcode: NewRowid P1 P2 P3 * * 4691 ** Synopsis: r[P2]=rowid 4692 ** 4693 ** Get a new integer record number (a.k.a "rowid") used as the key to a table. 4694 ** The record number is not previously used as a key in the database 4695 ** table that cursor P1 points to. The new record number is written 4696 ** written to register P2. 4697 ** 4698 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 4699 ** the largest previously generated record number. No new record numbers are 4700 ** allowed to be less than this value. When this value reaches its maximum, 4701 ** an SQLITE_FULL error is generated. The P3 register is updated with the ' 4702 ** generated record number. This P3 mechanism is used to help implement the 4703 ** AUTOINCREMENT feature. 4704 */ 4705 case OP_NewRowid: { /* out2 */ 4706 i64 v; /* The new rowid */ 4707 VdbeCursor *pC; /* Cursor of table to get the new rowid */ 4708 int res; /* Result of an sqlite3BtreeLast() */ 4709 int cnt; /* Counter to limit the number of searches */ 4710 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */ 4711 VdbeFrame *pFrame; /* Root frame of VDBE */ 4712 4713 v = 0; 4714 res = 0; 4715 pOut = out2Prerelease(p, pOp); 4716 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4717 pC = p->apCsr[pOp->p1]; 4718 assert( pC!=0 ); 4719 assert( pC->isTable ); 4720 assert( pC->eCurType==CURTYPE_BTREE ); 4721 assert( pC->uc.pCursor!=0 ); 4722 { 4723 /* The next rowid or record number (different terms for the same 4724 ** thing) is obtained in a two-step algorithm. 4725 ** 4726 ** First we attempt to find the largest existing rowid and add one 4727 ** to that. But if the largest existing rowid is already the maximum 4728 ** positive integer, we have to fall through to the second 4729 ** probabilistic algorithm 4730 ** 4731 ** The second algorithm is to select a rowid at random and see if 4732 ** it already exists in the table. If it does not exist, we have 4733 ** succeeded. If the random rowid does exist, we select a new one 4734 ** and try again, up to 100 times. 4735 */ 4736 assert( pC->isTable ); 4737 4738 #ifdef SQLITE_32BIT_ROWID 4739 # define MAX_ROWID 0x7fffffff 4740 #else 4741 /* Some compilers complain about constants of the form 0x7fffffffffffffff. 4742 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems 4743 ** to provide the constant while making all compilers happy. 4744 */ 4745 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff ) 4746 #endif 4747 4748 if( !pC->useRandomRowid ){ 4749 rc = sqlite3BtreeLast(pC->uc.pCursor, &res); 4750 if( rc!=SQLITE_OK ){ 4751 goto abort_due_to_error; 4752 } 4753 if( res ){ 4754 v = 1; /* IMP: R-61914-48074 */ 4755 }else{ 4756 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) ); 4757 v = sqlite3BtreeIntegerKey(pC->uc.pCursor); 4758 if( v>=MAX_ROWID ){ 4759 pC->useRandomRowid = 1; 4760 }else{ 4761 v++; /* IMP: R-29538-34987 */ 4762 } 4763 } 4764 } 4765 4766 #ifndef SQLITE_OMIT_AUTOINCREMENT 4767 if( pOp->p3 ){ 4768 /* Assert that P3 is a valid memory cell. */ 4769 assert( pOp->p3>0 ); 4770 if( p->pFrame ){ 4771 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); 4772 /* Assert that P3 is a valid memory cell. */ 4773 assert( pOp->p3<=pFrame->nMem ); 4774 pMem = &pFrame->aMem[pOp->p3]; 4775 }else{ 4776 /* Assert that P3 is a valid memory cell. */ 4777 assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); 4778 pMem = &aMem[pOp->p3]; 4779 memAboutToChange(p, pMem); 4780 } 4781 assert( memIsValid(pMem) ); 4782 4783 REGISTER_TRACE(pOp->p3, pMem); 4784 sqlite3VdbeMemIntegerify(pMem); 4785 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */ 4786 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){ 4787 rc = SQLITE_FULL; /* IMP: R-17817-00630 */ 4788 goto abort_due_to_error; 4789 } 4790 if( v<pMem->u.i+1 ){ 4791 v = pMem->u.i + 1; 4792 } 4793 pMem->u.i = v; 4794 } 4795 #endif 4796 if( pC->useRandomRowid ){ 4797 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the 4798 ** largest possible integer (9223372036854775807) then the database 4799 ** engine starts picking positive candidate ROWIDs at random until 4800 ** it finds one that is not previously used. */ 4801 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is 4802 ** an AUTOINCREMENT table. */ 4803 cnt = 0; 4804 do{ 4805 sqlite3_randomness(sizeof(v), &v); 4806 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */ 4807 }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v, 4808 0, &res))==SQLITE_OK) 4809 && (res==0) 4810 && (++cnt<100)); 4811 if( rc ) goto abort_due_to_error; 4812 if( res==0 ){ 4813 rc = SQLITE_FULL; /* IMP: R-38219-53002 */ 4814 goto abort_due_to_error; 4815 } 4816 assert( v>0 ); /* EV: R-40812-03570 */ 4817 } 4818 pC->deferredMoveto = 0; 4819 pC->cacheStatus = CACHE_STALE; 4820 } 4821 pOut->u.i = v; 4822 break; 4823 } 4824 4825 /* Opcode: Insert P1 P2 P3 P4 P5 4826 ** Synopsis: intkey=r[P3] data=r[P2] 4827 ** 4828 ** Write an entry into the table of cursor P1. A new entry is 4829 ** created if it doesn't already exist or the data for an existing 4830 ** entry is overwritten. The data is the value MEM_Blob stored in register 4831 ** number P2. The key is stored in register P3. The key must 4832 ** be a MEM_Int. 4833 ** 4834 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is 4835 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set, 4836 ** then rowid is stored for subsequent return by the 4837 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified). 4838 ** 4839 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might 4840 ** run faster by avoiding an unnecessary seek on cursor P1. However, 4841 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior 4842 ** seeks on the cursor or if the most recent seek used a key equal to P3. 4843 ** 4844 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an 4845 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode 4846 ** is part of an INSERT operation. The difference is only important to 4847 ** the update hook. 4848 ** 4849 ** Parameter P4 may point to a Table structure, or may be NULL. If it is 4850 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked 4851 ** following a successful insert. 4852 ** 4853 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically 4854 ** allocated, then ownership of P2 is transferred to the pseudo-cursor 4855 ** and register P2 becomes ephemeral. If the cursor is changed, the 4856 ** value of register P2 will then change. Make sure this does not 4857 ** cause any problems.) 4858 ** 4859 ** This instruction only works on tables. The equivalent instruction 4860 ** for indices is OP_IdxInsert. 4861 */ 4862 case OP_Insert: { 4863 Mem *pData; /* MEM cell holding data for the record to be inserted */ 4864 Mem *pKey; /* MEM cell holding key for the record */ 4865 VdbeCursor *pC; /* Cursor to table into which insert is written */ 4866 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */ 4867 const char *zDb; /* database name - used by the update hook */ 4868 Table *pTab; /* Table structure - used by update and pre-update hooks */ 4869 BtreePayload x; /* Payload to be inserted */ 4870 4871 pData = &aMem[pOp->p2]; 4872 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4873 assert( memIsValid(pData) ); 4874 pC = p->apCsr[pOp->p1]; 4875 assert( pC!=0 ); 4876 assert( pC->eCurType==CURTYPE_BTREE ); 4877 assert( pC->deferredMoveto==0 ); 4878 assert( pC->uc.pCursor!=0 ); 4879 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable ); 4880 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC ); 4881 REGISTER_TRACE(pOp->p2, pData); 4882 sqlite3VdbeIncrWriteCounter(p, pC); 4883 4884 pKey = &aMem[pOp->p3]; 4885 assert( pKey->flags & MEM_Int ); 4886 assert( memIsValid(pKey) ); 4887 REGISTER_TRACE(pOp->p3, pKey); 4888 x.nKey = pKey->u.i; 4889 4890 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){ 4891 assert( pC->iDb>=0 ); 4892 zDb = db->aDb[pC->iDb].zDbSName; 4893 pTab = pOp->p4.pTab; 4894 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) ); 4895 }else{ 4896 pTab = 0; 4897 zDb = 0; /* Not needed. Silence a compiler warning. */ 4898 } 4899 4900 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 4901 /* Invoke the pre-update hook, if any */ 4902 if( pTab ){ 4903 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){ 4904 sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2); 4905 } 4906 if( db->xUpdateCallback==0 || pTab->aCol==0 ){ 4907 /* Prevent post-update hook from running in cases when it should not */ 4908 pTab = 0; 4909 } 4910 } 4911 if( pOp->p5 & OPFLAG_ISNOOP ) break; 4912 #endif 4913 4914 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; 4915 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey; 4916 assert( pData->flags & (MEM_Blob|MEM_Str) ); 4917 x.pData = pData->z; 4918 x.nData = pData->n; 4919 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0); 4920 if( pData->flags & MEM_Zero ){ 4921 x.nZero = pData->u.nZero; 4922 }else{ 4923 x.nZero = 0; 4924 } 4925 x.pKey = 0; 4926 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, 4927 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult 4928 ); 4929 pC->deferredMoveto = 0; 4930 pC->cacheStatus = CACHE_STALE; 4931 4932 /* Invoke the update-hook if required. */ 4933 if( rc ) goto abort_due_to_error; 4934 if( pTab ){ 4935 assert( db->xUpdateCallback!=0 ); 4936 assert( pTab->aCol!=0 ); 4937 db->xUpdateCallback(db->pUpdateArg, 4938 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT, 4939 zDb, pTab->zName, x.nKey); 4940 } 4941 break; 4942 } 4943 4944 /* Opcode: Delete P1 P2 P3 P4 P5 4945 ** 4946 ** Delete the record at which the P1 cursor is currently pointing. 4947 ** 4948 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then 4949 ** the cursor will be left pointing at either the next or the previous 4950 ** record in the table. If it is left pointing at the next record, then 4951 ** the next Next instruction will be a no-op. As a result, in this case 4952 ** it is ok to delete a record from within a Next loop. If 4953 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be 4954 ** left in an undefined state. 4955 ** 4956 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this 4957 ** delete one of several associated with deleting a table row and all its 4958 ** associated index entries. Exactly one of those deletes is the "primary" 4959 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are 4960 ** marked with the AUXDELETE flag. 4961 ** 4962 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row 4963 ** change count is incremented (otherwise not). 4964 ** 4965 ** P1 must not be pseudo-table. It has to be a real table with 4966 ** multiple rows. 4967 ** 4968 ** If P4 is not NULL then it points to a Table object. In this case either 4969 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must 4970 ** have been positioned using OP_NotFound prior to invoking this opcode in 4971 ** this case. Specifically, if one is configured, the pre-update hook is 4972 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured, 4973 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2. 4974 ** 4975 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address 4976 ** of the memory cell that contains the value that the rowid of the row will 4977 ** be set to by the update. 4978 */ 4979 case OP_Delete: { 4980 VdbeCursor *pC; 4981 const char *zDb; 4982 Table *pTab; 4983 int opflags; 4984 4985 opflags = pOp->p2; 4986 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4987 pC = p->apCsr[pOp->p1]; 4988 assert( pC!=0 ); 4989 assert( pC->eCurType==CURTYPE_BTREE ); 4990 assert( pC->uc.pCursor!=0 ); 4991 assert( pC->deferredMoveto==0 ); 4992 sqlite3VdbeIncrWriteCounter(p, pC); 4993 4994 #ifdef SQLITE_DEBUG 4995 if( pOp->p4type==P4_TABLE 4996 && HasRowid(pOp->p4.pTab) 4997 && pOp->p5==0 4998 && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) 4999 ){ 5000 /* If p5 is zero, the seek operation that positioned the cursor prior to 5001 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of 5002 ** the row that is being deleted */ 5003 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor); 5004 assert( CORRUPT_DB || pC->movetoTarget==iKey ); 5005 } 5006 #endif 5007 5008 /* If the update-hook or pre-update-hook will be invoked, set zDb to 5009 ** the name of the db to pass as to it. Also set local pTab to a copy 5010 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was 5011 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set 5012 ** VdbeCursor.movetoTarget to the current rowid. */ 5013 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){ 5014 assert( pC->iDb>=0 ); 5015 assert( pOp->p4.pTab!=0 ); 5016 zDb = db->aDb[pC->iDb].zDbSName; 5017 pTab = pOp->p4.pTab; 5018 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){ 5019 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor); 5020 } 5021 }else{ 5022 zDb = 0; /* Not needed. Silence a compiler warning. */ 5023 pTab = 0; /* Not needed. Silence a compiler warning. */ 5024 } 5025 5026 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 5027 /* Invoke the pre-update-hook if required. */ 5028 if( db->xPreUpdateCallback && pOp->p4.pTab ){ 5029 assert( !(opflags & OPFLAG_ISUPDATE) 5030 || HasRowid(pTab)==0 5031 || (aMem[pOp->p3].flags & MEM_Int) 5032 ); 5033 sqlite3VdbePreUpdateHook(p, pC, 5034 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE, 5035 zDb, pTab, pC->movetoTarget, 5036 pOp->p3 5037 ); 5038 } 5039 if( opflags & OPFLAG_ISNOOP ) break; 5040 #endif 5041 5042 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */ 5043 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 ); 5044 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION ); 5045 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE ); 5046 5047 #ifdef SQLITE_DEBUG 5048 if( p->pFrame==0 ){ 5049 if( pC->isEphemeral==0 5050 && (pOp->p5 & OPFLAG_AUXDELETE)==0 5051 && (pC->wrFlag & OPFLAG_FORDELETE)==0 5052 ){ 5053 nExtraDelete++; 5054 } 5055 if( pOp->p2 & OPFLAG_NCHANGE ){ 5056 nExtraDelete--; 5057 } 5058 } 5059 #endif 5060 5061 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5); 5062 pC->cacheStatus = CACHE_STALE; 5063 pC->seekResult = 0; 5064 if( rc ) goto abort_due_to_error; 5065 5066 /* Invoke the update-hook if required. */ 5067 if( opflags & OPFLAG_NCHANGE ){ 5068 p->nChange++; 5069 if( db->xUpdateCallback && HasRowid(pTab) ){ 5070 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName, 5071 pC->movetoTarget); 5072 assert( pC->iDb>=0 ); 5073 } 5074 } 5075 5076 break; 5077 } 5078 /* Opcode: ResetCount * * * * * 5079 ** 5080 ** The value of the change counter is copied to the database handle 5081 ** change counter (returned by subsequent calls to sqlite3_changes()). 5082 ** Then the VMs internal change counter resets to 0. 5083 ** This is used by trigger programs. 5084 */ 5085 case OP_ResetCount: { 5086 sqlite3VdbeSetChanges(db, p->nChange); 5087 p->nChange = 0; 5088 break; 5089 } 5090 5091 /* Opcode: SorterCompare P1 P2 P3 P4 5092 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2 5093 ** 5094 ** P1 is a sorter cursor. This instruction compares a prefix of the 5095 ** record blob in register P3 against a prefix of the entry that 5096 ** the sorter cursor currently points to. Only the first P4 fields 5097 ** of r[P3] and the sorter record are compared. 5098 ** 5099 ** If either P3 or the sorter contains a NULL in one of their significant 5100 ** fields (not counting the P4 fields at the end which are ignored) then 5101 ** the comparison is assumed to be equal. 5102 ** 5103 ** Fall through to next instruction if the two records compare equal to 5104 ** each other. Jump to P2 if they are different. 5105 */ 5106 case OP_SorterCompare: { 5107 VdbeCursor *pC; 5108 int res; 5109 int nKeyCol; 5110 5111 pC = p->apCsr[pOp->p1]; 5112 assert( isSorter(pC) ); 5113 assert( pOp->p4type==P4_INT32 ); 5114 pIn3 = &aMem[pOp->p3]; 5115 nKeyCol = pOp->p4.i; 5116 res = 0; 5117 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res); 5118 VdbeBranchTaken(res!=0,2); 5119 if( rc ) goto abort_due_to_error; 5120 if( res ) goto jump_to_p2; 5121 break; 5122 }; 5123 5124 /* Opcode: SorterData P1 P2 P3 * * 5125 ** Synopsis: r[P2]=data 5126 ** 5127 ** Write into register P2 the current sorter data for sorter cursor P1. 5128 ** Then clear the column header cache on cursor P3. 5129 ** 5130 ** This opcode is normally use to move a record out of the sorter and into 5131 ** a register that is the source for a pseudo-table cursor created using 5132 ** OpenPseudo. That pseudo-table cursor is the one that is identified by 5133 ** parameter P3. Clearing the P3 column cache as part of this opcode saves 5134 ** us from having to issue a separate NullRow instruction to clear that cache. 5135 */ 5136 case OP_SorterData: { 5137 VdbeCursor *pC; 5138 5139 pOut = &aMem[pOp->p2]; 5140 pC = p->apCsr[pOp->p1]; 5141 assert( isSorter(pC) ); 5142 rc = sqlite3VdbeSorterRowkey(pC, pOut); 5143 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) ); 5144 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5145 if( rc ) goto abort_due_to_error; 5146 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE; 5147 break; 5148 } 5149 5150 /* Opcode: RowData P1 P2 P3 * * 5151 ** Synopsis: r[P2]=data 5152 ** 5153 ** Write into register P2 the complete row content for the row at 5154 ** which cursor P1 is currently pointing. 5155 ** There is no interpretation of the data. 5156 ** It is just copied onto the P2 register exactly as 5157 ** it is found in the database file. 5158 ** 5159 ** If cursor P1 is an index, then the content is the key of the row. 5160 ** If cursor P2 is a table, then the content extracted is the data. 5161 ** 5162 ** If the P1 cursor must be pointing to a valid row (not a NULL row) 5163 ** of a real table, not a pseudo-table. 5164 ** 5165 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer 5166 ** into the database page. That means that the content of the output 5167 ** register will be invalidated as soon as the cursor moves - including 5168 ** moves caused by other cursors that "save" the current cursors 5169 ** position in order that they can write to the same table. If P3==0 5170 ** then a copy of the data is made into memory. P3!=0 is faster, but 5171 ** P3==0 is safer. 5172 ** 5173 ** If P3!=0 then the content of the P2 register is unsuitable for use 5174 ** in OP_Result and any OP_Result will invalidate the P2 register content. 5175 ** The P2 register content is invalidated by opcodes like OP_Function or 5176 ** by any use of another cursor pointing to the same table. 5177 */ 5178 case OP_RowData: { 5179 VdbeCursor *pC; 5180 BtCursor *pCrsr; 5181 u32 n; 5182 5183 pOut = out2Prerelease(p, pOp); 5184 5185 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5186 pC = p->apCsr[pOp->p1]; 5187 assert( pC!=0 ); 5188 assert( pC->eCurType==CURTYPE_BTREE ); 5189 assert( isSorter(pC)==0 ); 5190 assert( pC->nullRow==0 ); 5191 assert( pC->uc.pCursor!=0 ); 5192 pCrsr = pC->uc.pCursor; 5193 5194 /* The OP_RowData opcodes always follow OP_NotExists or 5195 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions 5196 ** that might invalidate the cursor. 5197 ** If this where not the case, on of the following assert()s 5198 ** would fail. Should this ever change (because of changes in the code 5199 ** generator) then the fix would be to insert a call to 5200 ** sqlite3VdbeCursorMoveto(). 5201 */ 5202 assert( pC->deferredMoveto==0 ); 5203 assert( sqlite3BtreeCursorIsValid(pCrsr) ); 5204 #if 0 /* Not required due to the previous to assert() statements */ 5205 rc = sqlite3VdbeCursorMoveto(pC); 5206 if( rc!=SQLITE_OK ) goto abort_due_to_error; 5207 #endif 5208 5209 n = sqlite3BtreePayloadSize(pCrsr); 5210 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ 5211 goto too_big; 5212 } 5213 testcase( n==0 ); 5214 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut); 5215 if( rc ) goto abort_due_to_error; 5216 if( !pOp->p3 ) Deephemeralize(pOut); 5217 UPDATE_MAX_BLOBSIZE(pOut); 5218 REGISTER_TRACE(pOp->p2, pOut); 5219 break; 5220 } 5221 5222 /* Opcode: Rowid P1 P2 * * * 5223 ** Synopsis: r[P2]=rowid 5224 ** 5225 ** Store in register P2 an integer which is the key of the table entry that 5226 ** P1 is currently point to. 5227 ** 5228 ** P1 can be either an ordinary table or a virtual table. There used to 5229 ** be a separate OP_VRowid opcode for use with virtual tables, but this 5230 ** one opcode now works for both table types. 5231 */ 5232 case OP_Rowid: { /* out2 */ 5233 VdbeCursor *pC; 5234 i64 v; 5235 sqlite3_vtab *pVtab; 5236 const sqlite3_module *pModule; 5237 5238 pOut = out2Prerelease(p, pOp); 5239 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5240 pC = p->apCsr[pOp->p1]; 5241 assert( pC!=0 ); 5242 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow ); 5243 if( pC->nullRow ){ 5244 pOut->flags = MEM_Null; 5245 break; 5246 }else if( pC->deferredMoveto ){ 5247 v = pC->movetoTarget; 5248 #ifndef SQLITE_OMIT_VIRTUALTABLE 5249 }else if( pC->eCurType==CURTYPE_VTAB ){ 5250 assert( pC->uc.pVCur!=0 ); 5251 pVtab = pC->uc.pVCur->pVtab; 5252 pModule = pVtab->pModule; 5253 assert( pModule->xRowid ); 5254 rc = pModule->xRowid(pC->uc.pVCur, &v); 5255 sqlite3VtabImportErrmsg(p, pVtab); 5256 if( rc ) goto abort_due_to_error; 5257 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 5258 }else{ 5259 assert( pC->eCurType==CURTYPE_BTREE ); 5260 assert( pC->uc.pCursor!=0 ); 5261 rc = sqlite3VdbeCursorRestore(pC); 5262 if( rc ) goto abort_due_to_error; 5263 if( pC->nullRow ){ 5264 pOut->flags = MEM_Null; 5265 break; 5266 } 5267 v = sqlite3BtreeIntegerKey(pC->uc.pCursor); 5268 } 5269 pOut->u.i = v; 5270 break; 5271 } 5272 5273 /* Opcode: NullRow P1 * * * * 5274 ** 5275 ** Move the cursor P1 to a null row. Any OP_Column operations 5276 ** that occur while the cursor is on the null row will always 5277 ** write a NULL. 5278 */ 5279 case OP_NullRow: { 5280 VdbeCursor *pC; 5281 5282 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5283 pC = p->apCsr[pOp->p1]; 5284 assert( pC!=0 ); 5285 pC->nullRow = 1; 5286 pC->cacheStatus = CACHE_STALE; 5287 if( pC->eCurType==CURTYPE_BTREE ){ 5288 assert( pC->uc.pCursor!=0 ); 5289 sqlite3BtreeClearCursor(pC->uc.pCursor); 5290 } 5291 #ifdef SQLITE_DEBUG 5292 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow; 5293 #endif 5294 break; 5295 } 5296 5297 /* Opcode: SeekEnd P1 * * * * 5298 ** 5299 ** Position cursor P1 at the end of the btree for the purpose of 5300 ** appending a new entry onto the btree. 5301 ** 5302 ** It is assumed that the cursor is used only for appending and so 5303 ** if the cursor is valid, then the cursor must already be pointing 5304 ** at the end of the btree and so no changes are made to 5305 ** the cursor. 5306 */ 5307 /* Opcode: Last P1 P2 * * * 5308 ** 5309 ** The next use of the Rowid or Column or Prev instruction for P1 5310 ** will refer to the last entry in the database table or index. 5311 ** If the table or index is empty and P2>0, then jump immediately to P2. 5312 ** If P2 is 0 or if the table or index is not empty, fall through 5313 ** to the following instruction. 5314 ** 5315 ** This opcode leaves the cursor configured to move in reverse order, 5316 ** from the end toward the beginning. In other words, the cursor is 5317 ** configured to use Prev, not Next. 5318 */ 5319 case OP_SeekEnd: 5320 case OP_Last: { /* jump */ 5321 VdbeCursor *pC; 5322 BtCursor *pCrsr; 5323 int res; 5324 5325 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5326 pC = p->apCsr[pOp->p1]; 5327 assert( pC!=0 ); 5328 assert( pC->eCurType==CURTYPE_BTREE ); 5329 pCrsr = pC->uc.pCursor; 5330 res = 0; 5331 assert( pCrsr!=0 ); 5332 #ifdef SQLITE_DEBUG 5333 pC->seekOp = pOp->opcode; 5334 #endif 5335 if( pOp->opcode==OP_SeekEnd ){ 5336 assert( pOp->p2==0 ); 5337 pC->seekResult = -1; 5338 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){ 5339 break; 5340 } 5341 } 5342 rc = sqlite3BtreeLast(pCrsr, &res); 5343 pC->nullRow = (u8)res; 5344 pC->deferredMoveto = 0; 5345 pC->cacheStatus = CACHE_STALE; 5346 if( rc ) goto abort_due_to_error; 5347 if( pOp->p2>0 ){ 5348 VdbeBranchTaken(res!=0,2); 5349 if( res ) goto jump_to_p2; 5350 } 5351 break; 5352 } 5353 5354 /* Opcode: IfSmaller P1 P2 P3 * * 5355 ** 5356 ** Estimate the number of rows in the table P1. Jump to P2 if that 5357 ** estimate is less than approximately 2**(0.1*P3). 5358 */ 5359 case OP_IfSmaller: { /* jump */ 5360 VdbeCursor *pC; 5361 BtCursor *pCrsr; 5362 int res; 5363 i64 sz; 5364 5365 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5366 pC = p->apCsr[pOp->p1]; 5367 assert( pC!=0 ); 5368 pCrsr = pC->uc.pCursor; 5369 assert( pCrsr ); 5370 rc = sqlite3BtreeFirst(pCrsr, &res); 5371 if( rc ) goto abort_due_to_error; 5372 if( res==0 ){ 5373 sz = sqlite3BtreeRowCountEst(pCrsr); 5374 if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1; 5375 } 5376 VdbeBranchTaken(res!=0,2); 5377 if( res ) goto jump_to_p2; 5378 break; 5379 } 5380 5381 5382 /* Opcode: SorterSort P1 P2 * * * 5383 ** 5384 ** After all records have been inserted into the Sorter object 5385 ** identified by P1, invoke this opcode to actually do the sorting. 5386 ** Jump to P2 if there are no records to be sorted. 5387 ** 5388 ** This opcode is an alias for OP_Sort and OP_Rewind that is used 5389 ** for Sorter objects. 5390 */ 5391 /* Opcode: Sort P1 P2 * * * 5392 ** 5393 ** This opcode does exactly the same thing as OP_Rewind except that 5394 ** it increments an undocumented global variable used for testing. 5395 ** 5396 ** Sorting is accomplished by writing records into a sorting index, 5397 ** then rewinding that index and playing it back from beginning to 5398 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the 5399 ** rewinding so that the global variable will be incremented and 5400 ** regression tests can determine whether or not the optimizer is 5401 ** correctly optimizing out sorts. 5402 */ 5403 case OP_SorterSort: /* jump */ 5404 case OP_Sort: { /* jump */ 5405 #ifdef SQLITE_TEST 5406 sqlite3_sort_count++; 5407 sqlite3_search_count--; 5408 #endif 5409 p->aCounter[SQLITE_STMTSTATUS_SORT]++; 5410 /* Fall through into OP_Rewind */ 5411 } 5412 /* Opcode: Rewind P1 P2 * * * 5413 ** 5414 ** The next use of the Rowid or Column or Next instruction for P1 5415 ** will refer to the first entry in the database table or index. 5416 ** If the table or index is empty, jump immediately to P2. 5417 ** If the table or index is not empty, fall through to the following 5418 ** instruction. 5419 ** 5420 ** This opcode leaves the cursor configured to move in forward order, 5421 ** from the beginning toward the end. In other words, the cursor is 5422 ** configured to use Next, not Prev. 5423 */ 5424 case OP_Rewind: { /* jump */ 5425 VdbeCursor *pC; 5426 BtCursor *pCrsr; 5427 int res; 5428 5429 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5430 assert( pOp->p5==0 ); 5431 pC = p->apCsr[pOp->p1]; 5432 assert( pC!=0 ); 5433 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) ); 5434 res = 1; 5435 #ifdef SQLITE_DEBUG 5436 pC->seekOp = OP_Rewind; 5437 #endif 5438 if( isSorter(pC) ){ 5439 rc = sqlite3VdbeSorterRewind(pC, &res); 5440 }else{ 5441 assert( pC->eCurType==CURTYPE_BTREE ); 5442 pCrsr = pC->uc.pCursor; 5443 assert( pCrsr ); 5444 rc = sqlite3BtreeFirst(pCrsr, &res); 5445 pC->deferredMoveto = 0; 5446 pC->cacheStatus = CACHE_STALE; 5447 } 5448 if( rc ) goto abort_due_to_error; 5449 pC->nullRow = (u8)res; 5450 assert( pOp->p2>0 && pOp->p2<p->nOp ); 5451 VdbeBranchTaken(res!=0,2); 5452 if( res ) goto jump_to_p2; 5453 break; 5454 } 5455 5456 /* Opcode: Next P1 P2 P3 P4 P5 5457 ** 5458 ** Advance cursor P1 so that it points to the next key/data pair in its 5459 ** table or index. If there are no more key/value pairs then fall through 5460 ** to the following instruction. But if the cursor advance was successful, 5461 ** jump immediately to P2. 5462 ** 5463 ** The Next opcode is only valid following an SeekGT, SeekGE, or 5464 ** OP_Rewind opcode used to position the cursor. Next is not allowed 5465 ** to follow SeekLT, SeekLE, or OP_Last. 5466 ** 5467 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have 5468 ** been opened prior to this opcode or the program will segfault. 5469 ** 5470 ** The P3 value is a hint to the btree implementation. If P3==1, that 5471 ** means P1 is an SQL index and that this instruction could have been 5472 ** omitted if that index had been unique. P3 is usually 0. P3 is 5473 ** always either 0 or 1. 5474 ** 5475 ** P4 is always of type P4_ADVANCE. The function pointer points to 5476 ** sqlite3BtreeNext(). 5477 ** 5478 ** If P5 is positive and the jump is taken, then event counter 5479 ** number P5-1 in the prepared statement is incremented. 5480 ** 5481 ** See also: Prev 5482 */ 5483 /* Opcode: Prev P1 P2 P3 P4 P5 5484 ** 5485 ** Back up cursor P1 so that it points to the previous key/data pair in its 5486 ** table or index. If there is no previous key/value pairs then fall through 5487 ** to the following instruction. But if the cursor backup was successful, 5488 ** jump immediately to P2. 5489 ** 5490 ** 5491 ** The Prev opcode is only valid following an SeekLT, SeekLE, or 5492 ** OP_Last opcode used to position the cursor. Prev is not allowed 5493 ** to follow SeekGT, SeekGE, or OP_Rewind. 5494 ** 5495 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is 5496 ** not open then the behavior is undefined. 5497 ** 5498 ** The P3 value is a hint to the btree implementation. If P3==1, that 5499 ** means P1 is an SQL index and that this instruction could have been 5500 ** omitted if that index had been unique. P3 is usually 0. P3 is 5501 ** always either 0 or 1. 5502 ** 5503 ** P4 is always of type P4_ADVANCE. The function pointer points to 5504 ** sqlite3BtreePrevious(). 5505 ** 5506 ** If P5 is positive and the jump is taken, then event counter 5507 ** number P5-1 in the prepared statement is incremented. 5508 */ 5509 /* Opcode: SorterNext P1 P2 * * P5 5510 ** 5511 ** This opcode works just like OP_Next except that P1 must be a 5512 ** sorter object for which the OP_SorterSort opcode has been 5513 ** invoked. This opcode advances the cursor to the next sorted 5514 ** record, or jumps to P2 if there are no more sorted records. 5515 */ 5516 case OP_SorterNext: { /* jump */ 5517 VdbeCursor *pC; 5518 5519 pC = p->apCsr[pOp->p1]; 5520 assert( isSorter(pC) ); 5521 rc = sqlite3VdbeSorterNext(db, pC); 5522 goto next_tail; 5523 case OP_Prev: /* jump */ 5524 case OP_Next: /* jump */ 5525 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5526 assert( pOp->p5<ArraySize(p->aCounter) ); 5527 pC = p->apCsr[pOp->p1]; 5528 assert( pC!=0 ); 5529 assert( pC->deferredMoveto==0 ); 5530 assert( pC->eCurType==CURTYPE_BTREE ); 5531 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext ); 5532 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious ); 5533 5534 /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found. 5535 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */ 5536 assert( pOp->opcode!=OP_Next 5537 || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE 5538 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found 5539 || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid 5540 || pC->seekOp==OP_IfNoHope); 5541 assert( pOp->opcode!=OP_Prev 5542 || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE 5543 || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope 5544 || pC->seekOp==OP_NullRow); 5545 5546 rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3); 5547 next_tail: 5548 pC->cacheStatus = CACHE_STALE; 5549 VdbeBranchTaken(rc==SQLITE_OK,2); 5550 if( rc==SQLITE_OK ){ 5551 pC->nullRow = 0; 5552 p->aCounter[pOp->p5]++; 5553 #ifdef SQLITE_TEST 5554 sqlite3_search_count++; 5555 #endif 5556 goto jump_to_p2_and_check_for_interrupt; 5557 } 5558 if( rc!=SQLITE_DONE ) goto abort_due_to_error; 5559 rc = SQLITE_OK; 5560 pC->nullRow = 1; 5561 goto check_for_interrupt; 5562 } 5563 5564 /* Opcode: IdxInsert P1 P2 P3 P4 P5 5565 ** Synopsis: key=r[P2] 5566 ** 5567 ** Register P2 holds an SQL index key made using the 5568 ** MakeRecord instructions. This opcode writes that key 5569 ** into the index P1. Data for the entry is nil. 5570 ** 5571 ** If P4 is not zero, then it is the number of values in the unpacked 5572 ** key of reg(P2). In that case, P3 is the index of the first register 5573 ** for the unpacked key. The availability of the unpacked key can sometimes 5574 ** be an optimization. 5575 ** 5576 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer 5577 ** that this insert is likely to be an append. 5578 ** 5579 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is 5580 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear, 5581 ** then the change counter is unchanged. 5582 ** 5583 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might 5584 ** run faster by avoiding an unnecessary seek on cursor P1. However, 5585 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior 5586 ** seeks on the cursor or if the most recent seek used a key equivalent 5587 ** to P2. 5588 ** 5589 ** This instruction only works for indices. The equivalent instruction 5590 ** for tables is OP_Insert. 5591 */ 5592 /* Opcode: SorterInsert P1 P2 * * * 5593 ** Synopsis: key=r[P2] 5594 ** 5595 ** Register P2 holds an SQL index key made using the 5596 ** MakeRecord instructions. This opcode writes that key 5597 ** into the sorter P1. Data for the entry is nil. 5598 */ 5599 case OP_SorterInsert: /* in2 */ 5600 case OP_IdxInsert: { /* in2 */ 5601 VdbeCursor *pC; 5602 BtreePayload x; 5603 5604 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5605 pC = p->apCsr[pOp->p1]; 5606 sqlite3VdbeIncrWriteCounter(p, pC); 5607 assert( pC!=0 ); 5608 assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) ); 5609 pIn2 = &aMem[pOp->p2]; 5610 assert( pIn2->flags & MEM_Blob ); 5611 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; 5612 assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert ); 5613 assert( pC->isTable==0 ); 5614 rc = ExpandBlob(pIn2); 5615 if( rc ) goto abort_due_to_error; 5616 if( pOp->opcode==OP_SorterInsert ){ 5617 rc = sqlite3VdbeSorterWrite(pC, pIn2); 5618 }else{ 5619 x.nKey = pIn2->n; 5620 x.pKey = pIn2->z; 5621 x.aMem = aMem + pOp->p3; 5622 x.nMem = (u16)pOp->p4.i; 5623 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, 5624 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), 5625 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0) 5626 ); 5627 assert( pC->deferredMoveto==0 ); 5628 pC->cacheStatus = CACHE_STALE; 5629 } 5630 if( rc) goto abort_due_to_error; 5631 break; 5632 } 5633 5634 /* Opcode: IdxDelete P1 P2 P3 * * 5635 ** Synopsis: key=r[P2@P3] 5636 ** 5637 ** The content of P3 registers starting at register P2 form 5638 ** an unpacked index key. This opcode removes that entry from the 5639 ** index opened by cursor P1. 5640 */ 5641 case OP_IdxDelete: { 5642 VdbeCursor *pC; 5643 BtCursor *pCrsr; 5644 int res; 5645 UnpackedRecord r; 5646 5647 assert( pOp->p3>0 ); 5648 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 ); 5649 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5650 pC = p->apCsr[pOp->p1]; 5651 assert( pC!=0 ); 5652 assert( pC->eCurType==CURTYPE_BTREE ); 5653 sqlite3VdbeIncrWriteCounter(p, pC); 5654 pCrsr = pC->uc.pCursor; 5655 assert( pCrsr!=0 ); 5656 assert( pOp->p5==0 ); 5657 r.pKeyInfo = pC->pKeyInfo; 5658 r.nField = (u16)pOp->p3; 5659 r.default_rc = 0; 5660 r.aMem = &aMem[pOp->p2]; 5661 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res); 5662 if( rc ) goto abort_due_to_error; 5663 if( res==0 ){ 5664 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE); 5665 if( rc ) goto abort_due_to_error; 5666 } 5667 assert( pC->deferredMoveto==0 ); 5668 pC->cacheStatus = CACHE_STALE; 5669 pC->seekResult = 0; 5670 break; 5671 } 5672 5673 /* Opcode: DeferredSeek P1 * P3 P4 * 5674 ** Synopsis: Move P3 to P1.rowid if needed 5675 ** 5676 ** P1 is an open index cursor and P3 is a cursor on the corresponding 5677 ** table. This opcode does a deferred seek of the P3 table cursor 5678 ** to the row that corresponds to the current row of P1. 5679 ** 5680 ** This is a deferred seek. Nothing actually happens until 5681 ** the cursor is used to read a record. That way, if no reads 5682 ** occur, no unnecessary I/O happens. 5683 ** 5684 ** P4 may be an array of integers (type P4_INTARRAY) containing 5685 ** one entry for each column in the P3 table. If array entry a(i) 5686 ** is non-zero, then reading column a(i)-1 from cursor P3 is 5687 ** equivalent to performing the deferred seek and then reading column i 5688 ** from P1. This information is stored in P3 and used to redirect 5689 ** reads against P3 over to P1, thus possibly avoiding the need to 5690 ** seek and read cursor P3. 5691 */ 5692 /* Opcode: IdxRowid P1 P2 * * * 5693 ** Synopsis: r[P2]=rowid 5694 ** 5695 ** Write into register P2 an integer which is the last entry in the record at 5696 ** the end of the index key pointed to by cursor P1. This integer should be 5697 ** the rowid of the table entry to which this index entry points. 5698 ** 5699 ** See also: Rowid, MakeRecord. 5700 */ 5701 case OP_DeferredSeek: 5702 case OP_IdxRowid: { /* out2 */ 5703 VdbeCursor *pC; /* The P1 index cursor */ 5704 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */ 5705 i64 rowid; /* Rowid that P1 current points to */ 5706 5707 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5708 pC = p->apCsr[pOp->p1]; 5709 assert( pC!=0 ); 5710 assert( pC->eCurType==CURTYPE_BTREE ); 5711 assert( pC->uc.pCursor!=0 ); 5712 assert( pC->isTable==0 ); 5713 assert( pC->deferredMoveto==0 ); 5714 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid ); 5715 5716 /* The IdxRowid and Seek opcodes are combined because of the commonality 5717 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */ 5718 rc = sqlite3VdbeCursorRestore(pC); 5719 5720 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted 5721 ** out from under the cursor. That will never happens for an IdxRowid 5722 ** or Seek opcode */ 5723 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error; 5724 5725 if( !pC->nullRow ){ 5726 rowid = 0; /* Not needed. Only used to silence a warning. */ 5727 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid); 5728 if( rc!=SQLITE_OK ){ 5729 goto abort_due_to_error; 5730 } 5731 if( pOp->opcode==OP_DeferredSeek ){ 5732 assert( pOp->p3>=0 && pOp->p3<p->nCursor ); 5733 pTabCur = p->apCsr[pOp->p3]; 5734 assert( pTabCur!=0 ); 5735 assert( pTabCur->eCurType==CURTYPE_BTREE ); 5736 assert( pTabCur->uc.pCursor!=0 ); 5737 assert( pTabCur->isTable ); 5738 pTabCur->nullRow = 0; 5739 pTabCur->movetoTarget = rowid; 5740 pTabCur->deferredMoveto = 1; 5741 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 ); 5742 pTabCur->aAltMap = pOp->p4.ai; 5743 pTabCur->pAltCursor = pC; 5744 }else{ 5745 pOut = out2Prerelease(p, pOp); 5746 pOut->u.i = rowid; 5747 } 5748 }else{ 5749 assert( pOp->opcode==OP_IdxRowid ); 5750 sqlite3VdbeMemSetNull(&aMem[pOp->p2]); 5751 } 5752 break; 5753 } 5754 5755 /* Opcode: FinishSeek P1 * * * * 5756 ** 5757 ** If cursor P1 was previously moved via OP_DeferredSeek, complete that 5758 ** seek operation now, without further delay. If the cursor seek has 5759 ** already occurred, this instruction is a no-op. 5760 */ 5761 case OP_FinishSeek: { 5762 VdbeCursor *pC; /* The P1 index cursor */ 5763 5764 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5765 pC = p->apCsr[pOp->p1]; 5766 if( pC->deferredMoveto ){ 5767 rc = sqlite3VdbeFinishMoveto(pC); 5768 if( rc ) goto abort_due_to_error; 5769 } 5770 break; 5771 } 5772 5773 /* Opcode: IdxGE P1 P2 P3 P4 P5 5774 ** Synopsis: key=r[P3@P4] 5775 ** 5776 ** The P4 register values beginning with P3 form an unpacked index 5777 ** key that omits the PRIMARY KEY. Compare this key value against the index 5778 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 5779 ** fields at the end. 5780 ** 5781 ** If the P1 index entry is greater than or equal to the key value 5782 ** then jump to P2. Otherwise fall through to the next instruction. 5783 */ 5784 /* Opcode: IdxGT P1 P2 P3 P4 P5 5785 ** Synopsis: key=r[P3@P4] 5786 ** 5787 ** The P4 register values beginning with P3 form an unpacked index 5788 ** key that omits the PRIMARY KEY. Compare this key value against the index 5789 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 5790 ** fields at the end. 5791 ** 5792 ** If the P1 index entry is greater than the key value 5793 ** then jump to P2. Otherwise fall through to the next instruction. 5794 */ 5795 /* Opcode: IdxLT P1 P2 P3 P4 P5 5796 ** Synopsis: key=r[P3@P4] 5797 ** 5798 ** The P4 register values beginning with P3 form an unpacked index 5799 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against 5800 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or 5801 ** ROWID on the P1 index. 5802 ** 5803 ** If the P1 index entry is less than the key value then jump to P2. 5804 ** Otherwise fall through to the next instruction. 5805 */ 5806 /* Opcode: IdxLE P1 P2 P3 P4 P5 5807 ** Synopsis: key=r[P3@P4] 5808 ** 5809 ** The P4 register values beginning with P3 form an unpacked index 5810 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against 5811 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or 5812 ** ROWID on the P1 index. 5813 ** 5814 ** If the P1 index entry is less than or equal to the key value then jump 5815 ** to P2. Otherwise fall through to the next instruction. 5816 */ 5817 case OP_IdxLE: /* jump */ 5818 case OP_IdxGT: /* jump */ 5819 case OP_IdxLT: /* jump */ 5820 case OP_IdxGE: { /* jump */ 5821 VdbeCursor *pC; 5822 int res; 5823 UnpackedRecord r; 5824 5825 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5826 pC = p->apCsr[pOp->p1]; 5827 assert( pC!=0 ); 5828 assert( pC->isOrdered ); 5829 assert( pC->eCurType==CURTYPE_BTREE ); 5830 assert( pC->uc.pCursor!=0); 5831 assert( pC->deferredMoveto==0 ); 5832 assert( pOp->p5==0 || pOp->p5==1 ); 5833 assert( pOp->p4type==P4_INT32 ); 5834 r.pKeyInfo = pC->pKeyInfo; 5835 r.nField = (u16)pOp->p4.i; 5836 if( pOp->opcode<OP_IdxLT ){ 5837 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT ); 5838 r.default_rc = -1; 5839 }else{ 5840 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT ); 5841 r.default_rc = 0; 5842 } 5843 r.aMem = &aMem[pOp->p3]; 5844 #ifdef SQLITE_DEBUG 5845 { 5846 int i; 5847 for(i=0; i<r.nField; i++){ 5848 assert( memIsValid(&r.aMem[i]) ); 5849 REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]); 5850 } 5851 } 5852 #endif 5853 res = 0; /* Not needed. Only used to silence a warning. */ 5854 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res); 5855 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) ); 5856 if( (pOp->opcode&1)==(OP_IdxLT&1) ){ 5857 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT ); 5858 res = -res; 5859 }else{ 5860 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT ); 5861 res++; 5862 } 5863 VdbeBranchTaken(res>0,2); 5864 if( rc ) goto abort_due_to_error; 5865 if( res>0 ) goto jump_to_p2; 5866 break; 5867 } 5868 5869 /* Opcode: Destroy P1 P2 P3 * * 5870 ** 5871 ** Delete an entire database table or index whose root page in the database 5872 ** file is given by P1. 5873 ** 5874 ** The table being destroyed is in the main database file if P3==0. If 5875 ** P3==1 then the table to be clear is in the auxiliary database file 5876 ** that is used to store tables create using CREATE TEMPORARY TABLE. 5877 ** 5878 ** If AUTOVACUUM is enabled then it is possible that another root page 5879 ** might be moved into the newly deleted root page in order to keep all 5880 ** root pages contiguous at the beginning of the database. The former 5881 ** value of the root page that moved - its value before the move occurred - 5882 ** is stored in register P2. If no page movement was required (because the 5883 ** table being dropped was already the last one in the database) then a 5884 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero 5885 ** is stored in register P2. 5886 ** 5887 ** This opcode throws an error if there are any active reader VMs when 5888 ** it is invoked. This is done to avoid the difficulty associated with 5889 ** updating existing cursors when a root page is moved in an AUTOVACUUM 5890 ** database. This error is thrown even if the database is not an AUTOVACUUM 5891 ** db in order to avoid introducing an incompatibility between autovacuum 5892 ** and non-autovacuum modes. 5893 ** 5894 ** See also: Clear 5895 */ 5896 case OP_Destroy: { /* out2 */ 5897 int iMoved; 5898 int iDb; 5899 5900 sqlite3VdbeIncrWriteCounter(p, 0); 5901 assert( p->readOnly==0 ); 5902 assert( pOp->p1>1 ); 5903 pOut = out2Prerelease(p, pOp); 5904 pOut->flags = MEM_Null; 5905 if( db->nVdbeRead > db->nVDestroy+1 ){ 5906 rc = SQLITE_LOCKED; 5907 p->errorAction = OE_Abort; 5908 goto abort_due_to_error; 5909 }else{ 5910 iDb = pOp->p3; 5911 assert( DbMaskTest(p->btreeMask, iDb) ); 5912 iMoved = 0; /* Not needed. Only to silence a warning. */ 5913 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved); 5914 pOut->flags = MEM_Int; 5915 pOut->u.i = iMoved; 5916 if( rc ) goto abort_due_to_error; 5917 #ifndef SQLITE_OMIT_AUTOVACUUM 5918 if( iMoved!=0 ){ 5919 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1); 5920 /* All OP_Destroy operations occur on the same btree */ 5921 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 ); 5922 resetSchemaOnFault = iDb+1; 5923 } 5924 #endif 5925 } 5926 break; 5927 } 5928 5929 /* Opcode: Clear P1 P2 P3 5930 ** 5931 ** Delete all contents of the database table or index whose root page 5932 ** in the database file is given by P1. But, unlike Destroy, do not 5933 ** remove the table or index from the database file. 5934 ** 5935 ** The table being clear is in the main database file if P2==0. If 5936 ** P2==1 then the table to be clear is in the auxiliary database file 5937 ** that is used to store tables create using CREATE TEMPORARY TABLE. 5938 ** 5939 ** If the P3 value is non-zero, then the table referred to must be an 5940 ** intkey table (an SQL table, not an index). In this case the row change 5941 ** count is incremented by the number of rows in the table being cleared. 5942 ** If P3 is greater than zero, then the value stored in register P3 is 5943 ** also incremented by the number of rows in the table being cleared. 5944 ** 5945 ** See also: Destroy 5946 */ 5947 case OP_Clear: { 5948 int nChange; 5949 5950 sqlite3VdbeIncrWriteCounter(p, 0); 5951 nChange = 0; 5952 assert( p->readOnly==0 ); 5953 assert( DbMaskTest(p->btreeMask, pOp->p2) ); 5954 rc = sqlite3BtreeClearTable( 5955 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0) 5956 ); 5957 if( pOp->p3 ){ 5958 p->nChange += nChange; 5959 if( pOp->p3>0 ){ 5960 assert( memIsValid(&aMem[pOp->p3]) ); 5961 memAboutToChange(p, &aMem[pOp->p3]); 5962 aMem[pOp->p3].u.i += nChange; 5963 } 5964 } 5965 if( rc ) goto abort_due_to_error; 5966 break; 5967 } 5968 5969 /* Opcode: ResetSorter P1 * * * * 5970 ** 5971 ** Delete all contents from the ephemeral table or sorter 5972 ** that is open on cursor P1. 5973 ** 5974 ** This opcode only works for cursors used for sorting and 5975 ** opened with OP_OpenEphemeral or OP_SorterOpen. 5976 */ 5977 case OP_ResetSorter: { 5978 VdbeCursor *pC; 5979 5980 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5981 pC = p->apCsr[pOp->p1]; 5982 assert( pC!=0 ); 5983 if( isSorter(pC) ){ 5984 sqlite3VdbeSorterReset(db, pC->uc.pSorter); 5985 }else{ 5986 assert( pC->eCurType==CURTYPE_BTREE ); 5987 assert( pC->isEphemeral ); 5988 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor); 5989 if( rc ) goto abort_due_to_error; 5990 } 5991 break; 5992 } 5993 5994 /* Opcode: CreateBtree P1 P2 P3 * * 5995 ** Synopsis: r[P2]=root iDb=P1 flags=P3 5996 ** 5997 ** Allocate a new b-tree in the main database file if P1==0 or in the 5998 ** TEMP database file if P1==1 or in an attached database if 5999 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table 6000 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table. 6001 ** The root page number of the new b-tree is stored in register P2. 6002 */ 6003 case OP_CreateBtree: { /* out2 */ 6004 int pgno; 6005 Db *pDb; 6006 6007 sqlite3VdbeIncrWriteCounter(p, 0); 6008 pOut = out2Prerelease(p, pOp); 6009 pgno = 0; 6010 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY ); 6011 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 6012 assert( DbMaskTest(p->btreeMask, pOp->p1) ); 6013 assert( p->readOnly==0 ); 6014 pDb = &db->aDb[pOp->p1]; 6015 assert( pDb->pBt!=0 ); 6016 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3); 6017 if( rc ) goto abort_due_to_error; 6018 pOut->u.i = pgno; 6019 break; 6020 } 6021 6022 /* Opcode: SqlExec * * * P4 * 6023 ** 6024 ** Run the SQL statement or statements specified in the P4 string. 6025 */ 6026 case OP_SqlExec: { 6027 sqlite3VdbeIncrWriteCounter(p, 0); 6028 db->nSqlExec++; 6029 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0); 6030 db->nSqlExec--; 6031 if( rc ) goto abort_due_to_error; 6032 break; 6033 } 6034 6035 /* Opcode: ParseSchema P1 * * P4 * 6036 ** 6037 ** Read and parse all entries from the SQLITE_MASTER table of database P1 6038 ** that match the WHERE clause P4. If P4 is a NULL pointer, then the 6039 ** entire schema for P1 is reparsed. 6040 ** 6041 ** This opcode invokes the parser to create a new virtual machine, 6042 ** then runs the new virtual machine. It is thus a re-entrant opcode. 6043 */ 6044 case OP_ParseSchema: { 6045 int iDb; 6046 const char *zMaster; 6047 char *zSql; 6048 InitData initData; 6049 6050 /* Any prepared statement that invokes this opcode will hold mutexes 6051 ** on every btree. This is a prerequisite for invoking 6052 ** sqlite3InitCallback(). 6053 */ 6054 #ifdef SQLITE_DEBUG 6055 for(iDb=0; iDb<db->nDb; iDb++){ 6056 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); 6057 } 6058 #endif 6059 6060 iDb = pOp->p1; 6061 assert( iDb>=0 && iDb<db->nDb ); 6062 assert( DbHasProperty(db, iDb, DB_SchemaLoaded) ); 6063 6064 #ifndef SQLITE_OMIT_ALTERTABLE 6065 if( pOp->p4.z==0 ){ 6066 sqlite3SchemaClear(db->aDb[iDb].pSchema); 6067 db->mDbFlags &= ~DBFLAG_SchemaKnownOk; 6068 rc = sqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable); 6069 db->mDbFlags |= DBFLAG_SchemaChange; 6070 p->expired = 0; 6071 }else 6072 #endif 6073 { 6074 zMaster = MASTER_NAME; 6075 initData.db = db; 6076 initData.iDb = iDb; 6077 initData.pzErrMsg = &p->zErrMsg; 6078 initData.mInitFlags = 0; 6079 zSql = sqlite3MPrintf(db, 6080 "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid", 6081 db->aDb[iDb].zDbSName, zMaster, pOp->p4.z); 6082 if( zSql==0 ){ 6083 rc = SQLITE_NOMEM_BKPT; 6084 }else{ 6085 assert( db->init.busy==0 ); 6086 db->init.busy = 1; 6087 initData.rc = SQLITE_OK; 6088 initData.nInitRow = 0; 6089 assert( !db->mallocFailed ); 6090 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); 6091 if( rc==SQLITE_OK ) rc = initData.rc; 6092 if( rc==SQLITE_OK && initData.nInitRow==0 ){ 6093 /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse 6094 ** at least one SQL statement. Any less than that indicates that 6095 ** the sqlite_master table is corrupt. */ 6096 rc = SQLITE_CORRUPT_BKPT; 6097 } 6098 sqlite3DbFreeNN(db, zSql); 6099 db->init.busy = 0; 6100 } 6101 } 6102 if( rc ){ 6103 sqlite3ResetAllSchemasOfConnection(db); 6104 if( rc==SQLITE_NOMEM ){ 6105 goto no_mem; 6106 } 6107 goto abort_due_to_error; 6108 } 6109 break; 6110 } 6111 6112 #if !defined(SQLITE_OMIT_ANALYZE) 6113 /* Opcode: LoadAnalysis P1 * * * * 6114 ** 6115 ** Read the sqlite_stat1 table for database P1 and load the content 6116 ** of that table into the internal index hash table. This will cause 6117 ** the analysis to be used when preparing all subsequent queries. 6118 */ 6119 case OP_LoadAnalysis: { 6120 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 6121 rc = sqlite3AnalysisLoad(db, pOp->p1); 6122 if( rc ) goto abort_due_to_error; 6123 break; 6124 } 6125 #endif /* !defined(SQLITE_OMIT_ANALYZE) */ 6126 6127 /* Opcode: DropTable P1 * * P4 * 6128 ** 6129 ** Remove the internal (in-memory) data structures that describe 6130 ** the table named P4 in database P1. This is called after a table 6131 ** is dropped from disk (using the Destroy opcode) in order to keep 6132 ** the internal representation of the 6133 ** schema consistent with what is on disk. 6134 */ 6135 case OP_DropTable: { 6136 sqlite3VdbeIncrWriteCounter(p, 0); 6137 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z); 6138 break; 6139 } 6140 6141 /* Opcode: DropIndex P1 * * P4 * 6142 ** 6143 ** Remove the internal (in-memory) data structures that describe 6144 ** the index named P4 in database P1. This is called after an index 6145 ** is dropped from disk (using the Destroy opcode) 6146 ** in order to keep the internal representation of the 6147 ** schema consistent with what is on disk. 6148 */ 6149 case OP_DropIndex: { 6150 sqlite3VdbeIncrWriteCounter(p, 0); 6151 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z); 6152 break; 6153 } 6154 6155 /* Opcode: DropTrigger P1 * * P4 * 6156 ** 6157 ** Remove the internal (in-memory) data structures that describe 6158 ** the trigger named P4 in database P1. This is called after a trigger 6159 ** is dropped from disk (using the Destroy opcode) in order to keep 6160 ** the internal representation of the 6161 ** schema consistent with what is on disk. 6162 */ 6163 case OP_DropTrigger: { 6164 sqlite3VdbeIncrWriteCounter(p, 0); 6165 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z); 6166 break; 6167 } 6168 6169 6170 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 6171 /* Opcode: IntegrityCk P1 P2 P3 P4 P5 6172 ** 6173 ** Do an analysis of the currently open database. Store in 6174 ** register P1 the text of an error message describing any problems. 6175 ** If no problems are found, store a NULL in register P1. 6176 ** 6177 ** The register P3 contains one less than the maximum number of allowed errors. 6178 ** At most reg(P3) errors will be reported. 6179 ** In other words, the analysis stops as soon as reg(P1) errors are 6180 ** seen. Reg(P1) is updated with the number of errors remaining. 6181 ** 6182 ** The root page numbers of all tables in the database are integers 6183 ** stored in P4_INTARRAY argument. 6184 ** 6185 ** If P5 is not zero, the check is done on the auxiliary database 6186 ** file, not the main database file. 6187 ** 6188 ** This opcode is used to implement the integrity_check pragma. 6189 */ 6190 case OP_IntegrityCk: { 6191 int nRoot; /* Number of tables to check. (Number of root pages.) */ 6192 int *aRoot; /* Array of rootpage numbers for tables to be checked */ 6193 int nErr; /* Number of errors reported */ 6194 char *z; /* Text of the error report */ 6195 Mem *pnErr; /* Register keeping track of errors remaining */ 6196 6197 assert( p->bIsReader ); 6198 nRoot = pOp->p2; 6199 aRoot = pOp->p4.ai; 6200 assert( nRoot>0 ); 6201 assert( aRoot[0]==nRoot ); 6202 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); 6203 pnErr = &aMem[pOp->p3]; 6204 assert( (pnErr->flags & MEM_Int)!=0 ); 6205 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 ); 6206 pIn1 = &aMem[pOp->p1]; 6207 assert( pOp->p5<db->nDb ); 6208 assert( DbMaskTest(p->btreeMask, pOp->p5) ); 6209 z = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot, 6210 (int)pnErr->u.i+1, &nErr); 6211 sqlite3VdbeMemSetNull(pIn1); 6212 if( nErr==0 ){ 6213 assert( z==0 ); 6214 }else if( z==0 ){ 6215 goto no_mem; 6216 }else{ 6217 pnErr->u.i -= nErr-1; 6218 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free); 6219 } 6220 UPDATE_MAX_BLOBSIZE(pIn1); 6221 sqlite3VdbeChangeEncoding(pIn1, encoding); 6222 goto check_for_interrupt; 6223 } 6224 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 6225 6226 /* Opcode: RowSetAdd P1 P2 * * * 6227 ** Synopsis: rowset(P1)=r[P2] 6228 ** 6229 ** Insert the integer value held by register P2 into a RowSet object 6230 ** held in register P1. 6231 ** 6232 ** An assertion fails if P2 is not an integer. 6233 */ 6234 case OP_RowSetAdd: { /* in1, in2 */ 6235 pIn1 = &aMem[pOp->p1]; 6236 pIn2 = &aMem[pOp->p2]; 6237 assert( (pIn2->flags & MEM_Int)!=0 ); 6238 if( (pIn1->flags & MEM_Blob)==0 ){ 6239 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem; 6240 } 6241 assert( sqlite3VdbeMemIsRowSet(pIn1) ); 6242 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i); 6243 break; 6244 } 6245 6246 /* Opcode: RowSetRead P1 P2 P3 * * 6247 ** Synopsis: r[P3]=rowset(P1) 6248 ** 6249 ** Extract the smallest value from the RowSet object in P1 6250 ** and put that value into register P3. 6251 ** Or, if RowSet object P1 is initially empty, leave P3 6252 ** unchanged and jump to instruction P2. 6253 */ 6254 case OP_RowSetRead: { /* jump, in1, out3 */ 6255 i64 val; 6256 6257 pIn1 = &aMem[pOp->p1]; 6258 assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) ); 6259 if( (pIn1->flags & MEM_Blob)==0 6260 || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0 6261 ){ 6262 /* The boolean index is empty */ 6263 sqlite3VdbeMemSetNull(pIn1); 6264 VdbeBranchTaken(1,2); 6265 goto jump_to_p2_and_check_for_interrupt; 6266 }else{ 6267 /* A value was pulled from the index */ 6268 VdbeBranchTaken(0,2); 6269 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val); 6270 } 6271 goto check_for_interrupt; 6272 } 6273 6274 /* Opcode: RowSetTest P1 P2 P3 P4 6275 ** Synopsis: if r[P3] in rowset(P1) goto P2 6276 ** 6277 ** Register P3 is assumed to hold a 64-bit integer value. If register P1 6278 ** contains a RowSet object and that RowSet object contains 6279 ** the value held in P3, jump to register P2. Otherwise, insert the 6280 ** integer in P3 into the RowSet and continue on to the 6281 ** next opcode. 6282 ** 6283 ** The RowSet object is optimized for the case where sets of integers 6284 ** are inserted in distinct phases, which each set contains no duplicates. 6285 ** Each set is identified by a unique P4 value. The first set 6286 ** must have P4==0, the final set must have P4==-1, and for all other sets 6287 ** must have P4>0. 6288 ** 6289 ** This allows optimizations: (a) when P4==0 there is no need to test 6290 ** the RowSet object for P3, as it is guaranteed not to contain it, 6291 ** (b) when P4==-1 there is no need to insert the value, as it will 6292 ** never be tested for, and (c) when a value that is part of set X is 6293 ** inserted, there is no need to search to see if the same value was 6294 ** previously inserted as part of set X (only if it was previously 6295 ** inserted as part of some other set). 6296 */ 6297 case OP_RowSetTest: { /* jump, in1, in3 */ 6298 int iSet; 6299 int exists; 6300 6301 pIn1 = &aMem[pOp->p1]; 6302 pIn3 = &aMem[pOp->p3]; 6303 iSet = pOp->p4.i; 6304 assert( pIn3->flags&MEM_Int ); 6305 6306 /* If there is anything other than a rowset object in memory cell P1, 6307 ** delete it now and initialize P1 with an empty rowset 6308 */ 6309 if( (pIn1->flags & MEM_Blob)==0 ){ 6310 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem; 6311 } 6312 assert( sqlite3VdbeMemIsRowSet(pIn1) ); 6313 assert( pOp->p4type==P4_INT32 ); 6314 assert( iSet==-1 || iSet>=0 ); 6315 if( iSet ){ 6316 exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i); 6317 VdbeBranchTaken(exists!=0,2); 6318 if( exists ) goto jump_to_p2; 6319 } 6320 if( iSet>=0 ){ 6321 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i); 6322 } 6323 break; 6324 } 6325 6326 6327 #ifndef SQLITE_OMIT_TRIGGER 6328 6329 /* Opcode: Program P1 P2 P3 P4 P5 6330 ** 6331 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 6332 ** 6333 ** P1 contains the address of the memory cell that contains the first memory 6334 ** cell in an array of values used as arguments to the sub-program. P2 6335 ** contains the address to jump to if the sub-program throws an IGNORE 6336 ** exception using the RAISE() function. Register P3 contains the address 6337 ** of a memory cell in this (the parent) VM that is used to allocate the 6338 ** memory required by the sub-vdbe at runtime. 6339 ** 6340 ** P4 is a pointer to the VM containing the trigger program. 6341 ** 6342 ** If P5 is non-zero, then recursive program invocation is enabled. 6343 */ 6344 case OP_Program: { /* jump */ 6345 int nMem; /* Number of memory registers for sub-program */ 6346 int nByte; /* Bytes of runtime space required for sub-program */ 6347 Mem *pRt; /* Register to allocate runtime space */ 6348 Mem *pMem; /* Used to iterate through memory cells */ 6349 Mem *pEnd; /* Last memory cell in new array */ 6350 VdbeFrame *pFrame; /* New vdbe frame to execute in */ 6351 SubProgram *pProgram; /* Sub-program to execute */ 6352 void *t; /* Token identifying trigger */ 6353 6354 pProgram = pOp->p4.pProgram; 6355 pRt = &aMem[pOp->p3]; 6356 assert( pProgram->nOp>0 ); 6357 6358 /* If the p5 flag is clear, then recursive invocation of triggers is 6359 ** disabled for backwards compatibility (p5 is set if this sub-program 6360 ** is really a trigger, not a foreign key action, and the flag set 6361 ** and cleared by the "PRAGMA recursive_triggers" command is clear). 6362 ** 6363 ** It is recursive invocation of triggers, at the SQL level, that is 6364 ** disabled. In some cases a single trigger may generate more than one 6365 ** SubProgram (if the trigger may be executed with more than one different 6366 ** ON CONFLICT algorithm). SubProgram structures associated with a 6367 ** single trigger all have the same value for the SubProgram.token 6368 ** variable. */ 6369 if( pOp->p5 ){ 6370 t = pProgram->token; 6371 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent); 6372 if( pFrame ) break; 6373 } 6374 6375 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){ 6376 rc = SQLITE_ERROR; 6377 sqlite3VdbeError(p, "too many levels of trigger recursion"); 6378 goto abort_due_to_error; 6379 } 6380 6381 /* Register pRt is used to store the memory required to save the state 6382 ** of the current program, and the memory required at runtime to execute 6383 ** the trigger program. If this trigger has been fired before, then pRt 6384 ** is already allocated. Otherwise, it must be initialized. */ 6385 if( (pRt->flags&MEM_Blob)==0 ){ 6386 /* SubProgram.nMem is set to the number of memory cells used by the 6387 ** program stored in SubProgram.aOp. As well as these, one memory 6388 ** cell is required for each cursor used by the program. Set local 6389 ** variable nMem (and later, VdbeFrame.nChildMem) to this value. 6390 */ 6391 nMem = pProgram->nMem + pProgram->nCsr; 6392 assert( nMem>0 ); 6393 if( pProgram->nCsr==0 ) nMem++; 6394 nByte = ROUND8(sizeof(VdbeFrame)) 6395 + nMem * sizeof(Mem) 6396 + pProgram->nCsr * sizeof(VdbeCursor*) 6397 + (pProgram->nOp + 7)/8; 6398 pFrame = sqlite3DbMallocZero(db, nByte); 6399 if( !pFrame ){ 6400 goto no_mem; 6401 } 6402 sqlite3VdbeMemRelease(pRt); 6403 pRt->flags = MEM_Blob|MEM_Dyn; 6404 pRt->z = (char*)pFrame; 6405 pRt->n = nByte; 6406 pRt->xDel = sqlite3VdbeFrameMemDel; 6407 6408 pFrame->v = p; 6409 pFrame->nChildMem = nMem; 6410 pFrame->nChildCsr = pProgram->nCsr; 6411 pFrame->pc = (int)(pOp - aOp); 6412 pFrame->aMem = p->aMem; 6413 pFrame->nMem = p->nMem; 6414 pFrame->apCsr = p->apCsr; 6415 pFrame->nCursor = p->nCursor; 6416 pFrame->aOp = p->aOp; 6417 pFrame->nOp = p->nOp; 6418 pFrame->token = pProgram->token; 6419 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 6420 pFrame->anExec = p->anExec; 6421 #endif 6422 #ifdef SQLITE_DEBUG 6423 pFrame->iFrameMagic = SQLITE_FRAME_MAGIC; 6424 #endif 6425 6426 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem]; 6427 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){ 6428 pMem->flags = MEM_Undefined; 6429 pMem->db = db; 6430 } 6431 }else{ 6432 pFrame = (VdbeFrame*)pRt->z; 6433 assert( pRt->xDel==sqlite3VdbeFrameMemDel ); 6434 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem 6435 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) ); 6436 assert( pProgram->nCsr==pFrame->nChildCsr ); 6437 assert( (int)(pOp - aOp)==pFrame->pc ); 6438 } 6439 6440 p->nFrame++; 6441 pFrame->pParent = p->pFrame; 6442 pFrame->lastRowid = db->lastRowid; 6443 pFrame->nChange = p->nChange; 6444 pFrame->nDbChange = p->db->nChange; 6445 assert( pFrame->pAuxData==0 ); 6446 pFrame->pAuxData = p->pAuxData; 6447 p->pAuxData = 0; 6448 p->nChange = 0; 6449 p->pFrame = pFrame; 6450 p->aMem = aMem = VdbeFrameMem(pFrame); 6451 p->nMem = pFrame->nChildMem; 6452 p->nCursor = (u16)pFrame->nChildCsr; 6453 p->apCsr = (VdbeCursor **)&aMem[p->nMem]; 6454 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr]; 6455 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8); 6456 p->aOp = aOp = pProgram->aOp; 6457 p->nOp = pProgram->nOp; 6458 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 6459 p->anExec = 0; 6460 #endif 6461 #ifdef SQLITE_DEBUG 6462 /* Verify that second and subsequent executions of the same trigger do not 6463 ** try to reuse register values from the first use. */ 6464 { 6465 int i; 6466 for(i=0; i<p->nMem; i++){ 6467 aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */ 6468 aMem[i].flags |= MEM_Undefined; /* Cause a fault if this reg is reused */ 6469 } 6470 } 6471 #endif 6472 pOp = &aOp[-1]; 6473 goto check_for_interrupt; 6474 } 6475 6476 /* Opcode: Param P1 P2 * * * 6477 ** 6478 ** This opcode is only ever present in sub-programs called via the 6479 ** OP_Program instruction. Copy a value currently stored in a memory 6480 ** cell of the calling (parent) frame to cell P2 in the current frames 6481 ** address space. This is used by trigger programs to access the new.* 6482 ** and old.* values. 6483 ** 6484 ** The address of the cell in the parent frame is determined by adding 6485 ** the value of the P1 argument to the value of the P1 argument to the 6486 ** calling OP_Program instruction. 6487 */ 6488 case OP_Param: { /* out2 */ 6489 VdbeFrame *pFrame; 6490 Mem *pIn; 6491 pOut = out2Prerelease(p, pOp); 6492 pFrame = p->pFrame; 6493 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1]; 6494 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem); 6495 break; 6496 } 6497 6498 #endif /* #ifndef SQLITE_OMIT_TRIGGER */ 6499 6500 #ifndef SQLITE_OMIT_FOREIGN_KEY 6501 /* Opcode: FkCounter P1 P2 * * * 6502 ** Synopsis: fkctr[P1]+=P2 6503 ** 6504 ** Increment a "constraint counter" by P2 (P2 may be negative or positive). 6505 ** If P1 is non-zero, the database constraint counter is incremented 6506 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 6507 ** statement counter is incremented (immediate foreign key constraints). 6508 */ 6509 case OP_FkCounter: { 6510 if( db->flags & SQLITE_DeferFKs ){ 6511 db->nDeferredImmCons += pOp->p2; 6512 }else if( pOp->p1 ){ 6513 db->nDeferredCons += pOp->p2; 6514 }else{ 6515 p->nFkConstraint += pOp->p2; 6516 } 6517 break; 6518 } 6519 6520 /* Opcode: FkIfZero P1 P2 * * * 6521 ** Synopsis: if fkctr[P1]==0 goto P2 6522 ** 6523 ** This opcode tests if a foreign key constraint-counter is currently zero. 6524 ** If so, jump to instruction P2. Otherwise, fall through to the next 6525 ** instruction. 6526 ** 6527 ** If P1 is non-zero, then the jump is taken if the database constraint-counter 6528 ** is zero (the one that counts deferred constraint violations). If P1 is 6529 ** zero, the jump is taken if the statement constraint-counter is zero 6530 ** (immediate foreign key constraint violations). 6531 */ 6532 case OP_FkIfZero: { /* jump */ 6533 if( pOp->p1 ){ 6534 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2); 6535 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2; 6536 }else{ 6537 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2); 6538 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2; 6539 } 6540 break; 6541 } 6542 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */ 6543 6544 #ifndef SQLITE_OMIT_AUTOINCREMENT 6545 /* Opcode: MemMax P1 P2 * * * 6546 ** Synopsis: r[P1]=max(r[P1],r[P2]) 6547 ** 6548 ** P1 is a register in the root frame of this VM (the root frame is 6549 ** different from the current frame if this instruction is being executed 6550 ** within a sub-program). Set the value of register P1 to the maximum of 6551 ** its current value and the value in register P2. 6552 ** 6553 ** This instruction throws an error if the memory cell is not initially 6554 ** an integer. 6555 */ 6556 case OP_MemMax: { /* in2 */ 6557 VdbeFrame *pFrame; 6558 if( p->pFrame ){ 6559 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); 6560 pIn1 = &pFrame->aMem[pOp->p1]; 6561 }else{ 6562 pIn1 = &aMem[pOp->p1]; 6563 } 6564 assert( memIsValid(pIn1) ); 6565 sqlite3VdbeMemIntegerify(pIn1); 6566 pIn2 = &aMem[pOp->p2]; 6567 sqlite3VdbeMemIntegerify(pIn2); 6568 if( pIn1->u.i<pIn2->u.i){ 6569 pIn1->u.i = pIn2->u.i; 6570 } 6571 break; 6572 } 6573 #endif /* SQLITE_OMIT_AUTOINCREMENT */ 6574 6575 /* Opcode: IfPos P1 P2 P3 * * 6576 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 6577 ** 6578 ** Register P1 must contain an integer. 6579 ** If the value of register P1 is 1 or greater, subtract P3 from the 6580 ** value in P1 and jump to P2. 6581 ** 6582 ** If the initial value of register P1 is less than 1, then the 6583 ** value is unchanged and control passes through to the next instruction. 6584 */ 6585 case OP_IfPos: { /* jump, in1 */ 6586 pIn1 = &aMem[pOp->p1]; 6587 assert( pIn1->flags&MEM_Int ); 6588 VdbeBranchTaken( pIn1->u.i>0, 2); 6589 if( pIn1->u.i>0 ){ 6590 pIn1->u.i -= pOp->p3; 6591 goto jump_to_p2; 6592 } 6593 break; 6594 } 6595 6596 /* Opcode: OffsetLimit P1 P2 P3 * * 6597 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) 6598 ** 6599 ** This opcode performs a commonly used computation associated with 6600 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3] 6601 ** holds the offset counter. The opcode computes the combined value 6602 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2] 6603 ** value computed is the total number of rows that will need to be 6604 ** visited in order to complete the query. 6605 ** 6606 ** If r[P3] is zero or negative, that means there is no OFFSET 6607 ** and r[P2] is set to be the value of the LIMIT, r[P1]. 6608 ** 6609 ** if r[P1] is zero or negative, that means there is no LIMIT 6610 ** and r[P2] is set to -1. 6611 ** 6612 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3]. 6613 */ 6614 case OP_OffsetLimit: { /* in1, out2, in3 */ 6615 i64 x; 6616 pIn1 = &aMem[pOp->p1]; 6617 pIn3 = &aMem[pOp->p3]; 6618 pOut = out2Prerelease(p, pOp); 6619 assert( pIn1->flags & MEM_Int ); 6620 assert( pIn3->flags & MEM_Int ); 6621 x = pIn1->u.i; 6622 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){ 6623 /* If the LIMIT is less than or equal to zero, loop forever. This 6624 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then 6625 ** also loop forever. This is undocumented. In fact, one could argue 6626 ** that the loop should terminate. But assuming 1 billion iterations 6627 ** per second (far exceeding the capabilities of any current hardware) 6628 ** it would take nearly 300 years to actually reach the limit. So 6629 ** looping forever is a reasonable approximation. */ 6630 pOut->u.i = -1; 6631 }else{ 6632 pOut->u.i = x; 6633 } 6634 break; 6635 } 6636 6637 /* Opcode: IfNotZero P1 P2 * * * 6638 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2 6639 ** 6640 ** Register P1 must contain an integer. If the content of register P1 is 6641 ** initially greater than zero, then decrement the value in register P1. 6642 ** If it is non-zero (negative or positive) and then also jump to P2. 6643 ** If register P1 is initially zero, leave it unchanged and fall through. 6644 */ 6645 case OP_IfNotZero: { /* jump, in1 */ 6646 pIn1 = &aMem[pOp->p1]; 6647 assert( pIn1->flags&MEM_Int ); 6648 VdbeBranchTaken(pIn1->u.i<0, 2); 6649 if( pIn1->u.i ){ 6650 if( pIn1->u.i>0 ) pIn1->u.i--; 6651 goto jump_to_p2; 6652 } 6653 break; 6654 } 6655 6656 /* Opcode: DecrJumpZero P1 P2 * * * 6657 ** Synopsis: if (--r[P1])==0 goto P2 6658 ** 6659 ** Register P1 must hold an integer. Decrement the value in P1 6660 ** and jump to P2 if the new value is exactly zero. 6661 */ 6662 case OP_DecrJumpZero: { /* jump, in1 */ 6663 pIn1 = &aMem[pOp->p1]; 6664 assert( pIn1->flags&MEM_Int ); 6665 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--; 6666 VdbeBranchTaken(pIn1->u.i==0, 2); 6667 if( pIn1->u.i==0 ) goto jump_to_p2; 6668 break; 6669 } 6670 6671 6672 /* Opcode: AggStep * P2 P3 P4 P5 6673 ** Synopsis: accum=r[P3] step(r[P2@P5]) 6674 ** 6675 ** Execute the xStep function for an aggregate. 6676 ** The function has P5 arguments. P4 is a pointer to the 6677 ** FuncDef structure that specifies the function. Register P3 is the 6678 ** accumulator. 6679 ** 6680 ** The P5 arguments are taken from register P2 and its 6681 ** successors. 6682 */ 6683 /* Opcode: AggInverse * P2 P3 P4 P5 6684 ** Synopsis: accum=r[P3] inverse(r[P2@P5]) 6685 ** 6686 ** Execute the xInverse function for an aggregate. 6687 ** The function has P5 arguments. P4 is a pointer to the 6688 ** FuncDef structure that specifies the function. Register P3 is the 6689 ** accumulator. 6690 ** 6691 ** The P5 arguments are taken from register P2 and its 6692 ** successors. 6693 */ 6694 /* Opcode: AggStep1 P1 P2 P3 P4 P5 6695 ** Synopsis: accum=r[P3] step(r[P2@P5]) 6696 ** 6697 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an 6698 ** aggregate. The function has P5 arguments. P4 is a pointer to the 6699 ** FuncDef structure that specifies the function. Register P3 is the 6700 ** accumulator. 6701 ** 6702 ** The P5 arguments are taken from register P2 and its 6703 ** successors. 6704 ** 6705 ** This opcode is initially coded as OP_AggStep0. On first evaluation, 6706 ** the FuncDef stored in P4 is converted into an sqlite3_context and 6707 ** the opcode is changed. In this way, the initialization of the 6708 ** sqlite3_context only happens once, instead of on each call to the 6709 ** step function. 6710 */ 6711 case OP_AggInverse: 6712 case OP_AggStep: { 6713 int n; 6714 sqlite3_context *pCtx; 6715 6716 assert( pOp->p4type==P4_FUNCDEF ); 6717 n = pOp->p5; 6718 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); 6719 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) ); 6720 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n ); 6721 pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) + 6722 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*))); 6723 if( pCtx==0 ) goto no_mem; 6724 pCtx->pMem = 0; 6725 pCtx->pOut = (Mem*)&(pCtx->argv[n]); 6726 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null); 6727 pCtx->pFunc = pOp->p4.pFunc; 6728 pCtx->iOp = (int)(pOp - aOp); 6729 pCtx->pVdbe = p; 6730 pCtx->skipFlag = 0; 6731 pCtx->isError = 0; 6732 pCtx->argc = n; 6733 pOp->p4type = P4_FUNCCTX; 6734 pOp->p4.pCtx = pCtx; 6735 6736 /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */ 6737 assert( pOp->p1==(pOp->opcode==OP_AggInverse) ); 6738 6739 pOp->opcode = OP_AggStep1; 6740 /* Fall through into OP_AggStep */ 6741 } 6742 case OP_AggStep1: { 6743 int i; 6744 sqlite3_context *pCtx; 6745 Mem *pMem; 6746 6747 assert( pOp->p4type==P4_FUNCCTX ); 6748 pCtx = pOp->p4.pCtx; 6749 pMem = &aMem[pOp->p3]; 6750 6751 #ifdef SQLITE_DEBUG 6752 if( pOp->p1 ){ 6753 /* This is an OP_AggInverse call. Verify that xStep has always 6754 ** been called at least once prior to any xInverse call. */ 6755 assert( pMem->uTemp==0x1122e0e3 ); 6756 }else{ 6757 /* This is an OP_AggStep call. Mark it as such. */ 6758 pMem->uTemp = 0x1122e0e3; 6759 } 6760 #endif 6761 6762 /* If this function is inside of a trigger, the register array in aMem[] 6763 ** might change from one evaluation to the next. The next block of code 6764 ** checks to see if the register array has changed, and if so it 6765 ** reinitializes the relavant parts of the sqlite3_context object */ 6766 if( pCtx->pMem != pMem ){ 6767 pCtx->pMem = pMem; 6768 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; 6769 } 6770 6771 #ifdef SQLITE_DEBUG 6772 for(i=0; i<pCtx->argc; i++){ 6773 assert( memIsValid(pCtx->argv[i]) ); 6774 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]); 6775 } 6776 #endif 6777 6778 pMem->n++; 6779 assert( pCtx->pOut->flags==MEM_Null ); 6780 assert( pCtx->isError==0 ); 6781 assert( pCtx->skipFlag==0 ); 6782 #ifndef SQLITE_OMIT_WINDOWFUNC 6783 if( pOp->p1 ){ 6784 (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv); 6785 }else 6786 #endif 6787 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */ 6788 6789 if( pCtx->isError ){ 6790 if( pCtx->isError>0 ){ 6791 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut)); 6792 rc = pCtx->isError; 6793 } 6794 if( pCtx->skipFlag ){ 6795 assert( pOp[-1].opcode==OP_CollSeq ); 6796 i = pOp[-1].p1; 6797 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1); 6798 pCtx->skipFlag = 0; 6799 } 6800 sqlite3VdbeMemRelease(pCtx->pOut); 6801 pCtx->pOut->flags = MEM_Null; 6802 pCtx->isError = 0; 6803 if( rc ) goto abort_due_to_error; 6804 } 6805 assert( pCtx->pOut->flags==MEM_Null ); 6806 assert( pCtx->skipFlag==0 ); 6807 break; 6808 } 6809 6810 /* Opcode: AggFinal P1 P2 * P4 * 6811 ** Synopsis: accum=r[P1] N=P2 6812 ** 6813 ** P1 is the memory location that is the accumulator for an aggregate 6814 ** or window function. Execute the finalizer function 6815 ** for an aggregate and store the result in P1. 6816 ** 6817 ** P2 is the number of arguments that the step function takes and 6818 ** P4 is a pointer to the FuncDef for this function. The P2 6819 ** argument is not used by this opcode. It is only there to disambiguate 6820 ** functions that can take varying numbers of arguments. The 6821 ** P4 argument is only needed for the case where 6822 ** the step function was not previously called. 6823 */ 6824 /* Opcode: AggValue * P2 P3 P4 * 6825 ** Synopsis: r[P3]=value N=P2 6826 ** 6827 ** Invoke the xValue() function and store the result in register P3. 6828 ** 6829 ** P2 is the number of arguments that the step function takes and 6830 ** P4 is a pointer to the FuncDef for this function. The P2 6831 ** argument is not used by this opcode. It is only there to disambiguate 6832 ** functions that can take varying numbers of arguments. The 6833 ** P4 argument is only needed for the case where 6834 ** the step function was not previously called. 6835 */ 6836 case OP_AggValue: 6837 case OP_AggFinal: { 6838 Mem *pMem; 6839 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); 6840 assert( pOp->p3==0 || pOp->opcode==OP_AggValue ); 6841 pMem = &aMem[pOp->p1]; 6842 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 ); 6843 #ifndef SQLITE_OMIT_WINDOWFUNC 6844 if( pOp->p3 ){ 6845 memAboutToChange(p, &aMem[pOp->p3]); 6846 rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc); 6847 pMem = &aMem[pOp->p3]; 6848 }else 6849 #endif 6850 { 6851 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc); 6852 } 6853 6854 if( rc ){ 6855 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem)); 6856 goto abort_due_to_error; 6857 } 6858 sqlite3VdbeChangeEncoding(pMem, encoding); 6859 UPDATE_MAX_BLOBSIZE(pMem); 6860 if( sqlite3VdbeMemTooBig(pMem) ){ 6861 goto too_big; 6862 } 6863 break; 6864 } 6865 6866 #ifndef SQLITE_OMIT_WAL 6867 /* Opcode: Checkpoint P1 P2 P3 * * 6868 ** 6869 ** Checkpoint database P1. This is a no-op if P1 is not currently in 6870 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL, 6871 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns 6872 ** SQLITE_BUSY or not, respectively. Write the number of pages in the 6873 ** WAL after the checkpoint into mem[P3+1] and the number of pages 6874 ** in the WAL that have been checkpointed after the checkpoint 6875 ** completes into mem[P3+2]. However on an error, mem[P3+1] and 6876 ** mem[P3+2] are initialized to -1. 6877 */ 6878 case OP_Checkpoint: { 6879 int i; /* Loop counter */ 6880 int aRes[3]; /* Results */ 6881 Mem *pMem; /* Write results here */ 6882 6883 assert( p->readOnly==0 ); 6884 aRes[0] = 0; 6885 aRes[1] = aRes[2] = -1; 6886 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE 6887 || pOp->p2==SQLITE_CHECKPOINT_FULL 6888 || pOp->p2==SQLITE_CHECKPOINT_RESTART 6889 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE 6890 ); 6891 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]); 6892 if( rc ){ 6893 if( rc!=SQLITE_BUSY ) goto abort_due_to_error; 6894 rc = SQLITE_OK; 6895 aRes[0] = 1; 6896 } 6897 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){ 6898 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]); 6899 } 6900 break; 6901 }; 6902 #endif 6903 6904 #ifndef SQLITE_OMIT_PRAGMA 6905 /* Opcode: JournalMode P1 P2 P3 * * 6906 ** 6907 ** Change the journal mode of database P1 to P3. P3 must be one of the 6908 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback 6909 ** modes (delete, truncate, persist, off and memory), this is a simple 6910 ** operation. No IO is required. 6911 ** 6912 ** If changing into or out of WAL mode the procedure is more complicated. 6913 ** 6914 ** Write a string containing the final journal-mode to register P2. 6915 */ 6916 case OP_JournalMode: { /* out2 */ 6917 Btree *pBt; /* Btree to change journal mode of */ 6918 Pager *pPager; /* Pager associated with pBt */ 6919 int eNew; /* New journal mode */ 6920 int eOld; /* The old journal mode */ 6921 #ifndef SQLITE_OMIT_WAL 6922 const char *zFilename; /* Name of database file for pPager */ 6923 #endif 6924 6925 pOut = out2Prerelease(p, pOp); 6926 eNew = pOp->p3; 6927 assert( eNew==PAGER_JOURNALMODE_DELETE 6928 || eNew==PAGER_JOURNALMODE_TRUNCATE 6929 || eNew==PAGER_JOURNALMODE_PERSIST 6930 || eNew==PAGER_JOURNALMODE_OFF 6931 || eNew==PAGER_JOURNALMODE_MEMORY 6932 || eNew==PAGER_JOURNALMODE_WAL 6933 || eNew==PAGER_JOURNALMODE_QUERY 6934 ); 6935 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 6936 assert( p->readOnly==0 ); 6937 6938 pBt = db->aDb[pOp->p1].pBt; 6939 pPager = sqlite3BtreePager(pBt); 6940 eOld = sqlite3PagerGetJournalMode(pPager); 6941 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld; 6942 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld; 6943 6944 #ifndef SQLITE_OMIT_WAL 6945 zFilename = sqlite3PagerFilename(pPager, 1); 6946 6947 /* Do not allow a transition to journal_mode=WAL for a database 6948 ** in temporary storage or if the VFS does not support shared memory 6949 */ 6950 if( eNew==PAGER_JOURNALMODE_WAL 6951 && (sqlite3Strlen30(zFilename)==0 /* Temp file */ 6952 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */ 6953 ){ 6954 eNew = eOld; 6955 } 6956 6957 if( (eNew!=eOld) 6958 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL) 6959 ){ 6960 if( !db->autoCommit || db->nVdbeRead>1 ){ 6961 rc = SQLITE_ERROR; 6962 sqlite3VdbeError(p, 6963 "cannot change %s wal mode from within a transaction", 6964 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of") 6965 ); 6966 goto abort_due_to_error; 6967 }else{ 6968 6969 if( eOld==PAGER_JOURNALMODE_WAL ){ 6970 /* If leaving WAL mode, close the log file. If successful, the call 6971 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log 6972 ** file. An EXCLUSIVE lock may still be held on the database file 6973 ** after a successful return. 6974 */ 6975 rc = sqlite3PagerCloseWal(pPager, db); 6976 if( rc==SQLITE_OK ){ 6977 sqlite3PagerSetJournalMode(pPager, eNew); 6978 } 6979 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){ 6980 /* Cannot transition directly from MEMORY to WAL. Use mode OFF 6981 ** as an intermediate */ 6982 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF); 6983 } 6984 6985 /* Open a transaction on the database file. Regardless of the journal 6986 ** mode, this transaction always uses a rollback journal. 6987 */ 6988 assert( sqlite3BtreeIsInTrans(pBt)==0 ); 6989 if( rc==SQLITE_OK ){ 6990 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1)); 6991 } 6992 } 6993 } 6994 #endif /* ifndef SQLITE_OMIT_WAL */ 6995 6996 if( rc ) eNew = eOld; 6997 eNew = sqlite3PagerSetJournalMode(pPager, eNew); 6998 6999 pOut->flags = MEM_Str|MEM_Static|MEM_Term; 7000 pOut->z = (char *)sqlite3JournalModename(eNew); 7001 pOut->n = sqlite3Strlen30(pOut->z); 7002 pOut->enc = SQLITE_UTF8; 7003 sqlite3VdbeChangeEncoding(pOut, encoding); 7004 if( rc ) goto abort_due_to_error; 7005 break; 7006 }; 7007 #endif /* SQLITE_OMIT_PRAGMA */ 7008 7009 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) 7010 /* Opcode: Vacuum P1 P2 * * * 7011 ** 7012 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more 7013 ** for an attached database. The "temp" database may not be vacuumed. 7014 ** 7015 ** If P2 is not zero, then it is a register holding a string which is 7016 ** the file into which the result of vacuum should be written. When 7017 ** P2 is zero, the vacuum overwrites the original database. 7018 */ 7019 case OP_Vacuum: { 7020 assert( p->readOnly==0 ); 7021 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1, 7022 pOp->p2 ? &aMem[pOp->p2] : 0); 7023 if( rc ) goto abort_due_to_error; 7024 break; 7025 } 7026 #endif 7027 7028 #if !defined(SQLITE_OMIT_AUTOVACUUM) 7029 /* Opcode: IncrVacuum P1 P2 * * * 7030 ** 7031 ** Perform a single step of the incremental vacuum procedure on 7032 ** the P1 database. If the vacuum has finished, jump to instruction 7033 ** P2. Otherwise, fall through to the next instruction. 7034 */ 7035 case OP_IncrVacuum: { /* jump */ 7036 Btree *pBt; 7037 7038 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 7039 assert( DbMaskTest(p->btreeMask, pOp->p1) ); 7040 assert( p->readOnly==0 ); 7041 pBt = db->aDb[pOp->p1].pBt; 7042 rc = sqlite3BtreeIncrVacuum(pBt); 7043 VdbeBranchTaken(rc==SQLITE_DONE,2); 7044 if( rc ){ 7045 if( rc!=SQLITE_DONE ) goto abort_due_to_error; 7046 rc = SQLITE_OK; 7047 goto jump_to_p2; 7048 } 7049 break; 7050 } 7051 #endif 7052 7053 /* Opcode: Expire P1 P2 * * * 7054 ** 7055 ** Cause precompiled statements to expire. When an expired statement 7056 ** is executed using sqlite3_step() it will either automatically 7057 ** reprepare itself (if it was originally created using sqlite3_prepare_v2()) 7058 ** or it will fail with SQLITE_SCHEMA. 7059 ** 7060 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero, 7061 ** then only the currently executing statement is expired. 7062 ** 7063 ** If P2 is 0, then SQL statements are expired immediately. If P2 is 1, 7064 ** then running SQL statements are allowed to continue to run to completion. 7065 ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens 7066 ** that might help the statement run faster but which does not affect the 7067 ** correctness of operation. 7068 */ 7069 case OP_Expire: { 7070 assert( pOp->p2==0 || pOp->p2==1 ); 7071 if( !pOp->p1 ){ 7072 sqlite3ExpirePreparedStatements(db, pOp->p2); 7073 }else{ 7074 p->expired = pOp->p2+1; 7075 } 7076 break; 7077 } 7078 7079 /* Opcode: CursorLock P1 * * * * 7080 ** 7081 ** Lock the btree to which cursor P1 is pointing so that the btree cannot be 7082 ** written by an other cursor. 7083 */ 7084 case OP_CursorLock: { 7085 VdbeCursor *pC; 7086 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 7087 pC = p->apCsr[pOp->p1]; 7088 assert( pC!=0 ); 7089 assert( pC->eCurType==CURTYPE_BTREE ); 7090 sqlite3BtreeCursorPin(pC->uc.pCursor); 7091 break; 7092 } 7093 7094 /* Opcode: CursorUnlock P1 * * * * 7095 ** 7096 ** Unlock the btree to which cursor P1 is pointing so that it can be 7097 ** written by other cursors. 7098 */ 7099 case OP_CursorUnlock: { 7100 VdbeCursor *pC; 7101 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 7102 pC = p->apCsr[pOp->p1]; 7103 assert( pC!=0 ); 7104 assert( pC->eCurType==CURTYPE_BTREE ); 7105 sqlite3BtreeCursorUnpin(pC->uc.pCursor); 7106 break; 7107 } 7108 7109 #ifndef SQLITE_OMIT_SHARED_CACHE 7110 /* Opcode: TableLock P1 P2 P3 P4 * 7111 ** Synopsis: iDb=P1 root=P2 write=P3 7112 ** 7113 ** Obtain a lock on a particular table. This instruction is only used when 7114 ** the shared-cache feature is enabled. 7115 ** 7116 ** P1 is the index of the database in sqlite3.aDb[] of the database 7117 ** on which the lock is acquired. A readlock is obtained if P3==0 or 7118 ** a write lock if P3==1. 7119 ** 7120 ** P2 contains the root-page of the table to lock. 7121 ** 7122 ** P4 contains a pointer to the name of the table being locked. This is only 7123 ** used to generate an error message if the lock cannot be obtained. 7124 */ 7125 case OP_TableLock: { 7126 u8 isWriteLock = (u8)pOp->p3; 7127 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){ 7128 int p1 = pOp->p1; 7129 assert( p1>=0 && p1<db->nDb ); 7130 assert( DbMaskTest(p->btreeMask, p1) ); 7131 assert( isWriteLock==0 || isWriteLock==1 ); 7132 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock); 7133 if( rc ){ 7134 if( (rc&0xFF)==SQLITE_LOCKED ){ 7135 const char *z = pOp->p4.z; 7136 sqlite3VdbeError(p, "database table is locked: %s", z); 7137 } 7138 goto abort_due_to_error; 7139 } 7140 } 7141 break; 7142 } 7143 #endif /* SQLITE_OMIT_SHARED_CACHE */ 7144 7145 #ifndef SQLITE_OMIT_VIRTUALTABLE 7146 /* Opcode: VBegin * * * P4 * 7147 ** 7148 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 7149 ** xBegin method for that table. 7150 ** 7151 ** Also, whether or not P4 is set, check that this is not being called from 7152 ** within a callback to a virtual table xSync() method. If it is, the error 7153 ** code will be set to SQLITE_LOCKED. 7154 */ 7155 case OP_VBegin: { 7156 VTable *pVTab; 7157 pVTab = pOp->p4.pVtab; 7158 rc = sqlite3VtabBegin(db, pVTab); 7159 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab); 7160 if( rc ) goto abort_due_to_error; 7161 break; 7162 } 7163 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7164 7165 #ifndef SQLITE_OMIT_VIRTUALTABLE 7166 /* Opcode: VCreate P1 P2 * * * 7167 ** 7168 ** P2 is a register that holds the name of a virtual table in database 7169 ** P1. Call the xCreate method for that table. 7170 */ 7171 case OP_VCreate: { 7172 Mem sMem; /* For storing the record being decoded */ 7173 const char *zTab; /* Name of the virtual table */ 7174 7175 memset(&sMem, 0, sizeof(sMem)); 7176 sMem.db = db; 7177 /* Because P2 is always a static string, it is impossible for the 7178 ** sqlite3VdbeMemCopy() to fail */ 7179 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 ); 7180 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 ); 7181 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]); 7182 assert( rc==SQLITE_OK ); 7183 zTab = (const char*)sqlite3_value_text(&sMem); 7184 assert( zTab || db->mallocFailed ); 7185 if( zTab ){ 7186 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg); 7187 } 7188 sqlite3VdbeMemRelease(&sMem); 7189 if( rc ) goto abort_due_to_error; 7190 break; 7191 } 7192 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7193 7194 #ifndef SQLITE_OMIT_VIRTUALTABLE 7195 /* Opcode: VDestroy P1 * * P4 * 7196 ** 7197 ** P4 is the name of a virtual table in database P1. Call the xDestroy method 7198 ** of that table. 7199 */ 7200 case OP_VDestroy: { 7201 db->nVDestroy++; 7202 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z); 7203 db->nVDestroy--; 7204 assert( p->errorAction==OE_Abort && p->usesStmtJournal ); 7205 if( rc ) goto abort_due_to_error; 7206 break; 7207 } 7208 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7209 7210 #ifndef SQLITE_OMIT_VIRTUALTABLE 7211 /* Opcode: VOpen P1 * * P4 * 7212 ** 7213 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. 7214 ** P1 is a cursor number. This opcode opens a cursor to the virtual 7215 ** table and stores that cursor in P1. 7216 */ 7217 case OP_VOpen: { 7218 VdbeCursor *pCur; 7219 sqlite3_vtab_cursor *pVCur; 7220 sqlite3_vtab *pVtab; 7221 const sqlite3_module *pModule; 7222 7223 assert( p->bIsReader ); 7224 pCur = 0; 7225 pVCur = 0; 7226 pVtab = pOp->p4.pVtab->pVtab; 7227 if( pVtab==0 || NEVER(pVtab->pModule==0) ){ 7228 rc = SQLITE_LOCKED; 7229 goto abort_due_to_error; 7230 } 7231 pModule = pVtab->pModule; 7232 rc = pModule->xOpen(pVtab, &pVCur); 7233 sqlite3VtabImportErrmsg(p, pVtab); 7234 if( rc ) goto abort_due_to_error; 7235 7236 /* Initialize sqlite3_vtab_cursor base class */ 7237 pVCur->pVtab = pVtab; 7238 7239 /* Initialize vdbe cursor object */ 7240 pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB); 7241 if( pCur ){ 7242 pCur->uc.pVCur = pVCur; 7243 pVtab->nRef++; 7244 }else{ 7245 assert( db->mallocFailed ); 7246 pModule->xClose(pVCur); 7247 goto no_mem; 7248 } 7249 break; 7250 } 7251 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7252 7253 #ifndef SQLITE_OMIT_VIRTUALTABLE 7254 /* Opcode: VFilter P1 P2 P3 P4 * 7255 ** Synopsis: iplan=r[P3] zplan='P4' 7256 ** 7257 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if 7258 ** the filtered result set is empty. 7259 ** 7260 ** P4 is either NULL or a string that was generated by the xBestIndex 7261 ** method of the module. The interpretation of the P4 string is left 7262 ** to the module implementation. 7263 ** 7264 ** This opcode invokes the xFilter method on the virtual table specified 7265 ** by P1. The integer query plan parameter to xFilter is stored in register 7266 ** P3. Register P3+1 stores the argc parameter to be passed to the 7267 ** xFilter method. Registers P3+2..P3+1+argc are the argc 7268 ** additional parameters which are passed to 7269 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter. 7270 ** 7271 ** A jump is made to P2 if the result set after filtering would be empty. 7272 */ 7273 case OP_VFilter: { /* jump */ 7274 int nArg; 7275 int iQuery; 7276 const sqlite3_module *pModule; 7277 Mem *pQuery; 7278 Mem *pArgc; 7279 sqlite3_vtab_cursor *pVCur; 7280 sqlite3_vtab *pVtab; 7281 VdbeCursor *pCur; 7282 int res; 7283 int i; 7284 Mem **apArg; 7285 7286 pQuery = &aMem[pOp->p3]; 7287 pArgc = &pQuery[1]; 7288 pCur = p->apCsr[pOp->p1]; 7289 assert( memIsValid(pQuery) ); 7290 REGISTER_TRACE(pOp->p3, pQuery); 7291 assert( pCur->eCurType==CURTYPE_VTAB ); 7292 pVCur = pCur->uc.pVCur; 7293 pVtab = pVCur->pVtab; 7294 pModule = pVtab->pModule; 7295 7296 /* Grab the index number and argc parameters */ 7297 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int ); 7298 nArg = (int)pArgc->u.i; 7299 iQuery = (int)pQuery->u.i; 7300 7301 /* Invoke the xFilter method */ 7302 res = 0; 7303 apArg = p->apArg; 7304 for(i = 0; i<nArg; i++){ 7305 apArg[i] = &pArgc[i+1]; 7306 } 7307 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg); 7308 sqlite3VtabImportErrmsg(p, pVtab); 7309 if( rc ) goto abort_due_to_error; 7310 res = pModule->xEof(pVCur); 7311 pCur->nullRow = 0; 7312 VdbeBranchTaken(res!=0,2); 7313 if( res ) goto jump_to_p2; 7314 break; 7315 } 7316 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7317 7318 #ifndef SQLITE_OMIT_VIRTUALTABLE 7319 /* Opcode: VColumn P1 P2 P3 * P5 7320 ** Synopsis: r[P3]=vcolumn(P2) 7321 ** 7322 ** Store in register P3 the value of the P2-th column of 7323 ** the current row of the virtual-table of cursor P1. 7324 ** 7325 ** If the VColumn opcode is being used to fetch the value of 7326 ** an unchanging column during an UPDATE operation, then the P5 7327 ** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange() 7328 ** function to return true inside the xColumn method of the virtual 7329 ** table implementation. The P5 column might also contain other 7330 ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are 7331 ** unused by OP_VColumn. 7332 */ 7333 case OP_VColumn: { 7334 sqlite3_vtab *pVtab; 7335 const sqlite3_module *pModule; 7336 Mem *pDest; 7337 sqlite3_context sContext; 7338 7339 VdbeCursor *pCur = p->apCsr[pOp->p1]; 7340 assert( pCur->eCurType==CURTYPE_VTAB ); 7341 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); 7342 pDest = &aMem[pOp->p3]; 7343 memAboutToChange(p, pDest); 7344 if( pCur->nullRow ){ 7345 sqlite3VdbeMemSetNull(pDest); 7346 break; 7347 } 7348 pVtab = pCur->uc.pVCur->pVtab; 7349 pModule = pVtab->pModule; 7350 assert( pModule->xColumn ); 7351 memset(&sContext, 0, sizeof(sContext)); 7352 sContext.pOut = pDest; 7353 assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 ); 7354 if( pOp->p5 & OPFLAG_NOCHNG ){ 7355 sqlite3VdbeMemSetNull(pDest); 7356 pDest->flags = MEM_Null|MEM_Zero; 7357 pDest->u.nZero = 0; 7358 }else{ 7359 MemSetTypeFlag(pDest, MEM_Null); 7360 } 7361 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2); 7362 sqlite3VtabImportErrmsg(p, pVtab); 7363 if( sContext.isError>0 ){ 7364 sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest)); 7365 rc = sContext.isError; 7366 } 7367 sqlite3VdbeChangeEncoding(pDest, encoding); 7368 REGISTER_TRACE(pOp->p3, pDest); 7369 UPDATE_MAX_BLOBSIZE(pDest); 7370 7371 if( sqlite3VdbeMemTooBig(pDest) ){ 7372 goto too_big; 7373 } 7374 if( rc ) goto abort_due_to_error; 7375 break; 7376 } 7377 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7378 7379 #ifndef SQLITE_OMIT_VIRTUALTABLE 7380 /* Opcode: VNext P1 P2 * * * 7381 ** 7382 ** Advance virtual table P1 to the next row in its result set and 7383 ** jump to instruction P2. Or, if the virtual table has reached 7384 ** the end of its result set, then fall through to the next instruction. 7385 */ 7386 case OP_VNext: { /* jump */ 7387 sqlite3_vtab *pVtab; 7388 const sqlite3_module *pModule; 7389 int res; 7390 VdbeCursor *pCur; 7391 7392 res = 0; 7393 pCur = p->apCsr[pOp->p1]; 7394 assert( pCur->eCurType==CURTYPE_VTAB ); 7395 if( pCur->nullRow ){ 7396 break; 7397 } 7398 pVtab = pCur->uc.pVCur->pVtab; 7399 pModule = pVtab->pModule; 7400 assert( pModule->xNext ); 7401 7402 /* Invoke the xNext() method of the module. There is no way for the 7403 ** underlying implementation to return an error if one occurs during 7404 ** xNext(). Instead, if an error occurs, true is returned (indicating that 7405 ** data is available) and the error code returned when xColumn or 7406 ** some other method is next invoked on the save virtual table cursor. 7407 */ 7408 rc = pModule->xNext(pCur->uc.pVCur); 7409 sqlite3VtabImportErrmsg(p, pVtab); 7410 if( rc ) goto abort_due_to_error; 7411 res = pModule->xEof(pCur->uc.pVCur); 7412 VdbeBranchTaken(!res,2); 7413 if( !res ){ 7414 /* If there is data, jump to P2 */ 7415 goto jump_to_p2_and_check_for_interrupt; 7416 } 7417 goto check_for_interrupt; 7418 } 7419 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7420 7421 #ifndef SQLITE_OMIT_VIRTUALTABLE 7422 /* Opcode: VRename P1 * * P4 * 7423 ** 7424 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. 7425 ** This opcode invokes the corresponding xRename method. The value 7426 ** in register P1 is passed as the zName argument to the xRename method. 7427 */ 7428 case OP_VRename: { 7429 sqlite3_vtab *pVtab; 7430 Mem *pName; 7431 int isLegacy; 7432 7433 isLegacy = (db->flags & SQLITE_LegacyAlter); 7434 db->flags |= SQLITE_LegacyAlter; 7435 pVtab = pOp->p4.pVtab->pVtab; 7436 pName = &aMem[pOp->p1]; 7437 assert( pVtab->pModule->xRename ); 7438 assert( memIsValid(pName) ); 7439 assert( p->readOnly==0 ); 7440 REGISTER_TRACE(pOp->p1, pName); 7441 assert( pName->flags & MEM_Str ); 7442 testcase( pName->enc==SQLITE_UTF8 ); 7443 testcase( pName->enc==SQLITE_UTF16BE ); 7444 testcase( pName->enc==SQLITE_UTF16LE ); 7445 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8); 7446 if( rc ) goto abort_due_to_error; 7447 rc = pVtab->pModule->xRename(pVtab, pName->z); 7448 if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter; 7449 sqlite3VtabImportErrmsg(p, pVtab); 7450 p->expired = 0; 7451 if( rc ) goto abort_due_to_error; 7452 break; 7453 } 7454 #endif 7455 7456 #ifndef SQLITE_OMIT_VIRTUALTABLE 7457 /* Opcode: VUpdate P1 P2 P3 P4 P5 7458 ** Synopsis: data=r[P3@P2] 7459 ** 7460 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. 7461 ** This opcode invokes the corresponding xUpdate method. P2 values 7462 ** are contiguous memory cells starting at P3 to pass to the xUpdate 7463 ** invocation. The value in register (P3+P2-1) corresponds to the 7464 ** p2th element of the argv array passed to xUpdate. 7465 ** 7466 ** The xUpdate method will do a DELETE or an INSERT or both. 7467 ** The argv[0] element (which corresponds to memory cell P3) 7468 ** is the rowid of a row to delete. If argv[0] is NULL then no 7469 ** deletion occurs. The argv[1] element is the rowid of the new 7470 ** row. This can be NULL to have the virtual table select the new 7471 ** rowid for itself. The subsequent elements in the array are 7472 ** the values of columns in the new row. 7473 ** 7474 ** If P2==1 then no insert is performed. argv[0] is the rowid of 7475 ** a row to delete. 7476 ** 7477 ** P1 is a boolean flag. If it is set to true and the xUpdate call 7478 ** is successful, then the value returned by sqlite3_last_insert_rowid() 7479 ** is set to the value of the rowid for the row just inserted. 7480 ** 7481 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to 7482 ** apply in the case of a constraint failure on an insert or update. 7483 */ 7484 case OP_VUpdate: { 7485 sqlite3_vtab *pVtab; 7486 const sqlite3_module *pModule; 7487 int nArg; 7488 int i; 7489 sqlite_int64 rowid; 7490 Mem **apArg; 7491 Mem *pX; 7492 7493 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback 7494 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace 7495 ); 7496 assert( p->readOnly==0 ); 7497 if( db->mallocFailed ) goto no_mem; 7498 sqlite3VdbeIncrWriteCounter(p, 0); 7499 pVtab = pOp->p4.pVtab->pVtab; 7500 if( pVtab==0 || NEVER(pVtab->pModule==0) ){ 7501 rc = SQLITE_LOCKED; 7502 goto abort_due_to_error; 7503 } 7504 pModule = pVtab->pModule; 7505 nArg = pOp->p2; 7506 assert( pOp->p4type==P4_VTAB ); 7507 if( ALWAYS(pModule->xUpdate) ){ 7508 u8 vtabOnConflict = db->vtabOnConflict; 7509 apArg = p->apArg; 7510 pX = &aMem[pOp->p3]; 7511 for(i=0; i<nArg; i++){ 7512 assert( memIsValid(pX) ); 7513 memAboutToChange(p, pX); 7514 apArg[i] = pX; 7515 pX++; 7516 } 7517 db->vtabOnConflict = pOp->p5; 7518 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid); 7519 db->vtabOnConflict = vtabOnConflict; 7520 sqlite3VtabImportErrmsg(p, pVtab); 7521 if( rc==SQLITE_OK && pOp->p1 ){ 7522 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) ); 7523 db->lastRowid = rowid; 7524 } 7525 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){ 7526 if( pOp->p5==OE_Ignore ){ 7527 rc = SQLITE_OK; 7528 }else{ 7529 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5); 7530 } 7531 }else{ 7532 p->nChange++; 7533 } 7534 if( rc ) goto abort_due_to_error; 7535 } 7536 break; 7537 } 7538 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7539 7540 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 7541 /* Opcode: Pagecount P1 P2 * * * 7542 ** 7543 ** Write the current number of pages in database P1 to memory cell P2. 7544 */ 7545 case OP_Pagecount: { /* out2 */ 7546 pOut = out2Prerelease(p, pOp); 7547 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt); 7548 break; 7549 } 7550 #endif 7551 7552 7553 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 7554 /* Opcode: MaxPgcnt P1 P2 P3 * * 7555 ** 7556 ** Try to set the maximum page count for database P1 to the value in P3. 7557 ** Do not let the maximum page count fall below the current page count and 7558 ** do not change the maximum page count value if P3==0. 7559 ** 7560 ** Store the maximum page count after the change in register P2. 7561 */ 7562 case OP_MaxPgcnt: { /* out2 */ 7563 unsigned int newMax; 7564 Btree *pBt; 7565 7566 pOut = out2Prerelease(p, pOp); 7567 pBt = db->aDb[pOp->p1].pBt; 7568 newMax = 0; 7569 if( pOp->p3 ){ 7570 newMax = sqlite3BtreeLastPage(pBt); 7571 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3; 7572 } 7573 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax); 7574 break; 7575 } 7576 #endif 7577 7578 /* Opcode: Function P1 P2 P3 P4 * 7579 ** Synopsis: r[P3]=func(r[P2@P5]) 7580 ** 7581 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that 7582 ** contains a pointer to the function to be run) with arguments taken 7583 ** from register P2 and successors. The number of arguments is in 7584 ** the sqlite3_context object that P4 points to. 7585 ** The result of the function is stored 7586 ** in register P3. Register P3 must not be one of the function inputs. 7587 ** 7588 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 7589 ** function was determined to be constant at compile time. If the first 7590 ** argument was constant then bit 0 of P1 is set. This is used to determine 7591 ** whether meta data associated with a user function argument using the 7592 ** sqlite3_set_auxdata() API may be safely retained until the next 7593 ** invocation of this opcode. 7594 ** 7595 ** See also: AggStep, AggFinal, PureFunc 7596 */ 7597 /* Opcode: PureFunc P1 P2 P3 P4 * 7598 ** Synopsis: r[P3]=func(r[P2@P5]) 7599 ** 7600 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that 7601 ** contains a pointer to the function to be run) with arguments taken 7602 ** from register P2 and successors. The number of arguments is in 7603 ** the sqlite3_context object that P4 points to. 7604 ** The result of the function is stored 7605 ** in register P3. Register P3 must not be one of the function inputs. 7606 ** 7607 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 7608 ** function was determined to be constant at compile time. If the first 7609 ** argument was constant then bit 0 of P1 is set. This is used to determine 7610 ** whether meta data associated with a user function argument using the 7611 ** sqlite3_set_auxdata() API may be safely retained until the next 7612 ** invocation of this opcode. 7613 ** 7614 ** This opcode works exactly like OP_Function. The only difference is in 7615 ** its name. This opcode is used in places where the function must be 7616 ** purely non-deterministic. Some built-in date/time functions can be 7617 ** either determinitic of non-deterministic, depending on their arguments. 7618 ** When those function are used in a non-deterministic way, they will check 7619 ** to see if they were called using OP_PureFunc instead of OP_Function, and 7620 ** if they were, they throw an error. 7621 ** 7622 ** See also: AggStep, AggFinal, Function 7623 */ 7624 case OP_PureFunc: /* group */ 7625 case OP_Function: { /* group */ 7626 int i; 7627 sqlite3_context *pCtx; 7628 7629 assert( pOp->p4type==P4_FUNCCTX ); 7630 pCtx = pOp->p4.pCtx; 7631 7632 /* If this function is inside of a trigger, the register array in aMem[] 7633 ** might change from one evaluation to the next. The next block of code 7634 ** checks to see if the register array has changed, and if so it 7635 ** reinitializes the relavant parts of the sqlite3_context object */ 7636 pOut = &aMem[pOp->p3]; 7637 if( pCtx->pOut != pOut ){ 7638 pCtx->pVdbe = p; 7639 pCtx->pOut = pOut; 7640 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; 7641 } 7642 assert( pCtx->pVdbe==p ); 7643 7644 memAboutToChange(p, pOut); 7645 #ifdef SQLITE_DEBUG 7646 for(i=0; i<pCtx->argc; i++){ 7647 assert( memIsValid(pCtx->argv[i]) ); 7648 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]); 7649 } 7650 #endif 7651 MemSetTypeFlag(pOut, MEM_Null); 7652 assert( pCtx->isError==0 ); 7653 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */ 7654 7655 /* If the function returned an error, throw an exception */ 7656 if( pCtx->isError ){ 7657 if( pCtx->isError>0 ){ 7658 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut)); 7659 rc = pCtx->isError; 7660 } 7661 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1); 7662 pCtx->isError = 0; 7663 if( rc ) goto abort_due_to_error; 7664 } 7665 7666 /* Copy the result of the function into register P3 */ 7667 if( pOut->flags & (MEM_Str|MEM_Blob) ){ 7668 sqlite3VdbeChangeEncoding(pOut, encoding); 7669 if( sqlite3VdbeMemTooBig(pOut) ) goto too_big; 7670 } 7671 7672 REGISTER_TRACE(pOp->p3, pOut); 7673 UPDATE_MAX_BLOBSIZE(pOut); 7674 break; 7675 } 7676 7677 /* Opcode: Trace P1 P2 * P4 * 7678 ** 7679 ** Write P4 on the statement trace output if statement tracing is 7680 ** enabled. 7681 ** 7682 ** Operand P1 must be 0x7fffffff and P2 must positive. 7683 */ 7684 /* Opcode: Init P1 P2 P3 P4 * 7685 ** Synopsis: Start at P2 7686 ** 7687 ** Programs contain a single instance of this opcode as the very first 7688 ** opcode. 7689 ** 7690 ** If tracing is enabled (by the sqlite3_trace()) interface, then 7691 ** the UTF-8 string contained in P4 is emitted on the trace callback. 7692 ** Or if P4 is blank, use the string returned by sqlite3_sql(). 7693 ** 7694 ** If P2 is not zero, jump to instruction P2. 7695 ** 7696 ** Increment the value of P1 so that OP_Once opcodes will jump the 7697 ** first time they are evaluated for this run. 7698 ** 7699 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT 7700 ** error is encountered. 7701 */ 7702 case OP_Trace: 7703 case OP_Init: { /* jump */ 7704 int i; 7705 #ifndef SQLITE_OMIT_TRACE 7706 char *zTrace; 7707 #endif 7708 7709 /* If the P4 argument is not NULL, then it must be an SQL comment string. 7710 ** The "--" string is broken up to prevent false-positives with srcck1.c. 7711 ** 7712 ** This assert() provides evidence for: 7713 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that 7714 ** would have been returned by the legacy sqlite3_trace() interface by 7715 ** using the X argument when X begins with "--" and invoking 7716 ** sqlite3_expanded_sql(P) otherwise. 7717 */ 7718 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 ); 7719 7720 /* OP_Init is always instruction 0 */ 7721 assert( pOp==p->aOp || pOp->opcode==OP_Trace ); 7722 7723 #ifndef SQLITE_OMIT_TRACE 7724 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0 7725 && !p->doingRerun 7726 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 7727 ){ 7728 #ifndef SQLITE_OMIT_DEPRECATED 7729 if( db->mTrace & SQLITE_TRACE_LEGACY ){ 7730 void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace; 7731 char *z = sqlite3VdbeExpandSql(p, zTrace); 7732 x(db->pTraceArg, z); 7733 sqlite3_free(z); 7734 }else 7735 #endif 7736 if( db->nVdbeExec>1 ){ 7737 char *z = sqlite3MPrintf(db, "-- %s", zTrace); 7738 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z); 7739 sqlite3DbFree(db, z); 7740 }else{ 7741 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace); 7742 } 7743 } 7744 #ifdef SQLITE_USE_FCNTL_TRACE 7745 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql); 7746 if( zTrace ){ 7747 int j; 7748 for(j=0; j<db->nDb; j++){ 7749 if( DbMaskTest(p->btreeMask, j)==0 ) continue; 7750 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace); 7751 } 7752 } 7753 #endif /* SQLITE_USE_FCNTL_TRACE */ 7754 #ifdef SQLITE_DEBUG 7755 if( (db->flags & SQLITE_SqlTrace)!=0 7756 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 7757 ){ 7758 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace); 7759 } 7760 #endif /* SQLITE_DEBUG */ 7761 #endif /* SQLITE_OMIT_TRACE */ 7762 assert( pOp->p2>0 ); 7763 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){ 7764 if( pOp->opcode==OP_Trace ) break; 7765 for(i=1; i<p->nOp; i++){ 7766 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0; 7767 } 7768 pOp->p1 = 0; 7769 } 7770 pOp->p1++; 7771 p->aCounter[SQLITE_STMTSTATUS_RUN]++; 7772 goto jump_to_p2; 7773 } 7774 7775 #ifdef SQLITE_ENABLE_CURSOR_HINTS 7776 /* Opcode: CursorHint P1 * * P4 * 7777 ** 7778 ** Provide a hint to cursor P1 that it only needs to return rows that 7779 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer 7780 ** to values currently held in registers. TK_COLUMN terms in the P4 7781 ** expression refer to columns in the b-tree to which cursor P1 is pointing. 7782 */ 7783 case OP_CursorHint: { 7784 VdbeCursor *pC; 7785 7786 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 7787 assert( pOp->p4type==P4_EXPR ); 7788 pC = p->apCsr[pOp->p1]; 7789 if( pC ){ 7790 assert( pC->eCurType==CURTYPE_BTREE ); 7791 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE, 7792 pOp->p4.pExpr, aMem); 7793 } 7794 break; 7795 } 7796 #endif /* SQLITE_ENABLE_CURSOR_HINTS */ 7797 7798 #ifdef SQLITE_DEBUG 7799 /* Opcode: Abortable * * * * * 7800 ** 7801 ** Verify that an Abort can happen. Assert if an Abort at this point 7802 ** might cause database corruption. This opcode only appears in debugging 7803 ** builds. 7804 ** 7805 ** An Abort is safe if either there have been no writes, or if there is 7806 ** an active statement journal. 7807 */ 7808 case OP_Abortable: { 7809 sqlite3VdbeAssertAbortable(p); 7810 break; 7811 } 7812 #endif 7813 7814 #ifdef SQLITE_DEBUG 7815 /* Opcode: ReleaseReg P1 P2 P3 * P5 7816 ** Synopsis: release r[P1@P2] mask P3 7817 ** 7818 ** Release registers from service. Any content that was in the 7819 ** the registers is unreliable after this opcode completes. 7820 ** 7821 ** The registers released will be the P2 registers starting at P1, 7822 ** except if bit ii of P3 set, then do not release register P1+ii. 7823 ** In other words, P3 is a mask of registers to preserve. 7824 ** 7825 ** Releasing a register clears the Mem.pScopyFrom pointer. That means 7826 ** that if the content of the released register was set using OP_SCopy, 7827 ** a change to the value of the source register for the OP_SCopy will no longer 7828 ** generate an assertion fault in sqlite3VdbeMemAboutToChange(). 7829 ** 7830 ** If P5 is set, then all released registers have their type set 7831 ** to MEM_Undefined so that any subsequent attempt to read the released 7832 ** register (before it is reinitialized) will generate an assertion fault. 7833 ** 7834 ** P5 ought to be set on every call to this opcode. 7835 ** However, there are places in the code generator will release registers 7836 ** before their are used, under the (valid) assumption that the registers 7837 ** will not be reallocated for some other purpose before they are used and 7838 ** hence are safe to release. 7839 ** 7840 ** This opcode is only available in testing and debugging builds. It is 7841 ** not generated for release builds. The purpose of this opcode is to help 7842 ** validate the generated bytecode. This opcode does not actually contribute 7843 ** to computing an answer. 7844 */ 7845 case OP_ReleaseReg: { 7846 Mem *pMem; 7847 int i; 7848 u32 constMask; 7849 assert( pOp->p1>0 ); 7850 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 ); 7851 pMem = &aMem[pOp->p1]; 7852 constMask = pOp->p3; 7853 for(i=0; i<pOp->p2; i++, pMem++){ 7854 if( i>=32 || (constMask & MASKBIT32(i))==0 ){ 7855 pMem->pScopyFrom = 0; 7856 if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined); 7857 } 7858 } 7859 break; 7860 } 7861 #endif 7862 7863 /* Opcode: Noop * * * * * 7864 ** 7865 ** Do nothing. This instruction is often useful as a jump 7866 ** destination. 7867 */ 7868 /* 7869 ** The magic Explain opcode are only inserted when explain==2 (which 7870 ** is to say when the EXPLAIN QUERY PLAN syntax is used.) 7871 ** This opcode records information from the optimizer. It is the 7872 ** the same as a no-op. This opcodesnever appears in a real VM program. 7873 */ 7874 default: { /* This is really OP_Noop, OP_Explain */ 7875 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain ); 7876 7877 break; 7878 } 7879 7880 /***************************************************************************** 7881 ** The cases of the switch statement above this line should all be indented 7882 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the 7883 ** readability. From this point on down, the normal indentation rules are 7884 ** restored. 7885 *****************************************************************************/ 7886 } 7887 7888 #ifdef VDBE_PROFILE 7889 { 7890 u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime(); 7891 if( endTime>start ) pOrigOp->cycles += endTime - start; 7892 pOrigOp->cnt++; 7893 } 7894 #endif 7895 7896 /* The following code adds nothing to the actual functionality 7897 ** of the program. It is only here for testing and debugging. 7898 ** On the other hand, it does burn CPU cycles every time through 7899 ** the evaluator loop. So we can leave it out when NDEBUG is defined. 7900 */ 7901 #ifndef NDEBUG 7902 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] ); 7903 7904 #ifdef SQLITE_DEBUG 7905 if( db->flags & SQLITE_VdbeTrace ){ 7906 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode]; 7907 if( rc!=0 ) printf("rc=%d\n",rc); 7908 if( opProperty & (OPFLG_OUT2) ){ 7909 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]); 7910 } 7911 if( opProperty & OPFLG_OUT3 ){ 7912 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]); 7913 } 7914 if( opProperty==0xff ){ 7915 /* Never happens. This code exists to avoid a harmless linkage 7916 ** warning aboud sqlite3VdbeRegisterDump() being defined but not 7917 ** used. */ 7918 sqlite3VdbeRegisterDump(p); 7919 } 7920 } 7921 #endif /* SQLITE_DEBUG */ 7922 #endif /* NDEBUG */ 7923 } /* The end of the for(;;) loop the loops through opcodes */ 7924 7925 /* If we reach this point, it means that execution is finished with 7926 ** an error of some kind. 7927 */ 7928 abort_due_to_error: 7929 if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT; 7930 assert( rc ); 7931 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){ 7932 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc)); 7933 } 7934 p->rc = rc; 7935 sqlite3SystemError(db, rc); 7936 testcase( sqlite3GlobalConfig.xLog!=0 ); 7937 sqlite3_log(rc, "statement aborts at %d: [%s] %s", 7938 (int)(pOp - aOp), p->zSql, p->zErrMsg); 7939 sqlite3VdbeHalt(p); 7940 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db); 7941 rc = SQLITE_ERROR; 7942 if( resetSchemaOnFault>0 ){ 7943 sqlite3ResetOneSchema(db, resetSchemaOnFault-1); 7944 } 7945 7946 /* This is the only way out of this procedure. We have to 7947 ** release the mutexes on btrees that were acquired at the 7948 ** top. */ 7949 vdbe_return: 7950 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 7951 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){ 7952 nProgressLimit += db->nProgressOps; 7953 if( db->xProgress(db->pProgressArg) ){ 7954 nProgressLimit = 0xffffffff; 7955 rc = SQLITE_INTERRUPT; 7956 goto abort_due_to_error; 7957 } 7958 } 7959 #endif 7960 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep; 7961 sqlite3VdbeLeave(p); 7962 assert( rc!=SQLITE_OK || nExtraDelete==0 7963 || sqlite3_strlike("DELETE%",p->zSql,0)!=0 7964 ); 7965 return rc; 7966 7967 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH 7968 ** is encountered. 7969 */ 7970 too_big: 7971 sqlite3VdbeError(p, "string or blob too big"); 7972 rc = SQLITE_TOOBIG; 7973 goto abort_due_to_error; 7974 7975 /* Jump to here if a malloc() fails. 7976 */ 7977 no_mem: 7978 sqlite3OomFault(db); 7979 sqlite3VdbeError(p, "out of memory"); 7980 rc = SQLITE_NOMEM_BKPT; 7981 goto abort_due_to_error; 7982 7983 /* Jump to here if the sqlite3_interrupt() API sets the interrupt 7984 ** flag. 7985 */ 7986 abort_due_to_interrupt: 7987 assert( db->u1.isInterrupted ); 7988 rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT; 7989 p->rc = rc; 7990 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc)); 7991 goto abort_due_to_error; 7992 } 7993