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