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