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