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