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