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