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