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