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