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