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