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