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. If P2 is 2 or more 3491 ** then an exclusive transaction is started. 3492 ** 3493 ** P1 is the index of the database file on which the transaction is 3494 ** started. Index 0 is the main database file and index 1 is the 3495 ** file used for temporary tables. Indices of 2 or more are used for 3496 ** attached databases. 3497 ** 3498 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is 3499 ** true (this flag is set if the Vdbe may modify more than one row and may 3500 ** throw an ABORT exception), a statement transaction may also be opened. 3501 ** More specifically, a statement transaction is opened iff the database 3502 ** connection is currently not in autocommit mode, or if there are other 3503 ** active statements. A statement transaction allows the changes made by this 3504 ** VDBE to be rolled back after an error without having to roll back the 3505 ** entire transaction. If no error is encountered, the statement transaction 3506 ** will automatically commit when the VDBE halts. 3507 ** 3508 ** If P5!=0 then this opcode also checks the schema cookie against P3 3509 ** and the schema generation counter against P4. 3510 ** The cookie changes its value whenever the database schema changes. 3511 ** This operation is used to detect when that the cookie has changed 3512 ** and that the current process needs to reread the schema. If the schema 3513 ** cookie in P3 differs from the schema cookie in the database header or 3514 ** if the schema generation counter in P4 differs from the current 3515 ** generation counter, then an SQLITE_SCHEMA error is raised and execution 3516 ** halts. The sqlite3_step() wrapper function might then reprepare the 3517 ** statement and rerun it from the beginning. 3518 */ 3519 case OP_Transaction: { 3520 Btree *pBt; 3521 int iMeta = 0; 3522 3523 assert( p->bIsReader ); 3524 assert( p->readOnly==0 || pOp->p2==0 ); 3525 assert( pOp->p2>=0 && pOp->p2<=2 ); 3526 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 3527 assert( DbMaskTest(p->btreeMask, pOp->p1) ); 3528 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){ 3529 rc = SQLITE_READONLY; 3530 goto abort_due_to_error; 3531 } 3532 pBt = db->aDb[pOp->p1].pBt; 3533 3534 if( pBt ){ 3535 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta); 3536 testcase( rc==SQLITE_BUSY_SNAPSHOT ); 3537 testcase( rc==SQLITE_BUSY_RECOVERY ); 3538 if( rc!=SQLITE_OK ){ 3539 if( (rc&0xff)==SQLITE_BUSY ){ 3540 p->pc = (int)(pOp - aOp); 3541 p->rc = rc; 3542 goto vdbe_return; 3543 } 3544 goto abort_due_to_error; 3545 } 3546 3547 if( p->usesStmtJournal 3548 && pOp->p2 3549 && (db->autoCommit==0 || db->nVdbeRead>1) 3550 ){ 3551 assert( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ); 3552 if( p->iStatement==0 ){ 3553 assert( db->nStatement>=0 && db->nSavepoint>=0 ); 3554 db->nStatement++; 3555 p->iStatement = db->nSavepoint + db->nStatement; 3556 } 3557 3558 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1); 3559 if( rc==SQLITE_OK ){ 3560 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement); 3561 } 3562 3563 /* Store the current value of the database handles deferred constraint 3564 ** counter. If the statement transaction needs to be rolled back, 3565 ** the value of this counter needs to be restored too. */ 3566 p->nStmtDefCons = db->nDeferredCons; 3567 p->nStmtDefImmCons = db->nDeferredImmCons; 3568 } 3569 } 3570 assert( pOp->p5==0 || pOp->p4type==P4_INT32 ); 3571 if( pOp->p5 3572 && (iMeta!=pOp->p3 3573 || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i) 3574 ){ 3575 /* 3576 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema 3577 ** version is checked to ensure that the schema has not changed since the 3578 ** SQL statement was prepared. 3579 */ 3580 sqlite3DbFree(db, p->zErrMsg); 3581 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed"); 3582 /* If the schema-cookie from the database file matches the cookie 3583 ** stored with the in-memory representation of the schema, do 3584 ** not reload the schema from the database file. 3585 ** 3586 ** If virtual-tables are in use, this is not just an optimization. 3587 ** Often, v-tables store their data in other SQLite tables, which 3588 ** are queried from within xNext() and other v-table methods using 3589 ** prepared queries. If such a query is out-of-date, we do not want to 3590 ** discard the database schema, as the user code implementing the 3591 ** v-table would have to be ready for the sqlite3_vtab structure itself 3592 ** to be invalidated whenever sqlite3_step() is called from within 3593 ** a v-table method. 3594 */ 3595 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){ 3596 sqlite3ResetOneSchema(db, pOp->p1); 3597 } 3598 p->expired = 1; 3599 rc = SQLITE_SCHEMA; 3600 } 3601 if( rc ) goto abort_due_to_error; 3602 break; 3603 } 3604 3605 /* Opcode: ReadCookie P1 P2 P3 * * 3606 ** 3607 ** Read cookie number P3 from database P1 and write it into register P2. 3608 ** P3==1 is the schema version. P3==2 is the database format. 3609 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is 3610 ** the main database file and P1==1 is the database file used to store 3611 ** temporary tables. 3612 ** 3613 ** There must be a read-lock on the database (either a transaction 3614 ** must be started or there must be an open cursor) before 3615 ** executing this instruction. 3616 */ 3617 case OP_ReadCookie: { /* out2 */ 3618 int iMeta; 3619 int iDb; 3620 int iCookie; 3621 3622 assert( p->bIsReader ); 3623 iDb = pOp->p1; 3624 iCookie = pOp->p3; 3625 assert( pOp->p3<SQLITE_N_BTREE_META ); 3626 assert( iDb>=0 && iDb<db->nDb ); 3627 assert( db->aDb[iDb].pBt!=0 ); 3628 assert( DbMaskTest(p->btreeMask, iDb) ); 3629 3630 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta); 3631 pOut = out2Prerelease(p, pOp); 3632 pOut->u.i = iMeta; 3633 break; 3634 } 3635 3636 /* Opcode: SetCookie P1 P2 P3 * P5 3637 ** 3638 ** Write the integer value P3 into cookie number P2 of database P1. 3639 ** P2==1 is the schema version. P2==2 is the database format. 3640 ** P2==3 is the recommended pager cache 3641 ** size, and so forth. P1==0 is the main database file and P1==1 is the 3642 ** database file used to store temporary tables. 3643 ** 3644 ** A transaction must be started before executing this opcode. 3645 ** 3646 ** If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal 3647 ** schema version is set to P3-P5. The "PRAGMA schema_version=N" statement 3648 ** has P5 set to 1, so that the internal schema version will be different 3649 ** from the database schema version, resulting in a schema reset. 3650 */ 3651 case OP_SetCookie: { 3652 Db *pDb; 3653 3654 sqlite3VdbeIncrWriteCounter(p, 0); 3655 assert( pOp->p2<SQLITE_N_BTREE_META ); 3656 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 3657 assert( DbMaskTest(p->btreeMask, pOp->p1) ); 3658 assert( p->readOnly==0 ); 3659 pDb = &db->aDb[pOp->p1]; 3660 assert( pDb->pBt!=0 ); 3661 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) ); 3662 /* See note about index shifting on OP_ReadCookie */ 3663 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3); 3664 if( pOp->p2==BTREE_SCHEMA_VERSION ){ 3665 /* When the schema cookie changes, record the new cookie internally */ 3666 pDb->pSchema->schema_cookie = pOp->p3 - pOp->p5; 3667 db->mDbFlags |= DBFLAG_SchemaChange; 3668 }else if( pOp->p2==BTREE_FILE_FORMAT ){ 3669 /* Record changes in the file format */ 3670 pDb->pSchema->file_format = pOp->p3; 3671 } 3672 if( pOp->p1==1 ){ 3673 /* Invalidate all prepared statements whenever the TEMP database 3674 ** schema is changed. Ticket #1644 */ 3675 sqlite3ExpirePreparedStatements(db, 0); 3676 p->expired = 0; 3677 } 3678 if( rc ) goto abort_due_to_error; 3679 break; 3680 } 3681 3682 /* Opcode: OpenRead P1 P2 P3 P4 P5 3683 ** Synopsis: root=P2 iDb=P3 3684 ** 3685 ** Open a read-only cursor for the database table whose root page is 3686 ** P2 in a database file. The database file is determined by P3. 3687 ** P3==0 means the main database, P3==1 means the database used for 3688 ** temporary tables, and P3>1 means used the corresponding attached 3689 ** database. Give the new cursor an identifier of P1. The P1 3690 ** values need not be contiguous but all P1 values should be small integers. 3691 ** It is an error for P1 to be negative. 3692 ** 3693 ** Allowed P5 bits: 3694 ** <ul> 3695 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for 3696 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT 3697 ** of OP_SeekLE/OP_IdxLT) 3698 ** </ul> 3699 ** 3700 ** The P4 value may be either an integer (P4_INT32) or a pointer to 3701 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 3702 ** object, then table being opened must be an [index b-tree] where the 3703 ** KeyInfo object defines the content and collating 3704 ** sequence of that index b-tree. Otherwise, if P4 is an integer 3705 ** value, then the table being opened must be a [table b-tree] with a 3706 ** number of columns no less than the value of P4. 3707 ** 3708 ** See also: OpenWrite, ReopenIdx 3709 */ 3710 /* Opcode: ReopenIdx P1 P2 P3 P4 P5 3711 ** Synopsis: root=P2 iDb=P3 3712 ** 3713 ** The ReopenIdx opcode works like OP_OpenRead except that it first 3714 ** checks to see if the cursor on P1 is already open on the same 3715 ** b-tree and if it is this opcode becomes a no-op. In other words, 3716 ** if the cursor is already open, do not reopen it. 3717 ** 3718 ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ 3719 ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must 3720 ** be the same as every other ReopenIdx or OpenRead for the same cursor 3721 ** number. 3722 ** 3723 ** Allowed P5 bits: 3724 ** <ul> 3725 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for 3726 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT 3727 ** of OP_SeekLE/OP_IdxLT) 3728 ** </ul> 3729 ** 3730 ** See also: OP_OpenRead, OP_OpenWrite 3731 */ 3732 /* Opcode: OpenWrite P1 P2 P3 P4 P5 3733 ** Synopsis: root=P2 iDb=P3 3734 ** 3735 ** Open a read/write cursor named P1 on the table or index whose root 3736 ** page is P2 (or whose root page is held in register P2 if the 3737 ** OPFLAG_P2ISREG bit is set in P5 - see below). 3738 ** 3739 ** The P4 value may be either an integer (P4_INT32) or a pointer to 3740 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 3741 ** object, then table being opened must be an [index b-tree] where the 3742 ** KeyInfo object defines the content and collating 3743 ** sequence of that index b-tree. Otherwise, if P4 is an integer 3744 ** value, then the table being opened must be a [table b-tree] with a 3745 ** number of columns no less than the value of P4. 3746 ** 3747 ** Allowed P5 bits: 3748 ** <ul> 3749 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for 3750 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT 3751 ** of OP_SeekLE/OP_IdxLT) 3752 ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek 3753 ** and subsequently delete entries in an index btree. This is a 3754 ** hint to the storage engine that the storage engine is allowed to 3755 ** ignore. The hint is not used by the official SQLite b*tree storage 3756 ** engine, but is used by COMDB2. 3757 ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2 3758 ** as the root page, not the value of P2 itself. 3759 ** </ul> 3760 ** 3761 ** This instruction works like OpenRead except that it opens the cursor 3762 ** in read/write mode. 3763 ** 3764 ** See also: OP_OpenRead, OP_ReopenIdx 3765 */ 3766 case OP_ReopenIdx: { 3767 int nField; 3768 KeyInfo *pKeyInfo; 3769 u32 p2; 3770 int iDb; 3771 int wrFlag; 3772 Btree *pX; 3773 VdbeCursor *pCur; 3774 Db *pDb; 3775 3776 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ ); 3777 assert( pOp->p4type==P4_KEYINFO ); 3778 pCur = p->apCsr[pOp->p1]; 3779 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){ 3780 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */ 3781 goto open_cursor_set_hints; 3782 } 3783 /* If the cursor is not currently open or is open on a different 3784 ** index, then fall through into OP_OpenRead to force a reopen */ 3785 case OP_OpenRead: 3786 case OP_OpenWrite: 3787 3788 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ ); 3789 assert( p->bIsReader ); 3790 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx 3791 || p->readOnly==0 ); 3792 3793 if( p->expired==1 ){ 3794 rc = SQLITE_ABORT_ROLLBACK; 3795 goto abort_due_to_error; 3796 } 3797 3798 nField = 0; 3799 pKeyInfo = 0; 3800 p2 = (u32)pOp->p2; 3801 iDb = pOp->p3; 3802 assert( iDb>=0 && iDb<db->nDb ); 3803 assert( DbMaskTest(p->btreeMask, iDb) ); 3804 pDb = &db->aDb[iDb]; 3805 pX = pDb->pBt; 3806 assert( pX!=0 ); 3807 if( pOp->opcode==OP_OpenWrite ){ 3808 assert( OPFLAG_FORDELETE==BTREE_FORDELETE ); 3809 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE); 3810 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 3811 if( pDb->pSchema->file_format < p->minWriteFileFormat ){ 3812 p->minWriteFileFormat = pDb->pSchema->file_format; 3813 } 3814 }else{ 3815 wrFlag = 0; 3816 } 3817 if( pOp->p5 & OPFLAG_P2ISREG ){ 3818 assert( p2>0 ); 3819 assert( p2<=(u32)(p->nMem+1 - p->nCursor) ); 3820 assert( pOp->opcode==OP_OpenWrite ); 3821 pIn2 = &aMem[p2]; 3822 assert( memIsValid(pIn2) ); 3823 assert( (pIn2->flags & MEM_Int)!=0 ); 3824 sqlite3VdbeMemIntegerify(pIn2); 3825 p2 = (int)pIn2->u.i; 3826 /* The p2 value always comes from a prior OP_CreateBtree opcode and 3827 ** that opcode will always set the p2 value to 2 or more or else fail. 3828 ** If there were a failure, the prepared statement would have halted 3829 ** before reaching this instruction. */ 3830 assert( p2>=2 ); 3831 } 3832 if( pOp->p4type==P4_KEYINFO ){ 3833 pKeyInfo = pOp->p4.pKeyInfo; 3834 assert( pKeyInfo->enc==ENC(db) ); 3835 assert( pKeyInfo->db==db ); 3836 nField = pKeyInfo->nAllField; 3837 }else if( pOp->p4type==P4_INT32 ){ 3838 nField = pOp->p4.i; 3839 } 3840 assert( pOp->p1>=0 ); 3841 assert( nField>=0 ); 3842 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */ 3843 pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE); 3844 if( pCur==0 ) goto no_mem; 3845 pCur->nullRow = 1; 3846 pCur->isOrdered = 1; 3847 pCur->pgnoRoot = p2; 3848 #ifdef SQLITE_DEBUG 3849 pCur->wrFlag = wrFlag; 3850 #endif 3851 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor); 3852 pCur->pKeyInfo = pKeyInfo; 3853 /* Set the VdbeCursor.isTable variable. Previous versions of 3854 ** SQLite used to check if the root-page flags were sane at this point 3855 ** and report database corruption if they were not, but this check has 3856 ** since moved into the btree layer. */ 3857 pCur->isTable = pOp->p4type!=P4_KEYINFO; 3858 3859 open_cursor_set_hints: 3860 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD ); 3861 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ ); 3862 testcase( pOp->p5 & OPFLAG_BULKCSR ); 3863 testcase( pOp->p2 & OPFLAG_SEEKEQ ); 3864 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor, 3865 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ))); 3866 if( rc ) goto abort_due_to_error; 3867 break; 3868 } 3869 3870 /* Opcode: OpenDup P1 P2 * * * 3871 ** 3872 ** Open a new cursor P1 that points to the same ephemeral table as 3873 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral 3874 ** opcode. Only ephemeral cursors may be duplicated. 3875 ** 3876 ** Duplicate ephemeral cursors are used for self-joins of materialized views. 3877 */ 3878 case OP_OpenDup: { 3879 VdbeCursor *pOrig; /* The original cursor to be duplicated */ 3880 VdbeCursor *pCx; /* The new cursor */ 3881 3882 pOrig = p->apCsr[pOp->p2]; 3883 assert( pOrig ); 3884 assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */ 3885 3886 pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE); 3887 if( pCx==0 ) goto no_mem; 3888 pCx->nullRow = 1; 3889 pCx->isEphemeral = 1; 3890 pCx->pKeyInfo = pOrig->pKeyInfo; 3891 pCx->isTable = pOrig->isTable; 3892 pCx->pgnoRoot = pOrig->pgnoRoot; 3893 pCx->isOrdered = pOrig->isOrdered; 3894 rc = sqlite3BtreeCursor(pOrig->pBtx, pCx->pgnoRoot, BTREE_WRCSR, 3895 pCx->pKeyInfo, pCx->uc.pCursor); 3896 /* The sqlite3BtreeCursor() routine can only fail for the first cursor 3897 ** opened for a database. Since there is already an open cursor when this 3898 ** opcode is run, the sqlite3BtreeCursor() cannot fail */ 3899 assert( rc==SQLITE_OK ); 3900 break; 3901 } 3902 3903 3904 /* Opcode: OpenEphemeral P1 P2 P3 P4 P5 3905 ** Synopsis: nColumn=P2 3906 ** 3907 ** Open a new cursor P1 to a transient table. 3908 ** The cursor is always opened read/write even if 3909 ** the main database is read-only. The ephemeral 3910 ** table is deleted automatically when the cursor is closed. 3911 ** 3912 ** If the cursor P1 is already opened on an ephemeral table, the table 3913 ** is cleared (all content is erased). 3914 ** 3915 ** P2 is the number of columns in the ephemeral table. 3916 ** The cursor points to a BTree table if P4==0 and to a BTree index 3917 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure 3918 ** that defines the format of keys in the index. 3919 ** 3920 ** The P5 parameter can be a mask of the BTREE_* flags defined 3921 ** in btree.h. These flags control aspects of the operation of 3922 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are 3923 ** added automatically. 3924 ** 3925 ** If P3 is positive, then reg[P3] is modified slightly so that it 3926 ** can be used as zero-length data for OP_Insert. This is an optimization 3927 ** that avoids an extra OP_Blob opcode to initialize that register. 3928 */ 3929 /* Opcode: OpenAutoindex P1 P2 * P4 * 3930 ** Synopsis: nColumn=P2 3931 ** 3932 ** This opcode works the same as OP_OpenEphemeral. It has a 3933 ** different name to distinguish its use. Tables created using 3934 ** by this opcode will be used for automatically created transient 3935 ** indices in joins. 3936 */ 3937 case OP_OpenAutoindex: 3938 case OP_OpenEphemeral: { 3939 VdbeCursor *pCx; 3940 KeyInfo *pKeyInfo; 3941 3942 static const int vfsFlags = 3943 SQLITE_OPEN_READWRITE | 3944 SQLITE_OPEN_CREATE | 3945 SQLITE_OPEN_EXCLUSIVE | 3946 SQLITE_OPEN_DELETEONCLOSE | 3947 SQLITE_OPEN_TRANSIENT_DB; 3948 assert( pOp->p1>=0 ); 3949 assert( pOp->p2>=0 ); 3950 if( pOp->p3>0 ){ 3951 /* Make register reg[P3] into a value that can be used as the data 3952 ** form sqlite3BtreeInsert() where the length of the data is zero. */ 3953 assert( pOp->p2==0 ); /* Only used when number of columns is zero */ 3954 assert( pOp->opcode==OP_OpenEphemeral ); 3955 assert( aMem[pOp->p3].flags & MEM_Null ); 3956 aMem[pOp->p3].n = 0; 3957 aMem[pOp->p3].z = ""; 3958 } 3959 pCx = p->apCsr[pOp->p1]; 3960 if( pCx && pCx->pBtx ){ 3961 /* If the ephermeral table is already open, erase all existing content 3962 ** so that the table is empty again, rather than creating a new table. */ 3963 assert( pCx->isEphemeral ); 3964 pCx->seqCount = 0; 3965 pCx->cacheStatus = CACHE_STALE; 3966 rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0); 3967 }else{ 3968 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE); 3969 if( pCx==0 ) goto no_mem; 3970 pCx->isEphemeral = 1; 3971 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx, 3972 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, 3973 vfsFlags); 3974 if( rc==SQLITE_OK ){ 3975 rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0); 3976 } 3977 if( rc==SQLITE_OK ){ 3978 /* If a transient index is required, create it by calling 3979 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before 3980 ** opening it. If a transient table is required, just use the 3981 ** automatically created table with root-page 1 (an BLOB_INTKEY table). 3982 */ 3983 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){ 3984 assert( pOp->p4type==P4_KEYINFO ); 3985 rc = sqlite3BtreeCreateTable(pCx->pBtx, &pCx->pgnoRoot, 3986 BTREE_BLOBKEY | pOp->p5); 3987 if( rc==SQLITE_OK ){ 3988 assert( pCx->pgnoRoot==SCHEMA_ROOT+1 ); 3989 assert( pKeyInfo->db==db ); 3990 assert( pKeyInfo->enc==ENC(db) ); 3991 rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR, 3992 pKeyInfo, pCx->uc.pCursor); 3993 } 3994 pCx->isTable = 0; 3995 }else{ 3996 pCx->pgnoRoot = SCHEMA_ROOT; 3997 rc = sqlite3BtreeCursor(pCx->pBtx, SCHEMA_ROOT, BTREE_WRCSR, 3998 0, pCx->uc.pCursor); 3999 pCx->isTable = 1; 4000 } 4001 } 4002 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED); 4003 } 4004 if( rc ) goto abort_due_to_error; 4005 pCx->nullRow = 1; 4006 break; 4007 } 4008 4009 /* Opcode: SorterOpen P1 P2 P3 P4 * 4010 ** 4011 ** This opcode works like OP_OpenEphemeral except that it opens 4012 ** a transient index that is specifically designed to sort large 4013 ** tables using an external merge-sort algorithm. 4014 ** 4015 ** If argument P3 is non-zero, then it indicates that the sorter may 4016 ** assume that a stable sort considering the first P3 fields of each 4017 ** key is sufficient to produce the required results. 4018 */ 4019 case OP_SorterOpen: { 4020 VdbeCursor *pCx; 4021 4022 assert( pOp->p1>=0 ); 4023 assert( pOp->p2>=0 ); 4024 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER); 4025 if( pCx==0 ) goto no_mem; 4026 pCx->pKeyInfo = pOp->p4.pKeyInfo; 4027 assert( pCx->pKeyInfo->db==db ); 4028 assert( pCx->pKeyInfo->enc==ENC(db) ); 4029 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx); 4030 if( rc ) goto abort_due_to_error; 4031 break; 4032 } 4033 4034 /* Opcode: SequenceTest P1 P2 * * * 4035 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2 4036 ** 4037 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump 4038 ** to P2. Regardless of whether or not the jump is taken, increment the 4039 ** the sequence value. 4040 */ 4041 case OP_SequenceTest: { 4042 VdbeCursor *pC; 4043 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4044 pC = p->apCsr[pOp->p1]; 4045 assert( isSorter(pC) ); 4046 if( (pC->seqCount++)==0 ){ 4047 goto jump_to_p2; 4048 } 4049 break; 4050 } 4051 4052 /* Opcode: OpenPseudo P1 P2 P3 * * 4053 ** Synopsis: P3 columns in r[P2] 4054 ** 4055 ** Open a new cursor that points to a fake table that contains a single 4056 ** row of data. The content of that one row is the content of memory 4057 ** register P2. In other words, cursor P1 becomes an alias for the 4058 ** MEM_Blob content contained in register P2. 4059 ** 4060 ** A pseudo-table created by this opcode is used to hold a single 4061 ** row output from the sorter so that the row can be decomposed into 4062 ** individual columns using the OP_Column opcode. The OP_Column opcode 4063 ** is the only cursor opcode that works with a pseudo-table. 4064 ** 4065 ** P3 is the number of fields in the records that will be stored by 4066 ** the pseudo-table. 4067 */ 4068 case OP_OpenPseudo: { 4069 VdbeCursor *pCx; 4070 4071 assert( pOp->p1>=0 ); 4072 assert( pOp->p3>=0 ); 4073 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO); 4074 if( pCx==0 ) goto no_mem; 4075 pCx->nullRow = 1; 4076 pCx->seekResult = pOp->p2; 4077 pCx->isTable = 1; 4078 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx 4079 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test 4080 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto() 4081 ** which is a performance optimization */ 4082 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor(); 4083 assert( pOp->p5==0 ); 4084 break; 4085 } 4086 4087 /* Opcode: Close P1 * * * * 4088 ** 4089 ** Close a cursor previously opened as P1. If P1 is not 4090 ** currently open, this instruction is a no-op. 4091 */ 4092 case OP_Close: { 4093 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4094 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]); 4095 p->apCsr[pOp->p1] = 0; 4096 break; 4097 } 4098 4099 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK 4100 /* Opcode: ColumnsUsed P1 * * P4 * 4101 ** 4102 ** This opcode (which only exists if SQLite was compiled with 4103 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the 4104 ** table or index for cursor P1 are used. P4 is a 64-bit integer 4105 ** (P4_INT64) in which the first 63 bits are one for each of the 4106 ** first 63 columns of the table or index that are actually used 4107 ** by the cursor. The high-order bit is set if any column after 4108 ** the 64th is used. 4109 */ 4110 case OP_ColumnsUsed: { 4111 VdbeCursor *pC; 4112 pC = p->apCsr[pOp->p1]; 4113 assert( pC->eCurType==CURTYPE_BTREE ); 4114 pC->maskUsed = *(u64*)pOp->p4.pI64; 4115 break; 4116 } 4117 #endif 4118 4119 /* Opcode: SeekGE P1 P2 P3 P4 * 4120 ** Synopsis: key=r[P3@P4] 4121 ** 4122 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 4123 ** use the value in register P3 as the key. If cursor P1 refers 4124 ** to an SQL index, then P3 is the first in an array of P4 registers 4125 ** that are used as an unpacked index key. 4126 ** 4127 ** Reposition cursor P1 so that it points to the smallest entry that 4128 ** is greater than or equal to the key value. If there are no records 4129 ** greater than or equal to the key and P2 is not zero, then jump to P2. 4130 ** 4131 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this 4132 ** opcode will either land on a record that exactly matches the key, or 4133 ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ, 4134 ** this opcode must be followed by an IdxLE opcode with the same arguments. 4135 ** The IdxGT opcode will be skipped if this opcode succeeds, but the 4136 ** IdxGT opcode will be used on subsequent loop iterations. The 4137 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this 4138 ** is an equality search. 4139 ** 4140 ** This opcode leaves the cursor configured to move in forward order, 4141 ** from the beginning toward the end. In other words, the cursor is 4142 ** configured to use Next, not Prev. 4143 ** 4144 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe 4145 */ 4146 /* Opcode: SeekGT P1 P2 P3 P4 * 4147 ** Synopsis: key=r[P3@P4] 4148 ** 4149 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 4150 ** use the value in register P3 as a key. If cursor P1 refers 4151 ** to an SQL index, then P3 is the first in an array of P4 registers 4152 ** that are used as an unpacked index key. 4153 ** 4154 ** Reposition cursor P1 so that it points to the smallest entry that 4155 ** is greater than the key value. If there are no records greater than 4156 ** the key and P2 is not zero, then jump to P2. 4157 ** 4158 ** This opcode leaves the cursor configured to move in forward order, 4159 ** from the beginning toward the end. In other words, the cursor is 4160 ** configured to use Next, not Prev. 4161 ** 4162 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe 4163 */ 4164 /* Opcode: SeekLT P1 P2 P3 P4 * 4165 ** Synopsis: key=r[P3@P4] 4166 ** 4167 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 4168 ** use the value in register P3 as a key. If cursor P1 refers 4169 ** to an SQL index, then P3 is the first in an array of P4 registers 4170 ** that are used as an unpacked index key. 4171 ** 4172 ** Reposition cursor P1 so that it points to the largest entry that 4173 ** is less than the key value. If there are no records less than 4174 ** the key and P2 is not zero, then jump to P2. 4175 ** 4176 ** This opcode leaves the cursor configured to move in reverse order, 4177 ** from the end toward the beginning. In other words, the cursor is 4178 ** configured to use Prev, not Next. 4179 ** 4180 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe 4181 */ 4182 /* Opcode: SeekLE P1 P2 P3 P4 * 4183 ** Synopsis: key=r[P3@P4] 4184 ** 4185 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 4186 ** use the value in register P3 as a key. If cursor P1 refers 4187 ** to an SQL index, then P3 is the first in an array of P4 registers 4188 ** that are used as an unpacked index key. 4189 ** 4190 ** Reposition cursor P1 so that it points to the largest entry that 4191 ** is less than or equal to the key value. If there are no records 4192 ** less than or equal to the key and P2 is not zero, then jump to P2. 4193 ** 4194 ** This opcode leaves the cursor configured to move in reverse order, 4195 ** from the end toward the beginning. In other words, the cursor is 4196 ** configured to use Prev, not Next. 4197 ** 4198 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this 4199 ** opcode will either land on a record that exactly matches the key, or 4200 ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ, 4201 ** this opcode must be followed by an IdxLE opcode with the same arguments. 4202 ** The IdxGE opcode will be skipped if this opcode succeeds, but the 4203 ** IdxGE opcode will be used on subsequent loop iterations. The 4204 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this 4205 ** is an equality search. 4206 ** 4207 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt 4208 */ 4209 case OP_SeekLT: /* jump, in3, group */ 4210 case OP_SeekLE: /* jump, in3, group */ 4211 case OP_SeekGE: /* jump, in3, group */ 4212 case OP_SeekGT: { /* jump, in3, group */ 4213 int res; /* Comparison result */ 4214 int oc; /* Opcode */ 4215 VdbeCursor *pC; /* The cursor to seek */ 4216 UnpackedRecord r; /* The key to seek for */ 4217 int nField; /* Number of columns or fields in the key */ 4218 i64 iKey; /* The rowid we are to seek to */ 4219 int eqOnly; /* Only interested in == results */ 4220 4221 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4222 assert( pOp->p2!=0 ); 4223 pC = p->apCsr[pOp->p1]; 4224 assert( pC!=0 ); 4225 assert( pC->eCurType==CURTYPE_BTREE ); 4226 assert( OP_SeekLE == OP_SeekLT+1 ); 4227 assert( OP_SeekGE == OP_SeekLT+2 ); 4228 assert( OP_SeekGT == OP_SeekLT+3 ); 4229 assert( pC->isOrdered ); 4230 assert( pC->uc.pCursor!=0 ); 4231 oc = pOp->opcode; 4232 eqOnly = 0; 4233 pC->nullRow = 0; 4234 #ifdef SQLITE_DEBUG 4235 pC->seekOp = pOp->opcode; 4236 #endif 4237 4238 pC->deferredMoveto = 0; 4239 pC->cacheStatus = CACHE_STALE; 4240 if( pC->isTable ){ 4241 u16 flags3, newType; 4242 /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */ 4243 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 4244 || CORRUPT_DB ); 4245 4246 /* The input value in P3 might be of any type: integer, real, string, 4247 ** blob, or NULL. But it needs to be an integer before we can do 4248 ** the seek, so convert it. */ 4249 pIn3 = &aMem[pOp->p3]; 4250 flags3 = pIn3->flags; 4251 if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){ 4252 applyNumericAffinity(pIn3, 0); 4253 } 4254 iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */ 4255 newType = pIn3->flags; /* Record the type after applying numeric affinity */ 4256 pIn3->flags = flags3; /* But convert the type back to its original */ 4257 4258 /* If the P3 value could not be converted into an integer without 4259 ** loss of information, then special processing is required... */ 4260 if( (newType & (MEM_Int|MEM_IntReal))==0 ){ 4261 if( (newType & MEM_Real)==0 ){ 4262 if( (newType & MEM_Null) || oc>=OP_SeekGE ){ 4263 VdbeBranchTaken(1,2); 4264 goto jump_to_p2; 4265 }else{ 4266 rc = sqlite3BtreeLast(pC->uc.pCursor, &res); 4267 if( rc!=SQLITE_OK ) goto abort_due_to_error; 4268 goto seek_not_found; 4269 } 4270 }else 4271 4272 /* If the approximation iKey is larger than the actual real search 4273 ** term, substitute >= for > and < for <=. e.g. if the search term 4274 ** is 4.9 and the integer approximation 5: 4275 ** 4276 ** (x > 4.9) -> (x >= 5) 4277 ** (x <= 4.9) -> (x < 5) 4278 */ 4279 if( pIn3->u.r<(double)iKey ){ 4280 assert( OP_SeekGE==(OP_SeekGT-1) ); 4281 assert( OP_SeekLT==(OP_SeekLE-1) ); 4282 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) ); 4283 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--; 4284 } 4285 4286 /* If the approximation iKey is smaller than the actual real search 4287 ** term, substitute <= for < and > for >=. */ 4288 else if( pIn3->u.r>(double)iKey ){ 4289 assert( OP_SeekLE==(OP_SeekLT+1) ); 4290 assert( OP_SeekGT==(OP_SeekGE+1) ); 4291 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) ); 4292 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++; 4293 } 4294 } 4295 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res); 4296 pC->movetoTarget = iKey; /* Used by OP_Delete */ 4297 if( rc!=SQLITE_OK ){ 4298 goto abort_due_to_error; 4299 } 4300 }else{ 4301 /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the 4302 ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be 4303 ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively, 4304 ** with the same key. 4305 */ 4306 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){ 4307 eqOnly = 1; 4308 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE ); 4309 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT ); 4310 assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT ); 4311 assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT ); 4312 assert( pOp[1].p1==pOp[0].p1 ); 4313 assert( pOp[1].p2==pOp[0].p2 ); 4314 assert( pOp[1].p3==pOp[0].p3 ); 4315 assert( pOp[1].p4.i==pOp[0].p4.i ); 4316 } 4317 4318 nField = pOp->p4.i; 4319 assert( pOp->p4type==P4_INT32 ); 4320 assert( nField>0 ); 4321 r.pKeyInfo = pC->pKeyInfo; 4322 r.nField = (u16)nField; 4323 4324 /* The next line of code computes as follows, only faster: 4325 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){ 4326 ** r.default_rc = -1; 4327 ** }else{ 4328 ** r.default_rc = +1; 4329 ** } 4330 */ 4331 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1); 4332 assert( oc!=OP_SeekGT || r.default_rc==-1 ); 4333 assert( oc!=OP_SeekLE || r.default_rc==-1 ); 4334 assert( oc!=OP_SeekGE || r.default_rc==+1 ); 4335 assert( oc!=OP_SeekLT || r.default_rc==+1 ); 4336 4337 r.aMem = &aMem[pOp->p3]; 4338 #ifdef SQLITE_DEBUG 4339 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); } 4340 #endif 4341 r.eqSeen = 0; 4342 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res); 4343 if( rc!=SQLITE_OK ){ 4344 goto abort_due_to_error; 4345 } 4346 if( eqOnly && r.eqSeen==0 ){ 4347 assert( res!=0 ); 4348 goto seek_not_found; 4349 } 4350 } 4351 #ifdef SQLITE_TEST 4352 sqlite3_search_count++; 4353 #endif 4354 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT ); 4355 if( res<0 || (res==0 && oc==OP_SeekGT) ){ 4356 res = 0; 4357 rc = sqlite3BtreeNext(pC->uc.pCursor, 0); 4358 if( rc!=SQLITE_OK ){ 4359 if( rc==SQLITE_DONE ){ 4360 rc = SQLITE_OK; 4361 res = 1; 4362 }else{ 4363 goto abort_due_to_error; 4364 } 4365 } 4366 }else{ 4367 res = 0; 4368 } 4369 }else{ 4370 assert( oc==OP_SeekLT || oc==OP_SeekLE ); 4371 if( res>0 || (res==0 && oc==OP_SeekLT) ){ 4372 res = 0; 4373 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0); 4374 if( rc!=SQLITE_OK ){ 4375 if( rc==SQLITE_DONE ){ 4376 rc = SQLITE_OK; 4377 res = 1; 4378 }else{ 4379 goto abort_due_to_error; 4380 } 4381 } 4382 }else{ 4383 /* res might be negative because the table is empty. Check to 4384 ** see if this is the case. 4385 */ 4386 res = sqlite3BtreeEof(pC->uc.pCursor); 4387 } 4388 } 4389 seek_not_found: 4390 assert( pOp->p2>0 ); 4391 VdbeBranchTaken(res!=0,2); 4392 if( res ){ 4393 goto jump_to_p2; 4394 }else if( eqOnly ){ 4395 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT ); 4396 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */ 4397 } 4398 break; 4399 } 4400 4401 4402 /* Opcode: SeekScan P1 P2 * * * 4403 ** Synopsis: Scan-ahead up to P1 rows 4404 ** 4405 ** This opcode is a prefix opcode to OP_SeekGE. In other words, this 4406 ** opcode must be immediately followed by OP_SeekGE. This constraint is 4407 ** checked by assert() statements. 4408 ** 4409 ** This opcode uses the P1 through P4 operands of the subsequent 4410 ** OP_SeekGE. In the text that follows, the operands of the subsequent 4411 ** OP_SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4. Only 4412 ** the P1 and P2 operands of this opcode are also used, and are called 4413 ** This.P1 and This.P2. 4414 ** 4415 ** This opcode helps to optimize IN operators on a multi-column index 4416 ** where the IN operator is on the later terms of the index by avoiding 4417 ** unnecessary seeks on the btree, substituting steps to the next row 4418 ** of the b-tree instead. A correct answer is obtained if this opcode 4419 ** is omitted or is a no-op. 4420 ** 4421 ** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which 4422 ** is the desired entry that we want the cursor SeekGE.P1 to be pointing 4423 ** to. Call this SeekGE.P4/P5 row the "target". 4424 ** 4425 ** If the SeekGE.P1 cursor is not currently pointing to a valid row, 4426 ** then this opcode is a no-op and control passes through into the OP_SeekGE. 4427 ** 4428 ** If the SeekGE.P1 cursor is pointing to a valid row, then that row 4429 ** might be the target row, or it might be near and slightly before the 4430 ** target row. This opcode attempts to position the cursor on the target 4431 ** row by, perhaps by invoking sqlite3BtreeStep() on the cursor 4432 ** between 0 and This.P1 times. 4433 ** 4434 ** There are three possible outcomes from this opcode:<ol> 4435 ** 4436 ** <li> If after This.P1 steps, the cursor is still point to a place that 4437 ** is earlier in the btree than the target row, 4438 ** then fall through into the subsquence OP_SeekGE opcode. 4439 ** 4440 ** <li> If the cursor is successfully moved to the target row by 0 or more 4441 ** sqlite3BtreeNext() calls, then jump to This.P2, which will land just 4442 ** past the OP_IdxGT opcode that follows the OP_SeekGE. 4443 ** 4444 ** <li> If the cursor ends up past the target row (indicating the the target 4445 ** row does not exist in the btree) then jump to SeekOP.P2. 4446 ** </ol> 4447 */ 4448 case OP_SeekScan: { 4449 VdbeCursor *pC; 4450 int res; 4451 int nStep; 4452 UnpackedRecord r; 4453 4454 assert( pOp[1].opcode==OP_SeekGE ); 4455 4456 /* pOp->p2 points to the first instruction past the OP_IdxGT that 4457 ** follows the OP_SeekGE. */ 4458 assert( pOp->p2>=(int)(pOp-aOp)+2 ); 4459 assert( aOp[pOp->p2-1].opcode==OP_IdxGT ); 4460 assert( pOp[1].p1==aOp[pOp->p2-1].p1 ); 4461 assert( pOp[1].p2==aOp[pOp->p2-1].p2 ); 4462 assert( pOp[1].p3==aOp[pOp->p2-1].p3 ); 4463 4464 assert( pOp->p1>0 ); 4465 pC = p->apCsr[pOp[1].p1]; 4466 assert( pC!=0 ); 4467 assert( pC->eCurType==CURTYPE_BTREE ); 4468 assert( !pC->isTable ); 4469 if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){ 4470 #ifdef SQLITE_DEBUG 4471 if( db->flags&SQLITE_VdbeTrace ){ 4472 printf("... cursor not valid - fall through\n"); 4473 } 4474 #endif 4475 break; 4476 } 4477 nStep = pOp->p1; 4478 assert( nStep>=1 ); 4479 r.pKeyInfo = pC->pKeyInfo; 4480 r.nField = (u16)pOp[1].p4.i; 4481 r.default_rc = 0; 4482 r.aMem = &aMem[pOp[1].p3]; 4483 #ifdef SQLITE_DEBUG 4484 { 4485 int i; 4486 for(i=0; i<r.nField; i++){ 4487 assert( memIsValid(&r.aMem[i]) ); 4488 REGISTER_TRACE(pOp[1].p3+i, &aMem[pOp[1].p3+i]); 4489 } 4490 } 4491 #endif 4492 res = 0; /* Not needed. Only used to silence a warning. */ 4493 while(1){ 4494 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res); 4495 if( rc ) goto abort_due_to_error; 4496 if( res>0 ){ 4497 seekscan_search_fail: 4498 #ifdef SQLITE_DEBUG 4499 if( db->flags&SQLITE_VdbeTrace ){ 4500 printf("... %d steps and then skip\n", pOp->p1 - nStep); 4501 } 4502 #endif 4503 VdbeBranchTaken(1,3); 4504 pOp++; 4505 goto jump_to_p2; 4506 } 4507 if( res==0 ){ 4508 #ifdef SQLITE_DEBUG 4509 if( db->flags&SQLITE_VdbeTrace ){ 4510 printf("... %d steps and then success\n", pOp->p1 - nStep); 4511 } 4512 #endif 4513 VdbeBranchTaken(2,3); 4514 goto jump_to_p2; 4515 break; 4516 } 4517 if( nStep<=0 ){ 4518 #ifdef SQLITE_DEBUG 4519 if( db->flags&SQLITE_VdbeTrace ){ 4520 printf("... fall through after %d steps\n", pOp->p1); 4521 } 4522 #endif 4523 VdbeBranchTaken(0,3); 4524 break; 4525 } 4526 nStep--; 4527 rc = sqlite3BtreeNext(pC->uc.pCursor, 0); 4528 if( rc ){ 4529 if( rc==SQLITE_DONE ){ 4530 rc = SQLITE_OK; 4531 goto seekscan_search_fail; 4532 }else{ 4533 goto abort_due_to_error; 4534 } 4535 } 4536 } 4537 4538 break; 4539 } 4540 4541 4542 /* Opcode: SeekHit P1 P2 P3 * * 4543 ** Synopsis: set P2<=seekHit<=P3 4544 ** 4545 ** Increase or decrease the seekHit value for cursor P1, if necessary, 4546 ** so that it is no less than P2 and no greater than P3. 4547 ** 4548 ** The seekHit integer represents the maximum of terms in an index for which 4549 ** there is known to be at least one match. If the seekHit value is smaller 4550 ** than the total number of equality terms in an index lookup, then the 4551 ** OP_IfNoHope opcode might run to see if the IN loop can be abandoned 4552 ** early, thus saving work. This is part of the IN-early-out optimization. 4553 ** 4554 ** P1 must be a valid b-tree cursor. 4555 */ 4556 case OP_SeekHit: { 4557 VdbeCursor *pC; 4558 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4559 pC = p->apCsr[pOp->p1]; 4560 assert( pC!=0 ); 4561 assert( pOp->p3>=pOp->p2 ); 4562 if( pC->seekHit<pOp->p2 ){ 4563 pC->seekHit = pOp->p2; 4564 }else if( pC->seekHit>pOp->p3 ){ 4565 pC->seekHit = pOp->p3; 4566 } 4567 break; 4568 } 4569 4570 /* Opcode: IfNotOpen P1 P2 * * * 4571 ** Synopsis: if( !csr[P1] ) goto P2 4572 ** 4573 ** If cursor P1 is not open, jump to instruction P2. Otherwise, fall through. 4574 */ 4575 case OP_IfNotOpen: { /* jump */ 4576 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4577 VdbeBranchTaken(p->apCsr[pOp->p1]==0, 2); 4578 if( !p->apCsr[pOp->p1] ){ 4579 goto jump_to_p2_and_check_for_interrupt; 4580 } 4581 break; 4582 } 4583 4584 /* Opcode: Found P1 P2 P3 P4 * 4585 ** Synopsis: key=r[P3@P4] 4586 ** 4587 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If 4588 ** P4>0 then register P3 is the first of P4 registers that form an unpacked 4589 ** record. 4590 ** 4591 ** Cursor P1 is on an index btree. If the record identified by P3 and P4 4592 ** is a prefix of any entry in P1 then a jump is made to P2 and 4593 ** P1 is left pointing at the matching entry. 4594 ** 4595 ** This operation leaves the cursor in a state where it can be 4596 ** advanced in the forward direction. The Next instruction will work, 4597 ** but not the Prev instruction. 4598 ** 4599 ** See also: NotFound, NoConflict, NotExists. SeekGe 4600 */ 4601 /* Opcode: NotFound P1 P2 P3 P4 * 4602 ** Synopsis: key=r[P3@P4] 4603 ** 4604 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If 4605 ** P4>0 then register P3 is the first of P4 registers that form an unpacked 4606 ** record. 4607 ** 4608 ** Cursor P1 is on an index btree. If the record identified by P3 and P4 4609 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1 4610 ** does contain an entry whose prefix matches the P3/P4 record then control 4611 ** falls through to the next instruction and P1 is left pointing at the 4612 ** matching entry. 4613 ** 4614 ** This operation leaves the cursor in a state where it cannot be 4615 ** advanced in either direction. In other words, the Next and Prev 4616 ** opcodes do not work after this operation. 4617 ** 4618 ** See also: Found, NotExists, NoConflict, IfNoHope 4619 */ 4620 /* Opcode: IfNoHope P1 P2 P3 P4 * 4621 ** Synopsis: key=r[P3@P4] 4622 ** 4623 ** Register P3 is the first of P4 registers that form an unpacked 4624 ** record. Cursor P1 is an index btree. P2 is a jump destination. 4625 ** In other words, the operands to this opcode are the same as the 4626 ** operands to OP_NotFound and OP_IdxGT. 4627 ** 4628 ** This opcode is an optimization attempt only. If this opcode always 4629 ** falls through, the correct answer is still obtained, but extra works 4630 ** is performed. 4631 ** 4632 ** A value of N in the seekHit flag of cursor P1 means that there exists 4633 ** a key P3:N that will match some record in the index. We want to know 4634 ** if it is possible for a record P3:P4 to match some record in the 4635 ** index. If it is not possible, we can skips some work. So if seekHit 4636 ** is less than P4, attempt to find out if a match is possible by running 4637 ** OP_NotFound. 4638 ** 4639 ** This opcode is used in IN clause processing for a multi-column key. 4640 ** If an IN clause is attached to an element of the key other than the 4641 ** left-most element, and if there are no matches on the most recent 4642 ** seek over the whole key, then it might be that one of the key element 4643 ** to the left is prohibiting a match, and hence there is "no hope" of 4644 ** any match regardless of how many IN clause elements are checked. 4645 ** In such a case, we abandon the IN clause search early, using this 4646 ** opcode. The opcode name comes from the fact that the 4647 ** jump is taken if there is "no hope" of achieving a match. 4648 ** 4649 ** See also: NotFound, SeekHit 4650 */ 4651 /* Opcode: NoConflict P1 P2 P3 P4 * 4652 ** Synopsis: key=r[P3@P4] 4653 ** 4654 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If 4655 ** P4>0 then register P3 is the first of P4 registers that form an unpacked 4656 ** record. 4657 ** 4658 ** Cursor P1 is on an index btree. If the record identified by P3 and P4 4659 ** contains any NULL value, jump immediately to P2. If all terms of the 4660 ** record are not-NULL then a check is done to determine if any row in the 4661 ** P1 index btree has a matching key prefix. If there are no matches, jump 4662 ** immediately to P2. If there is a match, fall through and leave the P1 4663 ** cursor pointing to the matching row. 4664 ** 4665 ** This opcode is similar to OP_NotFound with the exceptions that the 4666 ** branch is always taken if any part of the search key input is NULL. 4667 ** 4668 ** This operation leaves the cursor in a state where it cannot be 4669 ** advanced in either direction. In other words, the Next and Prev 4670 ** opcodes do not work after this operation. 4671 ** 4672 ** See also: NotFound, Found, NotExists 4673 */ 4674 case OP_IfNoHope: { /* jump, in3 */ 4675 VdbeCursor *pC; 4676 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4677 pC = p->apCsr[pOp->p1]; 4678 assert( pC!=0 ); 4679 if( pC->seekHit>=pOp->p4.i ) break; 4680 /* Fall through into OP_NotFound */ 4681 /* no break */ deliberate_fall_through 4682 } 4683 case OP_NoConflict: /* jump, in3 */ 4684 case OP_NotFound: /* jump, in3 */ 4685 case OP_Found: { /* jump, in3 */ 4686 int alreadyExists; 4687 int takeJump; 4688 int ii; 4689 VdbeCursor *pC; 4690 int res; 4691 UnpackedRecord *pFree; 4692 UnpackedRecord *pIdxKey; 4693 UnpackedRecord r; 4694 4695 #ifdef SQLITE_TEST 4696 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++; 4697 #endif 4698 4699 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4700 assert( pOp->p4type==P4_INT32 ); 4701 pC = p->apCsr[pOp->p1]; 4702 assert( pC!=0 ); 4703 #ifdef SQLITE_DEBUG 4704 pC->seekOp = pOp->opcode; 4705 #endif 4706 pIn3 = &aMem[pOp->p3]; 4707 assert( pC->eCurType==CURTYPE_BTREE ); 4708 assert( pC->uc.pCursor!=0 ); 4709 assert( pC->isTable==0 ); 4710 if( pOp->p4.i>0 ){ 4711 r.pKeyInfo = pC->pKeyInfo; 4712 r.nField = (u16)pOp->p4.i; 4713 r.aMem = pIn3; 4714 #ifdef SQLITE_DEBUG 4715 for(ii=0; ii<r.nField; ii++){ 4716 assert( memIsValid(&r.aMem[ii]) ); 4717 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 ); 4718 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]); 4719 } 4720 #endif 4721 pIdxKey = &r; 4722 pFree = 0; 4723 }else{ 4724 assert( pIn3->flags & MEM_Blob ); 4725 rc = ExpandBlob(pIn3); 4726 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); 4727 if( rc ) goto no_mem; 4728 pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo); 4729 if( pIdxKey==0 ) goto no_mem; 4730 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey); 4731 } 4732 pIdxKey->default_rc = 0; 4733 takeJump = 0; 4734 if( pOp->opcode==OP_NoConflict ){ 4735 /* For the OP_NoConflict opcode, take the jump if any of the 4736 ** input fields are NULL, since any key with a NULL will not 4737 ** conflict */ 4738 for(ii=0; ii<pIdxKey->nField; ii++){ 4739 if( pIdxKey->aMem[ii].flags & MEM_Null ){ 4740 takeJump = 1; 4741 break; 4742 } 4743 } 4744 } 4745 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res); 4746 if( pFree ) sqlite3DbFreeNN(db, pFree); 4747 if( rc!=SQLITE_OK ){ 4748 goto abort_due_to_error; 4749 } 4750 pC->seekResult = res; 4751 alreadyExists = (res==0); 4752 pC->nullRow = 1-alreadyExists; 4753 pC->deferredMoveto = 0; 4754 pC->cacheStatus = CACHE_STALE; 4755 if( pOp->opcode==OP_Found ){ 4756 VdbeBranchTaken(alreadyExists!=0,2); 4757 if( alreadyExists ) goto jump_to_p2; 4758 }else{ 4759 VdbeBranchTaken(takeJump||alreadyExists==0,2); 4760 if( takeJump || !alreadyExists ) goto jump_to_p2; 4761 if( pOp->opcode==OP_IfNoHope ) pC->seekHit = pOp->p4.i; 4762 } 4763 break; 4764 } 4765 4766 /* Opcode: SeekRowid P1 P2 P3 * * 4767 ** Synopsis: intkey=r[P3] 4768 ** 4769 ** P1 is the index of a cursor open on an SQL table btree (with integer 4770 ** keys). If register P3 does not contain an integer or if P1 does not 4771 ** contain a record with rowid P3 then jump immediately to P2. 4772 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain 4773 ** a record with rowid P3 then 4774 ** leave the cursor pointing at that record and fall through to the next 4775 ** instruction. 4776 ** 4777 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists 4778 ** the P3 register must be guaranteed to contain an integer value. With this 4779 ** opcode, register P3 might not contain an integer. 4780 ** 4781 ** The OP_NotFound opcode performs the same operation on index btrees 4782 ** (with arbitrary multi-value keys). 4783 ** 4784 ** This opcode leaves the cursor in a state where it cannot be advanced 4785 ** in either direction. In other words, the Next and Prev opcodes will 4786 ** not work following this opcode. 4787 ** 4788 ** See also: Found, NotFound, NoConflict, SeekRowid 4789 */ 4790 /* Opcode: NotExists P1 P2 P3 * * 4791 ** Synopsis: intkey=r[P3] 4792 ** 4793 ** P1 is the index of a cursor open on an SQL table btree (with integer 4794 ** keys). P3 is an integer rowid. If P1 does not contain a record with 4795 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an 4796 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then 4797 ** leave the cursor pointing at that record and fall through to the next 4798 ** instruction. 4799 ** 4800 ** The OP_SeekRowid opcode performs the same operation but also allows the 4801 ** P3 register to contain a non-integer value, in which case the jump is 4802 ** always taken. This opcode requires that P3 always contain an integer. 4803 ** 4804 ** The OP_NotFound opcode performs the same operation on index btrees 4805 ** (with arbitrary multi-value keys). 4806 ** 4807 ** This opcode leaves the cursor in a state where it cannot be advanced 4808 ** in either direction. In other words, the Next and Prev opcodes will 4809 ** not work following this opcode. 4810 ** 4811 ** See also: Found, NotFound, NoConflict, SeekRowid 4812 */ 4813 case OP_SeekRowid: { /* jump, in3 */ 4814 VdbeCursor *pC; 4815 BtCursor *pCrsr; 4816 int res; 4817 u64 iKey; 4818 4819 pIn3 = &aMem[pOp->p3]; 4820 testcase( pIn3->flags & MEM_Int ); 4821 testcase( pIn3->flags & MEM_IntReal ); 4822 testcase( pIn3->flags & MEM_Real ); 4823 testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str ); 4824 if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){ 4825 /* If pIn3->u.i does not contain an integer, compute iKey as the 4826 ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted 4827 ** into an integer without loss of information. Take care to avoid 4828 ** changing the datatype of pIn3, however, as it is used by other 4829 ** parts of the prepared statement. */ 4830 Mem x = pIn3[0]; 4831 applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding); 4832 if( (x.flags & MEM_Int)==0 ) goto jump_to_p2; 4833 iKey = x.u.i; 4834 goto notExistsWithKey; 4835 } 4836 /* Fall through into OP_NotExists */ 4837 /* no break */ deliberate_fall_through 4838 case OP_NotExists: /* jump, in3 */ 4839 pIn3 = &aMem[pOp->p3]; 4840 assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid ); 4841 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4842 iKey = pIn3->u.i; 4843 notExistsWithKey: 4844 pC = p->apCsr[pOp->p1]; 4845 assert( pC!=0 ); 4846 #ifdef SQLITE_DEBUG 4847 if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid; 4848 #endif 4849 assert( pC->isTable ); 4850 assert( pC->eCurType==CURTYPE_BTREE ); 4851 pCrsr = pC->uc.pCursor; 4852 assert( pCrsr!=0 ); 4853 res = 0; 4854 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res); 4855 assert( rc==SQLITE_OK || res==0 ); 4856 pC->movetoTarget = iKey; /* Used by OP_Delete */ 4857 pC->nullRow = 0; 4858 pC->cacheStatus = CACHE_STALE; 4859 pC->deferredMoveto = 0; 4860 VdbeBranchTaken(res!=0,2); 4861 pC->seekResult = res; 4862 if( res!=0 ){ 4863 assert( rc==SQLITE_OK ); 4864 if( pOp->p2==0 ){ 4865 rc = SQLITE_CORRUPT_BKPT; 4866 }else{ 4867 goto jump_to_p2; 4868 } 4869 } 4870 if( rc ) goto abort_due_to_error; 4871 break; 4872 } 4873 4874 /* Opcode: Sequence P1 P2 * * * 4875 ** Synopsis: r[P2]=cursor[P1].ctr++ 4876 ** 4877 ** Find the next available sequence number for cursor P1. 4878 ** Write the sequence number into register P2. 4879 ** The sequence number on the cursor is incremented after this 4880 ** instruction. 4881 */ 4882 case OP_Sequence: { /* out2 */ 4883 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4884 assert( p->apCsr[pOp->p1]!=0 ); 4885 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB ); 4886 pOut = out2Prerelease(p, pOp); 4887 pOut->u.i = p->apCsr[pOp->p1]->seqCount++; 4888 break; 4889 } 4890 4891 4892 /* Opcode: NewRowid P1 P2 P3 * * 4893 ** Synopsis: r[P2]=rowid 4894 ** 4895 ** Get a new integer record number (a.k.a "rowid") used as the key to a table. 4896 ** The record number is not previously used as a key in the database 4897 ** table that cursor P1 points to. The new record number is written 4898 ** written to register P2. 4899 ** 4900 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 4901 ** the largest previously generated record number. No new record numbers are 4902 ** allowed to be less than this value. When this value reaches its maximum, 4903 ** an SQLITE_FULL error is generated. The P3 register is updated with the ' 4904 ** generated record number. This P3 mechanism is used to help implement the 4905 ** AUTOINCREMENT feature. 4906 */ 4907 case OP_NewRowid: { /* out2 */ 4908 i64 v; /* The new rowid */ 4909 VdbeCursor *pC; /* Cursor of table to get the new rowid */ 4910 int res; /* Result of an sqlite3BtreeLast() */ 4911 int cnt; /* Counter to limit the number of searches */ 4912 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */ 4913 VdbeFrame *pFrame; /* Root frame of VDBE */ 4914 4915 v = 0; 4916 res = 0; 4917 pOut = out2Prerelease(p, pOp); 4918 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4919 pC = p->apCsr[pOp->p1]; 4920 assert( pC!=0 ); 4921 assert( pC->isTable ); 4922 assert( pC->eCurType==CURTYPE_BTREE ); 4923 assert( pC->uc.pCursor!=0 ); 4924 { 4925 /* The next rowid or record number (different terms for the same 4926 ** thing) is obtained in a two-step algorithm. 4927 ** 4928 ** First we attempt to find the largest existing rowid and add one 4929 ** to that. But if the largest existing rowid is already the maximum 4930 ** positive integer, we have to fall through to the second 4931 ** probabilistic algorithm 4932 ** 4933 ** The second algorithm is to select a rowid at random and see if 4934 ** it already exists in the table. If it does not exist, we have 4935 ** succeeded. If the random rowid does exist, we select a new one 4936 ** and try again, up to 100 times. 4937 */ 4938 assert( pC->isTable ); 4939 4940 #ifdef SQLITE_32BIT_ROWID 4941 # define MAX_ROWID 0x7fffffff 4942 #else 4943 /* Some compilers complain about constants of the form 0x7fffffffffffffff. 4944 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems 4945 ** to provide the constant while making all compilers happy. 4946 */ 4947 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff ) 4948 #endif 4949 4950 if( !pC->useRandomRowid ){ 4951 rc = sqlite3BtreeLast(pC->uc.pCursor, &res); 4952 if( rc!=SQLITE_OK ){ 4953 goto abort_due_to_error; 4954 } 4955 if( res ){ 4956 v = 1; /* IMP: R-61914-48074 */ 4957 }else{ 4958 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) ); 4959 v = sqlite3BtreeIntegerKey(pC->uc.pCursor); 4960 if( v>=MAX_ROWID ){ 4961 pC->useRandomRowid = 1; 4962 }else{ 4963 v++; /* IMP: R-29538-34987 */ 4964 } 4965 } 4966 } 4967 4968 #ifndef SQLITE_OMIT_AUTOINCREMENT 4969 if( pOp->p3 ){ 4970 /* Assert that P3 is a valid memory cell. */ 4971 assert( pOp->p3>0 ); 4972 if( p->pFrame ){ 4973 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); 4974 /* Assert that P3 is a valid memory cell. */ 4975 assert( pOp->p3<=pFrame->nMem ); 4976 pMem = &pFrame->aMem[pOp->p3]; 4977 }else{ 4978 /* Assert that P3 is a valid memory cell. */ 4979 assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); 4980 pMem = &aMem[pOp->p3]; 4981 memAboutToChange(p, pMem); 4982 } 4983 assert( memIsValid(pMem) ); 4984 4985 REGISTER_TRACE(pOp->p3, pMem); 4986 sqlite3VdbeMemIntegerify(pMem); 4987 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */ 4988 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){ 4989 rc = SQLITE_FULL; /* IMP: R-17817-00630 */ 4990 goto abort_due_to_error; 4991 } 4992 if( v<pMem->u.i+1 ){ 4993 v = pMem->u.i + 1; 4994 } 4995 pMem->u.i = v; 4996 } 4997 #endif 4998 if( pC->useRandomRowid ){ 4999 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the 5000 ** largest possible integer (9223372036854775807) then the database 5001 ** engine starts picking positive candidate ROWIDs at random until 5002 ** it finds one that is not previously used. */ 5003 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is 5004 ** an AUTOINCREMENT table. */ 5005 cnt = 0; 5006 do{ 5007 sqlite3_randomness(sizeof(v), &v); 5008 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */ 5009 }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v, 5010 0, &res))==SQLITE_OK) 5011 && (res==0) 5012 && (++cnt<100)); 5013 if( rc ) goto abort_due_to_error; 5014 if( res==0 ){ 5015 rc = SQLITE_FULL; /* IMP: R-38219-53002 */ 5016 goto abort_due_to_error; 5017 } 5018 assert( v>0 ); /* EV: R-40812-03570 */ 5019 } 5020 pC->deferredMoveto = 0; 5021 pC->cacheStatus = CACHE_STALE; 5022 } 5023 pOut->u.i = v; 5024 break; 5025 } 5026 5027 /* Opcode: Insert P1 P2 P3 P4 P5 5028 ** Synopsis: intkey=r[P3] data=r[P2] 5029 ** 5030 ** Write an entry into the table of cursor P1. A new entry is 5031 ** created if it doesn't already exist or the data for an existing 5032 ** entry is overwritten. The data is the value MEM_Blob stored in register 5033 ** number P2. The key is stored in register P3. The key must 5034 ** be a MEM_Int. 5035 ** 5036 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is 5037 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set, 5038 ** then rowid is stored for subsequent return by the 5039 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified). 5040 ** 5041 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might 5042 ** run faster by avoiding an unnecessary seek on cursor P1. However, 5043 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior 5044 ** seeks on the cursor or if the most recent seek used a key equal to P3. 5045 ** 5046 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an 5047 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode 5048 ** is part of an INSERT operation. The difference is only important to 5049 ** the update hook. 5050 ** 5051 ** Parameter P4 may point to a Table structure, or may be NULL. If it is 5052 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked 5053 ** following a successful insert. 5054 ** 5055 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically 5056 ** allocated, then ownership of P2 is transferred to the pseudo-cursor 5057 ** and register P2 becomes ephemeral. If the cursor is changed, the 5058 ** value of register P2 will then change. Make sure this does not 5059 ** cause any problems.) 5060 ** 5061 ** This instruction only works on tables. The equivalent instruction 5062 ** for indices is OP_IdxInsert. 5063 */ 5064 case OP_Insert: { 5065 Mem *pData; /* MEM cell holding data for the record to be inserted */ 5066 Mem *pKey; /* MEM cell holding key for the record */ 5067 VdbeCursor *pC; /* Cursor to table into which insert is written */ 5068 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */ 5069 const char *zDb; /* database name - used by the update hook */ 5070 Table *pTab; /* Table structure - used by update and pre-update hooks */ 5071 BtreePayload x; /* Payload to be inserted */ 5072 5073 pData = &aMem[pOp->p2]; 5074 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5075 assert( memIsValid(pData) ); 5076 pC = p->apCsr[pOp->p1]; 5077 assert( pC!=0 ); 5078 assert( pC->eCurType==CURTYPE_BTREE ); 5079 assert( pC->deferredMoveto==0 ); 5080 assert( pC->uc.pCursor!=0 ); 5081 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable ); 5082 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC ); 5083 REGISTER_TRACE(pOp->p2, pData); 5084 sqlite3VdbeIncrWriteCounter(p, pC); 5085 5086 pKey = &aMem[pOp->p3]; 5087 assert( pKey->flags & MEM_Int ); 5088 assert( memIsValid(pKey) ); 5089 REGISTER_TRACE(pOp->p3, pKey); 5090 x.nKey = pKey->u.i; 5091 5092 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){ 5093 assert( pC->iDb>=0 ); 5094 zDb = db->aDb[pC->iDb].zDbSName; 5095 pTab = pOp->p4.pTab; 5096 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) ); 5097 }else{ 5098 pTab = 0; 5099 zDb = 0; /* Not needed. Silence a compiler warning. */ 5100 } 5101 5102 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 5103 /* Invoke the pre-update hook, if any */ 5104 if( pTab ){ 5105 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){ 5106 sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2); 5107 } 5108 if( db->xUpdateCallback==0 || pTab->aCol==0 ){ 5109 /* Prevent post-update hook from running in cases when it should not */ 5110 pTab = 0; 5111 } 5112 } 5113 if( pOp->p5 & OPFLAG_ISNOOP ) break; 5114 #endif 5115 5116 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; 5117 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey; 5118 assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 ); 5119 x.pData = pData->z; 5120 x.nData = pData->n; 5121 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0); 5122 if( pData->flags & MEM_Zero ){ 5123 x.nZero = pData->u.nZero; 5124 }else{ 5125 x.nZero = 0; 5126 } 5127 x.pKey = 0; 5128 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, 5129 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)), 5130 seekResult 5131 ); 5132 pC->deferredMoveto = 0; 5133 pC->cacheStatus = CACHE_STALE; 5134 5135 /* Invoke the update-hook if required. */ 5136 if( rc ) goto abort_due_to_error; 5137 if( pTab ){ 5138 assert( db->xUpdateCallback!=0 ); 5139 assert( pTab->aCol!=0 ); 5140 db->xUpdateCallback(db->pUpdateArg, 5141 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT, 5142 zDb, pTab->zName, x.nKey); 5143 } 5144 break; 5145 } 5146 5147 /* Opcode: RowCell P1 P2 P3 * * 5148 ** 5149 ** P1 and P2 are both open cursors. Both must be opened on the same type 5150 ** of table - intkey or index. This opcode is used as part of copying 5151 ** the current row from P2 into P1. If the cursors are opened on intkey 5152 ** tables, register P3 contains the rowid to use with the new record in 5153 ** P1. If they are opened on index tables, P3 is not used. 5154 ** 5155 ** This opcode must be followed by either an Insert or InsertIdx opcode 5156 ** with the OPFLAG_PREFORMAT flag set to complete the insert operation. 5157 */ 5158 case OP_RowCell: { 5159 VdbeCursor *pDest; /* Cursor to write to */ 5160 VdbeCursor *pSrc; /* Cursor to read from */ 5161 i64 iKey; /* Rowid value to insert with */ 5162 assert( pOp[1].opcode==OP_Insert || pOp[1].opcode==OP_IdxInsert ); 5163 assert( pOp[1].p5 & OPFLAG_PREFORMAT ); 5164 pDest = p->apCsr[pOp->p1]; 5165 pSrc = p->apCsr[pOp->p2]; 5166 iKey = pOp->p3 ? aMem[pOp->p3].u.i : 0; 5167 rc = sqlite3BtreeTransferRow(pDest->uc.pCursor, pSrc->uc.pCursor, iKey); 5168 if( rc!=SQLITE_OK ) goto abort_due_to_error; 5169 break; 5170 }; 5171 5172 /* Opcode: Delete P1 P2 P3 P4 P5 5173 ** 5174 ** Delete the record at which the P1 cursor is currently pointing. 5175 ** 5176 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then 5177 ** the cursor will be left pointing at either the next or the previous 5178 ** record in the table. If it is left pointing at the next record, then 5179 ** the next Next instruction will be a no-op. As a result, in this case 5180 ** it is ok to delete a record from within a Next loop. If 5181 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be 5182 ** left in an undefined state. 5183 ** 5184 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this 5185 ** delete one of several associated with deleting a table row and all its 5186 ** associated index entries. Exactly one of those deletes is the "primary" 5187 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are 5188 ** marked with the AUXDELETE flag. 5189 ** 5190 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row 5191 ** change count is incremented (otherwise not). 5192 ** 5193 ** P1 must not be pseudo-table. It has to be a real table with 5194 ** multiple rows. 5195 ** 5196 ** If P4 is not NULL then it points to a Table object. In this case either 5197 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must 5198 ** have been positioned using OP_NotFound prior to invoking this opcode in 5199 ** this case. Specifically, if one is configured, the pre-update hook is 5200 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured, 5201 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2. 5202 ** 5203 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address 5204 ** of the memory cell that contains the value that the rowid of the row will 5205 ** be set to by the update. 5206 */ 5207 case OP_Delete: { 5208 VdbeCursor *pC; 5209 const char *zDb; 5210 Table *pTab; 5211 int opflags; 5212 5213 opflags = pOp->p2; 5214 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5215 pC = p->apCsr[pOp->p1]; 5216 assert( pC!=0 ); 5217 assert( pC->eCurType==CURTYPE_BTREE ); 5218 assert( pC->uc.pCursor!=0 ); 5219 assert( pC->deferredMoveto==0 ); 5220 sqlite3VdbeIncrWriteCounter(p, pC); 5221 5222 #ifdef SQLITE_DEBUG 5223 if( pOp->p4type==P4_TABLE 5224 && HasRowid(pOp->p4.pTab) 5225 && pOp->p5==0 5226 && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) 5227 ){ 5228 /* If p5 is zero, the seek operation that positioned the cursor prior to 5229 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of 5230 ** the row that is being deleted */ 5231 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor); 5232 assert( CORRUPT_DB || pC->movetoTarget==iKey ); 5233 } 5234 #endif 5235 5236 /* If the update-hook or pre-update-hook will be invoked, set zDb to 5237 ** the name of the db to pass as to it. Also set local pTab to a copy 5238 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was 5239 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set 5240 ** VdbeCursor.movetoTarget to the current rowid. */ 5241 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){ 5242 assert( pC->iDb>=0 ); 5243 assert( pOp->p4.pTab!=0 ); 5244 zDb = db->aDb[pC->iDb].zDbSName; 5245 pTab = pOp->p4.pTab; 5246 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){ 5247 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor); 5248 } 5249 }else{ 5250 zDb = 0; /* Not needed. Silence a compiler warning. */ 5251 pTab = 0; /* Not needed. Silence a compiler warning. */ 5252 } 5253 5254 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 5255 /* Invoke the pre-update-hook if required. */ 5256 if( db->xPreUpdateCallback && pOp->p4.pTab ){ 5257 assert( !(opflags & OPFLAG_ISUPDATE) 5258 || HasRowid(pTab)==0 5259 || (aMem[pOp->p3].flags & MEM_Int) 5260 ); 5261 sqlite3VdbePreUpdateHook(p, pC, 5262 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE, 5263 zDb, pTab, pC->movetoTarget, 5264 pOp->p3 5265 ); 5266 } 5267 if( opflags & OPFLAG_ISNOOP ) break; 5268 #endif 5269 5270 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */ 5271 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 ); 5272 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION ); 5273 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE ); 5274 5275 #ifdef SQLITE_DEBUG 5276 if( p->pFrame==0 ){ 5277 if( pC->isEphemeral==0 5278 && (pOp->p5 & OPFLAG_AUXDELETE)==0 5279 && (pC->wrFlag & OPFLAG_FORDELETE)==0 5280 ){ 5281 nExtraDelete++; 5282 } 5283 if( pOp->p2 & OPFLAG_NCHANGE ){ 5284 nExtraDelete--; 5285 } 5286 } 5287 #endif 5288 5289 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5); 5290 pC->cacheStatus = CACHE_STALE; 5291 pC->seekResult = 0; 5292 if( rc ) goto abort_due_to_error; 5293 5294 /* Invoke the update-hook if required. */ 5295 if( opflags & OPFLAG_NCHANGE ){ 5296 p->nChange++; 5297 if( db->xUpdateCallback && HasRowid(pTab) ){ 5298 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName, 5299 pC->movetoTarget); 5300 assert( pC->iDb>=0 ); 5301 } 5302 } 5303 5304 break; 5305 } 5306 /* Opcode: ResetCount * * * * * 5307 ** 5308 ** The value of the change counter is copied to the database handle 5309 ** change counter (returned by subsequent calls to sqlite3_changes()). 5310 ** Then the VMs internal change counter resets to 0. 5311 ** This is used by trigger programs. 5312 */ 5313 case OP_ResetCount: { 5314 sqlite3VdbeSetChanges(db, p->nChange); 5315 p->nChange = 0; 5316 break; 5317 } 5318 5319 /* Opcode: SorterCompare P1 P2 P3 P4 5320 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2 5321 ** 5322 ** P1 is a sorter cursor. This instruction compares a prefix of the 5323 ** record blob in register P3 against a prefix of the entry that 5324 ** the sorter cursor currently points to. Only the first P4 fields 5325 ** of r[P3] and the sorter record are compared. 5326 ** 5327 ** If either P3 or the sorter contains a NULL in one of their significant 5328 ** fields (not counting the P4 fields at the end which are ignored) then 5329 ** the comparison is assumed to be equal. 5330 ** 5331 ** Fall through to next instruction if the two records compare equal to 5332 ** each other. Jump to P2 if they are different. 5333 */ 5334 case OP_SorterCompare: { 5335 VdbeCursor *pC; 5336 int res; 5337 int nKeyCol; 5338 5339 pC = p->apCsr[pOp->p1]; 5340 assert( isSorter(pC) ); 5341 assert( pOp->p4type==P4_INT32 ); 5342 pIn3 = &aMem[pOp->p3]; 5343 nKeyCol = pOp->p4.i; 5344 res = 0; 5345 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res); 5346 VdbeBranchTaken(res!=0,2); 5347 if( rc ) goto abort_due_to_error; 5348 if( res ) goto jump_to_p2; 5349 break; 5350 }; 5351 5352 /* Opcode: SorterData P1 P2 P3 * * 5353 ** Synopsis: r[P2]=data 5354 ** 5355 ** Write into register P2 the current sorter data for sorter cursor P1. 5356 ** Then clear the column header cache on cursor P3. 5357 ** 5358 ** This opcode is normally use to move a record out of the sorter and into 5359 ** a register that is the source for a pseudo-table cursor created using 5360 ** OpenPseudo. That pseudo-table cursor is the one that is identified by 5361 ** parameter P3. Clearing the P3 column cache as part of this opcode saves 5362 ** us from having to issue a separate NullRow instruction to clear that cache. 5363 */ 5364 case OP_SorterData: { 5365 VdbeCursor *pC; 5366 5367 pOut = &aMem[pOp->p2]; 5368 pC = p->apCsr[pOp->p1]; 5369 assert( isSorter(pC) ); 5370 rc = sqlite3VdbeSorterRowkey(pC, pOut); 5371 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) ); 5372 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5373 if( rc ) goto abort_due_to_error; 5374 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE; 5375 break; 5376 } 5377 5378 /* Opcode: RowData P1 P2 P3 * * 5379 ** Synopsis: r[P2]=data 5380 ** 5381 ** Write into register P2 the complete row content for the row at 5382 ** which cursor P1 is currently pointing. 5383 ** There is no interpretation of the data. 5384 ** It is just copied onto the P2 register exactly as 5385 ** it is found in the database file. 5386 ** 5387 ** If cursor P1 is an index, then the content is the key of the row. 5388 ** If cursor P2 is a table, then the content extracted is the data. 5389 ** 5390 ** If the P1 cursor must be pointing to a valid row (not a NULL row) 5391 ** of a real table, not a pseudo-table. 5392 ** 5393 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer 5394 ** into the database page. That means that the content of the output 5395 ** register will be invalidated as soon as the cursor moves - including 5396 ** moves caused by other cursors that "save" the current cursors 5397 ** position in order that they can write to the same table. If P3==0 5398 ** then a copy of the data is made into memory. P3!=0 is faster, but 5399 ** P3==0 is safer. 5400 ** 5401 ** If P3!=0 then the content of the P2 register is unsuitable for use 5402 ** in OP_Result and any OP_Result will invalidate the P2 register content. 5403 ** The P2 register content is invalidated by opcodes like OP_Function or 5404 ** by any use of another cursor pointing to the same table. 5405 */ 5406 case OP_RowData: { 5407 VdbeCursor *pC; 5408 BtCursor *pCrsr; 5409 u32 n; 5410 5411 pOut = out2Prerelease(p, pOp); 5412 5413 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5414 pC = p->apCsr[pOp->p1]; 5415 assert( pC!=0 ); 5416 assert( pC->eCurType==CURTYPE_BTREE ); 5417 assert( isSorter(pC)==0 ); 5418 assert( pC->nullRow==0 ); 5419 assert( pC->uc.pCursor!=0 ); 5420 pCrsr = pC->uc.pCursor; 5421 5422 /* The OP_RowData opcodes always follow OP_NotExists or 5423 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions 5424 ** that might invalidate the cursor. 5425 ** If this where not the case, on of the following assert()s 5426 ** would fail. Should this ever change (because of changes in the code 5427 ** generator) then the fix would be to insert a call to 5428 ** sqlite3VdbeCursorMoveto(). 5429 */ 5430 assert( pC->deferredMoveto==0 ); 5431 assert( sqlite3BtreeCursorIsValid(pCrsr) ); 5432 5433 n = sqlite3BtreePayloadSize(pCrsr); 5434 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ 5435 goto too_big; 5436 } 5437 testcase( n==0 ); 5438 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut); 5439 if( rc ) goto abort_due_to_error; 5440 if( !pOp->p3 ) Deephemeralize(pOut); 5441 UPDATE_MAX_BLOBSIZE(pOut); 5442 REGISTER_TRACE(pOp->p2, pOut); 5443 break; 5444 } 5445 5446 /* Opcode: Rowid P1 P2 * * * 5447 ** Synopsis: r[P2]=rowid 5448 ** 5449 ** Store in register P2 an integer which is the key of the table entry that 5450 ** P1 is currently point to. 5451 ** 5452 ** P1 can be either an ordinary table or a virtual table. There used to 5453 ** be a separate OP_VRowid opcode for use with virtual tables, but this 5454 ** one opcode now works for both table types. 5455 */ 5456 case OP_Rowid: { /* out2 */ 5457 VdbeCursor *pC; 5458 i64 v; 5459 sqlite3_vtab *pVtab; 5460 const sqlite3_module *pModule; 5461 5462 pOut = out2Prerelease(p, pOp); 5463 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5464 pC = p->apCsr[pOp->p1]; 5465 assert( pC!=0 ); 5466 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow ); 5467 if( pC->nullRow ){ 5468 pOut->flags = MEM_Null; 5469 break; 5470 }else if( pC->deferredMoveto ){ 5471 v = pC->movetoTarget; 5472 #ifndef SQLITE_OMIT_VIRTUALTABLE 5473 }else if( pC->eCurType==CURTYPE_VTAB ){ 5474 assert( pC->uc.pVCur!=0 ); 5475 pVtab = pC->uc.pVCur->pVtab; 5476 pModule = pVtab->pModule; 5477 assert( pModule->xRowid ); 5478 rc = pModule->xRowid(pC->uc.pVCur, &v); 5479 sqlite3VtabImportErrmsg(p, pVtab); 5480 if( rc ) goto abort_due_to_error; 5481 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 5482 }else{ 5483 assert( pC->eCurType==CURTYPE_BTREE ); 5484 assert( pC->uc.pCursor!=0 ); 5485 rc = sqlite3VdbeCursorRestore(pC); 5486 if( rc ) goto abort_due_to_error; 5487 if( pC->nullRow ){ 5488 pOut->flags = MEM_Null; 5489 break; 5490 } 5491 v = sqlite3BtreeIntegerKey(pC->uc.pCursor); 5492 } 5493 pOut->u.i = v; 5494 break; 5495 } 5496 5497 /* Opcode: NullRow P1 * * * * 5498 ** 5499 ** Move the cursor P1 to a null row. Any OP_Column operations 5500 ** that occur while the cursor is on the null row will always 5501 ** write a NULL. 5502 */ 5503 case OP_NullRow: { 5504 VdbeCursor *pC; 5505 5506 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5507 pC = p->apCsr[pOp->p1]; 5508 assert( pC!=0 ); 5509 pC->nullRow = 1; 5510 pC->cacheStatus = CACHE_STALE; 5511 if( pC->eCurType==CURTYPE_BTREE ){ 5512 assert( pC->uc.pCursor!=0 ); 5513 sqlite3BtreeClearCursor(pC->uc.pCursor); 5514 } 5515 #ifdef SQLITE_DEBUG 5516 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow; 5517 #endif 5518 break; 5519 } 5520 5521 /* Opcode: SeekEnd P1 * * * * 5522 ** 5523 ** Position cursor P1 at the end of the btree for the purpose of 5524 ** appending a new entry onto the btree. 5525 ** 5526 ** It is assumed that the cursor is used only for appending and so 5527 ** if the cursor is valid, then the cursor must already be pointing 5528 ** at the end of the btree and so no changes are made to 5529 ** the cursor. 5530 */ 5531 /* Opcode: Last P1 P2 * * * 5532 ** 5533 ** The next use of the Rowid or Column or Prev instruction for P1 5534 ** will refer to the last entry in the database table or index. 5535 ** If the table or index is empty and P2>0, then jump immediately to P2. 5536 ** If P2 is 0 or if the table or index is not empty, fall through 5537 ** to the following instruction. 5538 ** 5539 ** This opcode leaves the cursor configured to move in reverse order, 5540 ** from the end toward the beginning. In other words, the cursor is 5541 ** configured to use Prev, not Next. 5542 */ 5543 case OP_SeekEnd: 5544 case OP_Last: { /* jump */ 5545 VdbeCursor *pC; 5546 BtCursor *pCrsr; 5547 int res; 5548 5549 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5550 pC = p->apCsr[pOp->p1]; 5551 assert( pC!=0 ); 5552 assert( pC->eCurType==CURTYPE_BTREE ); 5553 pCrsr = pC->uc.pCursor; 5554 res = 0; 5555 assert( pCrsr!=0 ); 5556 #ifdef SQLITE_DEBUG 5557 pC->seekOp = pOp->opcode; 5558 #endif 5559 if( pOp->opcode==OP_SeekEnd ){ 5560 assert( pOp->p2==0 ); 5561 pC->seekResult = -1; 5562 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){ 5563 break; 5564 } 5565 } 5566 rc = sqlite3BtreeLast(pCrsr, &res); 5567 pC->nullRow = (u8)res; 5568 pC->deferredMoveto = 0; 5569 pC->cacheStatus = CACHE_STALE; 5570 if( rc ) goto abort_due_to_error; 5571 if( pOp->p2>0 ){ 5572 VdbeBranchTaken(res!=0,2); 5573 if( res ) goto jump_to_p2; 5574 } 5575 break; 5576 } 5577 5578 /* Opcode: IfSmaller P1 P2 P3 * * 5579 ** 5580 ** Estimate the number of rows in the table P1. Jump to P2 if that 5581 ** estimate is less than approximately 2**(0.1*P3). 5582 */ 5583 case OP_IfSmaller: { /* jump */ 5584 VdbeCursor *pC; 5585 BtCursor *pCrsr; 5586 int res; 5587 i64 sz; 5588 5589 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5590 pC = p->apCsr[pOp->p1]; 5591 assert( pC!=0 ); 5592 pCrsr = pC->uc.pCursor; 5593 assert( pCrsr ); 5594 rc = sqlite3BtreeFirst(pCrsr, &res); 5595 if( rc ) goto abort_due_to_error; 5596 if( res==0 ){ 5597 sz = sqlite3BtreeRowCountEst(pCrsr); 5598 if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1; 5599 } 5600 VdbeBranchTaken(res!=0,2); 5601 if( res ) goto jump_to_p2; 5602 break; 5603 } 5604 5605 5606 /* Opcode: SorterSort P1 P2 * * * 5607 ** 5608 ** After all records have been inserted into the Sorter object 5609 ** identified by P1, invoke this opcode to actually do the sorting. 5610 ** Jump to P2 if there are no records to be sorted. 5611 ** 5612 ** This opcode is an alias for OP_Sort and OP_Rewind that is used 5613 ** for Sorter objects. 5614 */ 5615 /* Opcode: Sort P1 P2 * * * 5616 ** 5617 ** This opcode does exactly the same thing as OP_Rewind except that 5618 ** it increments an undocumented global variable used for testing. 5619 ** 5620 ** Sorting is accomplished by writing records into a sorting index, 5621 ** then rewinding that index and playing it back from beginning to 5622 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the 5623 ** rewinding so that the global variable will be incremented and 5624 ** regression tests can determine whether or not the optimizer is 5625 ** correctly optimizing out sorts. 5626 */ 5627 case OP_SorterSort: /* jump */ 5628 case OP_Sort: { /* jump */ 5629 #ifdef SQLITE_TEST 5630 sqlite3_sort_count++; 5631 sqlite3_search_count--; 5632 #endif 5633 p->aCounter[SQLITE_STMTSTATUS_SORT]++; 5634 /* Fall through into OP_Rewind */ 5635 /* no break */ deliberate_fall_through 5636 } 5637 /* Opcode: Rewind P1 P2 * * * 5638 ** 5639 ** The next use of the Rowid or Column or Next instruction for P1 5640 ** will refer to the first entry in the database table or index. 5641 ** If the table or index is empty, jump immediately to P2. 5642 ** If the table or index is not empty, fall through to the following 5643 ** instruction. 5644 ** 5645 ** This opcode leaves the cursor configured to move in forward order, 5646 ** from the beginning toward the end. In other words, the cursor is 5647 ** configured to use Next, not Prev. 5648 */ 5649 case OP_Rewind: { /* jump */ 5650 VdbeCursor *pC; 5651 BtCursor *pCrsr; 5652 int res; 5653 5654 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5655 assert( pOp->p5==0 ); 5656 pC = p->apCsr[pOp->p1]; 5657 assert( pC!=0 ); 5658 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) ); 5659 res = 1; 5660 #ifdef SQLITE_DEBUG 5661 pC->seekOp = OP_Rewind; 5662 #endif 5663 if( isSorter(pC) ){ 5664 rc = sqlite3VdbeSorterRewind(pC, &res); 5665 }else{ 5666 assert( pC->eCurType==CURTYPE_BTREE ); 5667 pCrsr = pC->uc.pCursor; 5668 assert( pCrsr ); 5669 rc = sqlite3BtreeFirst(pCrsr, &res); 5670 pC->deferredMoveto = 0; 5671 pC->cacheStatus = CACHE_STALE; 5672 } 5673 if( rc ) goto abort_due_to_error; 5674 pC->nullRow = (u8)res; 5675 assert( pOp->p2>0 && pOp->p2<p->nOp ); 5676 VdbeBranchTaken(res!=0,2); 5677 if( res ) goto jump_to_p2; 5678 break; 5679 } 5680 5681 /* Opcode: Next P1 P2 P3 P4 P5 5682 ** 5683 ** Advance cursor P1 so that it points to the next key/data pair in its 5684 ** table or index. If there are no more key/value pairs then fall through 5685 ** to the following instruction. But if the cursor advance was successful, 5686 ** jump immediately to P2. 5687 ** 5688 ** The Next opcode is only valid following an SeekGT, SeekGE, or 5689 ** OP_Rewind opcode used to position the cursor. Next is not allowed 5690 ** to follow SeekLT, SeekLE, or OP_Last. 5691 ** 5692 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have 5693 ** been opened prior to this opcode or the program will segfault. 5694 ** 5695 ** The P3 value is a hint to the btree implementation. If P3==1, that 5696 ** means P1 is an SQL index and that this instruction could have been 5697 ** omitted if that index had been unique. P3 is usually 0. P3 is 5698 ** always either 0 or 1. 5699 ** 5700 ** P4 is always of type P4_ADVANCE. The function pointer points to 5701 ** sqlite3BtreeNext(). 5702 ** 5703 ** If P5 is positive and the jump is taken, then event counter 5704 ** number P5-1 in the prepared statement is incremented. 5705 ** 5706 ** See also: Prev 5707 */ 5708 /* Opcode: Prev P1 P2 P3 P4 P5 5709 ** 5710 ** Back up cursor P1 so that it points to the previous key/data pair in its 5711 ** table or index. If there is no previous key/value pairs then fall through 5712 ** to the following instruction. But if the cursor backup was successful, 5713 ** jump immediately to P2. 5714 ** 5715 ** 5716 ** The Prev opcode is only valid following an SeekLT, SeekLE, or 5717 ** OP_Last opcode used to position the cursor. Prev is not allowed 5718 ** to follow SeekGT, SeekGE, or OP_Rewind. 5719 ** 5720 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is 5721 ** not open then the behavior is undefined. 5722 ** 5723 ** The P3 value is a hint to the btree implementation. If P3==1, that 5724 ** means P1 is an SQL index and that this instruction could have been 5725 ** omitted if that index had been unique. P3 is usually 0. P3 is 5726 ** always either 0 or 1. 5727 ** 5728 ** P4 is always of type P4_ADVANCE. The function pointer points to 5729 ** sqlite3BtreePrevious(). 5730 ** 5731 ** If P5 is positive and the jump is taken, then event counter 5732 ** number P5-1 in the prepared statement is incremented. 5733 */ 5734 /* Opcode: SorterNext P1 P2 * * P5 5735 ** 5736 ** This opcode works just like OP_Next except that P1 must be a 5737 ** sorter object for which the OP_SorterSort opcode has been 5738 ** invoked. This opcode advances the cursor to the next sorted 5739 ** record, or jumps to P2 if there are no more sorted records. 5740 */ 5741 case OP_SorterNext: { /* jump */ 5742 VdbeCursor *pC; 5743 5744 pC = p->apCsr[pOp->p1]; 5745 assert( isSorter(pC) ); 5746 rc = sqlite3VdbeSorterNext(db, pC); 5747 goto next_tail; 5748 case OP_Prev: /* jump */ 5749 case OP_Next: /* jump */ 5750 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5751 assert( pOp->p5<ArraySize(p->aCounter) ); 5752 pC = p->apCsr[pOp->p1]; 5753 assert( pC!=0 ); 5754 assert( pC->deferredMoveto==0 ); 5755 assert( pC->eCurType==CURTYPE_BTREE ); 5756 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext ); 5757 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious ); 5758 5759 /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found. 5760 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */ 5761 assert( pOp->opcode!=OP_Next 5762 || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE 5763 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found 5764 || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid 5765 || pC->seekOp==OP_IfNoHope); 5766 assert( pOp->opcode!=OP_Prev 5767 || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE 5768 || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope 5769 || pC->seekOp==OP_NullRow); 5770 5771 rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3); 5772 next_tail: 5773 pC->cacheStatus = CACHE_STALE; 5774 VdbeBranchTaken(rc==SQLITE_OK,2); 5775 if( rc==SQLITE_OK ){ 5776 pC->nullRow = 0; 5777 p->aCounter[pOp->p5]++; 5778 #ifdef SQLITE_TEST 5779 sqlite3_search_count++; 5780 #endif 5781 goto jump_to_p2_and_check_for_interrupt; 5782 } 5783 if( rc!=SQLITE_DONE ) goto abort_due_to_error; 5784 rc = SQLITE_OK; 5785 pC->nullRow = 1; 5786 goto check_for_interrupt; 5787 } 5788 5789 /* Opcode: IdxInsert P1 P2 P3 P4 P5 5790 ** Synopsis: key=r[P2] 5791 ** 5792 ** Register P2 holds an SQL index key made using the 5793 ** MakeRecord instructions. This opcode writes that key 5794 ** into the index P1. Data for the entry is nil. 5795 ** 5796 ** If P4 is not zero, then it is the number of values in the unpacked 5797 ** key of reg(P2). In that case, P3 is the index of the first register 5798 ** for the unpacked key. The availability of the unpacked key can sometimes 5799 ** be an optimization. 5800 ** 5801 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer 5802 ** that this insert is likely to be an append. 5803 ** 5804 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is 5805 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear, 5806 ** then the change counter is unchanged. 5807 ** 5808 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might 5809 ** run faster by avoiding an unnecessary seek on cursor P1. However, 5810 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior 5811 ** seeks on the cursor or if the most recent seek used a key equivalent 5812 ** to P2. 5813 ** 5814 ** This instruction only works for indices. The equivalent instruction 5815 ** for tables is OP_Insert. 5816 */ 5817 case OP_IdxInsert: { /* in2 */ 5818 VdbeCursor *pC; 5819 BtreePayload x; 5820 5821 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5822 pC = p->apCsr[pOp->p1]; 5823 sqlite3VdbeIncrWriteCounter(p, pC); 5824 assert( pC!=0 ); 5825 assert( !isSorter(pC) ); 5826 pIn2 = &aMem[pOp->p2]; 5827 assert( (pIn2->flags & MEM_Blob) || (pOp->p5 & OPFLAG_PREFORMAT) ); 5828 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; 5829 assert( pC->eCurType==CURTYPE_BTREE ); 5830 assert( pC->isTable==0 ); 5831 rc = ExpandBlob(pIn2); 5832 if( rc ) goto abort_due_to_error; 5833 x.nKey = pIn2->n; 5834 x.pKey = pIn2->z; 5835 x.aMem = aMem + pOp->p3; 5836 x.nMem = (u16)pOp->p4.i; 5837 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, 5838 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)), 5839 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0) 5840 ); 5841 assert( pC->deferredMoveto==0 ); 5842 pC->cacheStatus = CACHE_STALE; 5843 if( rc) goto abort_due_to_error; 5844 break; 5845 } 5846 5847 /* Opcode: SorterInsert P1 P2 * * * 5848 ** Synopsis: key=r[P2] 5849 ** 5850 ** Register P2 holds an SQL index key made using the 5851 ** MakeRecord instructions. This opcode writes that key 5852 ** into the sorter P1. Data for the entry is nil. 5853 */ 5854 case OP_SorterInsert: { /* in2 */ 5855 VdbeCursor *pC; 5856 5857 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5858 pC = p->apCsr[pOp->p1]; 5859 sqlite3VdbeIncrWriteCounter(p, pC); 5860 assert( pC!=0 ); 5861 assert( isSorter(pC) ); 5862 pIn2 = &aMem[pOp->p2]; 5863 assert( pIn2->flags & MEM_Blob ); 5864 assert( pC->isTable==0 ); 5865 rc = ExpandBlob(pIn2); 5866 if( rc ) goto abort_due_to_error; 5867 rc = sqlite3VdbeSorterWrite(pC, pIn2); 5868 if( rc) goto abort_due_to_error; 5869 break; 5870 } 5871 5872 /* Opcode: IdxDelete P1 P2 P3 * P5 5873 ** Synopsis: key=r[P2@P3] 5874 ** 5875 ** The content of P3 registers starting at register P2 form 5876 ** an unpacked index key. This opcode removes that entry from the 5877 ** index opened by cursor P1. 5878 ** 5879 ** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error 5880 ** if no matching index entry is found. This happens when running 5881 ** an UPDATE or DELETE statement and the index entry to be updated 5882 ** or deleted is not found. For some uses of IdxDelete 5883 ** (example: the EXCEPT operator) it does not matter that no matching 5884 ** entry is found. For those cases, P5 is zero. 5885 */ 5886 case OP_IdxDelete: { 5887 VdbeCursor *pC; 5888 BtCursor *pCrsr; 5889 int res; 5890 UnpackedRecord r; 5891 5892 assert( pOp->p3>0 ); 5893 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 ); 5894 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5895 pC = p->apCsr[pOp->p1]; 5896 assert( pC!=0 ); 5897 assert( pC->eCurType==CURTYPE_BTREE ); 5898 sqlite3VdbeIncrWriteCounter(p, pC); 5899 pCrsr = pC->uc.pCursor; 5900 assert( pCrsr!=0 ); 5901 r.pKeyInfo = pC->pKeyInfo; 5902 r.nField = (u16)pOp->p3; 5903 r.default_rc = 0; 5904 r.aMem = &aMem[pOp->p2]; 5905 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res); 5906 if( rc ) goto abort_due_to_error; 5907 if( res==0 ){ 5908 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE); 5909 if( rc ) goto abort_due_to_error; 5910 }else if( pOp->p5 ){ 5911 rc = SQLITE_CORRUPT_INDEX; 5912 goto abort_due_to_error; 5913 } 5914 assert( pC->deferredMoveto==0 ); 5915 pC->cacheStatus = CACHE_STALE; 5916 pC->seekResult = 0; 5917 break; 5918 } 5919 5920 /* Opcode: DeferredSeek P1 * P3 P4 * 5921 ** Synopsis: Move P3 to P1.rowid if needed 5922 ** 5923 ** P1 is an open index cursor and P3 is a cursor on the corresponding 5924 ** table. This opcode does a deferred seek of the P3 table cursor 5925 ** to the row that corresponds to the current row of P1. 5926 ** 5927 ** This is a deferred seek. Nothing actually happens until 5928 ** the cursor is used to read a record. That way, if no reads 5929 ** occur, no unnecessary I/O happens. 5930 ** 5931 ** P4 may be an array of integers (type P4_INTARRAY) containing 5932 ** one entry for each column in the P3 table. If array entry a(i) 5933 ** is non-zero, then reading column a(i)-1 from cursor P3 is 5934 ** equivalent to performing the deferred seek and then reading column i 5935 ** from P1. This information is stored in P3 and used to redirect 5936 ** reads against P3 over to P1, thus possibly avoiding the need to 5937 ** seek and read cursor P3. 5938 */ 5939 /* Opcode: IdxRowid P1 P2 * * * 5940 ** Synopsis: r[P2]=rowid 5941 ** 5942 ** Write into register P2 an integer which is the last entry in the record at 5943 ** the end of the index key pointed to by cursor P1. This integer should be 5944 ** the rowid of the table entry to which this index entry points. 5945 ** 5946 ** See also: Rowid, MakeRecord. 5947 */ 5948 case OP_DeferredSeek: 5949 case OP_IdxRowid: { /* out2 */ 5950 VdbeCursor *pC; /* The P1 index cursor */ 5951 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */ 5952 i64 rowid; /* Rowid that P1 current points to */ 5953 5954 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 5955 pC = p->apCsr[pOp->p1]; 5956 assert( pC!=0 ); 5957 assert( pC->eCurType==CURTYPE_BTREE ); 5958 assert( pC->uc.pCursor!=0 ); 5959 assert( pC->isTable==0 ); 5960 assert( pC->deferredMoveto==0 ); 5961 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid ); 5962 5963 /* The IdxRowid and Seek opcodes are combined because of the commonality 5964 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */ 5965 rc = sqlite3VdbeCursorRestore(pC); 5966 5967 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted 5968 ** out from under the cursor. That will never happens for an IdxRowid 5969 ** or Seek opcode */ 5970 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error; 5971 5972 if( !pC->nullRow ){ 5973 rowid = 0; /* Not needed. Only used to silence a warning. */ 5974 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid); 5975 if( rc!=SQLITE_OK ){ 5976 goto abort_due_to_error; 5977 } 5978 if( pOp->opcode==OP_DeferredSeek ){ 5979 assert( pOp->p3>=0 && pOp->p3<p->nCursor ); 5980 pTabCur = p->apCsr[pOp->p3]; 5981 assert( pTabCur!=0 ); 5982 assert( pTabCur->eCurType==CURTYPE_BTREE ); 5983 assert( pTabCur->uc.pCursor!=0 ); 5984 assert( pTabCur->isTable ); 5985 pTabCur->nullRow = 0; 5986 pTabCur->movetoTarget = rowid; 5987 pTabCur->deferredMoveto = 1; 5988 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 ); 5989 pTabCur->aAltMap = pOp->p4.ai; 5990 pTabCur->pAltCursor = pC; 5991 }else{ 5992 pOut = out2Prerelease(p, pOp); 5993 pOut->u.i = rowid; 5994 } 5995 }else{ 5996 assert( pOp->opcode==OP_IdxRowid ); 5997 sqlite3VdbeMemSetNull(&aMem[pOp->p2]); 5998 } 5999 break; 6000 } 6001 6002 /* Opcode: FinishSeek P1 * * * * 6003 ** 6004 ** If cursor P1 was previously moved via OP_DeferredSeek, complete that 6005 ** seek operation now, without further delay. If the cursor seek has 6006 ** already occurred, this instruction is a no-op. 6007 */ 6008 case OP_FinishSeek: { 6009 VdbeCursor *pC; /* The P1 index cursor */ 6010 6011 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 6012 pC = p->apCsr[pOp->p1]; 6013 if( pC->deferredMoveto ){ 6014 rc = sqlite3VdbeFinishMoveto(pC); 6015 if( rc ) goto abort_due_to_error; 6016 } 6017 break; 6018 } 6019 6020 /* Opcode: IdxGE P1 P2 P3 P4 * 6021 ** Synopsis: key=r[P3@P4] 6022 ** 6023 ** The P4 register values beginning with P3 form an unpacked index 6024 ** key that omits the PRIMARY KEY. Compare this key value against the index 6025 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 6026 ** fields at the end. 6027 ** 6028 ** If the P1 index entry is greater than or equal to the key value 6029 ** then jump to P2. Otherwise fall through to the next instruction. 6030 */ 6031 /* Opcode: IdxGT P1 P2 P3 P4 * 6032 ** Synopsis: key=r[P3@P4] 6033 ** 6034 ** The P4 register values beginning with P3 form an unpacked index 6035 ** key that omits the PRIMARY KEY. Compare this key value against the index 6036 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 6037 ** fields at the end. 6038 ** 6039 ** If the P1 index entry is greater than the key value 6040 ** then jump to P2. Otherwise fall through to the next instruction. 6041 */ 6042 /* Opcode: IdxLT P1 P2 P3 P4 * 6043 ** Synopsis: key=r[P3@P4] 6044 ** 6045 ** The P4 register values beginning with P3 form an unpacked index 6046 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against 6047 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or 6048 ** ROWID on the P1 index. 6049 ** 6050 ** If the P1 index entry is less than the key value then jump to P2. 6051 ** Otherwise fall through to the next instruction. 6052 */ 6053 /* Opcode: IdxLE P1 P2 P3 P4 * 6054 ** Synopsis: key=r[P3@P4] 6055 ** 6056 ** The P4 register values beginning with P3 form an unpacked index 6057 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against 6058 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or 6059 ** ROWID on the P1 index. 6060 ** 6061 ** If the P1 index entry is less than or equal to the key value then jump 6062 ** to P2. Otherwise fall through to the next instruction. 6063 */ 6064 case OP_IdxLE: /* jump */ 6065 case OP_IdxGT: /* jump */ 6066 case OP_IdxLT: /* jump */ 6067 case OP_IdxGE: { /* jump */ 6068 VdbeCursor *pC; 6069 int res; 6070 UnpackedRecord r; 6071 6072 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 6073 pC = p->apCsr[pOp->p1]; 6074 assert( pC!=0 ); 6075 assert( pC->isOrdered ); 6076 assert( pC->eCurType==CURTYPE_BTREE ); 6077 assert( pC->uc.pCursor!=0); 6078 assert( pC->deferredMoveto==0 ); 6079 assert( pOp->p4type==P4_INT32 ); 6080 r.pKeyInfo = pC->pKeyInfo; 6081 r.nField = (u16)pOp->p4.i; 6082 if( pOp->opcode<OP_IdxLT ){ 6083 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT ); 6084 r.default_rc = -1; 6085 }else{ 6086 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT ); 6087 r.default_rc = 0; 6088 } 6089 r.aMem = &aMem[pOp->p3]; 6090 #ifdef SQLITE_DEBUG 6091 { 6092 int i; 6093 for(i=0; i<r.nField; i++){ 6094 assert( memIsValid(&r.aMem[i]) ); 6095 REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]); 6096 } 6097 } 6098 #endif 6099 6100 /* Inlined version of sqlite3VdbeIdxKeyCompare() */ 6101 { 6102 i64 nCellKey = 0; 6103 BtCursor *pCur; 6104 Mem m; 6105 6106 assert( pC->eCurType==CURTYPE_BTREE ); 6107 pCur = pC->uc.pCursor; 6108 assert( sqlite3BtreeCursorIsValid(pCur) ); 6109 nCellKey = sqlite3BtreePayloadSize(pCur); 6110 /* nCellKey will always be between 0 and 0xffffffff because of the way 6111 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */ 6112 if( nCellKey<=0 || nCellKey>0x7fffffff ){ 6113 rc = SQLITE_CORRUPT_BKPT; 6114 goto abort_due_to_error; 6115 } 6116 sqlite3VdbeMemInit(&m, db, 0); 6117 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m); 6118 if( rc ) goto abort_due_to_error; 6119 res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, &r, 0); 6120 sqlite3VdbeMemRelease(&m); 6121 } 6122 /* End of inlined sqlite3VdbeIdxKeyCompare() */ 6123 6124 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) ); 6125 if( (pOp->opcode&1)==(OP_IdxLT&1) ){ 6126 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT ); 6127 res = -res; 6128 }else{ 6129 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT ); 6130 res++; 6131 } 6132 VdbeBranchTaken(res>0,2); 6133 assert( rc==SQLITE_OK ); 6134 if( res>0 ) goto jump_to_p2; 6135 break; 6136 } 6137 6138 /* Opcode: Destroy P1 P2 P3 * * 6139 ** 6140 ** Delete an entire database table or index whose root page in the database 6141 ** file is given by P1. 6142 ** 6143 ** The table being destroyed is in the main database file if P3==0. If 6144 ** P3==1 then the table to be clear is in the auxiliary database file 6145 ** that is used to store tables create using CREATE TEMPORARY TABLE. 6146 ** 6147 ** If AUTOVACUUM is enabled then it is possible that another root page 6148 ** might be moved into the newly deleted root page in order to keep all 6149 ** root pages contiguous at the beginning of the database. The former 6150 ** value of the root page that moved - its value before the move occurred - 6151 ** is stored in register P2. If no page movement was required (because the 6152 ** table being dropped was already the last one in the database) then a 6153 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero 6154 ** is stored in register P2. 6155 ** 6156 ** This opcode throws an error if there are any active reader VMs when 6157 ** it is invoked. This is done to avoid the difficulty associated with 6158 ** updating existing cursors when a root page is moved in an AUTOVACUUM 6159 ** database. This error is thrown even if the database is not an AUTOVACUUM 6160 ** db in order to avoid introducing an incompatibility between autovacuum 6161 ** and non-autovacuum modes. 6162 ** 6163 ** See also: Clear 6164 */ 6165 case OP_Destroy: { /* out2 */ 6166 int iMoved; 6167 int iDb; 6168 6169 sqlite3VdbeIncrWriteCounter(p, 0); 6170 assert( p->readOnly==0 ); 6171 assert( pOp->p1>1 ); 6172 pOut = out2Prerelease(p, pOp); 6173 pOut->flags = MEM_Null; 6174 if( db->nVdbeRead > db->nVDestroy+1 ){ 6175 rc = SQLITE_LOCKED; 6176 p->errorAction = OE_Abort; 6177 goto abort_due_to_error; 6178 }else{ 6179 iDb = pOp->p3; 6180 assert( DbMaskTest(p->btreeMask, iDb) ); 6181 iMoved = 0; /* Not needed. Only to silence a warning. */ 6182 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved); 6183 pOut->flags = MEM_Int; 6184 pOut->u.i = iMoved; 6185 if( rc ) goto abort_due_to_error; 6186 #ifndef SQLITE_OMIT_AUTOVACUUM 6187 if( iMoved!=0 ){ 6188 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1); 6189 /* All OP_Destroy operations occur on the same btree */ 6190 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 ); 6191 resetSchemaOnFault = iDb+1; 6192 } 6193 #endif 6194 } 6195 break; 6196 } 6197 6198 /* Opcode: Clear P1 P2 P3 6199 ** 6200 ** Delete all contents of the database table or index whose root page 6201 ** in the database file is given by P1. But, unlike Destroy, do not 6202 ** remove the table or index from the database file. 6203 ** 6204 ** The table being clear is in the main database file if P2==0. If 6205 ** P2==1 then the table to be clear is in the auxiliary database file 6206 ** that is used to store tables create using CREATE TEMPORARY TABLE. 6207 ** 6208 ** If the P3 value is non-zero, then the table referred to must be an 6209 ** intkey table (an SQL table, not an index). In this case the row change 6210 ** count is incremented by the number of rows in the table being cleared. 6211 ** If P3 is greater than zero, then the value stored in register P3 is 6212 ** also incremented by the number of rows in the table being cleared. 6213 ** 6214 ** See also: Destroy 6215 */ 6216 case OP_Clear: { 6217 int nChange; 6218 6219 sqlite3VdbeIncrWriteCounter(p, 0); 6220 nChange = 0; 6221 assert( p->readOnly==0 ); 6222 assert( DbMaskTest(p->btreeMask, pOp->p2) ); 6223 rc = sqlite3BtreeClearTable( 6224 db->aDb[pOp->p2].pBt, (u32)pOp->p1, (pOp->p3 ? &nChange : 0) 6225 ); 6226 if( pOp->p3 ){ 6227 p->nChange += nChange; 6228 if( pOp->p3>0 ){ 6229 assert( memIsValid(&aMem[pOp->p3]) ); 6230 memAboutToChange(p, &aMem[pOp->p3]); 6231 aMem[pOp->p3].u.i += nChange; 6232 } 6233 } 6234 if( rc ) goto abort_due_to_error; 6235 break; 6236 } 6237 6238 /* Opcode: ResetSorter P1 * * * * 6239 ** 6240 ** Delete all contents from the ephemeral table or sorter 6241 ** that is open on cursor P1. 6242 ** 6243 ** This opcode only works for cursors used for sorting and 6244 ** opened with OP_OpenEphemeral or OP_SorterOpen. 6245 */ 6246 case OP_ResetSorter: { 6247 VdbeCursor *pC; 6248 6249 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 6250 pC = p->apCsr[pOp->p1]; 6251 assert( pC!=0 ); 6252 if( isSorter(pC) ){ 6253 sqlite3VdbeSorterReset(db, pC->uc.pSorter); 6254 }else{ 6255 assert( pC->eCurType==CURTYPE_BTREE ); 6256 assert( pC->isEphemeral ); 6257 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor); 6258 if( rc ) goto abort_due_to_error; 6259 } 6260 break; 6261 } 6262 6263 /* Opcode: CreateBtree P1 P2 P3 * * 6264 ** Synopsis: r[P2]=root iDb=P1 flags=P3 6265 ** 6266 ** Allocate a new b-tree in the main database file if P1==0 or in the 6267 ** TEMP database file if P1==1 or in an attached database if 6268 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table 6269 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table. 6270 ** The root page number of the new b-tree is stored in register P2. 6271 */ 6272 case OP_CreateBtree: { /* out2 */ 6273 Pgno pgno; 6274 Db *pDb; 6275 6276 sqlite3VdbeIncrWriteCounter(p, 0); 6277 pOut = out2Prerelease(p, pOp); 6278 pgno = 0; 6279 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY ); 6280 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 6281 assert( DbMaskTest(p->btreeMask, pOp->p1) ); 6282 assert( p->readOnly==0 ); 6283 pDb = &db->aDb[pOp->p1]; 6284 assert( pDb->pBt!=0 ); 6285 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3); 6286 if( rc ) goto abort_due_to_error; 6287 pOut->u.i = pgno; 6288 break; 6289 } 6290 6291 /* Opcode: SqlExec * * * P4 * 6292 ** 6293 ** Run the SQL statement or statements specified in the P4 string. 6294 */ 6295 case OP_SqlExec: { 6296 sqlite3VdbeIncrWriteCounter(p, 0); 6297 db->nSqlExec++; 6298 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0); 6299 db->nSqlExec--; 6300 if( rc ) goto abort_due_to_error; 6301 break; 6302 } 6303 6304 /* Opcode: ParseSchema P1 * * P4 * 6305 ** 6306 ** Read and parse all entries from the schema table of database P1 6307 ** that match the WHERE clause P4. If P4 is a NULL pointer, then the 6308 ** entire schema for P1 is reparsed. 6309 ** 6310 ** This opcode invokes the parser to create a new virtual machine, 6311 ** then runs the new virtual machine. It is thus a re-entrant opcode. 6312 */ 6313 case OP_ParseSchema: { 6314 int iDb; 6315 const char *zSchema; 6316 char *zSql; 6317 InitData initData; 6318 6319 /* Any prepared statement that invokes this opcode will hold mutexes 6320 ** on every btree. This is a prerequisite for invoking 6321 ** sqlite3InitCallback(). 6322 */ 6323 #ifdef SQLITE_DEBUG 6324 for(iDb=0; iDb<db->nDb; iDb++){ 6325 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); 6326 } 6327 #endif 6328 6329 iDb = pOp->p1; 6330 assert( iDb>=0 && iDb<db->nDb ); 6331 assert( DbHasProperty(db, iDb, DB_SchemaLoaded) ); 6332 6333 #ifndef SQLITE_OMIT_ALTERTABLE 6334 if( pOp->p4.z==0 ){ 6335 sqlite3SchemaClear(db->aDb[iDb].pSchema); 6336 db->mDbFlags &= ~DBFLAG_SchemaKnownOk; 6337 rc = sqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable); 6338 db->mDbFlags |= DBFLAG_SchemaChange; 6339 p->expired = 0; 6340 }else 6341 #endif 6342 { 6343 zSchema = DFLT_SCHEMA_TABLE; 6344 initData.db = db; 6345 initData.iDb = iDb; 6346 initData.pzErrMsg = &p->zErrMsg; 6347 initData.mInitFlags = 0; 6348 initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt); 6349 zSql = sqlite3MPrintf(db, 6350 "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid", 6351 db->aDb[iDb].zDbSName, zSchema, pOp->p4.z); 6352 if( zSql==0 ){ 6353 rc = SQLITE_NOMEM_BKPT; 6354 }else{ 6355 assert( db->init.busy==0 ); 6356 db->init.busy = 1; 6357 initData.rc = SQLITE_OK; 6358 initData.nInitRow = 0; 6359 assert( !db->mallocFailed ); 6360 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); 6361 if( rc==SQLITE_OK ) rc = initData.rc; 6362 if( rc==SQLITE_OK && initData.nInitRow==0 ){ 6363 /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse 6364 ** at least one SQL statement. Any less than that indicates that 6365 ** the sqlite_schema table is corrupt. */ 6366 rc = SQLITE_CORRUPT_BKPT; 6367 } 6368 sqlite3DbFreeNN(db, zSql); 6369 db->init.busy = 0; 6370 } 6371 } 6372 if( rc ){ 6373 sqlite3ResetAllSchemasOfConnection(db); 6374 if( rc==SQLITE_NOMEM ){ 6375 goto no_mem; 6376 } 6377 goto abort_due_to_error; 6378 } 6379 break; 6380 } 6381 6382 #if !defined(SQLITE_OMIT_ANALYZE) 6383 /* Opcode: LoadAnalysis P1 * * * * 6384 ** 6385 ** Read the sqlite_stat1 table for database P1 and load the content 6386 ** of that table into the internal index hash table. This will cause 6387 ** the analysis to be used when preparing all subsequent queries. 6388 */ 6389 case OP_LoadAnalysis: { 6390 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 6391 rc = sqlite3AnalysisLoad(db, pOp->p1); 6392 if( rc ) goto abort_due_to_error; 6393 break; 6394 } 6395 #endif /* !defined(SQLITE_OMIT_ANALYZE) */ 6396 6397 /* Opcode: DropTable P1 * * P4 * 6398 ** 6399 ** Remove the internal (in-memory) data structures that describe 6400 ** the table named P4 in database P1. This is called after a table 6401 ** is dropped from disk (using the Destroy opcode) in order to keep 6402 ** the internal representation of the 6403 ** schema consistent with what is on disk. 6404 */ 6405 case OP_DropTable: { 6406 sqlite3VdbeIncrWriteCounter(p, 0); 6407 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z); 6408 break; 6409 } 6410 6411 /* Opcode: DropIndex P1 * * P4 * 6412 ** 6413 ** Remove the internal (in-memory) data structures that describe 6414 ** the index named P4 in database P1. This is called after an index 6415 ** is dropped from disk (using the Destroy opcode) 6416 ** in order to keep the internal representation of the 6417 ** schema consistent with what is on disk. 6418 */ 6419 case OP_DropIndex: { 6420 sqlite3VdbeIncrWriteCounter(p, 0); 6421 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z); 6422 break; 6423 } 6424 6425 /* Opcode: DropTrigger P1 * * P4 * 6426 ** 6427 ** Remove the internal (in-memory) data structures that describe 6428 ** the trigger named P4 in database P1. This is called after a trigger 6429 ** is dropped from disk (using the Destroy opcode) in order to keep 6430 ** the internal representation of the 6431 ** schema consistent with what is on disk. 6432 */ 6433 case OP_DropTrigger: { 6434 sqlite3VdbeIncrWriteCounter(p, 0); 6435 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z); 6436 break; 6437 } 6438 6439 6440 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 6441 /* Opcode: IntegrityCk P1 P2 P3 P4 P5 6442 ** 6443 ** Do an analysis of the currently open database. Store in 6444 ** register P1 the text of an error message describing any problems. 6445 ** If no problems are found, store a NULL in register P1. 6446 ** 6447 ** The register P3 contains one less than the maximum number of allowed errors. 6448 ** At most reg(P3) errors will be reported. 6449 ** In other words, the analysis stops as soon as reg(P1) errors are 6450 ** seen. Reg(P1) is updated with the number of errors remaining. 6451 ** 6452 ** The root page numbers of all tables in the database are integers 6453 ** stored in P4_INTARRAY argument. 6454 ** 6455 ** If P5 is not zero, the check is done on the auxiliary database 6456 ** file, not the main database file. 6457 ** 6458 ** This opcode is used to implement the integrity_check pragma. 6459 */ 6460 case OP_IntegrityCk: { 6461 int nRoot; /* Number of tables to check. (Number of root pages.) */ 6462 Pgno *aRoot; /* Array of rootpage numbers for tables to be checked */ 6463 int nErr; /* Number of errors reported */ 6464 char *z; /* Text of the error report */ 6465 Mem *pnErr; /* Register keeping track of errors remaining */ 6466 6467 assert( p->bIsReader ); 6468 nRoot = pOp->p2; 6469 aRoot = pOp->p4.ai; 6470 assert( nRoot>0 ); 6471 assert( aRoot[0]==(Pgno)nRoot ); 6472 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); 6473 pnErr = &aMem[pOp->p3]; 6474 assert( (pnErr->flags & MEM_Int)!=0 ); 6475 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 ); 6476 pIn1 = &aMem[pOp->p1]; 6477 assert( pOp->p5<db->nDb ); 6478 assert( DbMaskTest(p->btreeMask, pOp->p5) ); 6479 z = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot, 6480 (int)pnErr->u.i+1, &nErr); 6481 sqlite3VdbeMemSetNull(pIn1); 6482 if( nErr==0 ){ 6483 assert( z==0 ); 6484 }else if( z==0 ){ 6485 goto no_mem; 6486 }else{ 6487 pnErr->u.i -= nErr-1; 6488 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free); 6489 } 6490 UPDATE_MAX_BLOBSIZE(pIn1); 6491 sqlite3VdbeChangeEncoding(pIn1, encoding); 6492 goto check_for_interrupt; 6493 } 6494 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 6495 6496 /* Opcode: RowSetAdd P1 P2 * * * 6497 ** Synopsis: rowset(P1)=r[P2] 6498 ** 6499 ** Insert the integer value held by register P2 into a RowSet object 6500 ** held in register P1. 6501 ** 6502 ** An assertion fails if P2 is not an integer. 6503 */ 6504 case OP_RowSetAdd: { /* in1, in2 */ 6505 pIn1 = &aMem[pOp->p1]; 6506 pIn2 = &aMem[pOp->p2]; 6507 assert( (pIn2->flags & MEM_Int)!=0 ); 6508 if( (pIn1->flags & MEM_Blob)==0 ){ 6509 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem; 6510 } 6511 assert( sqlite3VdbeMemIsRowSet(pIn1) ); 6512 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i); 6513 break; 6514 } 6515 6516 /* Opcode: RowSetRead P1 P2 P3 * * 6517 ** Synopsis: r[P3]=rowset(P1) 6518 ** 6519 ** Extract the smallest value from the RowSet object in P1 6520 ** and put that value into register P3. 6521 ** Or, if RowSet object P1 is initially empty, leave P3 6522 ** unchanged and jump to instruction P2. 6523 */ 6524 case OP_RowSetRead: { /* jump, in1, out3 */ 6525 i64 val; 6526 6527 pIn1 = &aMem[pOp->p1]; 6528 assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) ); 6529 if( (pIn1->flags & MEM_Blob)==0 6530 || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0 6531 ){ 6532 /* The boolean index is empty */ 6533 sqlite3VdbeMemSetNull(pIn1); 6534 VdbeBranchTaken(1,2); 6535 goto jump_to_p2_and_check_for_interrupt; 6536 }else{ 6537 /* A value was pulled from the index */ 6538 VdbeBranchTaken(0,2); 6539 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val); 6540 } 6541 goto check_for_interrupt; 6542 } 6543 6544 /* Opcode: RowSetTest P1 P2 P3 P4 6545 ** Synopsis: if r[P3] in rowset(P1) goto P2 6546 ** 6547 ** Register P3 is assumed to hold a 64-bit integer value. If register P1 6548 ** contains a RowSet object and that RowSet object contains 6549 ** the value held in P3, jump to register P2. Otherwise, insert the 6550 ** integer in P3 into the RowSet and continue on to the 6551 ** next opcode. 6552 ** 6553 ** The RowSet object is optimized for the case where sets of integers 6554 ** are inserted in distinct phases, which each set contains no duplicates. 6555 ** Each set is identified by a unique P4 value. The first set 6556 ** must have P4==0, the final set must have P4==-1, and for all other sets 6557 ** must have P4>0. 6558 ** 6559 ** This allows optimizations: (a) when P4==0 there is no need to test 6560 ** the RowSet object for P3, as it is guaranteed not to contain it, 6561 ** (b) when P4==-1 there is no need to insert the value, as it will 6562 ** never be tested for, and (c) when a value that is part of set X is 6563 ** inserted, there is no need to search to see if the same value was 6564 ** previously inserted as part of set X (only if it was previously 6565 ** inserted as part of some other set). 6566 */ 6567 case OP_RowSetTest: { /* jump, in1, in3 */ 6568 int iSet; 6569 int exists; 6570 6571 pIn1 = &aMem[pOp->p1]; 6572 pIn3 = &aMem[pOp->p3]; 6573 iSet = pOp->p4.i; 6574 assert( pIn3->flags&MEM_Int ); 6575 6576 /* If there is anything other than a rowset object in memory cell P1, 6577 ** delete it now and initialize P1 with an empty rowset 6578 */ 6579 if( (pIn1->flags & MEM_Blob)==0 ){ 6580 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem; 6581 } 6582 assert( sqlite3VdbeMemIsRowSet(pIn1) ); 6583 assert( pOp->p4type==P4_INT32 ); 6584 assert( iSet==-1 || iSet>=0 ); 6585 if( iSet ){ 6586 exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i); 6587 VdbeBranchTaken(exists!=0,2); 6588 if( exists ) goto jump_to_p2; 6589 } 6590 if( iSet>=0 ){ 6591 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i); 6592 } 6593 break; 6594 } 6595 6596 6597 #ifndef SQLITE_OMIT_TRIGGER 6598 6599 /* Opcode: Program P1 P2 P3 P4 P5 6600 ** 6601 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 6602 ** 6603 ** P1 contains the address of the memory cell that contains the first memory 6604 ** cell in an array of values used as arguments to the sub-program. P2 6605 ** contains the address to jump to if the sub-program throws an IGNORE 6606 ** exception using the RAISE() function. Register P3 contains the address 6607 ** of a memory cell in this (the parent) VM that is used to allocate the 6608 ** memory required by the sub-vdbe at runtime. 6609 ** 6610 ** P4 is a pointer to the VM containing the trigger program. 6611 ** 6612 ** If P5 is non-zero, then recursive program invocation is enabled. 6613 */ 6614 case OP_Program: { /* jump */ 6615 int nMem; /* Number of memory registers for sub-program */ 6616 int nByte; /* Bytes of runtime space required for sub-program */ 6617 Mem *pRt; /* Register to allocate runtime space */ 6618 Mem *pMem; /* Used to iterate through memory cells */ 6619 Mem *pEnd; /* Last memory cell in new array */ 6620 VdbeFrame *pFrame; /* New vdbe frame to execute in */ 6621 SubProgram *pProgram; /* Sub-program to execute */ 6622 void *t; /* Token identifying trigger */ 6623 6624 pProgram = pOp->p4.pProgram; 6625 pRt = &aMem[pOp->p3]; 6626 assert( pProgram->nOp>0 ); 6627 6628 /* If the p5 flag is clear, then recursive invocation of triggers is 6629 ** disabled for backwards compatibility (p5 is set if this sub-program 6630 ** is really a trigger, not a foreign key action, and the flag set 6631 ** and cleared by the "PRAGMA recursive_triggers" command is clear). 6632 ** 6633 ** It is recursive invocation of triggers, at the SQL level, that is 6634 ** disabled. In some cases a single trigger may generate more than one 6635 ** SubProgram (if the trigger may be executed with more than one different 6636 ** ON CONFLICT algorithm). SubProgram structures associated with a 6637 ** single trigger all have the same value for the SubProgram.token 6638 ** variable. */ 6639 if( pOp->p5 ){ 6640 t = pProgram->token; 6641 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent); 6642 if( pFrame ) break; 6643 } 6644 6645 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){ 6646 rc = SQLITE_ERROR; 6647 sqlite3VdbeError(p, "too many levels of trigger recursion"); 6648 goto abort_due_to_error; 6649 } 6650 6651 /* Register pRt is used to store the memory required to save the state 6652 ** of the current program, and the memory required at runtime to execute 6653 ** the trigger program. If this trigger has been fired before, then pRt 6654 ** is already allocated. Otherwise, it must be initialized. */ 6655 if( (pRt->flags&MEM_Blob)==0 ){ 6656 /* SubProgram.nMem is set to the number of memory cells used by the 6657 ** program stored in SubProgram.aOp. As well as these, one memory 6658 ** cell is required for each cursor used by the program. Set local 6659 ** variable nMem (and later, VdbeFrame.nChildMem) to this value. 6660 */ 6661 nMem = pProgram->nMem + pProgram->nCsr; 6662 assert( nMem>0 ); 6663 if( pProgram->nCsr==0 ) nMem++; 6664 nByte = ROUND8(sizeof(VdbeFrame)) 6665 + nMem * sizeof(Mem) 6666 + pProgram->nCsr * sizeof(VdbeCursor*) 6667 + (pProgram->nOp + 7)/8; 6668 pFrame = sqlite3DbMallocZero(db, nByte); 6669 if( !pFrame ){ 6670 goto no_mem; 6671 } 6672 sqlite3VdbeMemRelease(pRt); 6673 pRt->flags = MEM_Blob|MEM_Dyn; 6674 pRt->z = (char*)pFrame; 6675 pRt->n = nByte; 6676 pRt->xDel = sqlite3VdbeFrameMemDel; 6677 6678 pFrame->v = p; 6679 pFrame->nChildMem = nMem; 6680 pFrame->nChildCsr = pProgram->nCsr; 6681 pFrame->pc = (int)(pOp - aOp); 6682 pFrame->aMem = p->aMem; 6683 pFrame->nMem = p->nMem; 6684 pFrame->apCsr = p->apCsr; 6685 pFrame->nCursor = p->nCursor; 6686 pFrame->aOp = p->aOp; 6687 pFrame->nOp = p->nOp; 6688 pFrame->token = pProgram->token; 6689 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 6690 pFrame->anExec = p->anExec; 6691 #endif 6692 #ifdef SQLITE_DEBUG 6693 pFrame->iFrameMagic = SQLITE_FRAME_MAGIC; 6694 #endif 6695 6696 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem]; 6697 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){ 6698 pMem->flags = MEM_Undefined; 6699 pMem->db = db; 6700 } 6701 }else{ 6702 pFrame = (VdbeFrame*)pRt->z; 6703 assert( pRt->xDel==sqlite3VdbeFrameMemDel ); 6704 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem 6705 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) ); 6706 assert( pProgram->nCsr==pFrame->nChildCsr ); 6707 assert( (int)(pOp - aOp)==pFrame->pc ); 6708 } 6709 6710 p->nFrame++; 6711 pFrame->pParent = p->pFrame; 6712 pFrame->lastRowid = db->lastRowid; 6713 pFrame->nChange = p->nChange; 6714 pFrame->nDbChange = p->db->nChange; 6715 assert( pFrame->pAuxData==0 ); 6716 pFrame->pAuxData = p->pAuxData; 6717 p->pAuxData = 0; 6718 p->nChange = 0; 6719 p->pFrame = pFrame; 6720 p->aMem = aMem = VdbeFrameMem(pFrame); 6721 p->nMem = pFrame->nChildMem; 6722 p->nCursor = (u16)pFrame->nChildCsr; 6723 p->apCsr = (VdbeCursor **)&aMem[p->nMem]; 6724 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr]; 6725 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8); 6726 p->aOp = aOp = pProgram->aOp; 6727 p->nOp = pProgram->nOp; 6728 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 6729 p->anExec = 0; 6730 #endif 6731 #ifdef SQLITE_DEBUG 6732 /* Verify that second and subsequent executions of the same trigger do not 6733 ** try to reuse register values from the first use. */ 6734 { 6735 int i; 6736 for(i=0; i<p->nMem; i++){ 6737 aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */ 6738 MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */ 6739 } 6740 } 6741 #endif 6742 pOp = &aOp[-1]; 6743 goto check_for_interrupt; 6744 } 6745 6746 /* Opcode: Param P1 P2 * * * 6747 ** 6748 ** This opcode is only ever present in sub-programs called via the 6749 ** OP_Program instruction. Copy a value currently stored in a memory 6750 ** cell of the calling (parent) frame to cell P2 in the current frames 6751 ** address space. This is used by trigger programs to access the new.* 6752 ** and old.* values. 6753 ** 6754 ** The address of the cell in the parent frame is determined by adding 6755 ** the value of the P1 argument to the value of the P1 argument to the 6756 ** calling OP_Program instruction. 6757 */ 6758 case OP_Param: { /* out2 */ 6759 VdbeFrame *pFrame; 6760 Mem *pIn; 6761 pOut = out2Prerelease(p, pOp); 6762 pFrame = p->pFrame; 6763 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1]; 6764 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem); 6765 break; 6766 } 6767 6768 #endif /* #ifndef SQLITE_OMIT_TRIGGER */ 6769 6770 #ifndef SQLITE_OMIT_FOREIGN_KEY 6771 /* Opcode: FkCounter P1 P2 * * * 6772 ** Synopsis: fkctr[P1]+=P2 6773 ** 6774 ** Increment a "constraint counter" by P2 (P2 may be negative or positive). 6775 ** If P1 is non-zero, the database constraint counter is incremented 6776 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 6777 ** statement counter is incremented (immediate foreign key constraints). 6778 */ 6779 case OP_FkCounter: { 6780 if( db->flags & SQLITE_DeferFKs ){ 6781 db->nDeferredImmCons += pOp->p2; 6782 }else if( pOp->p1 ){ 6783 db->nDeferredCons += pOp->p2; 6784 }else{ 6785 p->nFkConstraint += pOp->p2; 6786 } 6787 break; 6788 } 6789 6790 /* Opcode: FkIfZero P1 P2 * * * 6791 ** Synopsis: if fkctr[P1]==0 goto P2 6792 ** 6793 ** This opcode tests if a foreign key constraint-counter is currently zero. 6794 ** If so, jump to instruction P2. Otherwise, fall through to the next 6795 ** instruction. 6796 ** 6797 ** If P1 is non-zero, then the jump is taken if the database constraint-counter 6798 ** is zero (the one that counts deferred constraint violations). If P1 is 6799 ** zero, the jump is taken if the statement constraint-counter is zero 6800 ** (immediate foreign key constraint violations). 6801 */ 6802 case OP_FkIfZero: { /* jump */ 6803 if( pOp->p1 ){ 6804 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2); 6805 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2; 6806 }else{ 6807 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2); 6808 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2; 6809 } 6810 break; 6811 } 6812 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */ 6813 6814 #ifndef SQLITE_OMIT_AUTOINCREMENT 6815 /* Opcode: MemMax P1 P2 * * * 6816 ** Synopsis: r[P1]=max(r[P1],r[P2]) 6817 ** 6818 ** P1 is a register in the root frame of this VM (the root frame is 6819 ** different from the current frame if this instruction is being executed 6820 ** within a sub-program). Set the value of register P1 to the maximum of 6821 ** its current value and the value in register P2. 6822 ** 6823 ** This instruction throws an error if the memory cell is not initially 6824 ** an integer. 6825 */ 6826 case OP_MemMax: { /* in2 */ 6827 VdbeFrame *pFrame; 6828 if( p->pFrame ){ 6829 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); 6830 pIn1 = &pFrame->aMem[pOp->p1]; 6831 }else{ 6832 pIn1 = &aMem[pOp->p1]; 6833 } 6834 assert( memIsValid(pIn1) ); 6835 sqlite3VdbeMemIntegerify(pIn1); 6836 pIn2 = &aMem[pOp->p2]; 6837 sqlite3VdbeMemIntegerify(pIn2); 6838 if( pIn1->u.i<pIn2->u.i){ 6839 pIn1->u.i = pIn2->u.i; 6840 } 6841 break; 6842 } 6843 #endif /* SQLITE_OMIT_AUTOINCREMENT */ 6844 6845 /* Opcode: IfPos P1 P2 P3 * * 6846 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 6847 ** 6848 ** Register P1 must contain an integer. 6849 ** If the value of register P1 is 1 or greater, subtract P3 from the 6850 ** value in P1 and jump to P2. 6851 ** 6852 ** If the initial value of register P1 is less than 1, then the 6853 ** value is unchanged and control passes through to the next instruction. 6854 */ 6855 case OP_IfPos: { /* jump, in1 */ 6856 pIn1 = &aMem[pOp->p1]; 6857 assert( pIn1->flags&MEM_Int ); 6858 VdbeBranchTaken( pIn1->u.i>0, 2); 6859 if( pIn1->u.i>0 ){ 6860 pIn1->u.i -= pOp->p3; 6861 goto jump_to_p2; 6862 } 6863 break; 6864 } 6865 6866 /* Opcode: OffsetLimit P1 P2 P3 * * 6867 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) 6868 ** 6869 ** This opcode performs a commonly used computation associated with 6870 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3] 6871 ** holds the offset counter. The opcode computes the combined value 6872 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2] 6873 ** value computed is the total number of rows that will need to be 6874 ** visited in order to complete the query. 6875 ** 6876 ** If r[P3] is zero or negative, that means there is no OFFSET 6877 ** and r[P2] is set to be the value of the LIMIT, r[P1]. 6878 ** 6879 ** if r[P1] is zero or negative, that means there is no LIMIT 6880 ** and r[P2] is set to -1. 6881 ** 6882 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3]. 6883 */ 6884 case OP_OffsetLimit: { /* in1, out2, in3 */ 6885 i64 x; 6886 pIn1 = &aMem[pOp->p1]; 6887 pIn3 = &aMem[pOp->p3]; 6888 pOut = out2Prerelease(p, pOp); 6889 assert( pIn1->flags & MEM_Int ); 6890 assert( pIn3->flags & MEM_Int ); 6891 x = pIn1->u.i; 6892 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){ 6893 /* If the LIMIT is less than or equal to zero, loop forever. This 6894 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then 6895 ** also loop forever. This is undocumented. In fact, one could argue 6896 ** that the loop should terminate. But assuming 1 billion iterations 6897 ** per second (far exceeding the capabilities of any current hardware) 6898 ** it would take nearly 300 years to actually reach the limit. So 6899 ** looping forever is a reasonable approximation. */ 6900 pOut->u.i = -1; 6901 }else{ 6902 pOut->u.i = x; 6903 } 6904 break; 6905 } 6906 6907 /* Opcode: IfNotZero P1 P2 * * * 6908 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2 6909 ** 6910 ** Register P1 must contain an integer. If the content of register P1 is 6911 ** initially greater than zero, then decrement the value in register P1. 6912 ** If it is non-zero (negative or positive) and then also jump to P2. 6913 ** If register P1 is initially zero, leave it unchanged and fall through. 6914 */ 6915 case OP_IfNotZero: { /* jump, in1 */ 6916 pIn1 = &aMem[pOp->p1]; 6917 assert( pIn1->flags&MEM_Int ); 6918 VdbeBranchTaken(pIn1->u.i<0, 2); 6919 if( pIn1->u.i ){ 6920 if( pIn1->u.i>0 ) pIn1->u.i--; 6921 goto jump_to_p2; 6922 } 6923 break; 6924 } 6925 6926 /* Opcode: DecrJumpZero P1 P2 * * * 6927 ** Synopsis: if (--r[P1])==0 goto P2 6928 ** 6929 ** Register P1 must hold an integer. Decrement the value in P1 6930 ** and jump to P2 if the new value is exactly zero. 6931 */ 6932 case OP_DecrJumpZero: { /* jump, in1 */ 6933 pIn1 = &aMem[pOp->p1]; 6934 assert( pIn1->flags&MEM_Int ); 6935 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--; 6936 VdbeBranchTaken(pIn1->u.i==0, 2); 6937 if( pIn1->u.i==0 ) goto jump_to_p2; 6938 break; 6939 } 6940 6941 6942 /* Opcode: AggStep * P2 P3 P4 P5 6943 ** Synopsis: accum=r[P3] step(r[P2@P5]) 6944 ** 6945 ** Execute the xStep function for an aggregate. 6946 ** The function has P5 arguments. P4 is a pointer to the 6947 ** FuncDef structure that specifies the function. Register P3 is the 6948 ** accumulator. 6949 ** 6950 ** The P5 arguments are taken from register P2 and its 6951 ** successors. 6952 */ 6953 /* Opcode: AggInverse * P2 P3 P4 P5 6954 ** Synopsis: accum=r[P3] inverse(r[P2@P5]) 6955 ** 6956 ** Execute the xInverse function for an aggregate. 6957 ** The function has P5 arguments. P4 is a pointer to the 6958 ** FuncDef structure that specifies the function. Register P3 is the 6959 ** accumulator. 6960 ** 6961 ** The P5 arguments are taken from register P2 and its 6962 ** successors. 6963 */ 6964 /* Opcode: AggStep1 P1 P2 P3 P4 P5 6965 ** Synopsis: accum=r[P3] step(r[P2@P5]) 6966 ** 6967 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an 6968 ** aggregate. The function has P5 arguments. P4 is a pointer to the 6969 ** FuncDef structure that specifies the function. Register P3 is the 6970 ** accumulator. 6971 ** 6972 ** The P5 arguments are taken from register P2 and its 6973 ** successors. 6974 ** 6975 ** This opcode is initially coded as OP_AggStep0. On first evaluation, 6976 ** the FuncDef stored in P4 is converted into an sqlite3_context and 6977 ** the opcode is changed. In this way, the initialization of the 6978 ** sqlite3_context only happens once, instead of on each call to the 6979 ** step function. 6980 */ 6981 case OP_AggInverse: 6982 case OP_AggStep: { 6983 int n; 6984 sqlite3_context *pCtx; 6985 6986 assert( pOp->p4type==P4_FUNCDEF ); 6987 n = pOp->p5; 6988 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); 6989 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) ); 6990 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n ); 6991 pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) + 6992 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*))); 6993 if( pCtx==0 ) goto no_mem; 6994 pCtx->pMem = 0; 6995 pCtx->pOut = (Mem*)&(pCtx->argv[n]); 6996 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null); 6997 pCtx->pFunc = pOp->p4.pFunc; 6998 pCtx->iOp = (int)(pOp - aOp); 6999 pCtx->pVdbe = p; 7000 pCtx->skipFlag = 0; 7001 pCtx->isError = 0; 7002 pCtx->argc = n; 7003 pOp->p4type = P4_FUNCCTX; 7004 pOp->p4.pCtx = pCtx; 7005 7006 /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */ 7007 assert( pOp->p1==(pOp->opcode==OP_AggInverse) ); 7008 7009 pOp->opcode = OP_AggStep1; 7010 /* Fall through into OP_AggStep */ 7011 /* no break */ deliberate_fall_through 7012 } 7013 case OP_AggStep1: { 7014 int i; 7015 sqlite3_context *pCtx; 7016 Mem *pMem; 7017 7018 assert( pOp->p4type==P4_FUNCCTX ); 7019 pCtx = pOp->p4.pCtx; 7020 pMem = &aMem[pOp->p3]; 7021 7022 #ifdef SQLITE_DEBUG 7023 if( pOp->p1 ){ 7024 /* This is an OP_AggInverse call. Verify that xStep has always 7025 ** been called at least once prior to any xInverse call. */ 7026 assert( pMem->uTemp==0x1122e0e3 ); 7027 }else{ 7028 /* This is an OP_AggStep call. Mark it as such. */ 7029 pMem->uTemp = 0x1122e0e3; 7030 } 7031 #endif 7032 7033 /* If this function is inside of a trigger, the register array in aMem[] 7034 ** might change from one evaluation to the next. The next block of code 7035 ** checks to see if the register array has changed, and if so it 7036 ** reinitializes the relavant parts of the sqlite3_context object */ 7037 if( pCtx->pMem != pMem ){ 7038 pCtx->pMem = pMem; 7039 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; 7040 } 7041 7042 #ifdef SQLITE_DEBUG 7043 for(i=0; i<pCtx->argc; i++){ 7044 assert( memIsValid(pCtx->argv[i]) ); 7045 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]); 7046 } 7047 #endif 7048 7049 pMem->n++; 7050 assert( pCtx->pOut->flags==MEM_Null ); 7051 assert( pCtx->isError==0 ); 7052 assert( pCtx->skipFlag==0 ); 7053 #ifndef SQLITE_OMIT_WINDOWFUNC 7054 if( pOp->p1 ){ 7055 (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv); 7056 }else 7057 #endif 7058 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */ 7059 7060 if( pCtx->isError ){ 7061 if( pCtx->isError>0 ){ 7062 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut)); 7063 rc = pCtx->isError; 7064 } 7065 if( pCtx->skipFlag ){ 7066 assert( pOp[-1].opcode==OP_CollSeq ); 7067 i = pOp[-1].p1; 7068 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1); 7069 pCtx->skipFlag = 0; 7070 } 7071 sqlite3VdbeMemRelease(pCtx->pOut); 7072 pCtx->pOut->flags = MEM_Null; 7073 pCtx->isError = 0; 7074 if( rc ) goto abort_due_to_error; 7075 } 7076 assert( pCtx->pOut->flags==MEM_Null ); 7077 assert( pCtx->skipFlag==0 ); 7078 break; 7079 } 7080 7081 /* Opcode: AggFinal P1 P2 * P4 * 7082 ** Synopsis: accum=r[P1] N=P2 7083 ** 7084 ** P1 is the memory location that is the accumulator for an aggregate 7085 ** or window function. Execute the finalizer function 7086 ** for an aggregate and store the result in P1. 7087 ** 7088 ** P2 is the number of arguments that the step function takes and 7089 ** P4 is a pointer to the FuncDef for this function. The P2 7090 ** argument is not used by this opcode. It is only there to disambiguate 7091 ** functions that can take varying numbers of arguments. The 7092 ** P4 argument is only needed for the case where 7093 ** the step function was not previously called. 7094 */ 7095 /* Opcode: AggValue * P2 P3 P4 * 7096 ** Synopsis: r[P3]=value N=P2 7097 ** 7098 ** Invoke the xValue() function and store the result in register P3. 7099 ** 7100 ** P2 is the number of arguments that the step function takes and 7101 ** P4 is a pointer to the FuncDef for this function. The P2 7102 ** argument is not used by this opcode. It is only there to disambiguate 7103 ** functions that can take varying numbers of arguments. The 7104 ** P4 argument is only needed for the case where 7105 ** the step function was not previously called. 7106 */ 7107 case OP_AggValue: 7108 case OP_AggFinal: { 7109 Mem *pMem; 7110 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); 7111 assert( pOp->p3==0 || pOp->opcode==OP_AggValue ); 7112 pMem = &aMem[pOp->p1]; 7113 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 ); 7114 #ifndef SQLITE_OMIT_WINDOWFUNC 7115 if( pOp->p3 ){ 7116 memAboutToChange(p, &aMem[pOp->p3]); 7117 rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc); 7118 pMem = &aMem[pOp->p3]; 7119 }else 7120 #endif 7121 { 7122 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc); 7123 } 7124 7125 if( rc ){ 7126 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem)); 7127 goto abort_due_to_error; 7128 } 7129 sqlite3VdbeChangeEncoding(pMem, encoding); 7130 UPDATE_MAX_BLOBSIZE(pMem); 7131 if( sqlite3VdbeMemTooBig(pMem) ){ 7132 goto too_big; 7133 } 7134 break; 7135 } 7136 7137 #ifndef SQLITE_OMIT_WAL 7138 /* Opcode: Checkpoint P1 P2 P3 * * 7139 ** 7140 ** Checkpoint database P1. This is a no-op if P1 is not currently in 7141 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL, 7142 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns 7143 ** SQLITE_BUSY or not, respectively. Write the number of pages in the 7144 ** WAL after the checkpoint into mem[P3+1] and the number of pages 7145 ** in the WAL that have been checkpointed after the checkpoint 7146 ** completes into mem[P3+2]. However on an error, mem[P3+1] and 7147 ** mem[P3+2] are initialized to -1. 7148 */ 7149 case OP_Checkpoint: { 7150 int i; /* Loop counter */ 7151 int aRes[3]; /* Results */ 7152 Mem *pMem; /* Write results here */ 7153 7154 assert( p->readOnly==0 ); 7155 aRes[0] = 0; 7156 aRes[1] = aRes[2] = -1; 7157 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE 7158 || pOp->p2==SQLITE_CHECKPOINT_FULL 7159 || pOp->p2==SQLITE_CHECKPOINT_RESTART 7160 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE 7161 ); 7162 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]); 7163 if( rc ){ 7164 if( rc!=SQLITE_BUSY ) goto abort_due_to_error; 7165 rc = SQLITE_OK; 7166 aRes[0] = 1; 7167 } 7168 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){ 7169 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]); 7170 } 7171 break; 7172 }; 7173 #endif 7174 7175 #ifndef SQLITE_OMIT_PRAGMA 7176 /* Opcode: JournalMode P1 P2 P3 * * 7177 ** 7178 ** Change the journal mode of database P1 to P3. P3 must be one of the 7179 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback 7180 ** modes (delete, truncate, persist, off and memory), this is a simple 7181 ** operation. No IO is required. 7182 ** 7183 ** If changing into or out of WAL mode the procedure is more complicated. 7184 ** 7185 ** Write a string containing the final journal-mode to register P2. 7186 */ 7187 case OP_JournalMode: { /* out2 */ 7188 Btree *pBt; /* Btree to change journal mode of */ 7189 Pager *pPager; /* Pager associated with pBt */ 7190 int eNew; /* New journal mode */ 7191 int eOld; /* The old journal mode */ 7192 #ifndef SQLITE_OMIT_WAL 7193 const char *zFilename; /* Name of database file for pPager */ 7194 #endif 7195 7196 pOut = out2Prerelease(p, pOp); 7197 eNew = pOp->p3; 7198 assert( eNew==PAGER_JOURNALMODE_DELETE 7199 || eNew==PAGER_JOURNALMODE_TRUNCATE 7200 || eNew==PAGER_JOURNALMODE_PERSIST 7201 || eNew==PAGER_JOURNALMODE_OFF 7202 || eNew==PAGER_JOURNALMODE_MEMORY 7203 || eNew==PAGER_JOURNALMODE_WAL 7204 || eNew==PAGER_JOURNALMODE_QUERY 7205 ); 7206 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 7207 assert( p->readOnly==0 ); 7208 7209 pBt = db->aDb[pOp->p1].pBt; 7210 pPager = sqlite3BtreePager(pBt); 7211 eOld = sqlite3PagerGetJournalMode(pPager); 7212 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld; 7213 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld; 7214 7215 #ifndef SQLITE_OMIT_WAL 7216 zFilename = sqlite3PagerFilename(pPager, 1); 7217 7218 /* Do not allow a transition to journal_mode=WAL for a database 7219 ** in temporary storage or if the VFS does not support shared memory 7220 */ 7221 if( eNew==PAGER_JOURNALMODE_WAL 7222 && (sqlite3Strlen30(zFilename)==0 /* Temp file */ 7223 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */ 7224 ){ 7225 eNew = eOld; 7226 } 7227 7228 if( (eNew!=eOld) 7229 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL) 7230 ){ 7231 if( !db->autoCommit || db->nVdbeRead>1 ){ 7232 rc = SQLITE_ERROR; 7233 sqlite3VdbeError(p, 7234 "cannot change %s wal mode from within a transaction", 7235 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of") 7236 ); 7237 goto abort_due_to_error; 7238 }else{ 7239 7240 if( eOld==PAGER_JOURNALMODE_WAL ){ 7241 /* If leaving WAL mode, close the log file. If successful, the call 7242 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log 7243 ** file. An EXCLUSIVE lock may still be held on the database file 7244 ** after a successful return. 7245 */ 7246 rc = sqlite3PagerCloseWal(pPager, db); 7247 if( rc==SQLITE_OK ){ 7248 sqlite3PagerSetJournalMode(pPager, eNew); 7249 } 7250 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){ 7251 /* Cannot transition directly from MEMORY to WAL. Use mode OFF 7252 ** as an intermediate */ 7253 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF); 7254 } 7255 7256 /* Open a transaction on the database file. Regardless of the journal 7257 ** mode, this transaction always uses a rollback journal. 7258 */ 7259 assert( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ); 7260 if( rc==SQLITE_OK ){ 7261 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1)); 7262 } 7263 } 7264 } 7265 #endif /* ifndef SQLITE_OMIT_WAL */ 7266 7267 if( rc ) eNew = eOld; 7268 eNew = sqlite3PagerSetJournalMode(pPager, eNew); 7269 7270 pOut->flags = MEM_Str|MEM_Static|MEM_Term; 7271 pOut->z = (char *)sqlite3JournalModename(eNew); 7272 pOut->n = sqlite3Strlen30(pOut->z); 7273 pOut->enc = SQLITE_UTF8; 7274 sqlite3VdbeChangeEncoding(pOut, encoding); 7275 if( rc ) goto abort_due_to_error; 7276 break; 7277 }; 7278 #endif /* SQLITE_OMIT_PRAGMA */ 7279 7280 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) 7281 /* Opcode: Vacuum P1 P2 * * * 7282 ** 7283 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more 7284 ** for an attached database. The "temp" database may not be vacuumed. 7285 ** 7286 ** If P2 is not zero, then it is a register holding a string which is 7287 ** the file into which the result of vacuum should be written. When 7288 ** P2 is zero, the vacuum overwrites the original database. 7289 */ 7290 case OP_Vacuum: { 7291 assert( p->readOnly==0 ); 7292 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1, 7293 pOp->p2 ? &aMem[pOp->p2] : 0); 7294 if( rc ) goto abort_due_to_error; 7295 break; 7296 } 7297 #endif 7298 7299 #if !defined(SQLITE_OMIT_AUTOVACUUM) 7300 /* Opcode: IncrVacuum P1 P2 * * * 7301 ** 7302 ** Perform a single step of the incremental vacuum procedure on 7303 ** the P1 database. If the vacuum has finished, jump to instruction 7304 ** P2. Otherwise, fall through to the next instruction. 7305 */ 7306 case OP_IncrVacuum: { /* jump */ 7307 Btree *pBt; 7308 7309 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 7310 assert( DbMaskTest(p->btreeMask, pOp->p1) ); 7311 assert( p->readOnly==0 ); 7312 pBt = db->aDb[pOp->p1].pBt; 7313 rc = sqlite3BtreeIncrVacuum(pBt); 7314 VdbeBranchTaken(rc==SQLITE_DONE,2); 7315 if( rc ){ 7316 if( rc!=SQLITE_DONE ) goto abort_due_to_error; 7317 rc = SQLITE_OK; 7318 goto jump_to_p2; 7319 } 7320 break; 7321 } 7322 #endif 7323 7324 /* Opcode: Expire P1 P2 * * * 7325 ** 7326 ** Cause precompiled statements to expire. When an expired statement 7327 ** is executed using sqlite3_step() it will either automatically 7328 ** reprepare itself (if it was originally created using sqlite3_prepare_v2()) 7329 ** or it will fail with SQLITE_SCHEMA. 7330 ** 7331 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero, 7332 ** then only the currently executing statement is expired. 7333 ** 7334 ** If P2 is 0, then SQL statements are expired immediately. If P2 is 1, 7335 ** then running SQL statements are allowed to continue to run to completion. 7336 ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens 7337 ** that might help the statement run faster but which does not affect the 7338 ** correctness of operation. 7339 */ 7340 case OP_Expire: { 7341 assert( pOp->p2==0 || pOp->p2==1 ); 7342 if( !pOp->p1 ){ 7343 sqlite3ExpirePreparedStatements(db, pOp->p2); 7344 }else{ 7345 p->expired = pOp->p2+1; 7346 } 7347 break; 7348 } 7349 7350 /* Opcode: CursorLock P1 * * * * 7351 ** 7352 ** Lock the btree to which cursor P1 is pointing so that the btree cannot be 7353 ** written by an other cursor. 7354 */ 7355 case OP_CursorLock: { 7356 VdbeCursor *pC; 7357 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 7358 pC = p->apCsr[pOp->p1]; 7359 assert( pC!=0 ); 7360 assert( pC->eCurType==CURTYPE_BTREE ); 7361 sqlite3BtreeCursorPin(pC->uc.pCursor); 7362 break; 7363 } 7364 7365 /* Opcode: CursorUnlock P1 * * * * 7366 ** 7367 ** Unlock the btree to which cursor P1 is pointing so that it can be 7368 ** written by other cursors. 7369 */ 7370 case OP_CursorUnlock: { 7371 VdbeCursor *pC; 7372 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 7373 pC = p->apCsr[pOp->p1]; 7374 assert( pC!=0 ); 7375 assert( pC->eCurType==CURTYPE_BTREE ); 7376 sqlite3BtreeCursorUnpin(pC->uc.pCursor); 7377 break; 7378 } 7379 7380 #ifndef SQLITE_OMIT_SHARED_CACHE 7381 /* Opcode: TableLock P1 P2 P3 P4 * 7382 ** Synopsis: iDb=P1 root=P2 write=P3 7383 ** 7384 ** Obtain a lock on a particular table. This instruction is only used when 7385 ** the shared-cache feature is enabled. 7386 ** 7387 ** P1 is the index of the database in sqlite3.aDb[] of the database 7388 ** on which the lock is acquired. A readlock is obtained if P3==0 or 7389 ** a write lock if P3==1. 7390 ** 7391 ** P2 contains the root-page of the table to lock. 7392 ** 7393 ** P4 contains a pointer to the name of the table being locked. This is only 7394 ** used to generate an error message if the lock cannot be obtained. 7395 */ 7396 case OP_TableLock: { 7397 u8 isWriteLock = (u8)pOp->p3; 7398 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){ 7399 int p1 = pOp->p1; 7400 assert( p1>=0 && p1<db->nDb ); 7401 assert( DbMaskTest(p->btreeMask, p1) ); 7402 assert( isWriteLock==0 || isWriteLock==1 ); 7403 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock); 7404 if( rc ){ 7405 if( (rc&0xFF)==SQLITE_LOCKED ){ 7406 const char *z = pOp->p4.z; 7407 sqlite3VdbeError(p, "database table is locked: %s", z); 7408 } 7409 goto abort_due_to_error; 7410 } 7411 } 7412 break; 7413 } 7414 #endif /* SQLITE_OMIT_SHARED_CACHE */ 7415 7416 #ifndef SQLITE_OMIT_VIRTUALTABLE 7417 /* Opcode: VBegin * * * P4 * 7418 ** 7419 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 7420 ** xBegin method for that table. 7421 ** 7422 ** Also, whether or not P4 is set, check that this is not being called from 7423 ** within a callback to a virtual table xSync() method. If it is, the error 7424 ** code will be set to SQLITE_LOCKED. 7425 */ 7426 case OP_VBegin: { 7427 VTable *pVTab; 7428 pVTab = pOp->p4.pVtab; 7429 rc = sqlite3VtabBegin(db, pVTab); 7430 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab); 7431 if( rc ) goto abort_due_to_error; 7432 break; 7433 } 7434 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7435 7436 #ifndef SQLITE_OMIT_VIRTUALTABLE 7437 /* Opcode: VCreate P1 P2 * * * 7438 ** 7439 ** P2 is a register that holds the name of a virtual table in database 7440 ** P1. Call the xCreate method for that table. 7441 */ 7442 case OP_VCreate: { 7443 Mem sMem; /* For storing the record being decoded */ 7444 const char *zTab; /* Name of the virtual table */ 7445 7446 memset(&sMem, 0, sizeof(sMem)); 7447 sMem.db = db; 7448 /* Because P2 is always a static string, it is impossible for the 7449 ** sqlite3VdbeMemCopy() to fail */ 7450 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 ); 7451 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 ); 7452 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]); 7453 assert( rc==SQLITE_OK ); 7454 zTab = (const char*)sqlite3_value_text(&sMem); 7455 assert( zTab || db->mallocFailed ); 7456 if( zTab ){ 7457 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg); 7458 } 7459 sqlite3VdbeMemRelease(&sMem); 7460 if( rc ) goto abort_due_to_error; 7461 break; 7462 } 7463 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7464 7465 #ifndef SQLITE_OMIT_VIRTUALTABLE 7466 /* Opcode: VDestroy P1 * * P4 * 7467 ** 7468 ** P4 is the name of a virtual table in database P1. Call the xDestroy method 7469 ** of that table. 7470 */ 7471 case OP_VDestroy: { 7472 db->nVDestroy++; 7473 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z); 7474 db->nVDestroy--; 7475 assert( p->errorAction==OE_Abort && p->usesStmtJournal ); 7476 if( rc ) goto abort_due_to_error; 7477 break; 7478 } 7479 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7480 7481 #ifndef SQLITE_OMIT_VIRTUALTABLE 7482 /* Opcode: VOpen P1 * * P4 * 7483 ** 7484 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. 7485 ** P1 is a cursor number. This opcode opens a cursor to the virtual 7486 ** table and stores that cursor in P1. 7487 */ 7488 case OP_VOpen: { 7489 VdbeCursor *pCur; 7490 sqlite3_vtab_cursor *pVCur; 7491 sqlite3_vtab *pVtab; 7492 const sqlite3_module *pModule; 7493 7494 assert( p->bIsReader ); 7495 pCur = 0; 7496 pVCur = 0; 7497 pVtab = pOp->p4.pVtab->pVtab; 7498 if( pVtab==0 || NEVER(pVtab->pModule==0) ){ 7499 rc = SQLITE_LOCKED; 7500 goto abort_due_to_error; 7501 } 7502 pModule = pVtab->pModule; 7503 rc = pModule->xOpen(pVtab, &pVCur); 7504 sqlite3VtabImportErrmsg(p, pVtab); 7505 if( rc ) goto abort_due_to_error; 7506 7507 /* Initialize sqlite3_vtab_cursor base class */ 7508 pVCur->pVtab = pVtab; 7509 7510 /* Initialize vdbe cursor object */ 7511 pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB); 7512 if( pCur ){ 7513 pCur->uc.pVCur = pVCur; 7514 pVtab->nRef++; 7515 }else{ 7516 assert( db->mallocFailed ); 7517 pModule->xClose(pVCur); 7518 goto no_mem; 7519 } 7520 break; 7521 } 7522 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7523 7524 #ifndef SQLITE_OMIT_VIRTUALTABLE 7525 /* Opcode: VFilter P1 P2 P3 P4 * 7526 ** Synopsis: iplan=r[P3] zplan='P4' 7527 ** 7528 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if 7529 ** the filtered result set is empty. 7530 ** 7531 ** P4 is either NULL or a string that was generated by the xBestIndex 7532 ** method of the module. The interpretation of the P4 string is left 7533 ** to the module implementation. 7534 ** 7535 ** This opcode invokes the xFilter method on the virtual table specified 7536 ** by P1. The integer query plan parameter to xFilter is stored in register 7537 ** P3. Register P3+1 stores the argc parameter to be passed to the 7538 ** xFilter method. Registers P3+2..P3+1+argc are the argc 7539 ** additional parameters which are passed to 7540 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter. 7541 ** 7542 ** A jump is made to P2 if the result set after filtering would be empty. 7543 */ 7544 case OP_VFilter: { /* jump */ 7545 int nArg; 7546 int iQuery; 7547 const sqlite3_module *pModule; 7548 Mem *pQuery; 7549 Mem *pArgc; 7550 sqlite3_vtab_cursor *pVCur; 7551 sqlite3_vtab *pVtab; 7552 VdbeCursor *pCur; 7553 int res; 7554 int i; 7555 Mem **apArg; 7556 7557 pQuery = &aMem[pOp->p3]; 7558 pArgc = &pQuery[1]; 7559 pCur = p->apCsr[pOp->p1]; 7560 assert( memIsValid(pQuery) ); 7561 REGISTER_TRACE(pOp->p3, pQuery); 7562 assert( pCur->eCurType==CURTYPE_VTAB ); 7563 pVCur = pCur->uc.pVCur; 7564 pVtab = pVCur->pVtab; 7565 pModule = pVtab->pModule; 7566 7567 /* Grab the index number and argc parameters */ 7568 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int ); 7569 nArg = (int)pArgc->u.i; 7570 iQuery = (int)pQuery->u.i; 7571 7572 /* Invoke the xFilter method */ 7573 res = 0; 7574 apArg = p->apArg; 7575 for(i = 0; i<nArg; i++){ 7576 apArg[i] = &pArgc[i+1]; 7577 } 7578 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg); 7579 sqlite3VtabImportErrmsg(p, pVtab); 7580 if( rc ) goto abort_due_to_error; 7581 res = pModule->xEof(pVCur); 7582 pCur->nullRow = 0; 7583 VdbeBranchTaken(res!=0,2); 7584 if( res ) goto jump_to_p2; 7585 break; 7586 } 7587 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7588 7589 #ifndef SQLITE_OMIT_VIRTUALTABLE 7590 /* Opcode: VColumn P1 P2 P3 * P5 7591 ** Synopsis: r[P3]=vcolumn(P2) 7592 ** 7593 ** Store in register P3 the value of the P2-th column of 7594 ** the current row of the virtual-table of cursor P1. 7595 ** 7596 ** If the VColumn opcode is being used to fetch the value of 7597 ** an unchanging column during an UPDATE operation, then the P5 7598 ** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange() 7599 ** function to return true inside the xColumn method of the virtual 7600 ** table implementation. The P5 column might also contain other 7601 ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are 7602 ** unused by OP_VColumn. 7603 */ 7604 case OP_VColumn: { 7605 sqlite3_vtab *pVtab; 7606 const sqlite3_module *pModule; 7607 Mem *pDest; 7608 sqlite3_context sContext; 7609 7610 VdbeCursor *pCur = p->apCsr[pOp->p1]; 7611 assert( pCur->eCurType==CURTYPE_VTAB ); 7612 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); 7613 pDest = &aMem[pOp->p3]; 7614 memAboutToChange(p, pDest); 7615 if( pCur->nullRow ){ 7616 sqlite3VdbeMemSetNull(pDest); 7617 break; 7618 } 7619 pVtab = pCur->uc.pVCur->pVtab; 7620 pModule = pVtab->pModule; 7621 assert( pModule->xColumn ); 7622 memset(&sContext, 0, sizeof(sContext)); 7623 sContext.pOut = pDest; 7624 assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 ); 7625 if( pOp->p5 & OPFLAG_NOCHNG ){ 7626 sqlite3VdbeMemSetNull(pDest); 7627 pDest->flags = MEM_Null|MEM_Zero; 7628 pDest->u.nZero = 0; 7629 }else{ 7630 MemSetTypeFlag(pDest, MEM_Null); 7631 } 7632 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2); 7633 sqlite3VtabImportErrmsg(p, pVtab); 7634 if( sContext.isError>0 ){ 7635 sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest)); 7636 rc = sContext.isError; 7637 } 7638 sqlite3VdbeChangeEncoding(pDest, encoding); 7639 REGISTER_TRACE(pOp->p3, pDest); 7640 UPDATE_MAX_BLOBSIZE(pDest); 7641 7642 if( sqlite3VdbeMemTooBig(pDest) ){ 7643 goto too_big; 7644 } 7645 if( rc ) goto abort_due_to_error; 7646 break; 7647 } 7648 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7649 7650 #ifndef SQLITE_OMIT_VIRTUALTABLE 7651 /* Opcode: VNext P1 P2 * * * 7652 ** 7653 ** Advance virtual table P1 to the next row in its result set and 7654 ** jump to instruction P2. Or, if the virtual table has reached 7655 ** the end of its result set, then fall through to the next instruction. 7656 */ 7657 case OP_VNext: { /* jump */ 7658 sqlite3_vtab *pVtab; 7659 const sqlite3_module *pModule; 7660 int res; 7661 VdbeCursor *pCur; 7662 7663 res = 0; 7664 pCur = p->apCsr[pOp->p1]; 7665 assert( pCur->eCurType==CURTYPE_VTAB ); 7666 if( pCur->nullRow ){ 7667 break; 7668 } 7669 pVtab = pCur->uc.pVCur->pVtab; 7670 pModule = pVtab->pModule; 7671 assert( pModule->xNext ); 7672 7673 /* Invoke the xNext() method of the module. There is no way for the 7674 ** underlying implementation to return an error if one occurs during 7675 ** xNext(). Instead, if an error occurs, true is returned (indicating that 7676 ** data is available) and the error code returned when xColumn or 7677 ** some other method is next invoked on the save virtual table cursor. 7678 */ 7679 rc = pModule->xNext(pCur->uc.pVCur); 7680 sqlite3VtabImportErrmsg(p, pVtab); 7681 if( rc ) goto abort_due_to_error; 7682 res = pModule->xEof(pCur->uc.pVCur); 7683 VdbeBranchTaken(!res,2); 7684 if( !res ){ 7685 /* If there is data, jump to P2 */ 7686 goto jump_to_p2_and_check_for_interrupt; 7687 } 7688 goto check_for_interrupt; 7689 } 7690 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7691 7692 #ifndef SQLITE_OMIT_VIRTUALTABLE 7693 /* Opcode: VRename P1 * * P4 * 7694 ** 7695 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. 7696 ** This opcode invokes the corresponding xRename method. The value 7697 ** in register P1 is passed as the zName argument to the xRename method. 7698 */ 7699 case OP_VRename: { 7700 sqlite3_vtab *pVtab; 7701 Mem *pName; 7702 int isLegacy; 7703 7704 isLegacy = (db->flags & SQLITE_LegacyAlter); 7705 db->flags |= SQLITE_LegacyAlter; 7706 pVtab = pOp->p4.pVtab->pVtab; 7707 pName = &aMem[pOp->p1]; 7708 assert( pVtab->pModule->xRename ); 7709 assert( memIsValid(pName) ); 7710 assert( p->readOnly==0 ); 7711 REGISTER_TRACE(pOp->p1, pName); 7712 assert( pName->flags & MEM_Str ); 7713 testcase( pName->enc==SQLITE_UTF8 ); 7714 testcase( pName->enc==SQLITE_UTF16BE ); 7715 testcase( pName->enc==SQLITE_UTF16LE ); 7716 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8); 7717 if( rc ) goto abort_due_to_error; 7718 rc = pVtab->pModule->xRename(pVtab, pName->z); 7719 if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter; 7720 sqlite3VtabImportErrmsg(p, pVtab); 7721 p->expired = 0; 7722 if( rc ) goto abort_due_to_error; 7723 break; 7724 } 7725 #endif 7726 7727 #ifndef SQLITE_OMIT_VIRTUALTABLE 7728 /* Opcode: VUpdate P1 P2 P3 P4 P5 7729 ** Synopsis: data=r[P3@P2] 7730 ** 7731 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. 7732 ** This opcode invokes the corresponding xUpdate method. P2 values 7733 ** are contiguous memory cells starting at P3 to pass to the xUpdate 7734 ** invocation. The value in register (P3+P2-1) corresponds to the 7735 ** p2th element of the argv array passed to xUpdate. 7736 ** 7737 ** The xUpdate method will do a DELETE or an INSERT or both. 7738 ** The argv[0] element (which corresponds to memory cell P3) 7739 ** is the rowid of a row to delete. If argv[0] is NULL then no 7740 ** deletion occurs. The argv[1] element is the rowid of the new 7741 ** row. This can be NULL to have the virtual table select the new 7742 ** rowid for itself. The subsequent elements in the array are 7743 ** the values of columns in the new row. 7744 ** 7745 ** If P2==1 then no insert is performed. argv[0] is the rowid of 7746 ** a row to delete. 7747 ** 7748 ** P1 is a boolean flag. If it is set to true and the xUpdate call 7749 ** is successful, then the value returned by sqlite3_last_insert_rowid() 7750 ** is set to the value of the rowid for the row just inserted. 7751 ** 7752 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to 7753 ** apply in the case of a constraint failure on an insert or update. 7754 */ 7755 case OP_VUpdate: { 7756 sqlite3_vtab *pVtab; 7757 const sqlite3_module *pModule; 7758 int nArg; 7759 int i; 7760 sqlite_int64 rowid; 7761 Mem **apArg; 7762 Mem *pX; 7763 7764 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback 7765 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace 7766 ); 7767 assert( p->readOnly==0 ); 7768 if( db->mallocFailed ) goto no_mem; 7769 sqlite3VdbeIncrWriteCounter(p, 0); 7770 pVtab = pOp->p4.pVtab->pVtab; 7771 if( pVtab==0 || NEVER(pVtab->pModule==0) ){ 7772 rc = SQLITE_LOCKED; 7773 goto abort_due_to_error; 7774 } 7775 pModule = pVtab->pModule; 7776 nArg = pOp->p2; 7777 assert( pOp->p4type==P4_VTAB ); 7778 if( ALWAYS(pModule->xUpdate) ){ 7779 u8 vtabOnConflict = db->vtabOnConflict; 7780 apArg = p->apArg; 7781 pX = &aMem[pOp->p3]; 7782 for(i=0; i<nArg; i++){ 7783 assert( memIsValid(pX) ); 7784 memAboutToChange(p, pX); 7785 apArg[i] = pX; 7786 pX++; 7787 } 7788 db->vtabOnConflict = pOp->p5; 7789 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid); 7790 db->vtabOnConflict = vtabOnConflict; 7791 sqlite3VtabImportErrmsg(p, pVtab); 7792 if( rc==SQLITE_OK && pOp->p1 ){ 7793 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) ); 7794 db->lastRowid = rowid; 7795 } 7796 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){ 7797 if( pOp->p5==OE_Ignore ){ 7798 rc = SQLITE_OK; 7799 }else{ 7800 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5); 7801 } 7802 }else{ 7803 p->nChange++; 7804 } 7805 if( rc ) goto abort_due_to_error; 7806 } 7807 break; 7808 } 7809 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 7810 7811 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 7812 /* Opcode: Pagecount P1 P2 * * * 7813 ** 7814 ** Write the current number of pages in database P1 to memory cell P2. 7815 */ 7816 case OP_Pagecount: { /* out2 */ 7817 pOut = out2Prerelease(p, pOp); 7818 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt); 7819 break; 7820 } 7821 #endif 7822 7823 7824 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 7825 /* Opcode: MaxPgcnt P1 P2 P3 * * 7826 ** 7827 ** Try to set the maximum page count for database P1 to the value in P3. 7828 ** Do not let the maximum page count fall below the current page count and 7829 ** do not change the maximum page count value if P3==0. 7830 ** 7831 ** Store the maximum page count after the change in register P2. 7832 */ 7833 case OP_MaxPgcnt: { /* out2 */ 7834 unsigned int newMax; 7835 Btree *pBt; 7836 7837 pOut = out2Prerelease(p, pOp); 7838 pBt = db->aDb[pOp->p1].pBt; 7839 newMax = 0; 7840 if( pOp->p3 ){ 7841 newMax = sqlite3BtreeLastPage(pBt); 7842 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3; 7843 } 7844 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax); 7845 break; 7846 } 7847 #endif 7848 7849 /* Opcode: Function P1 P2 P3 P4 * 7850 ** Synopsis: r[P3]=func(r[P2@NP]) 7851 ** 7852 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that 7853 ** contains a pointer to the function to be run) with arguments taken 7854 ** from register P2 and successors. The number of arguments is in 7855 ** the sqlite3_context object that P4 points to. 7856 ** The result of the function is stored 7857 ** in register P3. Register P3 must not be one of the function inputs. 7858 ** 7859 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 7860 ** function was determined to be constant at compile time. If the first 7861 ** argument was constant then bit 0 of P1 is set. This is used to determine 7862 ** whether meta data associated with a user function argument using the 7863 ** sqlite3_set_auxdata() API may be safely retained until the next 7864 ** invocation of this opcode. 7865 ** 7866 ** See also: AggStep, AggFinal, PureFunc 7867 */ 7868 /* Opcode: PureFunc P1 P2 P3 P4 * 7869 ** Synopsis: r[P3]=func(r[P2@NP]) 7870 ** 7871 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that 7872 ** contains a pointer to the function to be run) with arguments taken 7873 ** from register P2 and successors. The number of arguments is in 7874 ** the sqlite3_context object that P4 points to. 7875 ** The result of the function is stored 7876 ** in register P3. Register P3 must not be one of the function inputs. 7877 ** 7878 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 7879 ** function was determined to be constant at compile time. If the first 7880 ** argument was constant then bit 0 of P1 is set. This is used to determine 7881 ** whether meta data associated with a user function argument using the 7882 ** sqlite3_set_auxdata() API may be safely retained until the next 7883 ** invocation of this opcode. 7884 ** 7885 ** This opcode works exactly like OP_Function. The only difference is in 7886 ** its name. This opcode is used in places where the function must be 7887 ** purely non-deterministic. Some built-in date/time functions can be 7888 ** either determinitic of non-deterministic, depending on their arguments. 7889 ** When those function are used in a non-deterministic way, they will check 7890 ** to see if they were called using OP_PureFunc instead of OP_Function, and 7891 ** if they were, they throw an error. 7892 ** 7893 ** See also: AggStep, AggFinal, Function 7894 */ 7895 case OP_PureFunc: /* group */ 7896 case OP_Function: { /* group */ 7897 int i; 7898 sqlite3_context *pCtx; 7899 7900 assert( pOp->p4type==P4_FUNCCTX ); 7901 pCtx = pOp->p4.pCtx; 7902 7903 /* If this function is inside of a trigger, the register array in aMem[] 7904 ** might change from one evaluation to the next. The next block of code 7905 ** checks to see if the register array has changed, and if so it 7906 ** reinitializes the relavant parts of the sqlite3_context object */ 7907 pOut = &aMem[pOp->p3]; 7908 if( pCtx->pOut != pOut ){ 7909 pCtx->pVdbe = p; 7910 pCtx->pOut = pOut; 7911 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; 7912 } 7913 assert( pCtx->pVdbe==p ); 7914 7915 memAboutToChange(p, pOut); 7916 #ifdef SQLITE_DEBUG 7917 for(i=0; i<pCtx->argc; i++){ 7918 assert( memIsValid(pCtx->argv[i]) ); 7919 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]); 7920 } 7921 #endif 7922 MemSetTypeFlag(pOut, MEM_Null); 7923 assert( pCtx->isError==0 ); 7924 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */ 7925 7926 /* If the function returned an error, throw an exception */ 7927 if( pCtx->isError ){ 7928 if( pCtx->isError>0 ){ 7929 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut)); 7930 rc = pCtx->isError; 7931 } 7932 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1); 7933 pCtx->isError = 0; 7934 if( rc ) goto abort_due_to_error; 7935 } 7936 7937 /* Copy the result of the function into register P3 */ 7938 if( pOut->flags & (MEM_Str|MEM_Blob) ){ 7939 sqlite3VdbeChangeEncoding(pOut, encoding); 7940 if( sqlite3VdbeMemTooBig(pOut) ) goto too_big; 7941 } 7942 7943 REGISTER_TRACE(pOp->p3, pOut); 7944 UPDATE_MAX_BLOBSIZE(pOut); 7945 break; 7946 } 7947 7948 /* Opcode: Trace P1 P2 * P4 * 7949 ** 7950 ** Write P4 on the statement trace output if statement tracing is 7951 ** enabled. 7952 ** 7953 ** Operand P1 must be 0x7fffffff and P2 must positive. 7954 */ 7955 /* Opcode: Init P1 P2 P3 P4 * 7956 ** Synopsis: Start at P2 7957 ** 7958 ** Programs contain a single instance of this opcode as the very first 7959 ** opcode. 7960 ** 7961 ** If tracing is enabled (by the sqlite3_trace()) interface, then 7962 ** the UTF-8 string contained in P4 is emitted on the trace callback. 7963 ** Or if P4 is blank, use the string returned by sqlite3_sql(). 7964 ** 7965 ** If P2 is not zero, jump to instruction P2. 7966 ** 7967 ** Increment the value of P1 so that OP_Once opcodes will jump the 7968 ** first time they are evaluated for this run. 7969 ** 7970 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT 7971 ** error is encountered. 7972 */ 7973 case OP_Trace: 7974 case OP_Init: { /* jump */ 7975 int i; 7976 #ifndef SQLITE_OMIT_TRACE 7977 char *zTrace; 7978 #endif 7979 7980 /* If the P4 argument is not NULL, then it must be an SQL comment string. 7981 ** The "--" string is broken up to prevent false-positives with srcck1.c. 7982 ** 7983 ** This assert() provides evidence for: 7984 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that 7985 ** would have been returned by the legacy sqlite3_trace() interface by 7986 ** using the X argument when X begins with "--" and invoking 7987 ** sqlite3_expanded_sql(P) otherwise. 7988 */ 7989 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 ); 7990 7991 /* OP_Init is always instruction 0 */ 7992 assert( pOp==p->aOp || pOp->opcode==OP_Trace ); 7993 7994 #ifndef SQLITE_OMIT_TRACE 7995 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0 7996 && !p->doingRerun 7997 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 7998 ){ 7999 #ifndef SQLITE_OMIT_DEPRECATED 8000 if( db->mTrace & SQLITE_TRACE_LEGACY ){ 8001 char *z = sqlite3VdbeExpandSql(p, zTrace); 8002 db->trace.xLegacy(db->pTraceArg, z); 8003 sqlite3_free(z); 8004 }else 8005 #endif 8006 if( db->nVdbeExec>1 ){ 8007 char *z = sqlite3MPrintf(db, "-- %s", zTrace); 8008 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z); 8009 sqlite3DbFree(db, z); 8010 }else{ 8011 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace); 8012 } 8013 } 8014 #ifdef SQLITE_USE_FCNTL_TRACE 8015 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql); 8016 if( zTrace ){ 8017 int j; 8018 for(j=0; j<db->nDb; j++){ 8019 if( DbMaskTest(p->btreeMask, j)==0 ) continue; 8020 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace); 8021 } 8022 } 8023 #endif /* SQLITE_USE_FCNTL_TRACE */ 8024 #ifdef SQLITE_DEBUG 8025 if( (db->flags & SQLITE_SqlTrace)!=0 8026 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 8027 ){ 8028 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace); 8029 } 8030 #endif /* SQLITE_DEBUG */ 8031 #endif /* SQLITE_OMIT_TRACE */ 8032 assert( pOp->p2>0 ); 8033 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){ 8034 if( pOp->opcode==OP_Trace ) break; 8035 for(i=1; i<p->nOp; i++){ 8036 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0; 8037 } 8038 pOp->p1 = 0; 8039 } 8040 pOp->p1++; 8041 p->aCounter[SQLITE_STMTSTATUS_RUN]++; 8042 goto jump_to_p2; 8043 } 8044 8045 #ifdef SQLITE_ENABLE_CURSOR_HINTS 8046 /* Opcode: CursorHint P1 * * P4 * 8047 ** 8048 ** Provide a hint to cursor P1 that it only needs to return rows that 8049 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer 8050 ** to values currently held in registers. TK_COLUMN terms in the P4 8051 ** expression refer to columns in the b-tree to which cursor P1 is pointing. 8052 */ 8053 case OP_CursorHint: { 8054 VdbeCursor *pC; 8055 8056 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 8057 assert( pOp->p4type==P4_EXPR ); 8058 pC = p->apCsr[pOp->p1]; 8059 if( pC ){ 8060 assert( pC->eCurType==CURTYPE_BTREE ); 8061 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE, 8062 pOp->p4.pExpr, aMem); 8063 } 8064 break; 8065 } 8066 #endif /* SQLITE_ENABLE_CURSOR_HINTS */ 8067 8068 #ifdef SQLITE_DEBUG 8069 /* Opcode: Abortable * * * * * 8070 ** 8071 ** Verify that an Abort can happen. Assert if an Abort at this point 8072 ** might cause database corruption. This opcode only appears in debugging 8073 ** builds. 8074 ** 8075 ** An Abort is safe if either there have been no writes, or if there is 8076 ** an active statement journal. 8077 */ 8078 case OP_Abortable: { 8079 sqlite3VdbeAssertAbortable(p); 8080 break; 8081 } 8082 #endif 8083 8084 #ifdef SQLITE_DEBUG 8085 /* Opcode: ReleaseReg P1 P2 P3 * P5 8086 ** Synopsis: release r[P1@P2] mask P3 8087 ** 8088 ** Release registers from service. Any content that was in the 8089 ** the registers is unreliable after this opcode completes. 8090 ** 8091 ** The registers released will be the P2 registers starting at P1, 8092 ** except if bit ii of P3 set, then do not release register P1+ii. 8093 ** In other words, P3 is a mask of registers to preserve. 8094 ** 8095 ** Releasing a register clears the Mem.pScopyFrom pointer. That means 8096 ** that if the content of the released register was set using OP_SCopy, 8097 ** a change to the value of the source register for the OP_SCopy will no longer 8098 ** generate an assertion fault in sqlite3VdbeMemAboutToChange(). 8099 ** 8100 ** If P5 is set, then all released registers have their type set 8101 ** to MEM_Undefined so that any subsequent attempt to read the released 8102 ** register (before it is reinitialized) will generate an assertion fault. 8103 ** 8104 ** P5 ought to be set on every call to this opcode. 8105 ** However, there are places in the code generator will release registers 8106 ** before their are used, under the (valid) assumption that the registers 8107 ** will not be reallocated for some other purpose before they are used and 8108 ** hence are safe to release. 8109 ** 8110 ** This opcode is only available in testing and debugging builds. It is 8111 ** not generated for release builds. The purpose of this opcode is to help 8112 ** validate the generated bytecode. This opcode does not actually contribute 8113 ** to computing an answer. 8114 */ 8115 case OP_ReleaseReg: { 8116 Mem *pMem; 8117 int i; 8118 u32 constMask; 8119 assert( pOp->p1>0 ); 8120 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 ); 8121 pMem = &aMem[pOp->p1]; 8122 constMask = pOp->p3; 8123 for(i=0; i<pOp->p2; i++, pMem++){ 8124 if( i>=32 || (constMask & MASKBIT32(i))==0 ){ 8125 pMem->pScopyFrom = 0; 8126 if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined); 8127 } 8128 } 8129 break; 8130 } 8131 #endif 8132 8133 /* Opcode: Noop * * * * * 8134 ** 8135 ** Do nothing. This instruction is often useful as a jump 8136 ** destination. 8137 */ 8138 /* 8139 ** The magic Explain opcode are only inserted when explain==2 (which 8140 ** is to say when the EXPLAIN QUERY PLAN syntax is used.) 8141 ** This opcode records information from the optimizer. It is the 8142 ** the same as a no-op. This opcodesnever appears in a real VM program. 8143 */ 8144 default: { /* This is really OP_Noop, OP_Explain */ 8145 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain ); 8146 8147 break; 8148 } 8149 8150 /***************************************************************************** 8151 ** The cases of the switch statement above this line should all be indented 8152 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the 8153 ** readability. From this point on down, the normal indentation rules are 8154 ** restored. 8155 *****************************************************************************/ 8156 } 8157 8158 #ifdef VDBE_PROFILE 8159 { 8160 u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime(); 8161 if( endTime>start ) pOrigOp->cycles += endTime - start; 8162 pOrigOp->cnt++; 8163 } 8164 #endif 8165 8166 /* The following code adds nothing to the actual functionality 8167 ** of the program. It is only here for testing and debugging. 8168 ** On the other hand, it does burn CPU cycles every time through 8169 ** the evaluator loop. So we can leave it out when NDEBUG is defined. 8170 */ 8171 #ifndef NDEBUG 8172 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] ); 8173 8174 #ifdef SQLITE_DEBUG 8175 if( db->flags & SQLITE_VdbeTrace ){ 8176 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode]; 8177 if( rc!=0 ) printf("rc=%d\n",rc); 8178 if( opProperty & (OPFLG_OUT2) ){ 8179 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]); 8180 } 8181 if( opProperty & OPFLG_OUT3 ){ 8182 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]); 8183 } 8184 if( opProperty==0xff ){ 8185 /* Never happens. This code exists to avoid a harmless linkage 8186 ** warning aboud sqlite3VdbeRegisterDump() being defined but not 8187 ** used. */ 8188 sqlite3VdbeRegisterDump(p); 8189 } 8190 } 8191 #endif /* SQLITE_DEBUG */ 8192 #endif /* NDEBUG */ 8193 } /* The end of the for(;;) loop the loops through opcodes */ 8194 8195 /* If we reach this point, it means that execution is finished with 8196 ** an error of some kind. 8197 */ 8198 abort_due_to_error: 8199 if( db->mallocFailed ){ 8200 rc = SQLITE_NOMEM_BKPT; 8201 }else if( rc==SQLITE_IOERR_CORRUPTFS ){ 8202 rc = SQLITE_CORRUPT_BKPT; 8203 } 8204 assert( rc ); 8205 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){ 8206 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc)); 8207 } 8208 p->rc = rc; 8209 sqlite3SystemError(db, rc); 8210 testcase( sqlite3GlobalConfig.xLog!=0 ); 8211 sqlite3_log(rc, "statement aborts at %d: [%s] %s", 8212 (int)(pOp - aOp), p->zSql, p->zErrMsg); 8213 sqlite3VdbeHalt(p); 8214 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db); 8215 rc = SQLITE_ERROR; 8216 if( resetSchemaOnFault>0 ){ 8217 sqlite3ResetOneSchema(db, resetSchemaOnFault-1); 8218 } 8219 8220 /* This is the only way out of this procedure. We have to 8221 ** release the mutexes on btrees that were acquired at the 8222 ** top. */ 8223 vdbe_return: 8224 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 8225 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){ 8226 nProgressLimit += db->nProgressOps; 8227 if( db->xProgress(db->pProgressArg) ){ 8228 nProgressLimit = LARGEST_UINT64; 8229 rc = SQLITE_INTERRUPT; 8230 goto abort_due_to_error; 8231 } 8232 } 8233 #endif 8234 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep; 8235 sqlite3VdbeLeave(p); 8236 assert( rc!=SQLITE_OK || nExtraDelete==0 8237 || sqlite3_strlike("DELETE%",p->zSql,0)!=0 8238 ); 8239 return rc; 8240 8241 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH 8242 ** is encountered. 8243 */ 8244 too_big: 8245 sqlite3VdbeError(p, "string or blob too big"); 8246 rc = SQLITE_TOOBIG; 8247 goto abort_due_to_error; 8248 8249 /* Jump to here if a malloc() fails. 8250 */ 8251 no_mem: 8252 sqlite3OomFault(db); 8253 sqlite3VdbeError(p, "out of memory"); 8254 rc = SQLITE_NOMEM_BKPT; 8255 goto abort_due_to_error; 8256 8257 /* Jump to here if the sqlite3_interrupt() API sets the interrupt 8258 ** flag. 8259 */ 8260 abort_due_to_interrupt: 8261 assert( AtomicLoad(&db->u1.isInterrupted) ); 8262 rc = SQLITE_INTERRUPT; 8263 goto abort_due_to_error; 8264 } 8265