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