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