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