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