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