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