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