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