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