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