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