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