Back to index

php5  5.3.10
vdbe.c
Go to the documentation of this file.
00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** The code in this file implements execution method of the 
00013 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
00014 ** handles housekeeping details such as creating and deleting
00015 ** VDBE instances.  This file is solely interested in executing
00016 ** the VDBE program.
00017 **
00018 ** In the external interface, an "sqlite_vm*" is an opaque pointer
00019 ** to a VDBE.
00020 **
00021 ** The SQL parser generates a program which is then executed by
00022 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
00023 ** similar in form to assembly language.  The program consists of
00024 ** a linear sequence of operations.  Each operation has an opcode 
00025 ** and 3 operands.  Operands P1 and P2 are integers.  Operand P3 
00026 ** is a null-terminated string.   The P2 operand must be non-negative.
00027 ** Opcodes will typically ignore one or more operands.  Many opcodes
00028 ** ignore all three operands.
00029 **
00030 ** Computation results are stored on a stack.  Each entry on the
00031 ** stack is either an integer, a null-terminated string, a floating point
00032 ** number, or the SQL "NULL" value.  An inplicit conversion from one
00033 ** type to the other occurs as necessary.
00034 ** 
00035 ** Most of the code in this file is taken up by the sqliteVdbeExec()
00036 ** function which does the work of interpreting a VDBE program.
00037 ** But other routines are also provided to help in building up
00038 ** a program instruction by instruction.
00039 **
00040 ** Various scripts scan this source file in order to generate HTML
00041 ** documentation, headers files, or other derived files.  The formatting
00042 ** of the code in this file is, therefore, important.  See other comments
00043 ** in this file for details.  If in doubt, do not deviate from existing
00044 ** commenting and indentation practices when changing or adding code.
00045 **
00046 ** $Id: vdbe.c 219681 2006-09-09 10:59:05Z tony2001 $
00047 */
00048 #include "sqliteInt.h"
00049 #include "os.h"
00050 #include <ctype.h>
00051 #include "vdbeInt.h"
00052 
00053 /*
00054 ** The following global variable is incremented every time a cursor
00055 ** moves, either by the OP_MoveTo or the OP_Next opcode.  The test
00056 ** procedures use this information to make sure that indices are
00057 ** working correctly.  This variable has no function other than to
00058 ** help verify the correct operation of the library.
00059 */
00060 int sqlite_search_count = 0;
00061 
00062 /*
00063 ** When this global variable is positive, it gets decremented once before
00064 ** each instruction in the VDBE.  When reaches zero, the SQLITE_Interrupt
00065 ** of the db.flags field is set in order to simulate an interrupt.
00066 **
00067 ** This facility is used for testing purposes only.  It does not function
00068 ** in an ordinary build.
00069 */
00070 int sqlite_interrupt_count = 0;
00071 
00072 /*
00073 ** Advance the virtual machine to the next output row.
00074 **
00075 ** The return vale will be either SQLITE_BUSY, SQLITE_DONE, 
00076 ** SQLITE_ROW, SQLITE_ERROR, or SQLITE_MISUSE.
00077 **
00078 ** SQLITE_BUSY means that the virtual machine attempted to open
00079 ** a locked database and there is no busy callback registered.
00080 ** Call sqlite_step() again to retry the open.  *pN is set to 0
00081 ** and *pazColName and *pazValue are both set to NULL.
00082 **
00083 ** SQLITE_DONE means that the virtual machine has finished
00084 ** executing.  sqlite_step() should not be called again on this
00085 ** virtual machine.  *pN and *pazColName are set appropriately
00086 ** but *pazValue is set to NULL.
00087 **
00088 ** SQLITE_ROW means that the virtual machine has generated another
00089 ** row of the result set.  *pN is set to the number of columns in
00090 ** the row.  *pazColName is set to the names of the columns followed
00091 ** by the column datatypes.  *pazValue is set to the values of each
00092 ** column in the row.  The value of the i-th column is (*pazValue)[i].
00093 ** The name of the i-th column is (*pazColName)[i] and the datatype
00094 ** of the i-th column is (*pazColName)[i+*pN].
00095 **
00096 ** SQLITE_ERROR means that a run-time error (such as a constraint
00097 ** violation) has occurred.  The details of the error will be returned
00098 ** by the next call to sqlite_finalize().  sqlite_step() should not
00099 ** be called again on the VM.
00100 **
00101 ** SQLITE_MISUSE means that the this routine was called inappropriately.
00102 ** Perhaps it was called on a virtual machine that had already been
00103 ** finalized or on one that had previously returned SQLITE_ERROR or
00104 ** SQLITE_DONE.  Or it could be the case the the same database connection
00105 ** is being used simulataneously by two or more threads.
00106 */
00107 int sqlite_step(
00108   sqlite_vm *pVm,              /* The virtual machine to execute */
00109   int *pN,                     /* OUT: Number of columns in result */
00110   const char ***pazValue,      /* OUT: Column data */
00111   const char ***pazColName     /* OUT: Column names and datatypes */
00112 ){
00113   Vdbe *p = (Vdbe*)pVm;
00114   sqlite *db;
00115   int rc;
00116 
00117   if( !p || p->magic!=VDBE_MAGIC_RUN ){
00118     return SQLITE_MISUSE;
00119   }
00120   db = p->db;
00121   if( sqliteSafetyOn(db) ){
00122     p->rc = SQLITE_MISUSE;
00123     return SQLITE_MISUSE;
00124   }
00125   if( p->explain ){
00126     rc = sqliteVdbeList(p);
00127   }else{
00128     rc = sqliteVdbeExec(p);
00129   }
00130   if( rc==SQLITE_DONE || rc==SQLITE_ROW ){
00131     if( pazColName ) *pazColName = (const char**)p->azColName;
00132     if( pN ) *pN = p->nResColumn;
00133   }else{
00134     if( pazColName) *pazColName = 0;
00135     if( pN ) *pN = 0;
00136   }
00137   if( pazValue ){
00138     if( rc==SQLITE_ROW ){
00139       *pazValue = (const char**)p->azResColumn;
00140     }else{
00141       *pazValue = 0;
00142     }
00143   }
00144   if( sqliteSafetyOff(db) ){
00145     return SQLITE_MISUSE;
00146   }
00147   return rc;
00148 }
00149 
00150 /*
00151 ** Insert a new aggregate element and make it the element that
00152 ** has focus.
00153 **
00154 ** Return 0 on success and 1 if memory is exhausted.
00155 */
00156 static int AggInsert(Agg *p, char *zKey, int nKey){
00157   AggElem *pElem, *pOld;
00158   int i;
00159   Mem *pMem;
00160   pElem = sqliteMalloc( sizeof(AggElem) + nKey +
00161                         (p->nMem-1)*sizeof(pElem->aMem[0]) );
00162   if( pElem==0 ) return 1;
00163   pElem->zKey = (char*)&pElem->aMem[p->nMem];
00164   memcpy(pElem->zKey, zKey, nKey);
00165   pElem->nKey = nKey;
00166   pOld = sqliteHashInsert(&p->hash, pElem->zKey, pElem->nKey, pElem);
00167   if( pOld!=0 ){
00168     assert( pOld==pElem );  /* Malloc failed on insert */
00169     sqliteFree(pOld);
00170     return 0;
00171   }
00172   for(i=0, pMem=pElem->aMem; i<p->nMem; i++, pMem++){
00173     pMem->flags = MEM_Null;
00174   }
00175   p->pCurrent = pElem;
00176   return 0;
00177 }
00178 
00179 /*
00180 ** Get the AggElem currently in focus
00181 */
00182 #define AggInFocus(P)   ((P).pCurrent ? (P).pCurrent : _AggInFocus(&(P)))
00183 static AggElem *_AggInFocus(Agg *p){
00184   HashElem *pElem = sqliteHashFirst(&p->hash);
00185   if( pElem==0 ){
00186     AggInsert(p,"",1);
00187     pElem = sqliteHashFirst(&p->hash);
00188   }
00189   return pElem ? sqliteHashData(pElem) : 0;
00190 }
00191 
00192 /*
00193 ** Convert the given stack entity into a string if it isn't one
00194 ** already.
00195 */
00196 #define Stringify(P) if(((P)->flags & MEM_Str)==0){hardStringify(P);}
00197 static int hardStringify(Mem *pStack){
00198   int fg = pStack->flags;
00199   if( fg & MEM_Real ){
00200     sqlite_snprintf(sizeof(pStack->zShort),pStack->zShort,"%.15g",pStack->r);
00201   }else if( fg & MEM_Int ){
00202     sqlite_snprintf(sizeof(pStack->zShort),pStack->zShort,"%d",pStack->i);
00203   }else{
00204     pStack->zShort[0] = 0;
00205   }
00206   pStack->z = pStack->zShort;
00207   pStack->n = strlen(pStack->zShort)+1;
00208   pStack->flags = MEM_Str | MEM_Short;
00209   return 0;
00210 }
00211 
00212 /*
00213 ** Convert the given stack entity into a string that has been obtained
00214 ** from sqliteMalloc().  This is different from Stringify() above in that
00215 ** Stringify() will use the NBFS bytes of static string space if the string
00216 ** will fit but this routine always mallocs for space.
00217 ** Return non-zero if we run out of memory.
00218 */
00219 #define Dynamicify(P) (((P)->flags & MEM_Dyn)==0 ? hardDynamicify(P):0)
00220 static int hardDynamicify(Mem *pStack){
00221   int fg = pStack->flags;
00222   char *z;
00223   if( (fg & MEM_Str)==0 ){
00224     hardStringify(pStack);
00225   }
00226   assert( (fg & MEM_Dyn)==0 );
00227   z = sqliteMallocRaw( pStack->n );
00228   if( z==0 ) return 1;
00229   memcpy(z, pStack->z, pStack->n);
00230   pStack->z = z;
00231   pStack->flags |= MEM_Dyn;
00232   return 0;
00233 }
00234 
00235 /*
00236 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
00237 ** a pointer to a dynamically allocated string where some other entity
00238 ** is responsible for deallocating that string.  Because the stack entry
00239 ** does not control the string, it might be deleted without the stack
00240 ** entry knowing it.
00241 **
00242 ** This routine converts an ephemeral string into a dynamically allocated
00243 ** string that the stack entry itself controls.  In other words, it
00244 ** converts an MEM_Ephem string into an MEM_Dyn string.
00245 */
00246 #define Deephemeralize(P) \
00247    if( ((P)->flags&MEM_Ephem)!=0 && hardDeephem(P) ){ goto no_mem;}
00248 static int hardDeephem(Mem *pStack){
00249   char *z;
00250   assert( (pStack->flags & MEM_Ephem)!=0 );
00251   z = sqliteMallocRaw( pStack->n );
00252   if( z==0 ) return 1;
00253   memcpy(z, pStack->z, pStack->n);
00254   pStack->z = z;
00255   pStack->flags &= ~MEM_Ephem;
00256   pStack->flags |= MEM_Dyn;
00257   return 0;
00258 }
00259 
00260 /*
00261 ** Release the memory associated with the given stack level.  This
00262 ** leaves the Mem.flags field in an inconsistent state.
00263 */
00264 #define Release(P) if((P)->flags&MEM_Dyn){ sqliteFree((P)->z); }
00265 
00266 /*
00267 ** Pop the stack N times.
00268 */
00269 static void popStack(Mem **ppTos, int N){
00270   Mem *pTos = *ppTos;
00271   while( N>0 ){
00272     N--;
00273     Release(pTos);
00274     pTos--;
00275   }
00276   *ppTos = pTos;
00277 }
00278 
00279 /*
00280 ** Return TRUE if zNum is a 32-bit signed integer and write
00281 ** the value of the integer into *pNum.  If zNum is not an integer
00282 ** or is an integer that is too large to be expressed with just 32
00283 ** bits, then return false.
00284 **
00285 ** Under Linux (RedHat 7.2) this routine is much faster than atoi()
00286 ** for converting strings into integers.
00287 */
00288 static int toInt(const char *zNum, int *pNum){
00289   int v = 0;
00290   int neg;
00291   int i, c;
00292   if( *zNum=='-' ){
00293     neg = 1;
00294     zNum++;
00295   }else if( *zNum=='+' ){
00296     neg = 0;
00297     zNum++;
00298   }else{
00299     neg = 0;
00300   }
00301   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
00302     v = v*10 + c - '0';
00303   }
00304   *pNum = neg ? -v : v;
00305   return c==0 && i>0 && (i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0));
00306 }
00307 
00308 /*
00309 ** Convert the given stack entity into a integer if it isn't one
00310 ** already.
00311 **
00312 ** Any prior string or real representation is invalidated.  
00313 ** NULLs are converted into 0.
00314 */
00315 #define Integerify(P) if(((P)->flags&MEM_Int)==0){ hardIntegerify(P); }
00316 static void hardIntegerify(Mem *pStack){
00317   if( pStack->flags & MEM_Real ){
00318     pStack->i = (int)pStack->r;
00319     Release(pStack);
00320   }else if( pStack->flags & MEM_Str ){
00321     toInt(pStack->z, &pStack->i);
00322     Release(pStack);
00323   }else{
00324     pStack->i = 0;
00325   }
00326   pStack->flags = MEM_Int;
00327 }
00328 
00329 /*
00330 ** Get a valid Real representation for the given stack element.
00331 **
00332 ** Any prior string or integer representation is retained.
00333 ** NULLs are converted into 0.0.
00334 */
00335 #define Realify(P) if(((P)->flags&MEM_Real)==0){ hardRealify(P); }
00336 static void hardRealify(Mem *pStack){
00337   if( pStack->flags & MEM_Str ){
00338     pStack->r = sqliteAtoF(pStack->z, 0);
00339   }else if( pStack->flags & MEM_Int ){
00340     pStack->r = pStack->i;
00341   }else{
00342     pStack->r = 0.0;
00343   }
00344   pStack->flags |= MEM_Real;
00345 }
00346 
00347 /*
00348 ** The parameters are pointers to the head of two sorted lists
00349 ** of Sorter structures.  Merge these two lists together and return
00350 ** a single sorted list.  This routine forms the core of the merge-sort
00351 ** algorithm.
00352 **
00353 ** In the case of a tie, left sorts in front of right.
00354 */
00355 static Sorter *Merge(Sorter *pLeft, Sorter *pRight){
00356   Sorter sHead;
00357   Sorter *pTail;
00358   pTail = &sHead;
00359   pTail->pNext = 0;
00360   while( pLeft && pRight ){
00361     int c = sqliteSortCompare(pLeft->zKey, pRight->zKey);
00362     if( c<=0 ){
00363       pTail->pNext = pLeft;
00364       pLeft = pLeft->pNext;
00365     }else{
00366       pTail->pNext = pRight;
00367       pRight = pRight->pNext;
00368     }
00369     pTail = pTail->pNext;
00370   }
00371   if( pLeft ){
00372     pTail->pNext = pLeft;
00373   }else if( pRight ){
00374     pTail->pNext = pRight;
00375   }
00376   return sHead.pNext;
00377 }
00378 
00379 /*
00380 ** The following routine works like a replacement for the standard
00381 ** library routine fgets().  The difference is in how end-of-line (EOL)
00382 ** is handled.  Standard fgets() uses LF for EOL under unix, CRLF
00383 ** under windows, and CR under mac.  This routine accepts any of these
00384 ** character sequences as an EOL mark.  The EOL mark is replaced by
00385 ** a single LF character in zBuf.
00386 */
00387 static char *vdbe_fgets(char *zBuf, int nBuf, FILE *in){
00388   int i, c;
00389   for(i=0; i<nBuf-1 && (c=getc(in))!=EOF; i++){
00390     zBuf[i] = c;
00391     if( c=='\r' || c=='\n' ){
00392       if( c=='\r' ){
00393         zBuf[i] = '\n';
00394         c = getc(in);
00395         if( c!=EOF && c!='\n' ) ungetc(c, in);
00396       }
00397       i++;
00398       break;
00399     }
00400   }
00401   zBuf[i]  = 0;
00402   return i>0 ? zBuf : 0;
00403 }
00404 
00405 /*
00406 ** Make sure there is space in the Vdbe structure to hold at least
00407 ** mxCursor cursors.  If there is not currently enough space, then
00408 ** allocate more.
00409 **
00410 ** If a memory allocation error occurs, return 1.  Return 0 if
00411 ** everything works.
00412 */
00413 static int expandCursorArraySize(Vdbe *p, int mxCursor){
00414   if( mxCursor>=p->nCursor ){
00415     Cursor *aCsr = sqliteRealloc( p->aCsr, (mxCursor+1)*sizeof(Cursor) );
00416     if( aCsr==0 ) return 1;
00417     p->aCsr = aCsr;
00418     memset(&p->aCsr[p->nCursor], 0, sizeof(Cursor)*(mxCursor+1-p->nCursor));
00419     p->nCursor = mxCursor+1;
00420   }
00421   return 0;
00422 }
00423 
00424 #ifdef VDBE_PROFILE
00425 /*
00426 ** The following routine only works on pentium-class processors.
00427 ** It uses the RDTSC opcode to read cycle count value out of the
00428 ** processor and returns that value.  This can be used for high-res
00429 ** profiling.
00430 */
00431 __inline__ unsigned long long int hwtime(void){
00432   unsigned long long int x;
00433   __asm__("rdtsc\n\t"
00434           "mov %%edx, %%ecx\n\t"
00435           :"=A" (x));
00436   return x;
00437 }
00438 #endif
00439 
00440 /*
00441 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
00442 ** sqlite_interrupt() routine has been called.  If it has been, then
00443 ** processing of the VDBE program is interrupted.
00444 **
00445 ** This macro added to every instruction that does a jump in order to
00446 ** implement a loop.  This test used to be on every single instruction,
00447 ** but that meant we more testing that we needed.  By only testing the
00448 ** flag on jump instructions, we get a (small) speed improvement.
00449 */
00450 #define CHECK_FOR_INTERRUPT \
00451    if( db->flags & SQLITE_Interrupt ) goto abort_due_to_interrupt;
00452 
00453 
00454 /*
00455 ** Execute as much of a VDBE program as we can then return.
00456 **
00457 ** sqliteVdbeMakeReady() must be called before this routine in order to
00458 ** close the program with a final OP_Halt and to set up the callbacks
00459 ** and the error message pointer.
00460 **
00461 ** Whenever a row or result data is available, this routine will either
00462 ** invoke the result callback (if there is one) or return with
00463 ** SQLITE_ROW.
00464 **
00465 ** If an attempt is made to open a locked database, then this routine
00466 ** will either invoke the busy callback (if there is one) or it will
00467 ** return SQLITE_BUSY.
00468 **
00469 ** If an error occurs, an error message is written to memory obtained
00470 ** from sqliteMalloc() and p->zErrMsg is made to point to that memory.
00471 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
00472 **
00473 ** If the callback ever returns non-zero, then the program exits
00474 ** immediately.  There will be no error message but the p->rc field is
00475 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
00476 **
00477 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
00478 ** routine to return SQLITE_ERROR.
00479 **
00480 ** Other fatal errors return SQLITE_ERROR.
00481 **
00482 ** After this routine has finished, sqliteVdbeFinalize() should be
00483 ** used to clean up the mess that was left behind.
00484 */
00485 int sqliteVdbeExec(
00486   Vdbe *p                    /* The VDBE */
00487 ){
00488   int pc;                    /* The program counter */
00489   Op *pOp;                   /* Current operation */
00490   int rc = SQLITE_OK;        /* Value to return */
00491   sqlite *db = p->db;        /* The database */
00492   Mem *pTos;                 /* Top entry in the operand stack */
00493   char zBuf[100];            /* Space to sprintf() an integer */
00494 #ifdef VDBE_PROFILE
00495   unsigned long long start;  /* CPU clock count at start of opcode */
00496   int origPc;                /* Program counter at start of opcode */
00497 #endif
00498 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
00499   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
00500 #endif
00501 
00502   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
00503   assert( db->magic==SQLITE_MAGIC_BUSY );
00504   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
00505   p->rc = SQLITE_OK;
00506   assert( p->explain==0 );
00507   if( sqlite_malloc_failed ) goto no_mem;
00508   pTos = p->pTos;
00509   if( p->popStack ){
00510     popStack(&pTos, p->popStack);
00511     p->popStack = 0;
00512   }
00513   CHECK_FOR_INTERRUPT;
00514   for(pc=p->pc; rc==SQLITE_OK; pc++){
00515     assert( pc>=0 && pc<p->nOp );
00516     assert( pTos<=&p->aStack[pc] );
00517 #ifdef VDBE_PROFILE
00518     origPc = pc;
00519     start = hwtime();
00520 #endif
00521     pOp = &p->aOp[pc];
00522 
00523     /* Only allow tracing if NDEBUG is not defined.
00524     */
00525 #ifndef NDEBUG
00526     if( p->trace ){
00527       sqliteVdbePrintOp(p->trace, pc, pOp);
00528     }
00529 #endif
00530 
00531     /* Check to see if we need to simulate an interrupt.  This only happens
00532     ** if we have a special test build.
00533     */
00534 #ifdef SQLITE_TEST
00535     if( sqlite_interrupt_count>0 ){
00536       sqlite_interrupt_count--;
00537       if( sqlite_interrupt_count==0 ){
00538         sqlite_interrupt(db);
00539       }
00540     }
00541 #endif
00542 
00543 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
00544     /* Call the progress callback if it is configured and the required number
00545     ** of VDBE ops have been executed (either since this invocation of
00546     ** sqliteVdbeExec() or since last time the progress callback was called).
00547     ** If the progress callback returns non-zero, exit the virtual machine with
00548     ** a return code SQLITE_ABORT.
00549     */
00550     if( db->xProgress ){
00551       if( db->nProgressOps==nProgressOps ){
00552         if( db->xProgress(db->pProgressArg)!=0 ){
00553           rc = SQLITE_ABORT;
00554           continue; /* skip to the next iteration of the for loop */
00555         }
00556         nProgressOps = 0;
00557       }
00558       nProgressOps++;
00559     }
00560 #endif
00561 
00562     switch( pOp->opcode ){
00563 
00564 /*****************************************************************************
00565 ** What follows is a massive switch statement where each case implements a
00566 ** separate instruction in the virtual machine.  If we follow the usual
00567 ** indentation conventions, each case should be indented by 6 spaces.  But
00568 ** that is a lot of wasted space on the left margin.  So the code within
00569 ** the switch statement will break with convention and be flush-left. Another
00570 ** big comment (similar to this one) will mark the point in the code where
00571 ** we transition back to normal indentation.
00572 **
00573 ** The formatting of each case is important.  The makefile for SQLite
00574 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
00575 ** file looking for lines that begin with "case OP_".  The opcodes.h files
00576 ** will be filled with #defines that give unique integer values to each
00577 ** opcode and the opcodes.c file is filled with an array of strings where
00578 ** each string is the symbolic name for the corresponding opcode.
00579 **
00580 ** Documentation about VDBE opcodes is generated by scanning this file
00581 ** for lines of that contain "Opcode:".  That line and all subsequent
00582 ** comment lines are used in the generation of the opcode.html documentation
00583 ** file.
00584 **
00585 ** SUMMARY:
00586 **
00587 **     Formatting is important to scripts that scan this file.
00588 **     Do not deviate from the formatting style currently in use.
00589 **
00590 *****************************************************************************/
00591 
00592 /* Opcode:  Goto * P2 *
00593 **
00594 ** An unconditional jump to address P2.
00595 ** The next instruction executed will be 
00596 ** the one at index P2 from the beginning of
00597 ** the program.
00598 */
00599 case OP_Goto: {
00600   CHECK_FOR_INTERRUPT;
00601   pc = pOp->p2 - 1;
00602   break;
00603 }
00604 
00605 /* Opcode:  Gosub * P2 *
00606 **
00607 ** Push the current address plus 1 onto the return address stack
00608 ** and then jump to address P2.
00609 **
00610 ** The return address stack is of limited depth.  If too many
00611 ** OP_Gosub operations occur without intervening OP_Returns, then
00612 ** the return address stack will fill up and processing will abort
00613 ** with a fatal error.
00614 */
00615 case OP_Gosub: {
00616   if( p->returnDepth>=sizeof(p->returnStack)/sizeof(p->returnStack[0]) ){
00617     sqliteSetString(&p->zErrMsg, "return address stack overflow", (char*)0);
00618     p->rc = SQLITE_INTERNAL;
00619     return SQLITE_ERROR;
00620   }
00621   p->returnStack[p->returnDepth++] = pc+1;
00622   pc = pOp->p2 - 1;
00623   break;
00624 }
00625 
00626 /* Opcode:  Return * * *
00627 **
00628 ** Jump immediately to the next instruction after the last unreturned
00629 ** OP_Gosub.  If an OP_Return has occurred for all OP_Gosubs, then
00630 ** processing aborts with a fatal error.
00631 */
00632 case OP_Return: {
00633   if( p->returnDepth<=0 ){
00634     sqliteSetString(&p->zErrMsg, "return address stack underflow", (char*)0);
00635     p->rc = SQLITE_INTERNAL;
00636     return SQLITE_ERROR;
00637   }
00638   p->returnDepth--;
00639   pc = p->returnStack[p->returnDepth] - 1;
00640   break;
00641 }
00642 
00643 /* Opcode:  Halt P1 P2 *
00644 **
00645 ** Exit immediately.  All open cursors, Lists, Sorts, etc are closed
00646 ** automatically.
00647 **
00648 ** P1 is the result code returned by sqlite_exec().  For a normal
00649 ** halt, this should be SQLITE_OK (0).  For errors, it can be some
00650 ** other value.  If P1!=0 then P2 will determine whether or not to
00651 ** rollback the current transaction.  Do not rollback if P2==OE_Fail.
00652 ** Do the rollback if P2==OE_Rollback.  If P2==OE_Abort, then back
00653 ** out all changes that have occurred during this execution of the
00654 ** VDBE, but do not rollback the transaction. 
00655 **
00656 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
00657 ** every program.  So a jump past the last instruction of the program
00658 ** is the same as executing Halt.
00659 */
00660 case OP_Halt: {
00661   p->magic = VDBE_MAGIC_HALT;
00662   p->pTos = pTos;
00663   if( pOp->p1!=SQLITE_OK ){
00664     p->rc = pOp->p1;
00665     p->errorAction = pOp->p2;
00666     if( pOp->p3 ){
00667       sqliteSetString(&p->zErrMsg, pOp->p3, (char*)0);
00668     }
00669     return SQLITE_ERROR;
00670   }else{
00671     p->rc = SQLITE_OK;
00672     return SQLITE_DONE;
00673   }
00674 }
00675 
00676 /* Opcode: Integer P1 * P3
00677 **
00678 ** The integer value P1 is pushed onto the stack.  If P3 is not zero
00679 ** then it is assumed to be a string representation of the same integer.
00680 */
00681 case OP_Integer: {
00682   pTos++;
00683   pTos->i = pOp->p1;
00684   pTos->flags = MEM_Int;
00685   if( pOp->p3 ){
00686     pTos->z = pOp->p3;
00687     pTos->flags |= MEM_Str | MEM_Static;
00688     pTos->n = strlen(pOp->p3)+1;
00689   }
00690   break;
00691 }
00692 
00693 /* Opcode: String * * P3
00694 **
00695 ** The string value P3 is pushed onto the stack.  If P3==0 then a
00696 ** NULL is pushed onto the stack.
00697 */
00698 case OP_String: {
00699   char *z = pOp->p3;
00700   pTos++;
00701   if( z==0 ){
00702     pTos->flags = MEM_Null;
00703   }else{
00704     pTos->z = z;
00705     pTos->n = strlen(z) + 1;
00706     pTos->flags = MEM_Str | MEM_Static;
00707   }
00708   break;
00709 }
00710 
00711 /* Opcode: Variable P1 * *
00712 **
00713 ** Push the value of variable P1 onto the stack.  A variable is
00714 ** an unknown in the original SQL string as handed to sqlite_compile().
00715 ** Any occurance of the '?' character in the original SQL is considered
00716 ** a variable.  Variables in the SQL string are number from left to
00717 ** right beginning with 1.  The values of variables are set using the
00718 ** sqlite_bind() API.
00719 */
00720 case OP_Variable: {
00721   int j = pOp->p1 - 1;
00722   pTos++;
00723   if( j>=0 && j<p->nVar && p->azVar[j]!=0 ){
00724     pTos->z = p->azVar[j];
00725     pTos->n = p->anVar[j];
00726     pTos->flags = MEM_Str | MEM_Static;
00727   }else{
00728     pTos->flags = MEM_Null;
00729   }
00730   break;
00731 }
00732 
00733 /* Opcode: Pop P1 * *
00734 **
00735 ** P1 elements are popped off of the top of stack and discarded.
00736 */
00737 case OP_Pop: {
00738   assert( pOp->p1>=0 );
00739   popStack(&pTos, pOp->p1);
00740   assert( pTos>=&p->aStack[-1] );
00741   break;
00742 }
00743 
00744 /* Opcode: Dup P1 P2 *
00745 **
00746 ** A copy of the P1-th element of the stack 
00747 ** is made and pushed onto the top of the stack.
00748 ** The top of the stack is element 0.  So the
00749 ** instruction "Dup 0 0 0" will make a copy of the
00750 ** top of the stack.
00751 **
00752 ** If the content of the P1-th element is a dynamically
00753 ** allocated string, then a new copy of that string
00754 ** is made if P2==0.  If P2!=0, then just a pointer
00755 ** to the string is copied.
00756 **
00757 ** Also see the Pull instruction.
00758 */
00759 case OP_Dup: {
00760   Mem *pFrom = &pTos[-pOp->p1];
00761   assert( pFrom<=pTos && pFrom>=p->aStack );
00762   pTos++;
00763   memcpy(pTos, pFrom, sizeof(*pFrom)-NBFS);
00764   if( pTos->flags & MEM_Str ){
00765     if( pOp->p2 && (pTos->flags & (MEM_Dyn|MEM_Ephem)) ){
00766       pTos->flags &= ~MEM_Dyn;
00767       pTos->flags |= MEM_Ephem;
00768     }else if( pTos->flags & MEM_Short ){
00769       memcpy(pTos->zShort, pFrom->zShort, pTos->n);
00770       pTos->z = pTos->zShort;
00771     }else if( (pTos->flags & MEM_Static)==0 ){
00772       pTos->z = sqliteMallocRaw(pFrom->n);
00773       if( sqlite_malloc_failed ) goto no_mem;
00774       memcpy(pTos->z, pFrom->z, pFrom->n);
00775       pTos->flags &= ~(MEM_Static|MEM_Ephem|MEM_Short);
00776       pTos->flags |= MEM_Dyn;
00777     }
00778   }
00779   break;
00780 }
00781 
00782 /* Opcode: Pull P1 * *
00783 **
00784 ** The P1-th element is removed from its current location on 
00785 ** the stack and pushed back on top of the stack.  The
00786 ** top of the stack is element 0, so "Pull 0 0 0" is
00787 ** a no-op.  "Pull 1 0 0" swaps the top two elements of
00788 ** the stack.
00789 **
00790 ** See also the Dup instruction.
00791 */
00792 case OP_Pull: {
00793   Mem *pFrom = &pTos[-pOp->p1];
00794   int i;
00795   Mem ts;
00796 
00797   ts = *pFrom;
00798   Deephemeralize(pTos);
00799   for(i=0; i<pOp->p1; i++, pFrom++){
00800     Deephemeralize(&pFrom[1]);
00801     *pFrom = pFrom[1];
00802     assert( (pFrom->flags & MEM_Ephem)==0 );
00803     if( pFrom->flags & MEM_Short ){
00804       assert( pFrom->flags & MEM_Str );
00805       assert( pFrom->z==pFrom[1].zShort );
00806       pFrom->z = pFrom->zShort;
00807     }
00808   }
00809   *pTos = ts;
00810   if( pTos->flags & MEM_Short ){
00811     assert( pTos->flags & MEM_Str );
00812     assert( pTos->z==pTos[-pOp->p1].zShort );
00813     pTos->z = pTos->zShort;
00814   }
00815   break;
00816 }
00817 
00818 /* Opcode: Push P1 * *
00819 **
00820 ** Overwrite the value of the P1-th element down on the
00821 ** stack (P1==0 is the top of the stack) with the value
00822 ** of the top of the stack.  Then pop the top of the stack.
00823 */
00824 case OP_Push: {
00825   Mem *pTo = &pTos[-pOp->p1];
00826 
00827   assert( pTo>=p->aStack );
00828   Deephemeralize(pTos);
00829   Release(pTo);
00830   *pTo = *pTos;
00831   if( pTo->flags & MEM_Short ){
00832     assert( pTo->z==pTos->zShort );
00833     pTo->z = pTo->zShort;
00834   }
00835   pTos--;
00836   break;
00837 }
00838 
00839 
00840 /* Opcode: ColumnName P1 P2 P3
00841 **
00842 ** P3 becomes the P1-th column name (first is 0).  An array of pointers
00843 ** to all column names is passed as the 4th parameter to the callback.
00844 ** If P2==1 then this is the last column in the result set and thus the
00845 ** number of columns in the result set will be P1.  There must be at least
00846 ** one OP_ColumnName with a P2==1 before invoking OP_Callback and the
00847 ** number of columns specified in OP_Callback must one more than the P1
00848 ** value of the OP_ColumnName that has P2==1.
00849 */
00850 case OP_ColumnName: {
00851   assert( pOp->p1>=0 && pOp->p1<p->nOp );
00852   p->azColName[pOp->p1] = pOp->p3;
00853   p->nCallback = 0;
00854   if( pOp->p2 ) p->nResColumn = pOp->p1+1;
00855   break;
00856 }
00857 
00858 /* Opcode: Callback P1 * *
00859 **
00860 ** Pop P1 values off the stack and form them into an array.  Then
00861 ** invoke the callback function using the newly formed array as the
00862 ** 3rd parameter.
00863 */
00864 case OP_Callback: {
00865   int i;
00866   char **azArgv = p->zArgv;
00867   Mem *pCol;
00868 
00869   pCol = &pTos[1-pOp->p1];
00870   assert( pCol>=p->aStack );
00871   for(i=0; i<pOp->p1; i++, pCol++){
00872     if( pCol->flags & MEM_Null ){
00873       azArgv[i] = 0;
00874     }else{
00875       Stringify(pCol);
00876       azArgv[i] = pCol->z;
00877     }
00878   }
00879   azArgv[i] = 0;
00880   p->nCallback++;
00881   p->azResColumn = azArgv;
00882   assert( p->nResColumn==pOp->p1 );
00883   p->popStack = pOp->p1;
00884   p->pc = pc + 1;
00885   p->pTos = pTos;
00886   return SQLITE_ROW;
00887 }
00888 
00889 /* Opcode: Concat P1 P2 P3
00890 **
00891 ** Look at the first P1 elements of the stack.  Append them all 
00892 ** together with the lowest element first.  Use P3 as a separator.  
00893 ** Put the result on the top of the stack.  The original P1 elements
00894 ** are popped from the stack if P2==0 and retained if P2==1.  If
00895 ** any element of the stack is NULL, then the result is NULL.
00896 **
00897 ** If P3 is NULL, then use no separator.  When P1==1, this routine
00898 ** makes a copy of the top stack element into memory obtained
00899 ** from sqliteMalloc().
00900 */
00901 case OP_Concat: {
00902   char *zNew;
00903   int nByte;
00904   int nField;
00905   int i, j;
00906   char *zSep;
00907   int nSep;
00908   Mem *pTerm;
00909 
00910   nField = pOp->p1;
00911   zSep = pOp->p3;
00912   if( zSep==0 ) zSep = "";
00913   nSep = strlen(zSep);
00914   assert( &pTos[1-nField] >= p->aStack );
00915   nByte = 1 - nSep;
00916   pTerm = &pTos[1-nField];
00917   for(i=0; i<nField; i++, pTerm++){
00918     if( pTerm->flags & MEM_Null ){
00919       nByte = -1;
00920       break;
00921     }else{
00922       Stringify(pTerm);
00923       nByte += pTerm->n - 1 + nSep;
00924     }
00925   }
00926   if( nByte<0 ){
00927     if( pOp->p2==0 ){
00928       popStack(&pTos, nField);
00929     }
00930     pTos++;
00931     pTos->flags = MEM_Null;
00932     break;
00933   }
00934   zNew = sqliteMallocRaw( nByte );
00935   if( zNew==0 ) goto no_mem;
00936   j = 0;
00937   pTerm = &pTos[1-nField];
00938   for(i=j=0; i<nField; i++, pTerm++){
00939     assert( pTerm->flags & MEM_Str );
00940     memcpy(&zNew[j], pTerm->z, pTerm->n-1);
00941     j += pTerm->n-1;
00942     if( nSep>0 && i<nField-1 ){
00943       memcpy(&zNew[j], zSep, nSep);
00944       j += nSep;
00945     }
00946   }
00947   zNew[j] = 0;
00948   if( pOp->p2==0 ){
00949     popStack(&pTos, nField);
00950   }
00951   pTos++;
00952   pTos->n = nByte;
00953   pTos->flags = MEM_Str|MEM_Dyn;
00954   pTos->z = zNew;
00955   break;
00956 }
00957 
00958 /* Opcode: Add * * *
00959 **
00960 ** Pop the top two elements from the stack, add them together,
00961 ** and push the result back onto the stack.  If either element
00962 ** is a string then it is converted to a double using the atof()
00963 ** function before the addition.
00964 ** If either operand is NULL, the result is NULL.
00965 */
00966 /* Opcode: Multiply * * *
00967 **
00968 ** Pop the top two elements from the stack, multiply them together,
00969 ** and push the result back onto the stack.  If either element
00970 ** is a string then it is converted to a double using the atof()
00971 ** function before the multiplication.
00972 ** If either operand is NULL, the result is NULL.
00973 */
00974 /* Opcode: Subtract * * *
00975 **
00976 ** Pop the top two elements from the stack, subtract the
00977 ** first (what was on top of the stack) from the second (the
00978 ** next on stack)
00979 ** and push the result back onto the stack.  If either element
00980 ** is a string then it is converted to a double using the atof()
00981 ** function before the subtraction.
00982 ** If either operand is NULL, the result is NULL.
00983 */
00984 /* Opcode: Divide * * *
00985 **
00986 ** Pop the top two elements from the stack, divide the
00987 ** first (what was on top of the stack) from the second (the
00988 ** next on stack)
00989 ** and push the result back onto the stack.  If either element
00990 ** is a string then it is converted to a double using the atof()
00991 ** function before the division.  Division by zero returns NULL.
00992 ** If either operand is NULL, the result is NULL.
00993 */
00994 /* Opcode: Remainder * * *
00995 **
00996 ** Pop the top two elements from the stack, divide the
00997 ** first (what was on top of the stack) from the second (the
00998 ** next on stack)
00999 ** and push the remainder after division onto the stack.  If either element
01000 ** is a string then it is converted to a double using the atof()
01001 ** function before the division.  Division by zero returns NULL.
01002 ** If either operand is NULL, the result is NULL.
01003 */
01004 case OP_Add:
01005 case OP_Subtract:
01006 case OP_Multiply:
01007 case OP_Divide:
01008 case OP_Remainder: {
01009   Mem *pNos = &pTos[-1];
01010   assert( pNos>=p->aStack );
01011   if( ((pTos->flags | pNos->flags) & MEM_Null)!=0 ){
01012     Release(pTos);
01013     pTos--;
01014     Release(pTos);
01015     pTos->flags = MEM_Null;
01016   }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){
01017     int a, b;
01018     a = pTos->i;
01019     b = pNos->i;
01020     switch( pOp->opcode ){
01021       case OP_Add:         b += a;       break;
01022       case OP_Subtract:    b -= a;       break;
01023       case OP_Multiply:    b *= a;       break;
01024       case OP_Divide: {
01025         if( a==0 ) goto divide_by_zero;
01026         b /= a;
01027         break;
01028       }
01029       default: {
01030         if( a==0 ) goto divide_by_zero;
01031         b %= a;
01032         break;
01033       }
01034     }
01035     Release(pTos);
01036     pTos--;
01037     Release(pTos);
01038     pTos->i = b;
01039     pTos->flags = MEM_Int;
01040   }else{
01041     double a, b;
01042     Realify(pTos);
01043     Realify(pNos);
01044     a = pTos->r;
01045     b = pNos->r;
01046     switch( pOp->opcode ){
01047       case OP_Add:         b += a;       break;
01048       case OP_Subtract:    b -= a;       break;
01049       case OP_Multiply:    b *= a;       break;
01050       case OP_Divide: {
01051         if( a==0.0 ) goto divide_by_zero;
01052         b /= a;
01053         break;
01054       }
01055       default: {
01056         int ia = (int)a;
01057         int ib = (int)b;
01058         if( ia==0.0 ) goto divide_by_zero;
01059         b = ib % ia;
01060         break;
01061       }
01062     }
01063     Release(pTos);
01064     pTos--;
01065     Release(pTos);
01066     pTos->r = b;
01067     pTos->flags = MEM_Real;
01068   }
01069   break;
01070 
01071 divide_by_zero:
01072   Release(pTos);
01073   pTos--;
01074   Release(pTos);
01075   pTos->flags = MEM_Null;
01076   break;
01077 }
01078 
01079 /* Opcode: Function P1 * P3
01080 **
01081 ** Invoke a user function (P3 is a pointer to a Function structure that
01082 ** defines the function) with P1 string arguments taken from the stack.
01083 ** Pop all arguments from the stack and push back the result.
01084 **
01085 ** See also: AggFunc
01086 */
01087 case OP_Function: {
01088   int n, i;
01089   Mem *pArg;
01090   char **azArgv;
01091   sqlite_func ctx;
01092 
01093   n = pOp->p1;
01094   pArg = &pTos[1-n];
01095   azArgv = p->zArgv;
01096   for(i=0; i<n; i++, pArg++){
01097     if( pArg->flags & MEM_Null ){
01098       azArgv[i] = 0;
01099     }else{
01100       Stringify(pArg);
01101       azArgv[i] = pArg->z;
01102     }
01103   }
01104   ctx.pFunc = (FuncDef*)pOp->p3;
01105   ctx.s.flags = MEM_Null;
01106   ctx.s.z = 0;
01107   ctx.isError = 0;
01108   ctx.isStep = 0;
01109   if( sqliteSafetyOff(db) ) goto abort_due_to_misuse;
01110   (*ctx.pFunc->xFunc)(&ctx, n, (const char**)azArgv);
01111   if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
01112   popStack(&pTos, n);
01113   pTos++;
01114   *pTos = ctx.s;
01115   if( pTos->flags & MEM_Short ){
01116     pTos->z = pTos->zShort;
01117   }
01118   if( ctx.isError ){
01119     sqliteSetString(&p->zErrMsg, 
01120        (pTos->flags & MEM_Str)!=0 ? pTos->z : "user function error", (char*)0);
01121     rc = SQLITE_ERROR;
01122   }
01123   break;
01124 }
01125 
01126 /* Opcode: BitAnd * * *
01127 **
01128 ** Pop the top two elements from the stack.  Convert both elements
01129 ** to integers.  Push back onto the stack the bit-wise AND of the
01130 ** two elements.
01131 ** If either operand is NULL, the result is NULL.
01132 */
01133 /* Opcode: BitOr * * *
01134 **
01135 ** Pop the top two elements from the stack.  Convert both elements
01136 ** to integers.  Push back onto the stack the bit-wise OR of the
01137 ** two elements.
01138 ** If either operand is NULL, the result is NULL.
01139 */
01140 /* Opcode: ShiftLeft * * *
01141 **
01142 ** Pop the top two elements from the stack.  Convert both elements
01143 ** to integers.  Push back onto the stack the top element shifted
01144 ** left by N bits where N is the second element on the stack.
01145 ** If either operand is NULL, the result is NULL.
01146 */
01147 /* Opcode: ShiftRight * * *
01148 **
01149 ** Pop the top two elements from the stack.  Convert both elements
01150 ** to integers.  Push back onto the stack the top element shifted
01151 ** right by N bits where N is the second element on the stack.
01152 ** If either operand is NULL, the result is NULL.
01153 */
01154 case OP_BitAnd:
01155 case OP_BitOr:
01156 case OP_ShiftLeft:
01157 case OP_ShiftRight: {
01158   Mem *pNos = &pTos[-1];
01159   int a, b;
01160 
01161   assert( pNos>=p->aStack );
01162   if( (pTos->flags | pNos->flags) & MEM_Null ){
01163     popStack(&pTos, 2);
01164     pTos++;
01165     pTos->flags = MEM_Null;
01166     break;
01167   }
01168   Integerify(pTos);
01169   Integerify(pNos);
01170   a = pTos->i;
01171   b = pNos->i;
01172   switch( pOp->opcode ){
01173     case OP_BitAnd:      a &= b;     break;
01174     case OP_BitOr:       a |= b;     break;
01175     case OP_ShiftLeft:   a <<= b;    break;
01176     case OP_ShiftRight:  a >>= b;    break;
01177     default:   /* CANT HAPPEN */     break;
01178   }
01179   assert( (pTos->flags & MEM_Dyn)==0 );
01180   assert( (pNos->flags & MEM_Dyn)==0 );
01181   pTos--;
01182   Release(pTos);
01183   pTos->i = a;
01184   pTos->flags = MEM_Int;
01185   break;
01186 }
01187 
01188 /* Opcode: AddImm  P1 * *
01189 ** 
01190 ** Add the value P1 to whatever is on top of the stack.  The result
01191 ** is always an integer.
01192 **
01193 ** To force the top of the stack to be an integer, just add 0.
01194 */
01195 case OP_AddImm: {
01196   assert( pTos>=p->aStack );
01197   Integerify(pTos);
01198   pTos->i += pOp->p1;
01199   break;
01200 }
01201 
01202 /* Opcode: ForceInt P1 P2 *
01203 **
01204 ** Convert the top of the stack into an integer.  If the current top of
01205 ** the stack is not numeric (meaning that is is a NULL or a string that
01206 ** does not look like an integer or floating point number) then pop the
01207 ** stack and jump to P2.  If the top of the stack is numeric then
01208 ** convert it into the least integer that is greater than or equal to its
01209 ** current value if P1==0, or to the least integer that is strictly
01210 ** greater than its current value if P1==1.
01211 */
01212 case OP_ForceInt: {
01213   int v;
01214   assert( pTos>=p->aStack );
01215   if( (pTos->flags & (MEM_Int|MEM_Real))==0
01216          && ((pTos->flags & MEM_Str)==0 || sqliteIsNumber(pTos->z)==0) ){
01217     Release(pTos);
01218     pTos--;
01219     pc = pOp->p2 - 1;
01220     break;
01221   }
01222   if( pTos->flags & MEM_Int ){
01223     v = pTos->i + (pOp->p1!=0);
01224   }else{
01225     Realify(pTos);
01226     v = (int)pTos->r;
01227     if( pTos->r>(double)v ) v++;
01228     if( pOp->p1 && pTos->r==(double)v ) v++;
01229   }
01230   Release(pTos);
01231   pTos->i = v;
01232   pTos->flags = MEM_Int;
01233   break;
01234 }
01235 
01236 /* Opcode: MustBeInt P1 P2 *
01237 ** 
01238 ** Force the top of the stack to be an integer.  If the top of the
01239 ** stack is not an integer and cannot be converted into an integer
01240 ** with out data loss, then jump immediately to P2, or if P2==0
01241 ** raise an SQLITE_MISMATCH exception.
01242 **
01243 ** If the top of the stack is not an integer and P2 is not zero and
01244 ** P1 is 1, then the stack is popped.  In all other cases, the depth
01245 ** of the stack is unchanged.
01246 */
01247 case OP_MustBeInt: {
01248   assert( pTos>=p->aStack );
01249   if( pTos->flags & MEM_Int ){
01250     /* Do nothing */
01251   }else if( pTos->flags & MEM_Real ){
01252     int i = (int)pTos->r;
01253     double r = (double)i;
01254     if( r!=pTos->r ){
01255       goto mismatch;
01256     }
01257     pTos->i = i;
01258   }else if( pTos->flags & MEM_Str ){
01259     int v;
01260     if( !toInt(pTos->z, &v) ){
01261       double r;
01262       if( !sqliteIsNumber(pTos->z) ){
01263         goto mismatch;
01264       }
01265       Realify(pTos);
01266       v = (int)pTos->r;
01267       r = (double)v;
01268       if( r!=pTos->r ){
01269         goto mismatch;
01270       }
01271     }
01272     pTos->i = v;
01273   }else{
01274     goto mismatch;
01275   }
01276   Release(pTos);
01277   pTos->flags = MEM_Int;
01278   break;
01279 
01280 mismatch:
01281   if( pOp->p2==0 ){
01282     rc = SQLITE_MISMATCH;
01283     goto abort_due_to_error;
01284   }else{
01285     if( pOp->p1 ) popStack(&pTos, 1);
01286     pc = pOp->p2 - 1;
01287   }
01288   break;
01289 }
01290 
01291 /* Opcode: Eq P1 P2 *
01292 **
01293 ** Pop the top two elements from the stack.  If they are equal, then
01294 ** jump to instruction P2.  Otherwise, continue to the next instruction.
01295 **
01296 ** If either operand is NULL (and thus if the result is unknown) then
01297 ** take the jump if P1 is true.
01298 **
01299 ** If both values are numeric, they are converted to doubles using atof()
01300 ** and compared for equality that way.  Otherwise the strcmp() library
01301 ** routine is used for the comparison.  For a pure text comparison
01302 ** use OP_StrEq.
01303 **
01304 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01305 ** stack if the jump would have been taken, or a 0 if not.  Push a
01306 ** NULL if either operand was NULL.
01307 */
01308 /* Opcode: Ne P1 P2 *
01309 **
01310 ** Pop the top two elements from the stack.  If they are not equal, then
01311 ** jump to instruction P2.  Otherwise, continue to the next instruction.
01312 **
01313 ** If either operand is NULL (and thus if the result is unknown) then
01314 ** take the jump if P1 is true.
01315 **
01316 ** If both values are numeric, they are converted to doubles using atof()
01317 ** and compared in that format.  Otherwise the strcmp() library
01318 ** routine is used for the comparison.  For a pure text comparison
01319 ** use OP_StrNe.
01320 **
01321 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01322 ** stack if the jump would have been taken, or a 0 if not.  Push a
01323 ** NULL if either operand was NULL.
01324 */
01325 /* Opcode: Lt P1 P2 *
01326 **
01327 ** Pop the top two elements from the stack.  If second element (the
01328 ** next on stack) is less than the first (the top of stack), then
01329 ** jump to instruction P2.  Otherwise, continue to the next instruction.
01330 ** In other words, jump if NOS<TOS.
01331 **
01332 ** If either operand is NULL (and thus if the result is unknown) then
01333 ** take the jump if P1 is true.
01334 **
01335 ** If both values are numeric, they are converted to doubles using atof()
01336 ** and compared in that format.  Numeric values are always less than
01337 ** non-numeric values.  If both operands are non-numeric, the strcmp() library
01338 ** routine is used for the comparison.  For a pure text comparison
01339 ** use OP_StrLt.
01340 **
01341 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01342 ** stack if the jump would have been taken, or a 0 if not.  Push a
01343 ** NULL if either operand was NULL.
01344 */
01345 /* Opcode: Le P1 P2 *
01346 **
01347 ** Pop the top two elements from the stack.  If second element (the
01348 ** next on stack) is less than or equal to the first (the top of stack),
01349 ** then jump to instruction P2. In other words, jump if NOS<=TOS.
01350 **
01351 ** If either operand is NULL (and thus if the result is unknown) then
01352 ** take the jump if P1 is true.
01353 **
01354 ** If both values are numeric, they are converted to doubles using atof()
01355 ** and compared in that format.  Numeric values are always less than
01356 ** non-numeric values.  If both operands are non-numeric, the strcmp() library
01357 ** routine is used for the comparison.  For a pure text comparison
01358 ** use OP_StrLe.
01359 **
01360 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01361 ** stack if the jump would have been taken, or a 0 if not.  Push a
01362 ** NULL if either operand was NULL.
01363 */
01364 /* Opcode: Gt P1 P2 *
01365 **
01366 ** Pop the top two elements from the stack.  If second element (the
01367 ** next on stack) is greater than the first (the top of stack),
01368 ** then jump to instruction P2. In other words, jump if NOS>TOS.
01369 **
01370 ** If either operand is NULL (and thus if the result is unknown) then
01371 ** take the jump if P1 is true.
01372 **
01373 ** If both values are numeric, they are converted to doubles using atof()
01374 ** and compared in that format.  Numeric values are always less than
01375 ** non-numeric values.  If both operands are non-numeric, the strcmp() library
01376 ** routine is used for the comparison.  For a pure text comparison
01377 ** use OP_StrGt.
01378 **
01379 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01380 ** stack if the jump would have been taken, or a 0 if not.  Push a
01381 ** NULL if either operand was NULL.
01382 */
01383 /* Opcode: Ge P1 P2 *
01384 **
01385 ** Pop the top two elements from the stack.  If second element (the next
01386 ** on stack) is greater than or equal to the first (the top of stack),
01387 ** then jump to instruction P2. In other words, jump if NOS>=TOS.
01388 **
01389 ** If either operand is NULL (and thus if the result is unknown) then
01390 ** take the jump if P1 is true.
01391 **
01392 ** If both values are numeric, they are converted to doubles using atof()
01393 ** and compared in that format.  Numeric values are always less than
01394 ** non-numeric values.  If both operands are non-numeric, the strcmp() library
01395 ** routine is used for the comparison.  For a pure text comparison
01396 ** use OP_StrGe.
01397 **
01398 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01399 ** stack if the jump would have been taken, or a 0 if not.  Push a
01400 ** NULL if either operand was NULL.
01401 */
01402 case OP_Eq:
01403 case OP_Ne:
01404 case OP_Lt:
01405 case OP_Le:
01406 case OP_Gt:
01407 case OP_Ge: {
01408   Mem *pNos = &pTos[-1];
01409   int c, v;
01410   int ft, fn;
01411   assert( pNos>=p->aStack );
01412   ft = pTos->flags;
01413   fn = pNos->flags;
01414   if( (ft | fn) & MEM_Null ){
01415     popStack(&pTos, 2);
01416     if( pOp->p2 ){
01417       if( pOp->p1 ) pc = pOp->p2-1;
01418     }else{
01419       pTos++;
01420       pTos->flags = MEM_Null;
01421     }
01422     break;
01423   }else if( (ft & fn & MEM_Int)==MEM_Int ){
01424     c = pNos->i - pTos->i;
01425   }else if( (ft & MEM_Int)!=0 && (fn & MEM_Str)!=0 && toInt(pNos->z,&v) ){
01426     c = v - pTos->i;
01427   }else if( (fn & MEM_Int)!=0 && (ft & MEM_Str)!=0 && toInt(pTos->z,&v) ){
01428     c = pNos->i - v;
01429   }else{
01430     Stringify(pTos);
01431     Stringify(pNos);
01432     c = sqliteCompare(pNos->z, pTos->z);
01433   }
01434   switch( pOp->opcode ){
01435     case OP_Eq:    c = c==0;     break;
01436     case OP_Ne:    c = c!=0;     break;
01437     case OP_Lt:    c = c<0;      break;
01438     case OP_Le:    c = c<=0;     break;
01439     case OP_Gt:    c = c>0;      break;
01440     default:       c = c>=0;     break;
01441   }
01442   popStack(&pTos, 2);
01443   if( pOp->p2 ){
01444     if( c ) pc = pOp->p2-1;
01445   }else{
01446     pTos++;
01447     pTos->i = c;
01448     pTos->flags = MEM_Int;
01449   }
01450   break;
01451 }
01452 /* INSERT NO CODE HERE!
01453 **
01454 ** The opcode numbers are extracted from this source file by doing
01455 **
01456 **    grep '^case OP_' vdbe.c | ... >opcodes.h
01457 **
01458 ** The opcodes are numbered in the order that they appear in this file.
01459 ** But in order for the expression generating code to work right, the
01460 ** string comparison operators that follow must be numbered exactly 6
01461 ** greater than the numeric comparison opcodes above.  So no other
01462 ** cases can appear between the two.
01463 */
01464 /* Opcode: StrEq P1 P2 *
01465 **
01466 ** Pop the top two elements from the stack.  If they are equal, then
01467 ** jump to instruction P2.  Otherwise, continue to the next instruction.
01468 **
01469 ** If either operand is NULL (and thus if the result is unknown) then
01470 ** take the jump if P1 is true.
01471 **
01472 ** The strcmp() library routine is used for the comparison.  For a
01473 ** numeric comparison, use OP_Eq.
01474 **
01475 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01476 ** stack if the jump would have been taken, or a 0 if not.  Push a
01477 ** NULL if either operand was NULL.
01478 */
01479 /* Opcode: StrNe P1 P2 *
01480 **
01481 ** Pop the top two elements from the stack.  If they are not equal, then
01482 ** jump to instruction P2.  Otherwise, continue to the next instruction.
01483 **
01484 ** If either operand is NULL (and thus if the result is unknown) then
01485 ** take the jump if P1 is true.
01486 **
01487 ** The strcmp() library routine is used for the comparison.  For a
01488 ** numeric comparison, use OP_Ne.
01489 **
01490 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01491 ** stack if the jump would have been taken, or a 0 if not.  Push a
01492 ** NULL if either operand was NULL.
01493 */
01494 /* Opcode: StrLt P1 P2 *
01495 **
01496 ** Pop the top two elements from the stack.  If second element (the
01497 ** next on stack) is less than the first (the top of stack), then
01498 ** jump to instruction P2.  Otherwise, continue to the next instruction.
01499 ** In other words, jump if NOS<TOS.
01500 **
01501 ** If either operand is NULL (and thus if the result is unknown) then
01502 ** take the jump if P1 is true.
01503 **
01504 ** The strcmp() library routine is used for the comparison.  For a
01505 ** numeric comparison, use OP_Lt.
01506 **
01507 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01508 ** stack if the jump would have been taken, or a 0 if not.  Push a
01509 ** NULL if either operand was NULL.
01510 */
01511 /* Opcode: StrLe P1 P2 *
01512 **
01513 ** Pop the top two elements from the stack.  If second element (the
01514 ** next on stack) is less than or equal to the first (the top of stack),
01515 ** then jump to instruction P2. In other words, jump if NOS<=TOS.
01516 **
01517 ** If either operand is NULL (and thus if the result is unknown) then
01518 ** take the jump if P1 is true.
01519 **
01520 ** The strcmp() library routine is used for the comparison.  For a
01521 ** numeric comparison, use OP_Le.
01522 **
01523 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01524 ** stack if the jump would have been taken, or a 0 if not.  Push a
01525 ** NULL if either operand was NULL.
01526 */
01527 /* Opcode: StrGt P1 P2 *
01528 **
01529 ** Pop the top two elements from the stack.  If second element (the
01530 ** next on stack) is greater than the first (the top of stack),
01531 ** then jump to instruction P2. In other words, jump if NOS>TOS.
01532 **
01533 ** If either operand is NULL (and thus if the result is unknown) then
01534 ** take the jump if P1 is true.
01535 **
01536 ** The strcmp() library routine is used for the comparison.  For a
01537 ** numeric comparison, use OP_Gt.
01538 **
01539 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01540 ** stack if the jump would have been taken, or a 0 if not.  Push a
01541 ** NULL if either operand was NULL.
01542 */
01543 /* Opcode: StrGe P1 P2 *
01544 **
01545 ** Pop the top two elements from the stack.  If second element (the next
01546 ** on stack) is greater than or equal to the first (the top of stack),
01547 ** then jump to instruction P2. In other words, jump if NOS>=TOS.
01548 **
01549 ** If either operand is NULL (and thus if the result is unknown) then
01550 ** take the jump if P1 is true.
01551 **
01552 ** The strcmp() library routine is used for the comparison.  For a
01553 ** numeric comparison, use OP_Ge.
01554 **
01555 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
01556 ** stack if the jump would have been taken, or a 0 if not.  Push a
01557 ** NULL if either operand was NULL.
01558 */
01559 case OP_StrEq:
01560 case OP_StrNe:
01561 case OP_StrLt:
01562 case OP_StrLe:
01563 case OP_StrGt:
01564 case OP_StrGe: {
01565   Mem *pNos = &pTos[-1];
01566   int c;
01567   assert( pNos>=p->aStack );
01568   if( (pNos->flags | pTos->flags) & MEM_Null ){
01569     popStack(&pTos, 2);
01570     if( pOp->p2 ){
01571       if( pOp->p1 ) pc = pOp->p2-1;
01572     }else{
01573       pTos++;
01574       pTos->flags = MEM_Null;
01575     }
01576     break;
01577   }else{
01578     Stringify(pTos);
01579     Stringify(pNos);
01580     c = strcmp(pNos->z, pTos->z);
01581   }
01582   /* The asserts on each case of the following switch are there to verify
01583   ** that string comparison opcodes are always exactly 6 greater than the
01584   ** corresponding numeric comparison opcodes.  The code generator depends
01585   ** on this fact.
01586   */
01587   switch( pOp->opcode ){
01588     case OP_StrEq:    c = c==0;    assert( pOp->opcode-6==OP_Eq );   break;
01589     case OP_StrNe:    c = c!=0;    assert( pOp->opcode-6==OP_Ne );   break;
01590     case OP_StrLt:    c = c<0;     assert( pOp->opcode-6==OP_Lt );   break;
01591     case OP_StrLe:    c = c<=0;    assert( pOp->opcode-6==OP_Le );   break;
01592     case OP_StrGt:    c = c>0;     assert( pOp->opcode-6==OP_Gt );   break;
01593     default:          c = c>=0;    assert( pOp->opcode-6==OP_Ge );   break;
01594   }
01595   popStack(&pTos, 2);
01596   if( pOp->p2 ){
01597     if( c ) pc = pOp->p2-1;
01598   }else{
01599     pTos++;
01600     pTos->flags = MEM_Int;
01601     pTos->i = c;
01602   }
01603   break;
01604 }
01605 
01606 /* Opcode: And * * *
01607 **
01608 ** Pop two values off the stack.  Take the logical AND of the
01609 ** two values and push the resulting boolean value back onto the
01610 ** stack. 
01611 */
01612 /* Opcode: Or * * *
01613 **
01614 ** Pop two values off the stack.  Take the logical OR of the
01615 ** two values and push the resulting boolean value back onto the
01616 ** stack. 
01617 */
01618 case OP_And:
01619 case OP_Or: {
01620   Mem *pNos = &pTos[-1];
01621   int v1, v2;    /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
01622 
01623   assert( pNos>=p->aStack );
01624   if( pTos->flags & MEM_Null ){
01625     v1 = 2;
01626   }else{
01627     Integerify(pTos);
01628     v1 = pTos->i==0;
01629   }
01630   if( pNos->flags & MEM_Null ){
01631     v2 = 2;
01632   }else{
01633     Integerify(pNos);
01634     v2 = pNos->i==0;
01635   }
01636   if( pOp->opcode==OP_And ){
01637     static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
01638     v1 = and_logic[v1*3+v2];
01639   }else{
01640     static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
01641     v1 = or_logic[v1*3+v2];
01642   }
01643   popStack(&pTos, 2);
01644   pTos++;
01645   if( v1==2 ){
01646     pTos->flags = MEM_Null;
01647   }else{
01648     pTos->i = v1==0;
01649     pTos->flags = MEM_Int;
01650   }
01651   break;
01652 }
01653 
01654 /* Opcode: Negative * * *
01655 **
01656 ** Treat the top of the stack as a numeric quantity.  Replace it
01657 ** with its additive inverse.  If the top of the stack is NULL
01658 ** its value is unchanged.
01659 */
01660 /* Opcode: AbsValue * * *
01661 **
01662 ** Treat the top of the stack as a numeric quantity.  Replace it
01663 ** with its absolute value. If the top of the stack is NULL
01664 ** its value is unchanged.
01665 */
01666 case OP_Negative:
01667 case OP_AbsValue: {
01668   assert( pTos>=p->aStack );
01669   if( pTos->flags & MEM_Real ){
01670     Release(pTos);
01671     if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
01672       pTos->r = -pTos->r;
01673     }
01674     pTos->flags = MEM_Real;
01675   }else if( pTos->flags & MEM_Int ){
01676     Release(pTos);
01677     if( pOp->opcode==OP_Negative || pTos->i<0 ){
01678       pTos->i = -pTos->i;
01679     }
01680     pTos->flags = MEM_Int;
01681   }else if( pTos->flags & MEM_Null ){
01682     /* Do nothing */
01683   }else{
01684     Realify(pTos);
01685     Release(pTos);
01686     if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
01687       pTos->r = -pTos->r;
01688     }
01689     pTos->flags = MEM_Real;
01690   }
01691   break;
01692 }
01693 
01694 /* Opcode: Not * * *
01695 **
01696 ** Interpret the top of the stack as a boolean value.  Replace it
01697 ** with its complement.  If the top of the stack is NULL its value
01698 ** is unchanged.
01699 */
01700 case OP_Not: {
01701   assert( pTos>=p->aStack );
01702   if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
01703   Integerify(pTos);
01704   Release(pTos);
01705   pTos->i = !pTos->i;
01706   pTos->flags = MEM_Int;
01707   break;
01708 }
01709 
01710 /* Opcode: BitNot * * *
01711 **
01712 ** Interpret the top of the stack as an value.  Replace it
01713 ** with its ones-complement.  If the top of the stack is NULL its
01714 ** value is unchanged.
01715 */
01716 case OP_BitNot: {
01717   assert( pTos>=p->aStack );
01718   if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
01719   Integerify(pTos);
01720   Release(pTos);
01721   pTos->i = ~pTos->i;
01722   pTos->flags = MEM_Int;
01723   break;
01724 }
01725 
01726 /* Opcode: Noop * * *
01727 **
01728 ** Do nothing.  This instruction is often useful as a jump
01729 ** destination.
01730 */
01731 case OP_Noop: {
01732   break;
01733 }
01734 
01735 /* Opcode: If P1 P2 *
01736 **
01737 ** Pop a single boolean from the stack.  If the boolean popped is
01738 ** true, then jump to p2.  Otherwise continue to the next instruction.
01739 ** An integer is false if zero and true otherwise.  A string is
01740 ** false if it has zero length and true otherwise.
01741 **
01742 ** If the value popped of the stack is NULL, then take the jump if P1
01743 ** is true and fall through if P1 is false.
01744 */
01745 /* Opcode: IfNot P1 P2 *
01746 **
01747 ** Pop a single boolean from the stack.  If the boolean popped is
01748 ** false, then jump to p2.  Otherwise continue to the next instruction.
01749 ** An integer is false if zero and true otherwise.  A string is
01750 ** false if it has zero length and true otherwise.
01751 **
01752 ** If the value popped of the stack is NULL, then take the jump if P1
01753 ** is true and fall through if P1 is false.
01754 */
01755 case OP_If:
01756 case OP_IfNot: {
01757   int c;
01758   assert( pTos>=p->aStack );
01759   if( pTos->flags & MEM_Null ){
01760     c = pOp->p1;
01761   }else{
01762     Integerify(pTos);
01763     c = pTos->i;
01764     if( pOp->opcode==OP_IfNot ) c = !c;
01765   }
01766   assert( (pTos->flags & MEM_Dyn)==0 );
01767   pTos--;
01768   if( c ) pc = pOp->p2-1;
01769   break;
01770 }
01771 
01772 /* Opcode: IsNull P1 P2 *
01773 **
01774 ** If any of the top abs(P1) values on the stack are NULL, then jump
01775 ** to P2.  Pop the stack P1 times if P1>0.   If P1<0 leave the stack
01776 ** unchanged.
01777 */
01778 case OP_IsNull: {
01779   int i, cnt;
01780   Mem *pTerm;
01781   cnt = pOp->p1;
01782   if( cnt<0 ) cnt = -cnt;
01783   pTerm = &pTos[1-cnt];
01784   assert( pTerm>=p->aStack );
01785   for(i=0; i<cnt; i++, pTerm++){
01786     if( pTerm->flags & MEM_Null ){
01787       pc = pOp->p2-1;
01788       break;
01789     }
01790   }
01791   if( pOp->p1>0 ) popStack(&pTos, cnt);
01792   break;
01793 }
01794 
01795 /* Opcode: NotNull P1 P2 *
01796 **
01797 ** Jump to P2 if the top P1 values on the stack are all not NULL.  Pop the
01798 ** stack if P1 times if P1 is greater than zero.  If P1 is less than
01799 ** zero then leave the stack unchanged.
01800 */
01801 case OP_NotNull: {
01802   int i, cnt;
01803   cnt = pOp->p1;
01804   if( cnt<0 ) cnt = -cnt;
01805   assert( &pTos[1-cnt] >= p->aStack );
01806   for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
01807   if( i>=cnt ) pc = pOp->p2-1;
01808   if( pOp->p1>0 ) popStack(&pTos, cnt);
01809   break;
01810 }
01811 
01812 /* Opcode: MakeRecord P1 P2 *
01813 **
01814 ** Convert the top P1 entries of the stack into a single entry
01815 ** suitable for use as a data record in a database table.  The
01816 ** details of the format are irrelavant as long as the OP_Column
01817 ** opcode can decode the record later.  Refer to source code
01818 ** comments for the details of the record format.
01819 **
01820 ** If P2 is true (non-zero) and one or more of the P1 entries
01821 ** that go into building the record is NULL, then add some extra
01822 ** bytes to the record to make it distinct for other entries created
01823 ** during the same run of the VDBE.  The extra bytes added are a
01824 ** counter that is reset with each run of the VDBE, so records
01825 ** created this way will not necessarily be distinct across runs.
01826 ** But they should be distinct for transient tables (created using
01827 ** OP_OpenTemp) which is what they are intended for.
01828 **
01829 ** (Later:) The P2==1 option was intended to make NULLs distinct
01830 ** for the UNION operator.  But I have since discovered that NULLs
01831 ** are indistinct for UNION.  So this option is never used.
01832 */
01833 case OP_MakeRecord: {
01834   char *zNewRecord;
01835   int nByte;
01836   int nField;
01837   int i, j;
01838   int idxWidth;
01839   u32 addr;
01840   Mem *pRec;
01841   int addUnique = 0;   /* True to cause bytes to be added to make the
01842                        ** generated record distinct */
01843   char zTemp[NBFS];    /* Temp space for small records */
01844 
01845   /* Assuming the record contains N fields, the record format looks
01846   ** like this:
01847   **
01848   **   -------------------------------------------------------------------
01849   **   | idx0 | idx1 | ... | idx(N-1) | idx(N) | data0 | ... | data(N-1) |
01850   **   -------------------------------------------------------------------
01851   **
01852   ** All data fields are converted to strings before being stored and
01853   ** are stored with their null terminators.  NULL entries omit the
01854   ** null terminator.  Thus an empty string uses 1 byte and a NULL uses
01855   ** zero bytes.  Data(0) is taken from the lowest element of the stack
01856   ** and data(N-1) is the top of the stack.
01857   **
01858   ** Each of the idx() entries is either 1, 2, or 3 bytes depending on
01859   ** how big the total record is.  Idx(0) contains the offset to the start
01860   ** of data(0).  Idx(k) contains the offset to the start of data(k).
01861   ** Idx(N) contains the total number of bytes in the record.
01862   */
01863   nField = pOp->p1;
01864   pRec = &pTos[1-nField];
01865   assert( pRec>=p->aStack );
01866   nByte = 0;
01867   for(i=0; i<nField; i++, pRec++){
01868     if( pRec->flags & MEM_Null ){
01869       addUnique = pOp->p2;
01870     }else{
01871       Stringify(pRec);
01872       nByte += pRec->n;
01873     }
01874   }
01875   if( addUnique ) nByte += sizeof(p->uniqueCnt);
01876   if( nByte + nField + 1 < 256 ){
01877     idxWidth = 1;
01878   }else if( nByte + 2*nField + 2 < 65536 ){
01879     idxWidth = 2;
01880   }else{
01881     idxWidth = 3;
01882   }
01883   nByte += idxWidth*(nField + 1);
01884   if( nByte>MAX_BYTES_PER_ROW ){
01885     rc = SQLITE_TOOBIG;
01886     goto abort_due_to_error;
01887   }
01888   if( nByte<=NBFS ){
01889     zNewRecord = zTemp;
01890   }else{
01891     zNewRecord = sqliteMallocRaw( nByte );
01892     if( zNewRecord==0 ) goto no_mem;
01893   }
01894   j = 0;
01895   addr = idxWidth*(nField+1) + addUnique*sizeof(p->uniqueCnt);
01896   for(i=0, pRec=&pTos[1-nField]; i<nField; i++, pRec++){
01897     zNewRecord[j++] = addr & 0xff;
01898     if( idxWidth>1 ){
01899       zNewRecord[j++] = (addr>>8)&0xff;
01900       if( idxWidth>2 ){
01901         zNewRecord[j++] = (addr>>16)&0xff;
01902       }
01903     }
01904     if( (pRec->flags & MEM_Null)==0 ){
01905       addr += pRec->n;
01906     }
01907   }
01908   zNewRecord[j++] = addr & 0xff;
01909   if( idxWidth>1 ){
01910     zNewRecord[j++] = (addr>>8)&0xff;
01911     if( idxWidth>2 ){
01912       zNewRecord[j++] = (addr>>16)&0xff;
01913     }
01914   }
01915   if( addUnique ){
01916     memcpy(&zNewRecord[j], &p->uniqueCnt, sizeof(p->uniqueCnt));
01917     p->uniqueCnt++;
01918     j += sizeof(p->uniqueCnt);
01919   }
01920   for(i=0, pRec=&pTos[1-nField]; i<nField; i++, pRec++){
01921     if( (pRec->flags & MEM_Null)==0 ){
01922       memcpy(&zNewRecord[j], pRec->z, pRec->n);
01923       j += pRec->n;
01924     }
01925   }
01926   popStack(&pTos, nField);
01927   pTos++;
01928   pTos->n = nByte;
01929   if( nByte<=NBFS ){
01930     assert( zNewRecord==zTemp );
01931     memcpy(pTos->zShort, zTemp, nByte);
01932     pTos->z = pTos->zShort;
01933     pTos->flags = MEM_Str | MEM_Short;
01934   }else{
01935     assert( zNewRecord!=zTemp );
01936     pTos->z = zNewRecord;
01937     pTos->flags = MEM_Str | MEM_Dyn;
01938   }
01939   break;
01940 }
01941 
01942 /* Opcode: MakeKey P1 P2 P3
01943 **
01944 ** Convert the top P1 entries of the stack into a single entry suitable
01945 ** for use as the key in an index.  The top P1 records are
01946 ** converted to strings and merged.  The null-terminators 
01947 ** are retained and used as separators.
01948 ** The lowest entry in the stack is the first field and the top of the
01949 ** stack becomes the last.
01950 **
01951 ** If P2 is not zero, then the original entries remain on the stack
01952 ** and the new key is pushed on top.  If P2 is zero, the original
01953 ** data is popped off the stack first then the new key is pushed
01954 ** back in its place.
01955 **
01956 ** P3 is a string that is P1 characters long.  Each character is either
01957 ** an 'n' or a 't' to indicates if the argument should be intepreted as
01958 ** numeric or text type.  The first character of P3 corresponds to the
01959 ** lowest element on the stack.  If P3 is NULL then all arguments are
01960 ** assumed to be of the numeric type.
01961 **
01962 ** The type makes a difference in that text-type fields may not be 
01963 ** introduced by 'b' (as described in the next paragraph).  The
01964 ** first character of a text-type field must be either 'a' (if it is NULL)
01965 ** or 'c'.  Numeric fields will be introduced by 'b' if their content
01966 ** looks like a well-formed number.  Otherwise the 'a' or 'c' will be
01967 ** used.
01968 **
01969 ** The key is a concatenation of fields.  Each field is terminated by
01970 ** a single 0x00 character.  A NULL field is introduced by an 'a' and
01971 ** is followed immediately by its 0x00 terminator.  A numeric field is
01972 ** introduced by a single character 'b' and is followed by a sequence
01973 ** of characters that represent the number such that a comparison of
01974 ** the character string using memcpy() sorts the numbers in numerical
01975 ** order.  The character strings for numbers are generated using the
01976 ** sqliteRealToSortable() function.  A text field is introduced by a
01977 ** 'c' character and is followed by the exact text of the field.  The
01978 ** use of an 'a', 'b', or 'c' character at the beginning of each field
01979 ** guarantees that NULLs sort before numbers and that numbers sort
01980 ** before text.  0x00 characters do not occur except as separators
01981 ** between fields.
01982 **
01983 ** See also: MakeIdxKey, SortMakeKey
01984 */
01985 /* Opcode: MakeIdxKey P1 P2 P3
01986 **
01987 ** Convert the top P1 entries of the stack into a single entry suitable
01988 ** for use as the key in an index.  In addition, take one additional integer
01989 ** off of the stack, treat that integer as a four-byte record number, and
01990 ** append the four bytes to the key.  Thus a total of P1+1 entries are
01991 ** popped from the stack for this instruction and a single entry is pushed
01992 ** back.  The first P1 entries that are popped are strings and the last
01993 ** entry (the lowest on the stack) is an integer record number.
01994 **
01995 ** The converstion of the first P1 string entries occurs just like in
01996 ** MakeKey.  Each entry is separated from the others by a null.
01997 ** The entire concatenation is null-terminated.  The lowest entry
01998 ** in the stack is the first field and the top of the stack becomes the
01999 ** last.
02000 **
02001 ** If P2 is not zero and one or more of the P1 entries that go into the
02002 ** generated key is NULL, then jump to P2 after the new key has been
02003 ** pushed on the stack.  In other words, jump to P2 if the key is
02004 ** guaranteed to be unique.  This jump can be used to skip a subsequent
02005 ** uniqueness test.
02006 **
02007 ** P3 is a string that is P1 characters long.  Each character is either
02008 ** an 'n' or a 't' to indicates if the argument should be numeric or
02009 ** text.  The first character corresponds to the lowest element on the
02010 ** stack.  If P3 is null then all arguments are assumed to be numeric.
02011 **
02012 ** See also:  MakeKey, SortMakeKey
02013 */
02014 case OP_MakeIdxKey:
02015 case OP_MakeKey: {
02016   char *zNewKey;
02017   int nByte;
02018   int nField;
02019   int addRowid;
02020   int i, j;
02021   int containsNull = 0;
02022   Mem *pRec;
02023   char zTemp[NBFS];
02024 
02025   addRowid = pOp->opcode==OP_MakeIdxKey;
02026   nField = pOp->p1;
02027   pRec = &pTos[1-nField];
02028   assert( pRec>=p->aStack );
02029   nByte = 0;
02030   for(j=0, i=0; i<nField; i++, j++, pRec++){
02031     int flags = pRec->flags;
02032     int len;
02033     char *z;
02034     if( flags & MEM_Null ){
02035       nByte += 2;
02036       containsNull = 1;
02037     }else if( pOp->p3 && pOp->p3[j]=='t' ){
02038       Stringify(pRec);
02039       pRec->flags &= ~(MEM_Int|MEM_Real);
02040       nByte += pRec->n+1;
02041     }else if( (flags & (MEM_Real|MEM_Int))!=0 || sqliteIsNumber(pRec->z) ){
02042       if( (flags & (MEM_Real|MEM_Int))==MEM_Int ){
02043         pRec->r = pRec->i;
02044       }else if( (flags & (MEM_Real|MEM_Int))==0 ){
02045         pRec->r = sqliteAtoF(pRec->z, 0);
02046       }
02047       Release(pRec);
02048       z = pRec->zShort;
02049       sqliteRealToSortable(pRec->r, z);
02050       len = strlen(z);
02051       pRec->z = 0;
02052       pRec->flags = MEM_Real;
02053       pRec->n = len+1;
02054       nByte += pRec->n+1;
02055     }else{
02056       nByte += pRec->n+1;
02057     }
02058   }
02059   if( nByte+sizeof(u32)>MAX_BYTES_PER_ROW ){
02060     rc = SQLITE_TOOBIG;
02061     goto abort_due_to_error;
02062   }
02063   if( addRowid ) nByte += sizeof(u32);
02064   if( nByte<=NBFS ){
02065     zNewKey = zTemp;
02066   }else{
02067     zNewKey = sqliteMallocRaw( nByte );
02068     if( zNewKey==0 ) goto no_mem;
02069   }
02070   j = 0;
02071   pRec = &pTos[1-nField];
02072   for(i=0; i<nField; i++, pRec++){
02073     if( pRec->flags & MEM_Null ){
02074       zNewKey[j++] = 'a';
02075       zNewKey[j++] = 0;
02076     }else if( pRec->flags==MEM_Real ){
02077       zNewKey[j++] = 'b';
02078       memcpy(&zNewKey[j], pRec->zShort, pRec->n);
02079       j += pRec->n;
02080     }else{
02081       assert( pRec->flags & MEM_Str );
02082       zNewKey[j++] = 'c';
02083       memcpy(&zNewKey[j], pRec->z, pRec->n);
02084       j += pRec->n;
02085     }
02086   }
02087   if( addRowid ){
02088     u32 iKey;
02089     pRec = &pTos[-nField];
02090     assert( pRec>=p->aStack );
02091     Integerify(pRec);
02092     iKey = intToKey(pRec->i);
02093     memcpy(&zNewKey[j], &iKey, sizeof(u32));
02094     popStack(&pTos, nField+1);
02095     if( pOp->p2 && containsNull ) pc = pOp->p2 - 1;
02096   }else{
02097     if( pOp->p2==0 ) popStack(&pTos, nField);
02098   }
02099   pTos++;
02100   pTos->n = nByte;
02101   if( nByte<=NBFS ){
02102     assert( zNewKey==zTemp );
02103     pTos->z = pTos->zShort;
02104     memcpy(pTos->zShort, zTemp, nByte);
02105     pTos->flags = MEM_Str | MEM_Short;
02106   }else{
02107     pTos->z = zNewKey;
02108     pTos->flags = MEM_Str | MEM_Dyn;
02109   }
02110   break;
02111 }
02112 
02113 /* Opcode: IncrKey * * *
02114 **
02115 ** The top of the stack should contain an index key generated by
02116 ** The MakeKey opcode.  This routine increases the least significant
02117 ** byte of that key by one.  This is used so that the MoveTo opcode
02118 ** will move to the first entry greater than the key rather than to
02119 ** the key itself.
02120 */
02121 case OP_IncrKey: {
02122   assert( pTos>=p->aStack );
02123   /* The IncrKey opcode is only applied to keys generated by
02124   ** MakeKey or MakeIdxKey and the results of those operands
02125   ** are always dynamic strings or zShort[] strings.  So we
02126   ** are always free to modify the string in place.
02127   */
02128   assert( pTos->flags & (MEM_Dyn|MEM_Short) );
02129   pTos->z[pTos->n-1]++;
02130   break;
02131 }
02132 
02133 /* Opcode: Checkpoint P1 * *
02134 **
02135 ** Begin a checkpoint.  A checkpoint is the beginning of a operation that
02136 ** is part of a larger transaction but which might need to be rolled back
02137 ** itself without effecting the containing transaction.  A checkpoint will
02138 ** be automatically committed or rollback when the VDBE halts.
02139 **
02140 ** The checkpoint is begun on the database file with index P1.  The main
02141 ** database file has an index of 0 and the file used for temporary tables
02142 ** has an index of 1.
02143 */
02144 case OP_Checkpoint: {
02145   int i = pOp->p1;
02146   if( i>=0 && i<db->nDb && db->aDb[i].pBt && db->aDb[i].inTrans==1 ){
02147     rc = sqliteBtreeBeginCkpt(db->aDb[i].pBt);
02148     if( rc==SQLITE_OK ) db->aDb[i].inTrans = 2;
02149   }
02150   break;
02151 }
02152 
02153 /* Opcode: Transaction P1 * *
02154 **
02155 ** Begin a transaction.  The transaction ends when a Commit or Rollback
02156 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
02157 ** transaction might also be rolled back if an error is encountered.
02158 **
02159 ** P1 is the index of the database file on which the transaction is
02160 ** started.  Index 0 is the main database file and index 1 is the
02161 ** file used for temporary tables.
02162 **
02163 ** A write lock is obtained on the database file when a transaction is
02164 ** started.  No other process can read or write the file while the
02165 ** transaction is underway.  Starting a transaction also creates a
02166 ** rollback journal.  A transaction must be started before any changes
02167 ** can be made to the database.
02168 */
02169 case OP_Transaction: {
02170   int busy = 1;
02171   int i = pOp->p1;
02172   assert( i>=0 && i<db->nDb );
02173   if( db->aDb[i].inTrans ) break;
02174   while( db->aDb[i].pBt!=0 && busy ){
02175     rc = sqliteBtreeBeginTrans(db->aDb[i].pBt);
02176     switch( rc ){
02177       case SQLITE_BUSY: {
02178         if( db->xBusyCallback==0 ){
02179           p->pc = pc;
02180           p->undoTransOnError = 1;
02181           p->rc = SQLITE_BUSY;
02182           p->pTos = pTos;
02183           return SQLITE_BUSY;
02184         }else if( (*db->xBusyCallback)(db->pBusyArg, "", busy++)==0 ){
02185           sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), (char*)0);
02186           busy = 0;
02187         }
02188         break;
02189       }
02190       case SQLITE_READONLY: {
02191         rc = SQLITE_OK;
02192         /* Fall thru into the next case */
02193       }
02194       case SQLITE_OK: {
02195         p->inTempTrans = 0;
02196         busy = 0;
02197         break;
02198       }
02199       default: {
02200         goto abort_due_to_error;
02201       }
02202     }
02203   }
02204   db->aDb[i].inTrans = 1;
02205   p->undoTransOnError = 1;
02206   break;
02207 }
02208 
02209 /* Opcode: Commit * * *
02210 **
02211 ** Cause all modifications to the database that have been made since the
02212 ** last Transaction to actually take effect.  No additional modifications
02213 ** are allowed until another transaction is started.  The Commit instruction
02214 ** deletes the journal file and releases the write lock on the database.
02215 ** A read lock continues to be held if there are still cursors open.
02216 */
02217 case OP_Commit: {
02218   int i;
02219   if( db->xCommitCallback!=0 ){
02220     if( sqliteSafetyOff(db) ) goto abort_due_to_misuse; 
02221     if( db->xCommitCallback(db->pCommitArg)!=0 ){
02222       rc = SQLITE_CONSTRAINT;
02223     }
02224     if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
02225   }
02226   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
02227     if( db->aDb[i].inTrans ){
02228       rc = sqliteBtreeCommit(db->aDb[i].pBt);
02229       db->aDb[i].inTrans = 0;
02230     }
02231   }
02232   if( rc==SQLITE_OK ){
02233     sqliteCommitInternalChanges(db);
02234   }else{
02235     sqliteRollbackAll(db);
02236   }
02237   break;
02238 }
02239 
02240 /* Opcode: Rollback P1 * *
02241 **
02242 ** Cause all modifications to the database that have been made since the
02243 ** last Transaction to be undone. The database is restored to its state
02244 ** before the Transaction opcode was executed.  No additional modifications
02245 ** are allowed until another transaction is started.
02246 **
02247 ** P1 is the index of the database file that is committed.  An index of 0
02248 ** is used for the main database and an index of 1 is used for the file used
02249 ** to hold temporary tables.
02250 **
02251 ** This instruction automatically closes all cursors and releases both
02252 ** the read and write locks on the indicated database.
02253 */
02254 case OP_Rollback: {
02255   sqliteRollbackAll(db);
02256   break;
02257 }
02258 
02259 /* Opcode: ReadCookie P1 P2 *
02260 **
02261 ** Read cookie number P2 from database P1 and push it onto the stack.
02262 ** P2==0 is the schema version.  P2==1 is the database format.
02263 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
02264 ** the main database file and P1==1 is the database file used to store
02265 ** temporary tables.
02266 **
02267 ** There must be a read-lock on the database (either a transaction
02268 ** must be started or there must be an open cursor) before
02269 ** executing this instruction.
02270 */
02271 case OP_ReadCookie: {
02272   int aMeta[SQLITE_N_BTREE_META];
02273   assert( pOp->p2<SQLITE_N_BTREE_META );
02274   assert( pOp->p1>=0 && pOp->p1<db->nDb );
02275   assert( db->aDb[pOp->p1].pBt!=0 );
02276   rc = sqliteBtreeGetMeta(db->aDb[pOp->p1].pBt, aMeta);
02277   pTos++;
02278   pTos->i = aMeta[1+pOp->p2];
02279   pTos->flags = MEM_Int;
02280   break;
02281 }
02282 
02283 /* Opcode: SetCookie P1 P2 *
02284 **
02285 ** Write the top of the stack into cookie number P2 of database P1.
02286 ** P2==0 is the schema version.  P2==1 is the database format.
02287 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
02288 ** the main database file and P1==1 is the database file used to store
02289 ** temporary tables.
02290 **
02291 ** A transaction must be started before executing this opcode.
02292 */
02293 case OP_SetCookie: {
02294   int aMeta[SQLITE_N_BTREE_META];
02295   assert( pOp->p2<SQLITE_N_BTREE_META );
02296   assert( pOp->p1>=0 && pOp->p1<db->nDb );
02297   assert( db->aDb[pOp->p1].pBt!=0 );
02298   assert( pTos>=p->aStack );
02299   Integerify(pTos)
02300   rc = sqliteBtreeGetMeta(db->aDb[pOp->p1].pBt, aMeta);
02301   if( rc==SQLITE_OK ){
02302     aMeta[1+pOp->p2] = pTos->i;
02303     rc = sqliteBtreeUpdateMeta(db->aDb[pOp->p1].pBt, aMeta);
02304   }
02305   Release(pTos);
02306   pTos--;
02307   break;
02308 }
02309 
02310 /* Opcode: VerifyCookie P1 P2 *
02311 **
02312 ** Check the value of global database parameter number 0 (the
02313 ** schema version) and make sure it is equal to P2.  
02314 ** P1 is the database number which is 0 for the main database file
02315 ** and 1 for the file holding temporary tables and some higher number
02316 ** for auxiliary databases.
02317 **
02318 ** The cookie changes its value whenever the database schema changes.
02319 ** This operation is used to detect when that the cookie has changed
02320 ** and that the current process needs to reread the schema.
02321 **
02322 ** Either a transaction needs to have been started or an OP_Open needs
02323 ** to be executed (to establish a read lock) before this opcode is
02324 ** invoked.
02325 */
02326 case OP_VerifyCookie: {
02327   int aMeta[SQLITE_N_BTREE_META];
02328   assert( pOp->p1>=0 && pOp->p1<db->nDb );
02329   rc = sqliteBtreeGetMeta(db->aDb[pOp->p1].pBt, aMeta);
02330   if( rc==SQLITE_OK && aMeta[1]!=pOp->p2 ){
02331     sqliteSetString(&p->zErrMsg, "database schema has changed", (char*)0);
02332     rc = SQLITE_SCHEMA;
02333   }
02334   break;
02335 }
02336 
02337 /* Opcode: OpenRead P1 P2 P3
02338 **
02339 ** Open a read-only cursor for the database table whose root page is
02340 ** P2 in a database file.  The database file is determined by an 
02341 ** integer from the top of the stack.  0 means the main database and
02342 ** 1 means the database used for temporary tables.  Give the new 
02343 ** cursor an identifier of P1.  The P1 values need not be contiguous
02344 ** but all P1 values should be small integers.  It is an error for
02345 ** P1 to be negative.
02346 **
02347 ** If P2==0 then take the root page number from the next of the stack.
02348 **
02349 ** There will be a read lock on the database whenever there is an
02350 ** open cursor.  If the database was unlocked prior to this instruction
02351 ** then a read lock is acquired as part of this instruction.  A read
02352 ** lock allows other processes to read the database but prohibits
02353 ** any other process from modifying the database.  The read lock is
02354 ** released when all cursors are closed.  If this instruction attempts
02355 ** to get a read lock but fails, the script terminates with an
02356 ** SQLITE_BUSY error code.
02357 **
02358 ** The P3 value is the name of the table or index being opened.
02359 ** The P3 value is not actually used by this opcode and may be
02360 ** omitted.  But the code generator usually inserts the index or
02361 ** table name into P3 to make the code easier to read.
02362 **
02363 ** See also OpenWrite.
02364 */
02365 /* Opcode: OpenWrite P1 P2 P3
02366 **
02367 ** Open a read/write cursor named P1 on the table or index whose root
02368 ** page is P2.  If P2==0 then take the root page number from the stack.
02369 **
02370 ** The P3 value is the name of the table or index being opened.
02371 ** The P3 value is not actually used by this opcode and may be
02372 ** omitted.  But the code generator usually inserts the index or
02373 ** table name into P3 to make the code easier to read.
02374 **
02375 ** This instruction works just like OpenRead except that it opens the cursor
02376 ** in read/write mode.  For a given table, there can be one or more read-only
02377 ** cursors or a single read/write cursor but not both.
02378 **
02379 ** See also OpenRead.
02380 */
02381 case OP_OpenRead:
02382 case OP_OpenWrite: {
02383   int busy = 0;
02384   int i = pOp->p1;
02385   int p2 = pOp->p2;
02386   int wrFlag;
02387   Btree *pX;
02388   int iDb;
02389   
02390   assert( pTos>=p->aStack );
02391   Integerify(pTos);
02392   iDb = pTos->i;
02393   pTos--;
02394   assert( iDb>=0 && iDb<db->nDb );
02395   pX = db->aDb[iDb].pBt;
02396   assert( pX!=0 );
02397   wrFlag = pOp->opcode==OP_OpenWrite;
02398   if( p2<=0 ){
02399     assert( pTos>=p->aStack );
02400     Integerify(pTos);
02401     p2 = pTos->i;
02402     pTos--;
02403     if( p2<2 ){
02404       sqliteSetString(&p->zErrMsg, "root page number less than 2", (char*)0);
02405       rc = SQLITE_INTERNAL;
02406       break;
02407     }
02408   }
02409   assert( i>=0 );
02410   if( expandCursorArraySize(p, i) ) goto no_mem;
02411   sqliteVdbeCleanupCursor(&p->aCsr[i]);
02412   memset(&p->aCsr[i], 0, sizeof(Cursor));
02413   p->aCsr[i].nullRow = 1;
02414   if( pX==0 ) break;
02415   do{
02416     rc = sqliteBtreeCursor(pX, p2, wrFlag, &p->aCsr[i].pCursor);
02417     switch( rc ){
02418       case SQLITE_BUSY: {
02419         if( db->xBusyCallback==0 ){
02420           p->pc = pc;
02421           p->rc = SQLITE_BUSY;
02422           p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
02423           return SQLITE_BUSY;
02424         }else if( (*db->xBusyCallback)(db->pBusyArg, pOp->p3, ++busy)==0 ){
02425           sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), (char*)0);
02426           busy = 0;
02427         }
02428         break;
02429       }
02430       case SQLITE_OK: {
02431         busy = 0;
02432         break;
02433       }
02434       default: {
02435         goto abort_due_to_error;
02436       }
02437     }
02438   }while( busy );
02439   break;
02440 }
02441 
02442 /* Opcode: OpenTemp P1 P2 *
02443 **
02444 ** Open a new cursor to a transient table.
02445 ** The transient cursor is always opened read/write even if 
02446 ** the main database is read-only.  The transient table is deleted
02447 ** automatically when the cursor is closed.
02448 **
02449 ** The cursor points to a BTree table if P2==0 and to a BTree index
02450 ** if P2==1.  A BTree table must have an integer key and can have arbitrary
02451 ** data.  A BTree index has no data but can have an arbitrary key.
02452 **
02453 ** This opcode is used for tables that exist for the duration of a single
02454 ** SQL statement only.  Tables created using CREATE TEMPORARY TABLE
02455 ** are opened using OP_OpenRead or OP_OpenWrite.  "Temporary" in the
02456 ** context of this opcode means for the duration of a single SQL statement
02457 ** whereas "Temporary" in the context of CREATE TABLE means for the duration
02458 ** of the connection to the database.  Same word; different meanings.
02459 */
02460 case OP_OpenTemp: {
02461   int i = pOp->p1;
02462   Cursor *pCx;
02463   assert( i>=0 );
02464   if( expandCursorArraySize(p, i) ) goto no_mem;
02465   pCx = &p->aCsr[i];
02466   sqliteVdbeCleanupCursor(pCx);
02467   memset(pCx, 0, sizeof(*pCx));
02468   pCx->nullRow = 1;
02469   rc = sqliteBtreeFactory(db, 0, 1, TEMP_PAGES, &pCx->pBt);
02470 
02471   if( rc==SQLITE_OK ){
02472     rc = sqliteBtreeBeginTrans(pCx->pBt);
02473   }
02474   if( rc==SQLITE_OK ){
02475     if( pOp->p2 ){
02476       int pgno;
02477       rc = sqliteBtreeCreateIndex(pCx->pBt, &pgno);
02478       if( rc==SQLITE_OK ){
02479         rc = sqliteBtreeCursor(pCx->pBt, pgno, 1, &pCx->pCursor);
02480       }
02481     }else{
02482       rc = sqliteBtreeCursor(pCx->pBt, 2, 1, &pCx->pCursor);
02483     }
02484   }
02485   break;
02486 }
02487 
02488 /* Opcode: OpenPseudo P1 * *
02489 **
02490 ** Open a new cursor that points to a fake table that contains a single
02491 ** row of data.  Any attempt to write a second row of data causes the
02492 ** first row to be deleted.  All data is deleted when the cursor is
02493 ** closed.
02494 **
02495 ** A pseudo-table created by this opcode is useful for holding the
02496 ** NEW or OLD tables in a trigger.
02497 */
02498 case OP_OpenPseudo: {
02499   int i = pOp->p1;
02500   Cursor *pCx;
02501   assert( i>=0 );
02502   if( expandCursorArraySize(p, i) ) goto no_mem;
02503   pCx = &p->aCsr[i];
02504   sqliteVdbeCleanupCursor(pCx);
02505   memset(pCx, 0, sizeof(*pCx));
02506   pCx->nullRow = 1;
02507   pCx->pseudoTable = 1;
02508   break;
02509 }
02510 
02511 /* Opcode: Close P1 * *
02512 **
02513 ** Close a cursor previously opened as P1.  If P1 is not
02514 ** currently open, this instruction is a no-op.
02515 */
02516 case OP_Close: {
02517   int i = pOp->p1;
02518   if( i>=0 && i<p->nCursor ){
02519     sqliteVdbeCleanupCursor(&p->aCsr[i]);
02520   }
02521   break;
02522 }
02523 
02524 /* Opcode: MoveTo P1 P2 *
02525 **
02526 ** Pop the top of the stack and use its value as a key.  Reposition
02527 ** cursor P1 so that it points to an entry with a matching key.  If
02528 ** the table contains no record with a matching key, then the cursor
02529 ** is left pointing at the first record that is greater than the key.
02530 ** If there are no records greater than the key and P2 is not zero,
02531 ** then an immediate jump to P2 is made.
02532 **
02533 ** See also: Found, NotFound, Distinct, MoveLt
02534 */
02535 /* Opcode: MoveLt P1 P2 *
02536 **
02537 ** Pop the top of the stack and use its value as a key.  Reposition
02538 ** cursor P1 so that it points to the entry with the largest key that is
02539 ** less than the key popped from the stack.
02540 ** If there are no records less than than the key and P2
02541 ** is not zero then an immediate jump to P2 is made.
02542 **
02543 ** See also: MoveTo
02544 */
02545 case OP_MoveLt:
02546 case OP_MoveTo: {
02547   int i = pOp->p1;
02548   Cursor *pC;
02549 
02550   assert( pTos>=p->aStack );
02551   assert( i>=0 && i<p->nCursor );
02552   pC = &p->aCsr[i];
02553   if( pC->pCursor!=0 ){
02554     int res, oc;
02555     pC->nullRow = 0;
02556     if( pTos->flags & MEM_Int ){
02557       int iKey = intToKey(pTos->i);
02558       if( pOp->p2==0 && pOp->opcode==OP_MoveTo ){
02559         pC->movetoTarget = iKey;
02560         pC->deferredMoveto = 1;
02561         Release(pTos);
02562         pTos--;
02563         break;
02564       }
02565       sqliteBtreeMoveto(pC->pCursor, (char*)&iKey, sizeof(int), &res);
02566       pC->lastRecno = pTos->i;
02567       pC->recnoIsValid = res==0;
02568     }else{
02569       Stringify(pTos);
02570       sqliteBtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
02571       pC->recnoIsValid = 0;
02572     }
02573     pC->deferredMoveto = 0;
02574     sqlite_search_count++;
02575     oc = pOp->opcode;
02576     if( oc==OP_MoveTo && res<0 ){
02577       sqliteBtreeNext(pC->pCursor, &res);
02578       pC->recnoIsValid = 0;
02579       if( res && pOp->p2>0 ){
02580         pc = pOp->p2 - 1;
02581       }
02582     }else if( oc==OP_MoveLt ){
02583       if( res>=0 ){
02584         sqliteBtreePrevious(pC->pCursor, &res);
02585         pC->recnoIsValid = 0;
02586       }else{
02587         /* res might be negative because the table is empty.  Check to
02588         ** see if this is the case.
02589         */
02590         int keysize;
02591         res = sqliteBtreeKeySize(pC->pCursor,&keysize)!=0 || keysize==0;
02592       }
02593       if( res && pOp->p2>0 ){
02594         pc = pOp->p2 - 1;
02595       }
02596     }
02597   }
02598   Release(pTos);
02599   pTos--;
02600   break;
02601 }
02602 
02603 /* Opcode: Distinct P1 P2 *
02604 **
02605 ** Use the top of the stack as a string key.  If a record with that key does
02606 ** not exist in the table of cursor P1, then jump to P2.  If the record
02607 ** does already exist, then fall thru.  The cursor is left pointing
02608 ** at the record if it exists. The key is not popped from the stack.
02609 **
02610 ** This operation is similar to NotFound except that this operation
02611 ** does not pop the key from the stack.
02612 **
02613 ** See also: Found, NotFound, MoveTo, IsUnique, NotExists
02614 */
02615 /* Opcode: Found P1 P2 *
02616 **
02617 ** Use the top of the stack as a string key.  If a record with that key
02618 ** does exist in table of P1, then jump to P2.  If the record
02619 ** does not exist, then fall thru.  The cursor is left pointing
02620 ** to the record if it exists.  The key is popped from the stack.
02621 **
02622 ** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
02623 */
02624 /* Opcode: NotFound P1 P2 *
02625 **
02626 ** Use the top of the stack as a string key.  If a record with that key
02627 ** does not exist in table of P1, then jump to P2.  If the record
02628 ** does exist, then fall thru.  The cursor is left pointing to the
02629 ** record if it exists.  The key is popped from the stack.
02630 **
02631 ** The difference between this operation and Distinct is that
02632 ** Distinct does not pop the key from the stack.
02633 **
02634 ** See also: Distinct, Found, MoveTo, NotExists, IsUnique
02635 */
02636 case OP_Distinct:
02637 case OP_NotFound:
02638 case OP_Found: {
02639   int i = pOp->p1;
02640   int alreadyExists = 0;
02641   Cursor *pC;
02642   assert( pTos>=p->aStack );
02643   assert( i>=0 && i<p->nCursor );
02644   if( (pC = &p->aCsr[i])->pCursor!=0 ){
02645     int res, rx;
02646     Stringify(pTos);
02647     rx = sqliteBtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
02648     alreadyExists = rx==SQLITE_OK && res==0;
02649     pC->deferredMoveto = 0;
02650   }
02651   if( pOp->opcode==OP_Found ){
02652     if( alreadyExists ) pc = pOp->p2 - 1;
02653   }else{
02654     if( !alreadyExists ) pc = pOp->p2 - 1;
02655   }
02656   if( pOp->opcode!=OP_Distinct ){
02657     Release(pTos);
02658     pTos--;
02659   }
02660   break;
02661 }
02662 
02663 /* Opcode: IsUnique P1 P2 *
02664 **
02665 ** The top of the stack is an integer record number.  Call this
02666 ** record number R.  The next on the stack is an index key created
02667 ** using MakeIdxKey.  Call it K.  This instruction pops R from the
02668 ** stack but it leaves K unchanged.
02669 **
02670 ** P1 is an index.  So all but the last four bytes of K are an
02671 ** index string.  The last four bytes of K are a record number.
02672 **
02673 ** This instruction asks if there is an entry in P1 where the
02674 ** index string matches K but the record number is different
02675 ** from R.  If there is no such entry, then there is an immediate
02676 ** jump to P2.  If any entry does exist where the index string
02677 ** matches K but the record number is not R, then the record
02678 ** number for that entry is pushed onto the stack and control
02679 ** falls through to the next instruction.
02680 **
02681 ** See also: Distinct, NotFound, NotExists, Found
02682 */
02683 case OP_IsUnique: {
02684   int i = pOp->p1;
02685   Mem *pNos = &pTos[-1];
02686   BtCursor *pCrsr;
02687   int R;
02688 
02689   /* Pop the value R off the top of the stack
02690   */
02691   assert( pNos>=p->aStack );
02692   Integerify(pTos);
02693   R = pTos->i;
02694   pTos--;
02695   assert( i>=0 && i<=p->nCursor );
02696   if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
02697     int res, rc;
02698     int v;         /* The record number on the P1 entry that matches K */
02699     char *zKey;    /* The value of K */
02700     int nKey;      /* Number of bytes in K */
02701 
02702     /* Make sure K is a string and make zKey point to K
02703     */
02704     Stringify(pNos);
02705     zKey = pNos->z;
02706     nKey = pNos->n;
02707     assert( nKey >= 4 );
02708 
02709     /* Search for an entry in P1 where all but the last four bytes match K.
02710     ** If there is no such entry, jump immediately to P2.
02711     */
02712     assert( p->aCsr[i].deferredMoveto==0 );
02713     rc = sqliteBtreeMoveto(pCrsr, zKey, nKey-4, &res);
02714     if( rc!=SQLITE_OK ) goto abort_due_to_error;
02715     if( res<0 ){
02716       rc = sqliteBtreeNext(pCrsr, &res);
02717       if( res ){
02718         pc = pOp->p2 - 1;
02719         break;
02720       }
02721     }
02722     rc = sqliteBtreeKeyCompare(pCrsr, zKey, nKey-4, 4, &res);
02723     if( rc!=SQLITE_OK ) goto abort_due_to_error;
02724     if( res>0 ){
02725       pc = pOp->p2 - 1;
02726       break;
02727     }
02728 
02729     /* At this point, pCrsr is pointing to an entry in P1 where all but
02730     ** the last for bytes of the key match K.  Check to see if the last
02731     ** four bytes of the key are different from R.  If the last four
02732     ** bytes equal R then jump immediately to P2.
02733     */
02734     sqliteBtreeKey(pCrsr, nKey - 4, 4, (char*)&v);
02735     v = keyToInt(v);
02736     if( v==R ){
02737       pc = pOp->p2 - 1;
02738       break;
02739     }
02740 
02741     /* The last four bytes of the key are different from R.  Convert the
02742     ** last four bytes of the key into an integer and push it onto the
02743     ** stack.  (These bytes are the record number of an entry that
02744     ** violates a UNIQUE constraint.)
02745     */
02746     pTos++;
02747     pTos->i = v;
02748     pTos->flags = MEM_Int;
02749   }
02750   break;
02751 }
02752 
02753 /* Opcode: NotExists P1 P2 *
02754 **
02755 ** Use the top of the stack as a integer key.  If a record with that key
02756 ** does not exist in table of P1, then jump to P2.  If the record
02757 ** does exist, then fall thru.  The cursor is left pointing to the
02758 ** record if it exists.  The integer key is popped from the stack.
02759 **
02760 ** The difference between this operation and NotFound is that this
02761 ** operation assumes the key is an integer and NotFound assumes it
02762 ** is a string.
02763 **
02764 ** See also: Distinct, Found, MoveTo, NotFound, IsUnique
02765 */
02766 case OP_NotExists: {
02767   int i = pOp->p1;
02768   BtCursor *pCrsr;
02769   assert( pTos>=p->aStack );
02770   assert( i>=0 && i<p->nCursor );
02771   if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
02772     int res, rx, iKey;
02773     assert( pTos->flags & MEM_Int );
02774     iKey = intToKey(pTos->i);
02775     rx = sqliteBtreeMoveto(pCrsr, (char*)&iKey, sizeof(int), &res);
02776     p->aCsr[i].lastRecno = pTos->i;
02777     p->aCsr[i].recnoIsValid = res==0;
02778     p->aCsr[i].nullRow = 0;
02779     if( rx!=SQLITE_OK || res!=0 ){
02780       pc = pOp->p2 - 1;
02781       p->aCsr[i].recnoIsValid = 0;
02782     }
02783   }
02784   Release(pTos);
02785   pTos--;
02786   break;
02787 }
02788 
02789 /* Opcode: NewRecno P1 * *
02790 **
02791 ** Get a new integer record number used as the key to a table.
02792 ** The record number is not previously used as a key in the database
02793 ** table that cursor P1 points to.  The new record number is pushed 
02794 ** onto the stack.
02795 */
02796 case OP_NewRecno: {
02797   int i = pOp->p1;
02798   int v = 0;
02799   Cursor *pC;
02800   assert( i>=0 && i<p->nCursor );
02801   if( (pC = &p->aCsr[i])->pCursor==0 ){
02802     v = 0;
02803   }else{
02804     /* The next rowid or record number (different terms for the same
02805     ** thing) is obtained in a two-step algorithm.
02806     **
02807     ** First we attempt to find the largest existing rowid and add one
02808     ** to that.  But if the largest existing rowid is already the maximum
02809     ** positive integer, we have to fall through to the second
02810     ** probabilistic algorithm
02811     **
02812     ** The second algorithm is to select a rowid at random and see if
02813     ** it already exists in the table.  If it does not exist, we have
02814     ** succeeded.  If the random rowid does exist, we select a new one
02815     ** and try again, up to 1000 times.
02816     **
02817     ** For a table with less than 2 billion entries, the probability
02818     ** of not finding a unused rowid is about 1.0e-300.  This is a 
02819     ** non-zero probability, but it is still vanishingly small and should
02820     ** never cause a problem.  You are much, much more likely to have a
02821     ** hardware failure than for this algorithm to fail.
02822     **
02823     ** The analysis in the previous paragraph assumes that you have a good
02824     ** source of random numbers.  Is a library function like lrand48()
02825     ** good enough?  Maybe. Maybe not. It's hard to know whether there
02826     ** might be subtle bugs is some implementations of lrand48() that
02827     ** could cause problems. To avoid uncertainty, SQLite uses its own 
02828     ** random number generator based on the RC4 algorithm.
02829     **
02830     ** To promote locality of reference for repetitive inserts, the
02831     ** first few attempts at chosing a random rowid pick values just a little
02832     ** larger than the previous rowid.  This has been shown experimentally
02833     ** to double the speed of the COPY operation.
02834     */
02835     int res, rx, cnt, x;
02836     cnt = 0;
02837     if( !pC->useRandomRowid ){
02838       if( pC->nextRowidValid ){
02839         v = pC->nextRowid;
02840       }else{
02841         rx = sqliteBtreeLast(pC->pCursor, &res);
02842         if( res ){
02843           v = 1;
02844         }else{
02845           sqliteBtreeKey(pC->pCursor, 0, sizeof(v), (void*)&v);
02846           v = keyToInt(v);
02847           if( v==0x7fffffff ){
02848             pC->useRandomRowid = 1;
02849           }else{
02850             v++;
02851           }
02852         }
02853       }
02854       if( v<0x7fffffff ){
02855         pC->nextRowidValid = 1;
02856         pC->nextRowid = v+1;
02857       }else{
02858         pC->nextRowidValid = 0;
02859       }
02860     }
02861     if( pC->useRandomRowid ){
02862       v = db->priorNewRowid;
02863       cnt = 0;
02864       do{
02865         if( v==0 || cnt>2 ){
02866           sqliteRandomness(sizeof(v), &v);
02867           if( cnt<5 ) v &= 0xffffff;
02868         }else{
02869           unsigned char r;
02870           sqliteRandomness(1, &r);
02871           v += r + 1;
02872         }
02873         if( v==0 ) continue;
02874         x = intToKey(v);
02875         rx = sqliteBtreeMoveto(pC->pCursor, &x, sizeof(int), &res);
02876         cnt++;
02877       }while( cnt<1000 && rx==SQLITE_OK && res==0 );
02878       db->priorNewRowid = v;
02879       if( rx==SQLITE_OK && res==0 ){
02880         rc = SQLITE_FULL;
02881         goto abort_due_to_error;
02882       }
02883     }
02884     pC->recnoIsValid = 0;
02885     pC->deferredMoveto = 0;
02886   }
02887   pTos++;
02888   pTos->i = v;
02889   pTos->flags = MEM_Int;
02890   break;
02891 }
02892 
02893 /* Opcode: PutIntKey P1 P2 *
02894 **
02895 ** Write an entry into the table of cursor P1.  A new entry is
02896 ** created if it doesn't already exist or the data for an existing
02897 ** entry is overwritten.  The data is the value on the top of the
02898 ** stack.  The key is the next value down on the stack.  The key must
02899 ** be an integer.  The stack is popped twice by this instruction.
02900 **
02901 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
02902 ** incremented (otherwise not).  If the OPFLAG_CSCHANGE flag is set,
02903 ** then the current statement change count is incremented (otherwise not).
02904 ** If the OPFLAG_LASTROWID flag of P2 is set, then rowid is
02905 ** stored for subsequent return by the sqlite_last_insert_rowid() function
02906 ** (otherwise it's unmodified).
02907 */
02908 /* Opcode: PutStrKey P1 * *
02909 **
02910 ** Write an entry into the table of cursor P1.  A new entry is
02911 ** created if it doesn't already exist or the data for an existing
02912 ** entry is overwritten.  The data is the value on the top of the
02913 ** stack.  The key is the next value down on the stack.  The key must
02914 ** be a string.  The stack is popped twice by this instruction.
02915 **
02916 ** P1 may not be a pseudo-table opened using the OpenPseudo opcode.
02917 */
02918 case OP_PutIntKey:
02919 case OP_PutStrKey: {
02920   Mem *pNos = &pTos[-1];
02921   int i = pOp->p1;
02922   Cursor *pC;
02923   assert( pNos>=p->aStack );
02924   assert( i>=0 && i<p->nCursor );
02925   if( ((pC = &p->aCsr[i])->pCursor!=0 || pC->pseudoTable) ){
02926     char *zKey;
02927     int nKey, iKey;
02928     if( pOp->opcode==OP_PutStrKey ){
02929       Stringify(pNos);
02930       nKey = pNos->n;
02931       zKey = pNos->z;
02932     }else{
02933       assert( pNos->flags & MEM_Int );
02934       nKey = sizeof(int);
02935       iKey = intToKey(pNos->i);
02936       zKey = (char*)&iKey;
02937       if( pOp->p2 & OPFLAG_NCHANGE ) db->nChange++;
02938       if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->i;
02939       if( pOp->p2 & OPFLAG_CSCHANGE ) db->csChange++;
02940       if( pC->nextRowidValid && pTos->i>=pC->nextRowid ){
02941         pC->nextRowidValid = 0;
02942       }
02943     }
02944     if( pTos->flags & MEM_Null ){
02945       pTos->z = 0;
02946       pTos->n = 0;
02947     }else{
02948       assert( pTos->flags & MEM_Str );
02949     }
02950     if( pC->pseudoTable ){
02951       /* PutStrKey does not work for pseudo-tables.
02952       ** The following assert makes sure we are not trying to use
02953       ** PutStrKey on a pseudo-table
02954       */
02955       assert( pOp->opcode==OP_PutIntKey );
02956       sqliteFree(pC->pData);
02957       pC->iKey = iKey;
02958       pC->nData = pTos->n;
02959       if( pTos->flags & MEM_Dyn ){
02960         pC->pData = pTos->z;
02961         pTos->flags = MEM_Null;
02962       }else{
02963         pC->pData = sqliteMallocRaw( pC->nData );
02964         if( pC->pData ){
02965           memcpy(pC->pData, pTos->z, pC->nData);
02966         }
02967       }
02968       pC->nullRow = 0;
02969     }else{
02970       rc = sqliteBtreeInsert(pC->pCursor, zKey, nKey, pTos->z, pTos->n);
02971     }
02972     pC->recnoIsValid = 0;
02973     pC->deferredMoveto = 0;
02974   }
02975   popStack(&pTos, 2);
02976   break;
02977 }
02978 
02979 /* Opcode: Delete P1 P2 *
02980 **
02981 ** Delete the record at which the P1 cursor is currently pointing.
02982 **
02983 ** The cursor will be left pointing at either the next or the previous
02984 ** record in the table. If it is left pointing at the next record, then
02985 ** the next Next instruction will be a no-op.  Hence it is OK to delete
02986 ** a record from within an Next loop.
02987 **
02988 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
02989 ** incremented (otherwise not).  If OPFLAG_CSCHANGE flag is set,
02990 ** then the current statement change count is incremented (otherwise not).
02991 **
02992 ** If P1 is a pseudo-table, then this instruction is a no-op.
02993 */
02994 case OP_Delete: {
02995   int i = pOp->p1;
02996   Cursor *pC;
02997   assert( i>=0 && i<p->nCursor );
02998   pC = &p->aCsr[i];
02999   if( pC->pCursor!=0 ){
03000     sqliteVdbeCursorMoveto(pC);
03001     rc = sqliteBtreeDelete(pC->pCursor);
03002     pC->nextRowidValid = 0;
03003   }
03004   if( pOp->p2 & OPFLAG_NCHANGE ) db->nChange++;
03005   if( pOp->p2 & OPFLAG_CSCHANGE ) db->csChange++;
03006   break;
03007 }
03008 
03009 /* Opcode: SetCounts * * *
03010 **
03011 ** Called at end of statement.  Updates lsChange (last statement change count)
03012 ** and resets csChange (current statement change count) to 0.
03013 */
03014 case OP_SetCounts: {
03015   db->lsChange=db->csChange;
03016   db->csChange=0;
03017   break;
03018 }
03019 
03020 /* Opcode: KeyAsData P1 P2 *
03021 **
03022 ** Turn the key-as-data mode for cursor P1 either on (if P2==1) or
03023 ** off (if P2==0).  In key-as-data mode, the OP_Column opcode pulls
03024 ** data off of the key rather than the data.  This is used for
03025 ** processing compound selects.
03026 */
03027 case OP_KeyAsData: {
03028   int i = pOp->p1;
03029   assert( i>=0 && i<p->nCursor );
03030   p->aCsr[i].keyAsData = pOp->p2;
03031   break;
03032 }
03033 
03034 /* Opcode: RowData P1 * *
03035 **
03036 ** Push onto the stack the complete row data for cursor P1.
03037 ** There is no interpretation of the data.  It is just copied
03038 ** onto the stack exactly as it is found in the database file.
03039 **
03040 ** If the cursor is not pointing to a valid row, a NULL is pushed
03041 ** onto the stack.
03042 */
03043 /* Opcode: RowKey P1 * *
03044 **
03045 ** Push onto the stack the complete row key for cursor P1.
03046 ** There is no interpretation of the key.  It is just copied
03047 ** onto the stack exactly as it is found in the database file.
03048 **
03049 ** If the cursor is not pointing to a valid row, a NULL is pushed
03050 ** onto the stack.
03051 */
03052 case OP_RowKey:
03053 case OP_RowData: {
03054   int i = pOp->p1;
03055   Cursor *pC;
03056   int n;
03057 
03058   pTos++;
03059   assert( i>=0 && i<p->nCursor );
03060   pC = &p->aCsr[i];
03061   if( pC->nullRow ){
03062     pTos->flags = MEM_Null;
03063   }else if( pC->pCursor!=0 ){
03064     BtCursor *pCrsr = pC->pCursor;
03065     sqliteVdbeCursorMoveto(pC);
03066     if( pC->nullRow ){
03067       pTos->flags = MEM_Null;
03068       break;
03069     }else if( pC->keyAsData || pOp->opcode==OP_RowKey ){
03070       sqliteBtreeKeySize(pCrsr, &n);
03071     }else{
03072       sqliteBtreeDataSize(pCrsr, &n);
03073     }
03074     pTos->n = n;
03075     if( n<=NBFS ){
03076       pTos->flags = MEM_Str | MEM_Short;
03077       pTos->z = pTos->zShort;
03078     }else{
03079       char *z = sqliteMallocRaw( n );
03080       if( z==0 ) goto no_mem;
03081       pTos->flags = MEM_Str | MEM_Dyn;
03082       pTos->z = z;
03083     }
03084     if( pC->keyAsData || pOp->opcode==OP_RowKey ){
03085       sqliteBtreeKey(pCrsr, 0, n, pTos->z);
03086     }else{
03087       sqliteBtreeData(pCrsr, 0, n, pTos->z);
03088     }
03089   }else if( pC->pseudoTable ){
03090     pTos->n = pC->nData;
03091     pTos->z = pC->pData;
03092     pTos->flags = MEM_Str|MEM_Ephem;
03093   }else{
03094     pTos->flags = MEM_Null;
03095   }
03096   break;
03097 }
03098 
03099 /* Opcode: Column P1 P2 *
03100 **
03101 ** Interpret the data that cursor P1 points to as
03102 ** a structure built using the MakeRecord instruction.
03103 ** (See the MakeRecord opcode for additional information about
03104 ** the format of the data.)
03105 ** Push onto the stack the value of the P2-th column contained
03106 ** in the data.
03107 **
03108 ** If the KeyAsData opcode has previously executed on this cursor,
03109 ** then the field might be extracted from the key rather than the
03110 ** data.
03111 **
03112 ** If P1 is negative, then the record is stored on the stack rather
03113 ** than in a table.  For P1==-1, the top of the stack is used.
03114 ** For P1==-2, the next on the stack is used.  And so forth.  The
03115 ** value pushed is always just a pointer into the record which is
03116 ** stored further down on the stack.  The column value is not copied.
03117 */
03118 case OP_Column: {
03119   int amt, offset, end, payloadSize;
03120   int i = pOp->p1;
03121   int p2 = pOp->p2;
03122   Cursor *pC;
03123   char *zRec;
03124   BtCursor *pCrsr;
03125   int idxWidth;
03126   unsigned char aHdr[10];
03127 
03128   assert( i<p->nCursor );
03129   pTos++;
03130   if( i<0 ){
03131     assert( &pTos[i]>=p->aStack );
03132     assert( pTos[i].flags & MEM_Str );
03133     zRec = pTos[i].z;
03134     payloadSize = pTos[i].n;
03135   }else if( (pC = &p->aCsr[i])->pCursor!=0 ){
03136     sqliteVdbeCursorMoveto(pC);
03137     zRec = 0;
03138     pCrsr = pC->pCursor;
03139     if( pC->nullRow ){
03140       payloadSize = 0;
03141     }else if( pC->keyAsData ){
03142       sqliteBtreeKeySize(pCrsr, &payloadSize);
03143     }else{
03144       sqliteBtreeDataSize(pCrsr, &payloadSize);
03145     }
03146   }else if( pC->pseudoTable ){
03147     payloadSize = pC->nData;
03148     zRec = pC->pData;
03149     assert( payloadSize==0 || zRec!=0 );
03150   }else{
03151     payloadSize = 0;
03152   }
03153 
03154   /* Figure out how many bytes in the column data and where the column
03155   ** data begins.
03156   */
03157   if( payloadSize==0 ){
03158     pTos->flags = MEM_Null;
03159     break;
03160   }else if( payloadSize<256 ){
03161     idxWidth = 1;
03162   }else if( payloadSize<65536 ){
03163     idxWidth = 2;
03164   }else{
03165     idxWidth = 3;
03166   }
03167 
03168   /* Figure out where the requested column is stored and how big it is.
03169   */
03170   if( payloadSize < idxWidth*(p2+1) ){
03171     rc = SQLITE_CORRUPT;
03172     goto abort_due_to_error;
03173   }
03174   if( zRec ){
03175     memcpy(aHdr, &zRec[idxWidth*p2], idxWidth*2);
03176   }else if( pC->keyAsData ){
03177     sqliteBtreeKey(pCrsr, idxWidth*p2, idxWidth*2, (char*)aHdr);
03178   }else{
03179     sqliteBtreeData(pCrsr, idxWidth*p2, idxWidth*2, (char*)aHdr);
03180   }
03181   offset = aHdr[0];
03182   end = aHdr[idxWidth];
03183   if( idxWidth>1 ){
03184     offset |= aHdr[1]<<8;
03185     end |= aHdr[idxWidth+1]<<8;
03186     if( idxWidth>2 ){
03187       offset |= aHdr[2]<<16;
03188       end |= aHdr[idxWidth+2]<<16;
03189     }
03190   }
03191   amt = end - offset;
03192   if( amt<0 || offset<0 || end>payloadSize ){
03193     rc = SQLITE_CORRUPT;
03194     goto abort_due_to_error;
03195   }
03196 
03197   /* amt and offset now hold the offset to the start of data and the
03198   ** amount of data.  Go get the data and put it on the stack.
03199   */
03200   pTos->n = amt;
03201   if( amt==0 ){
03202     pTos->flags = MEM_Null;
03203   }else if( zRec ){
03204     pTos->flags = MEM_Str | MEM_Ephem;
03205     pTos->z = &zRec[offset];
03206   }else{
03207     if( amt<=NBFS ){
03208       pTos->flags = MEM_Str | MEM_Short;
03209       pTos->z = pTos->zShort;
03210     }else{
03211       char *z = sqliteMallocRaw( amt );
03212       if( z==0 ) goto no_mem;
03213       pTos->flags = MEM_Str | MEM_Dyn;
03214       pTos->z = z;
03215     }
03216     if( pC->keyAsData ){
03217       sqliteBtreeKey(pCrsr, offset, amt, pTos->z);
03218     }else{
03219       sqliteBtreeData(pCrsr, offset, amt, pTos->z);
03220     }
03221   }
03222   break;
03223 }
03224 
03225 /* Opcode: Recno P1 * *
03226 **
03227 ** Push onto the stack an integer which is the first 4 bytes of the
03228 ** the key to the current entry in a sequential scan of the database
03229 ** file P1.  The sequential scan should have been started using the 
03230 ** Next opcode.
03231 */
03232 case OP_Recno: {
03233   int i = pOp->p1;
03234   Cursor *pC;
03235   int v;
03236 
03237   assert( i>=0 && i<p->nCursor );
03238   pC = &p->aCsr[i];
03239   sqliteVdbeCursorMoveto(pC);
03240   pTos++;
03241   if( pC->recnoIsValid ){
03242     v = pC->lastRecno;
03243   }else if( pC->pseudoTable ){
03244     v = keyToInt(pC->iKey);
03245   }else if( pC->nullRow || pC->pCursor==0 ){
03246     pTos->flags = MEM_Null;
03247     break;
03248   }else{
03249     assert( pC->pCursor!=0 );
03250     sqliteBtreeKey(pC->pCursor, 0, sizeof(u32), (char*)&v);
03251     v = keyToInt(v);
03252   }
03253   pTos->i = v;
03254   pTos->flags = MEM_Int;
03255   break;
03256 }
03257 
03258 /* Opcode: FullKey P1 * *
03259 **
03260 ** Extract the complete key from the record that cursor P1 is currently
03261 ** pointing to and push the key onto the stack as a string.
03262 **
03263 ** Compare this opcode to Recno.  The Recno opcode extracts the first
03264 ** 4 bytes of the key and pushes those bytes onto the stack as an
03265 ** integer.  This instruction pushes the entire key as a string.
03266 **
03267 ** This opcode may not be used on a pseudo-table.
03268 */
03269 case OP_FullKey: {
03270   int i = pOp->p1;
03271   BtCursor *pCrsr;
03272 
03273   assert( p->aCsr[i].keyAsData );
03274   assert( !p->aCsr[i].pseudoTable );
03275   assert( i>=0 && i<p->nCursor );
03276   pTos++;
03277   if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
03278     int amt;
03279     char *z;
03280 
03281     sqliteVdbeCursorMoveto(&p->aCsr[i]);
03282     sqliteBtreeKeySize(pCrsr, &amt);
03283     if( amt<=0 ){
03284       rc = SQLITE_CORRUPT;
03285       goto abort_due_to_error;
03286     }
03287     if( amt>NBFS ){
03288       z = sqliteMallocRaw( amt );
03289       if( z==0 ) goto no_mem;
03290       pTos->flags = MEM_Str | MEM_Dyn;
03291     }else{
03292       z = pTos->zShort;
03293       pTos->flags = MEM_Str | MEM_Short;
03294     }
03295     sqliteBtreeKey(pCrsr, 0, amt, z);
03296     pTos->z = z;
03297     pTos->n = amt;
03298   }
03299   break;
03300 }
03301 
03302 /* Opcode: NullRow P1 * *
03303 **
03304 ** Move the cursor P1 to a null row.  Any OP_Column operations
03305 ** that occur while the cursor is on the null row will always push 
03306 ** a NULL onto the stack.
03307 */
03308 case OP_NullRow: {
03309   int i = pOp->p1;
03310 
03311   assert( i>=0 && i<p->nCursor );
03312   p->aCsr[i].nullRow = 1;
03313   p->aCsr[i].recnoIsValid = 0;
03314   break;
03315 }
03316 
03317 /* Opcode: Last P1 P2 *
03318 **
03319 ** The next use of the Recno or Column or Next instruction for P1 
03320 ** will refer to the last entry in the database table or index.
03321 ** If the table or index is empty and P2>0, then jump immediately to P2.
03322 ** If P2 is 0 or if the table or index is not empty, fall through
03323 ** to the following instruction.
03324 */
03325 case OP_Last: {
03326   int i = pOp->p1;
03327   Cursor *pC;
03328   BtCursor *pCrsr;
03329 
03330   assert( i>=0 && i<p->nCursor );
03331   pC = &p->aCsr[i];
03332   if( (pCrsr = pC->pCursor)!=0 ){
03333     int res;
03334     rc = sqliteBtreeLast(pCrsr, &res);
03335     pC->nullRow = res;
03336     pC->deferredMoveto = 0;
03337     if( res && pOp->p2>0 ){
03338       pc = pOp->p2 - 1;
03339     }
03340   }else{
03341     pC->nullRow = 0;
03342   }
03343   break;
03344 }
03345 
03346 /* Opcode: Rewind P1 P2 *
03347 **
03348 ** The next use of the Recno or Column or Next instruction for P1 
03349 ** will refer to the first entry in the database table or index.
03350 ** If the table or index is empty and P2>0, then jump immediately to P2.
03351 ** If P2 is 0 or if the table or index is not empty, fall through
03352 ** to the following instruction.
03353 */
03354 case OP_Rewind: {
03355   int i = pOp->p1;
03356   Cursor *pC;
03357   BtCursor *pCrsr;
03358 
03359   assert( i>=0 && i<p->nCursor );
03360   pC = &p->aCsr[i];
03361   if( (pCrsr = pC->pCursor)!=0 ){
03362     int res;
03363     rc = sqliteBtreeFirst(pCrsr, &res);
03364     pC->atFirst = res==0;
03365     pC->nullRow = res;
03366     pC->deferredMoveto = 0;
03367     if( res && pOp->p2>0 ){
03368       pc = pOp->p2 - 1;
03369     }
03370   }else{
03371     pC->nullRow = 0;
03372   }
03373   break;
03374 }
03375 
03376 /* Opcode: Next P1 P2 *
03377 **
03378 ** Advance cursor P1 so that it points to the next key/data pair in its
03379 ** table or index.  If there are no more key/value pairs then fall through
03380 ** to the following instruction.  But if the cursor advance was successful,
03381 ** jump immediately to P2.
03382 **
03383 ** See also: Prev
03384 */
03385 /* Opcode: Prev P1 P2 *
03386 **
03387 ** Back up cursor P1 so that it points to the previous key/data pair in its
03388 ** table or index.  If there is no previous key/value pairs then fall through
03389 ** to the following instruction.  But if the cursor backup was successful,
03390 ** jump immediately to P2.
03391 */
03392 case OP_Prev:
03393 case OP_Next: {
03394   Cursor *pC;
03395   BtCursor *pCrsr;
03396 
03397   CHECK_FOR_INTERRUPT;
03398   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
03399   pC = &p->aCsr[pOp->p1];
03400   if( (pCrsr = pC->pCursor)!=0 ){
03401     int res;
03402     if( pC->nullRow ){
03403       res = 1;
03404     }else{
03405       assert( pC->deferredMoveto==0 );
03406       rc = pOp->opcode==OP_Next ? sqliteBtreeNext(pCrsr, &res) :
03407                                   sqliteBtreePrevious(pCrsr, &res);
03408       pC->nullRow = res;
03409     }
03410     if( res==0 ){
03411       pc = pOp->p2 - 1;
03412       sqlite_search_count++;
03413     }
03414   }else{
03415     pC->nullRow = 1;
03416   }
03417   pC->recnoIsValid = 0;
03418   break;
03419 }
03420 
03421 /* Opcode: IdxPut P1 P2 P3
03422 **
03423 ** The top of the stack holds a SQL index key made using the
03424 ** MakeIdxKey instruction.  This opcode writes that key into the
03425 ** index P1.  Data for the entry is nil.
03426 **
03427 ** If P2==1, then the key must be unique.  If the key is not unique,
03428 ** the program aborts with a SQLITE_CONSTRAINT error and the database
03429 ** is rolled back.  If P3 is not null, then it becomes part of the
03430 ** error message returned with the SQLITE_CONSTRAINT.
03431 */
03432 case OP_IdxPut: {
03433   int i = pOp->p1;
03434   BtCursor *pCrsr;
03435   assert( pTos>=p->aStack );
03436   assert( i>=0 && i<p->nCursor );
03437   assert( pTos->flags & MEM_Str );
03438   if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
03439     int nKey = pTos->n;
03440     const char *zKey = pTos->z;
03441     if( pOp->p2 ){
03442       int res, n;
03443       assert( nKey >= 4 );
03444       rc = sqliteBtreeMoveto(pCrsr, zKey, nKey-4, &res);
03445       if( rc!=SQLITE_OK ) goto abort_due_to_error;
03446       while( res!=0 ){
03447         int c;
03448         sqliteBtreeKeySize(pCrsr, &n);
03449         if( n==nKey
03450            && sqliteBtreeKeyCompare(pCrsr, zKey, nKey-4, 4, &c)==SQLITE_OK
03451            && c==0
03452         ){
03453           rc = SQLITE_CONSTRAINT;
03454           if( pOp->p3 && pOp->p3[0] ){
03455             sqliteSetString(&p->zErrMsg, pOp->p3, (char*)0);
03456           }
03457           goto abort_due_to_error;
03458         }
03459         if( res<0 ){
03460           sqliteBtreeNext(pCrsr, &res);
03461           res = +1;
03462         }else{
03463           break;
03464         }
03465       }
03466     }
03467     rc = sqliteBtreeInsert(pCrsr, zKey, nKey, "", 0);
03468     assert( p->aCsr[i].deferredMoveto==0 );
03469   }
03470   Release(pTos);
03471   pTos--;
03472   break;
03473 }
03474 
03475 /* Opcode: IdxDelete P1 * *
03476 **
03477 ** The top of the stack is an index key built using the MakeIdxKey opcode.
03478 ** This opcode removes that entry from the index.
03479 */
03480 case OP_IdxDelete: {
03481   int i = pOp->p1;
03482   BtCursor *pCrsr;
03483   assert( pTos>=p->aStack );
03484   assert( pTos->flags & MEM_Str );
03485   assert( i>=0 && i<p->nCursor );
03486   if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
03487     int rx, res;
03488     rx = sqliteBtreeMoveto(pCrsr, pTos->z, pTos->n, &res);
03489     if( rx==SQLITE_OK && res==0 ){
03490       rc = sqliteBtreeDelete(pCrsr);
03491     }
03492     assert( p->aCsr[i].deferredMoveto==0 );
03493   }
03494   Release(pTos);
03495   pTos--;
03496   break;
03497 }
03498 
03499 /* Opcode: IdxRecno P1 * *
03500 **
03501 ** Push onto the stack an integer which is the last 4 bytes of the
03502 ** the key to the current entry in index P1.  These 4 bytes should
03503 ** be the record number of the table entry to which this index entry
03504 ** points.
03505 **
03506 ** See also: Recno, MakeIdxKey.
03507 */
03508 case OP_IdxRecno: {
03509   int i = pOp->p1;
03510   BtCursor *pCrsr;
03511 
03512   assert( i>=0 && i<p->nCursor );
03513   pTos++;
03514   if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
03515     int v;
03516     int sz;
03517     assert( p->aCsr[i].deferredMoveto==0 );
03518     sqliteBtreeKeySize(pCrsr, &sz);
03519     if( sz<sizeof(u32) ){
03520       pTos->flags = MEM_Null;
03521     }else{
03522       sqliteBtreeKey(pCrsr, sz - sizeof(u32), sizeof(u32), (char*)&v);
03523       v = keyToInt(v);
03524       pTos->i = v;
03525       pTos->flags = MEM_Int;
03526     }
03527   }else{
03528     pTos->flags = MEM_Null;
03529   }
03530   break;
03531 }
03532 
03533 /* Opcode: IdxGT P1 P2 *
03534 **
03535 ** Compare the top of the stack against the key on the index entry that
03536 ** cursor P1 is currently pointing to.  Ignore the last 4 bytes of the
03537 ** index entry.  If the index entry is greater than the top of the stack
03538 ** then jump to P2.  Otherwise fall through to the next instruction.
03539 ** In either case, the stack is popped once.
03540 */
03541 /* Opcode: IdxGE P1 P2 *
03542 **
03543 ** Compare the top of the stack against the key on the index entry that
03544 ** cursor P1 is currently pointing to.  Ignore the last 4 bytes of the
03545 ** index entry.  If the index entry is greater than or equal to 
03546 ** the top of the stack
03547 ** then jump to P2.  Otherwise fall through to the next instruction.
03548 ** In either case, the stack is popped once.
03549 */
03550 /* Opcode: IdxLT P1 P2 *
03551 **
03552 ** Compare the top of the stack against the key on the index entry that
03553 ** cursor P1 is currently pointing to.  Ignore the last 4 bytes of the
03554 ** index entry.  If the index entry is less than the top of the stack
03555 ** then jump to P2.  Otherwise fall through to the next instruction.
03556 ** In either case, the stack is popped once.
03557 */
03558 case OP_IdxLT:
03559 case OP_IdxGT:
03560 case OP_IdxGE: {
03561   int i= pOp->p1;
03562   BtCursor *pCrsr;
03563 
03564   assert( i>=0 && i<p->nCursor );
03565   assert( pTos>=p->aStack );
03566   if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
03567     int res, rc;
03568  
03569     Stringify(pTos);
03570     assert( p->aCsr[i].deferredMoveto==0 );
03571     rc = sqliteBtreeKeyCompare(pCrsr, pTos->z, pTos->n, 4, &res);
03572     if( rc!=SQLITE_OK ){
03573       break;
03574     }
03575     if( pOp->opcode==OP_IdxLT ){
03576       res = -res;
03577     }else if( pOp->opcode==OP_IdxGE ){
03578       res++;
03579     }
03580     if( res>0 ){
03581       pc = pOp->p2 - 1 ;
03582     }
03583   }
03584   Release(pTos);
03585   pTos--;
03586   break;
03587 }
03588 
03589 /* Opcode: IdxIsNull P1 P2 *
03590 **
03591 ** The top of the stack contains an index entry such as might be generated
03592 ** by the MakeIdxKey opcode.  This routine looks at the first P1 fields of
03593 ** that key.  If any of the first P1 fields are NULL, then a jump is made
03594 ** to address P2.  Otherwise we fall straight through.
03595 **
03596 ** The index entry is always popped from the stack.
03597 */
03598 case OP_IdxIsNull: {
03599   int i = pOp->p1;
03600   int k, n;
03601   const char *z;
03602 
03603   assert( pTos>=p->aStack );
03604   assert( pTos->flags & MEM_Str );
03605   z = pTos->z;
03606   n = pTos->n;
03607   for(k=0; k<n && i>0; i--){
03608     if( z[k]=='a' ){
03609       pc = pOp->p2-1;
03610       break;
03611     }
03612     while( k<n && z[k] ){ k++; }
03613     k++;
03614   }
03615   Release(pTos);
03616   pTos--;
03617   break;
03618 }
03619 
03620 /* Opcode: Destroy P1 P2 *
03621 **
03622 ** Delete an entire database table or index whose root page in the database
03623 ** file is given by P1.
03624 **
03625 ** The table being destroyed is in the main database file if P2==0.  If
03626 ** P2==1 then the table to be clear is in the auxiliary database file
03627 ** that is used to store tables create using CREATE TEMPORARY TABLE.
03628 **
03629 ** See also: Clear
03630 */
03631 case OP_Destroy: {
03632   rc = sqliteBtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1);
03633   break;
03634 }
03635 
03636 /* Opcode: Clear P1 P2 *
03637 **
03638 ** Delete all contents of the database table or index whose root page
03639 ** in the database file is given by P1.  But, unlike Destroy, do not
03640 ** remove the table or index from the database file.
03641 **
03642 ** The table being clear is in the main database file if P2==0.  If
03643 ** P2==1 then the table to be clear is in the auxiliary database file
03644 ** that is used to store tables create using CREATE TEMPORARY TABLE.
03645 **
03646 ** See also: Destroy
03647 */
03648 case OP_Clear: {
03649   rc = sqliteBtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
03650   break;
03651 }
03652 
03653 /* Opcode: CreateTable * P2 P3
03654 **
03655 ** Allocate a new table in the main database file if P2==0 or in the
03656 ** auxiliary database file if P2==1.  Push the page number
03657 ** for the root page of the new table onto the stack.
03658 **
03659 ** The root page number is also written to a memory location that P3
03660 ** points to.  This is the mechanism is used to write the root page
03661 ** number into the parser's internal data structures that describe the
03662 ** new table.
03663 **
03664 ** The difference between a table and an index is this:  A table must
03665 ** have a 4-byte integer key and can have arbitrary data.  An index
03666 ** has an arbitrary key but no data.
03667 **
03668 ** See also: CreateIndex
03669 */
03670 /* Opcode: CreateIndex * P2 P3
03671 **
03672 ** Allocate a new index in the main database file if P2==0 or in the
03673 ** auxiliary database file if P2==1.  Push the page number of the
03674 ** root page of the new index onto the stack.
03675 **
03676 ** See documentation on OP_CreateTable for additional information.
03677 */
03678 case OP_CreateIndex:
03679 case OP_CreateTable: {
03680   int pgno;
03681   assert( pOp->p3!=0 && pOp->p3type==P3_POINTER );
03682   assert( pOp->p2>=0 && pOp->p2<db->nDb );
03683   assert( db->aDb[pOp->p2].pBt!=0 );
03684   if( pOp->opcode==OP_CreateTable ){
03685     rc = sqliteBtreeCreateTable(db->aDb[pOp->p2].pBt, &pgno);
03686   }else{
03687     rc = sqliteBtreeCreateIndex(db->aDb[pOp->p2].pBt, &pgno);
03688   }
03689   pTos++;
03690   if( rc==SQLITE_OK ){
03691     pTos->i = pgno;
03692     pTos->flags = MEM_Int;
03693     *(u32*)pOp->p3 = pgno;
03694     pOp->p3 = 0;
03695   }else{
03696     pTos->flags = MEM_Null;
03697   }
03698   break;
03699 }
03700 
03701 /* Opcode: IntegrityCk P1 P2 *
03702 **
03703 ** Do an analysis of the currently open database.  Push onto the
03704 ** stack the text of an error message describing any problems.
03705 ** If there are no errors, push a "ok" onto the stack.
03706 **
03707 ** P1 is the index of a set that contains the root page numbers
03708 ** for all tables and indices in the main database file.  The set
03709 ** is cleared by this opcode.  In other words, after this opcode
03710 ** has executed, the set will be empty.
03711 **
03712 ** If P2 is not zero, the check is done on the auxiliary database
03713 ** file, not the main database file.
03714 **
03715 ** This opcode is used for testing purposes only.
03716 */
03717 case OP_IntegrityCk: {
03718   int nRoot;
03719   int *aRoot;
03720   int iSet = pOp->p1;
03721   Set *pSet;
03722   int j;
03723   HashElem *i;
03724   char *z;
03725 
03726   assert( iSet>=0 && iSet<p->nSet );
03727   pTos++;
03728   pSet = &p->aSet[iSet];
03729   nRoot = sqliteHashCount(&pSet->hash);
03730   aRoot = sqliteMallocRaw( sizeof(int)*(nRoot+1) );
03731   if( aRoot==0 ) goto no_mem;
03732   for(j=0, i=sqliteHashFirst(&pSet->hash); i; i=sqliteHashNext(i), j++){
03733     toInt((char*)sqliteHashKey(i), &aRoot[j]);
03734   }
03735   aRoot[j] = 0;
03736   sqliteHashClear(&pSet->hash);
03737   pSet->prev = 0;
03738   z = sqliteBtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot);
03739   if( z==0 || z[0]==0 ){
03740     if( z ) sqliteFree(z);
03741     pTos->z = "ok";
03742     pTos->n = 3;
03743     pTos->flags = MEM_Str | MEM_Static;
03744   }else{
03745     pTos->z = z;
03746     pTos->n = strlen(z) + 1;
03747     pTos->flags = MEM_Str | MEM_Dyn;
03748   }
03749   sqliteFree(aRoot);
03750   break;
03751 }
03752 
03753 /* Opcode: ListWrite * * *
03754 **
03755 ** Write the integer on the top of the stack
03756 ** into the temporary storage list.
03757 */
03758 case OP_ListWrite: {
03759   Keylist *pKeylist;
03760   assert( pTos>=p->aStack );
03761   pKeylist = p->pList;
03762   if( pKeylist==0 || pKeylist->nUsed>=pKeylist->nKey ){
03763     pKeylist = sqliteMallocRaw( sizeof(Keylist)+999*sizeof(pKeylist->aKey[0]) );
03764     if( pKeylist==0 ) goto no_mem;
03765     pKeylist->nKey = 1000;
03766     pKeylist->nRead = 0;
03767     pKeylist->nUsed = 0;
03768     pKeylist->pNext = p->pList;
03769     p->pList = pKeylist;
03770   }
03771   Integerify(pTos);
03772   pKeylist->aKey[pKeylist->nUsed++] = pTos->i;
03773   Release(pTos);
03774   pTos--;
03775   break;
03776 }
03777 
03778 /* Opcode: ListRewind * * *
03779 **
03780 ** Rewind the temporary buffer back to the beginning.
03781 */
03782 case OP_ListRewind: {
03783   /* What this opcode codes, really, is reverse the order of the
03784   ** linked list of Keylist structures so that they are read out
03785   ** in the same order that they were read in. */
03786   Keylist *pRev, *pTop;
03787   pRev = 0;
03788   while( p->pList ){
03789     pTop = p->pList;
03790     p->pList = pTop->pNext;
03791     pTop->pNext = pRev;
03792     pRev = pTop;
03793   }
03794   p->pList = pRev;
03795   break;
03796 }
03797 
03798 /* Opcode: ListRead * P2 *
03799 **
03800 ** Attempt to read an integer from the temporary storage buffer
03801 ** and push it onto the stack.  If the storage buffer is empty, 
03802 ** push nothing but instead jump to P2.
03803 */
03804 case OP_ListRead: {
03805   Keylist *pKeylist;
03806   CHECK_FOR_INTERRUPT;
03807   pKeylist = p->pList;
03808   if( pKeylist!=0 ){
03809     assert( pKeylist->nRead>=0 );
03810     assert( pKeylist->nRead<pKeylist->nUsed );
03811     assert( pKeylist->nRead<pKeylist->nKey );
03812     pTos++;
03813     pTos->i = pKeylist->aKey[pKeylist->nRead++];
03814     pTos->flags = MEM_Int;
03815     if( pKeylist->nRead>=pKeylist->nUsed ){
03816       p->pList = pKeylist->pNext;
03817       sqliteFree(pKeylist);
03818     }
03819   }else{
03820     pc = pOp->p2 - 1;
03821   }
03822   break;
03823 }
03824 
03825 /* Opcode: ListReset * * *
03826 **
03827 ** Reset the temporary storage buffer so that it holds nothing.
03828 */
03829 case OP_ListReset: {
03830   if( p->pList ){
03831     sqliteVdbeKeylistFree(p->pList);
03832     p->pList = 0;
03833   }
03834   break;
03835 }
03836 
03837 /* Opcode: ListPush * * * 
03838 **
03839 ** Save the current Vdbe list such that it can be restored by a ListPop
03840 ** opcode. The list is empty after this is executed.
03841 */
03842 case OP_ListPush: {
03843   p->keylistStackDepth++;
03844   assert(p->keylistStackDepth > 0);
03845   p->keylistStack = sqliteRealloc(p->keylistStack, 
03846           sizeof(Keylist *) * p->keylistStackDepth);
03847   if( p->keylistStack==0 ) goto no_mem;
03848   p->keylistStack[p->keylistStackDepth - 1] = p->pList;
03849   p->pList = 0;
03850   break;
03851 }
03852 
03853 /* Opcode: ListPop * * * 
03854 **
03855 ** Restore the Vdbe list to the state it was in when ListPush was last
03856 ** executed.
03857 */
03858 case OP_ListPop: {
03859   assert(p->keylistStackDepth > 0);
03860   p->keylistStackDepth--;
03861   sqliteVdbeKeylistFree(p->pList);
03862   p->pList = p->keylistStack[p->keylistStackDepth];
03863   p->keylistStack[p->keylistStackDepth] = 0;
03864   if( p->keylistStackDepth == 0 ){
03865     sqliteFree(p->keylistStack);
03866     p->keylistStack = 0;
03867   }
03868   break;
03869 }
03870 
03871 /* Opcode: ContextPush * * * 
03872 **
03873 ** Save the current Vdbe context such that it can be restored by a ContextPop
03874 ** opcode. The context stores the last insert row id, the last statement change
03875 ** count, and the current statement change count.
03876 */
03877 case OP_ContextPush: {
03878   p->contextStackDepth++;
03879   assert(p->contextStackDepth > 0);
03880   p->contextStack = sqliteRealloc(p->contextStack, 
03881           sizeof(Context) * p->contextStackDepth);
03882   if( p->contextStack==0 ) goto no_mem;
03883   p->contextStack[p->contextStackDepth - 1].lastRowid = p->db->lastRowid;
03884   p->contextStack[p->contextStackDepth - 1].lsChange = p->db->lsChange;
03885   p->contextStack[p->contextStackDepth - 1].csChange = p->db->csChange;
03886   break;
03887 }
03888 
03889 /* Opcode: ContextPop * * * 
03890 **
03891 ** Restore the Vdbe context to the state it was in when contextPush was last
03892 ** executed. The context stores the last insert row id, the last statement
03893 ** change count, and the current statement change count.
03894 */
03895 case OP_ContextPop: {
03896   assert(p->contextStackDepth > 0);
03897   p->contextStackDepth--;
03898   p->db->lastRowid = p->contextStack[p->contextStackDepth].lastRowid;
03899   p->db->lsChange = p->contextStack[p->contextStackDepth].lsChange;
03900   p->db->csChange = p->contextStack[p->contextStackDepth].csChange;
03901   if( p->contextStackDepth == 0 ){
03902     sqliteFree(p->contextStack);
03903     p->contextStack = 0;
03904   }
03905   break;
03906 }
03907 
03908 /* Opcode: SortPut * * *
03909 **
03910 ** The TOS is the key and the NOS is the data.  Pop both from the stack
03911 ** and put them on the sorter.  The key and data should have been
03912 ** made using SortMakeKey and SortMakeRec, respectively.
03913 */
03914 case OP_SortPut: {
03915   Mem *pNos = &pTos[-1];
03916   Sorter *pSorter;
03917   assert( pNos>=p->aStack );
03918   if( Dynamicify(pTos) || Dynamicify(pNos) ) goto no_mem;
03919   pSorter = sqliteMallocRaw( sizeof(Sorter) );
03920   if( pSorter==0 ) goto no_mem;
03921   pSorter->pNext = p->pSort;
03922   p->pSort = pSorter;
03923   assert( pTos->flags & MEM_Dyn );
03924   pSorter->nKey = pTos->n;
03925   pSorter->zKey = pTos->z;
03926   assert( pNos->flags & MEM_Dyn );
03927   pSorter->nData = pNos->n;
03928   pSorter->pData = pNos->z;
03929   pTos -= 2;
03930   break;
03931 }
03932 
03933 /* Opcode: SortMakeRec P1 * *
03934 **
03935 ** The top P1 elements are the arguments to a callback.  Form these
03936 ** elements into a single data entry that can be stored on a sorter
03937 ** using SortPut and later fed to a callback using SortCallback.
03938 */
03939 case OP_SortMakeRec: {
03940   char *z;
03941   char **azArg;
03942   int nByte;
03943   int nField;
03944   int i;
03945   Mem *pRec;
03946 
03947   nField = pOp->p1;
03948   pRec = &pTos[1-nField];
03949   assert( pRec>=p->aStack );
03950   nByte = 0;
03951   for(i=0; i<nField; i++, pRec++){
03952     if( (pRec->flags & MEM_Null)==0 ){
03953       Stringify(pRec);
03954       nByte += pRec->n;
03955     }
03956   }
03957   nByte += sizeof(char*)*(nField+1);
03958   azArg = sqliteMallocRaw( nByte );
03959   if( azArg==0 ) goto no_mem;
03960   z = (char*)&azArg[nField+1];
03961   for(pRec=&pTos[1-nField], i=0; i<nField; i++, pRec++){
03962     if( pRec->flags & MEM_Null ){
03963       azArg[i] = 0;
03964     }else{
03965       azArg[i] = z;
03966       memcpy(z, pRec->z, pRec->n);
03967       z += pRec->n;
03968     }
03969   }
03970   popStack(&pTos, nField);
03971   pTos++;
03972   pTos->n = nByte;
03973   pTos->z = (char*)azArg;
03974   pTos->flags = MEM_Str | MEM_Dyn;
03975   break;
03976 }
03977 
03978 /* Opcode: SortMakeKey * * P3
03979 **
03980 ** Convert the top few entries of the stack into a sort key.  The
03981 ** number of stack entries consumed is the number of characters in 
03982 ** the string P3.  One character from P3 is prepended to each entry.
03983 ** The first character of P3 is prepended to the element lowest in
03984 ** the stack and the last character of P3 is prepended to the top of
03985 ** the stack.  All stack entries are separated by a \000 character
03986 ** in the result.  The whole key is terminated by two \000 characters
03987 ** in a row.
03988 **
03989 ** "N" is substituted in place of the P3 character for NULL values.
03990 **
03991 ** See also the MakeKey and MakeIdxKey opcodes.
03992 */
03993 case OP_SortMakeKey: {
03994   char *zNewKey;
03995   int nByte;
03996   int nField;
03997   int i, j, k;
03998   Mem *pRec;
03999 
04000   nField = strlen(pOp->p3);
04001   pRec = &pTos[1-nField];
04002   nByte = 1;
04003   for(i=0; i<nField; i++, pRec++){
04004     if( pRec->flags & MEM_Null ){
04005       nByte += 2;
04006     }else{
04007       Stringify(pRec);
04008       nByte += pRec->n+2;
04009     }
04010   }
04011   zNewKey = sqliteMallocRaw( nByte );
04012   if( zNewKey==0 ) goto no_mem;
04013   j = 0;
04014   k = 0;
04015   for(pRec=&pTos[1-nField], i=0; i<nField; i++, pRec++){
04016     if( pRec->flags & MEM_Null ){
04017       zNewKey[j++] = 'N';
04018       zNewKey[j++] = 0;
04019       k++;
04020     }else{
04021       zNewKey[j++] = pOp->p3[k++];
04022       memcpy(&zNewKey[j], pRec->z, pRec->n-1);
04023       j += pRec->n-1;
04024       zNewKey[j++] = 0;
04025     }
04026   }
04027   zNewKey[j] = 0;
04028   assert( j<nByte );
04029   popStack(&pTos, nField);
04030   pTos++;
04031   pTos->n = nByte;
04032   pTos->flags = MEM_Str|MEM_Dyn;
04033   pTos->z = zNewKey;
04034   break;
04035 }
04036 
04037 /* Opcode: Sort * * *
04038 **
04039 ** Sort all elements on the sorter.  The algorithm is a
04040 ** mergesort.
04041 */
04042 case OP_Sort: {
04043   int i;
04044   Sorter *pElem;
04045   Sorter *apSorter[NSORT];
04046   for(i=0; i<NSORT; i++){
04047     apSorter[i] = 0;
04048   }
04049   while( p->pSort ){
04050     pElem = p->pSort;
04051     p->pSort = pElem->pNext;
04052     pElem->pNext = 0;
04053     for(i=0; i<NSORT-1; i++){
04054     if( apSorter[i]==0 ){
04055         apSorter[i] = pElem;
04056         break;
04057       }else{
04058         pElem = Merge(apSorter[i], pElem);
04059         apSorter[i] = 0;
04060       }
04061     }
04062     if( i>=NSORT-1 ){
04063       apSorter[NSORT-1] = Merge(apSorter[NSORT-1],pElem);
04064     }
04065   }
04066   pElem = 0;
04067   for(i=0; i<NSORT; i++){
04068     pElem = Merge(apSorter[i], pElem);
04069   }
04070   p->pSort = pElem;
04071   break;
04072 }
04073 
04074 /* Opcode: SortNext * P2 *
04075 **
04076 ** Push the data for the topmost element in the sorter onto the
04077 ** stack, then remove the element from the sorter.  If the sorter
04078 ** is empty, push nothing on the stack and instead jump immediately 
04079 ** to instruction P2.
04080 */
04081 case OP_SortNext: {
04082   Sorter *pSorter = p->pSort;
04083   CHECK_FOR_INTERRUPT;
04084   if( pSorter!=0 ){
04085     p->pSort = pSorter->pNext;
04086     pTos++;
04087     pTos->z = pSorter->pData;
04088     pTos->n = pSorter->nData;
04089     pTos->flags = MEM_Str|MEM_Dyn;
04090     sqliteFree(pSorter->zKey);
04091     sqliteFree(pSorter);
04092   }else{
04093     pc = pOp->p2 - 1;
04094   }
04095   break;
04096 }
04097 
04098 /* Opcode: SortCallback P1 * *
04099 **
04100 ** The top of the stack contains a callback record built using
04101 ** the SortMakeRec operation with the same P1 value as this
04102 ** instruction.  Pop this record from the stack and invoke the
04103 ** callback on it.
04104 */
04105 case OP_SortCallback: {
04106   assert( pTos>=p->aStack );
04107   assert( pTos->flags & MEM_Str );
04108   p->nCallback++;
04109   p->pc = pc+1;
04110   p->azResColumn = (char**)pTos->z;
04111   assert( p->nResColumn==pOp->p1 );
04112   p->popStack = 1;
04113   p->pTos = pTos;
04114   return SQLITE_ROW;
04115 }
04116 
04117 /* Opcode: SortReset * * *
04118 **
04119 ** Remove any elements that remain on the sorter.
04120 */
04121 case OP_SortReset: {
04122   sqliteVdbeSorterReset(p);
04123   break;
04124 }
04125 
04126 /* Opcode: FileOpen * * P3
04127 **
04128 ** Open the file named by P3 for reading using the FileRead opcode.
04129 ** If P3 is "stdin" then open standard input for reading.
04130 */
04131 case OP_FileOpen: {
04132   assert( pOp->p3!=0 );
04133   if( p->pFile ){
04134     if( p->pFile!=stdin ) fclose(p->pFile);
04135     p->pFile = 0;
04136   }
04137   if( sqliteStrICmp(pOp->p3,"stdin")==0 ){
04138     p->pFile = stdin;
04139   }else{
04140     p->pFile = fopen(pOp->p3, "r");
04141   }
04142   if( p->pFile==0 ){
04143     sqliteSetString(&p->zErrMsg,"unable to open file: ", pOp->p3, (char*)0);
04144     rc = SQLITE_ERROR;
04145   }
04146   break;
04147 }
04148 
04149 /* Opcode: FileRead P1 P2 P3
04150 **
04151 ** Read a single line of input from the open file (the file opened using
04152 ** FileOpen).  If we reach end-of-file, jump immediately to P2.  If
04153 ** we are able to get another line, split the line apart using P3 as
04154 ** a delimiter.  There should be P1 fields.  If the input line contains
04155 ** more than P1 fields, ignore the excess.  If the input line contains
04156 ** fewer than P1 fields, assume the remaining fields contain NULLs.
04157 **
04158 ** Input ends if a line consists of just "\.".  A field containing only
04159 ** "\N" is a null field.  The backslash \ character can be used be used
04160 ** to escape newlines or the delimiter.
04161 */
04162 case OP_FileRead: {
04163   int n, eol, nField, i, c, nDelim;
04164   char *zDelim, *z;
04165   CHECK_FOR_INTERRUPT;
04166   if( p->pFile==0 ) goto fileread_jump;
04167   nField = pOp->p1;
04168   if( nField<=0 ) goto fileread_jump;
04169   if( nField!=p->nField || p->azField==0 ){
04170     char **azField = sqliteRealloc(p->azField, sizeof(char*)*nField+1);
04171     if( azField==0 ){ goto no_mem; }
04172     p->azField = azField;
04173     p->nField = nField;
04174   }
04175   n = 0;
04176   eol = 0;
04177   while( eol==0 ){
04178     if( p->zLine==0 || n+200>p->nLineAlloc ){
04179       char *zLine;
04180       p->nLineAlloc = p->nLineAlloc*2 + 300;
04181       zLine = sqliteRealloc(p->zLine, p->nLineAlloc);
04182       if( zLine==0 ){
04183         p->nLineAlloc = 0;
04184         sqliteFree(p->zLine);
04185         p->zLine = 0;
04186         goto no_mem;
04187       }
04188       p->zLine = zLine;
04189     }
04190     if( vdbe_fgets(&p->zLine[n], p->nLineAlloc-n, p->pFile)==0 ){
04191       eol = 1;
04192       p->zLine[n] = 0;
04193     }else{
04194       int c;
04195       while( (c = p->zLine[n])!=0 ){
04196         if( c=='\\' ){
04197           if( p->zLine[n+1]==0 ) break;
04198           n += 2;
04199         }else if( c=='\n' ){
04200           p->zLine[n] = 0;
04201           eol = 1;
04202           break;
04203         }else{
04204           n++;
04205         }
04206       }
04207     }
04208   }
04209   if( n==0 ) goto fileread_jump;
04210   z = p->zLine;
04211   if( z[0]=='\\' && z[1]=='.' && z[2]==0 ){
04212     goto fileread_jump;
04213   }
04214   zDelim = pOp->p3;
04215   if( zDelim==0 ) zDelim = "\t";
04216   c = zDelim[0];
04217   nDelim = strlen(zDelim);
04218   p->azField[0] = z;
04219   for(i=1; *z!=0 && i<=nField; i++){
04220     int from, to;
04221     from = to = 0;
04222     if( z[0]=='\\' && z[1]=='N' 
04223        && (z[2]==0 || strncmp(&z[2],zDelim,nDelim)==0) ){
04224       if( i<=nField ) p->azField[i-1] = 0;
04225       z += 2 + nDelim;
04226       if( i<nField ) p->azField[i] = z;
04227       continue;
04228     }
04229     while( z[from] ){
04230       if( z[from]=='\\' && z[from+1]!=0 ){
04231         int tx = z[from+1];
04232         switch( tx ){
04233           case 'b':  tx = '\b'; break;
04234           case 'f':  tx = '\f'; break;
04235           case 'n':  tx = '\n'; break;
04236           case 'r':  tx = '\r'; break;
04237           case 't':  tx = '\t'; break;
04238           case 'v':  tx = '\v'; break;
04239           default:   break;
04240         }
04241         z[to++] = tx;
04242         from += 2;
04243         continue;
04244       }
04245       if( z[from]==c && strncmp(&z[from],zDelim,nDelim)==0 ) break;
04246       z[to++] = z[from++];
04247     }
04248     if( z[from] ){
04249       z[to] = 0;
04250       z += from + nDelim;
04251       if( i<nField ) p->azField[i] = z;
04252     }else{
04253       z[to] = 0;
04254       z = "";
04255     }
04256   }
04257   while( i<nField ){
04258     p->azField[i++] = 0;
04259   }
04260   break;
04261 
04262   /* If we reach end-of-file, or if anything goes wrong, jump here.
04263   ** This code will cause a jump to P2 */
04264 fileread_jump:
04265   pc = pOp->p2 - 1;
04266   break;
04267 }
04268 
04269 /* Opcode: FileColumn P1 * *
04270 **
04271 ** Push onto the stack the P1-th column of the most recently read line
04272 ** from the input file.
04273 */
04274 case OP_FileColumn: {
04275   int i = pOp->p1;
04276   char *z;
04277   assert( i>=0 && i<p->nField );
04278   if( p->azField ){
04279     z = p->azField[i];
04280   }else{
04281     z = 0;
04282   }
04283   pTos++;
04284   if( z ){
04285     pTos->n = strlen(z) + 1;
04286     pTos->z = z;
04287     pTos->flags = MEM_Str | MEM_Ephem;
04288   }else{
04289     pTos->flags = MEM_Null;
04290   }
04291   break;
04292 }
04293 
04294 /* Opcode: MemStore P1 P2 *
04295 **
04296 ** Write the top of the stack into memory location P1.
04297 ** P1 should be a small integer since space is allocated
04298 ** for all memory locations between 0 and P1 inclusive.
04299 **
04300 ** After the data is stored in the memory location, the
04301 ** stack is popped once if P2 is 1.  If P2 is zero, then
04302 ** the original data remains on the stack.
04303 */
04304 case OP_MemStore: {
04305   int i = pOp->p1;
04306   Mem *pMem;
04307   assert( pTos>=p->aStack );
04308   if( i>=p->nMem ){
04309     int nOld = p->nMem;
04310     Mem *aMem;
04311     p->nMem = i + 5;
04312     aMem = sqliteRealloc(p->aMem, p->nMem*sizeof(p->aMem[0]));
04313     if( aMem==0 ) goto no_mem;
04314     if( aMem!=p->aMem ){
04315       int j;
04316       for(j=0; j<nOld; j++){
04317         if( aMem[j].flags & MEM_Short ){
04318           aMem[j].z = aMem[j].zShort;
04319         }
04320       }
04321     }
04322     p->aMem = aMem;
04323     if( nOld<p->nMem ){
04324       memset(&p->aMem[nOld], 0, sizeof(p->aMem[0])*(p->nMem-nOld));
04325     }
04326   }
04327   Deephemeralize(pTos);
04328   pMem = &p->aMem[i];
04329   Release(pMem);
04330   *pMem = *pTos;
04331   if( pMem->flags & MEM_Dyn ){
04332     if( pOp->p2 ){
04333       pTos->flags = MEM_Null;
04334     }else{
04335       pMem->z = sqliteMallocRaw( pMem->n );
04336       if( pMem->z==0 ) goto no_mem;
04337       memcpy(pMem->z, pTos->z, pMem->n);
04338     }
04339   }else if( pMem->flags & MEM_Short ){
04340     pMem->z = pMem->zShort;
04341   }
04342   if( pOp->p2 ){
04343     Release(pTos);
04344     pTos--;
04345   }
04346   break;
04347 }
04348 
04349 /* Opcode: MemLoad P1 * *
04350 **
04351 ** Push a copy of the value in memory location P1 onto the stack.
04352 **
04353 ** If the value is a string, then the value pushed is a pointer to
04354 ** the string that is stored in the memory location.  If the memory
04355 ** location is subsequently changed (using OP_MemStore) then the
04356 ** value pushed onto the stack will change too.
04357 */
04358 case OP_MemLoad: {
04359   int i = pOp->p1;
04360   assert( i>=0 && i<p->nMem );
04361   pTos++;
04362   memcpy(pTos, &p->aMem[i], sizeof(pTos[0])-NBFS);;
04363   if( pTos->flags & MEM_Str ){
04364     pTos->flags |= MEM_Ephem;
04365     pTos->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short);
04366   }
04367   break;
04368 }
04369 
04370 /* Opcode: MemIncr P1 P2 *
04371 **
04372 ** Increment the integer valued memory cell P1 by 1.  If P2 is not zero
04373 ** and the result after the increment is greater than zero, then jump
04374 ** to P2.
04375 **
04376 ** This instruction throws an error if the memory cell is not initially
04377 ** an integer.
04378 */
04379 case OP_MemIncr: {
04380   int i = pOp->p1;
04381   Mem *pMem;
04382   assert( i>=0 && i<p->nMem );
04383   pMem = &p->aMem[i];
04384   assert( pMem->flags==MEM_Int );
04385   pMem->i++;
04386   if( pOp->p2>0 && pMem->i>0 ){
04387      pc = pOp->p2 - 1;
04388   }
04389   break;
04390 }
04391 
04392 /* Opcode: AggReset * P2 *
04393 **
04394 ** Reset the aggregator so that it no longer contains any data.
04395 ** Future aggregator elements will contain P2 values each.
04396 */
04397 case OP_AggReset: {
04398   sqliteVdbeAggReset(&p->agg);
04399   p->agg.nMem = pOp->p2;
04400   p->agg.apFunc = sqliteMalloc( p->agg.nMem*sizeof(p->agg.apFunc[0]) );
04401   if( p->agg.apFunc==0 ) goto no_mem;
04402   break;
04403 }
04404 
04405 /* Opcode: AggInit * P2 P3
04406 **
04407 ** Initialize the function parameters for an aggregate function.
04408 ** The aggregate will operate out of aggregate column P2.
04409 ** P3 is a pointer to the FuncDef structure for the function.
04410 */
04411 case OP_AggInit: {
04412   int i = pOp->p2;
04413   assert( i>=0 && i<p->agg.nMem );
04414   p->agg.apFunc[i] = (FuncDef*)pOp->p3;
04415   break;
04416 }
04417 
04418 /* Opcode: AggFunc * P2 P3
04419 **
04420 ** Execute the step function for an aggregate.  The
04421 ** function has P2 arguments.  P3 is a pointer to the FuncDef
04422 ** structure that specifies the function.
04423 **
04424 ** The top of the stack must be an integer which is the index of
04425 ** the aggregate column that corresponds to this aggregate function.
04426 ** Ideally, this index would be another parameter, but there are
04427 ** no free parameters left.  The integer is popped from the stack.
04428 */
04429 case OP_AggFunc: {
04430   int n = pOp->p2;
04431   int i;
04432   Mem *pMem, *pRec;
04433   char **azArgv = p->zArgv;
04434   sqlite_func ctx;
04435 
04436   assert( n>=0 );
04437   assert( pTos->flags==MEM_Int );
04438   pRec = &pTos[-n];
04439   assert( pRec>=p->aStack );
04440   for(i=0; i<n; i++, pRec++){
04441     if( pRec->flags & MEM_Null ){
04442       azArgv[i] = 0;
04443     }else{
04444       Stringify(pRec);
04445       azArgv[i] = pRec->z;
04446     }
04447   }
04448   i = pTos->i;
04449   assert( i>=0 && i<p->agg.nMem );
04450   ctx.pFunc = (FuncDef*)pOp->p3;
04451   pMem = &p->agg.pCurrent->aMem[i];
04452   ctx.s.z = pMem->zShort;  /* Space used for small aggregate contexts */
04453   ctx.pAgg = pMem->z;
04454   ctx.cnt = ++pMem->i;
04455   ctx.isError = 0;
04456   ctx.isStep = 1;
04457   (ctx.pFunc->xStep)(&ctx, n, (const char**)azArgv);
04458   pMem->z = ctx.pAgg;
04459   pMem->flags = MEM_AggCtx;
04460   popStack(&pTos, n+1);
04461   if( ctx.isError ){
04462     rc = SQLITE_ERROR;
04463   }
04464   break;
04465 }
04466 
04467 /* Opcode: AggFocus * P2 *
04468 **
04469 ** Pop the top of the stack and use that as an aggregator key.  If
04470 ** an aggregator with that same key already exists, then make the
04471 ** aggregator the current aggregator and jump to P2.  If no aggregator
04472 ** with the given key exists, create one and make it current but
04473 ** do not jump.
04474 **
04475 ** The order of aggregator opcodes is important.  The order is:
04476 ** AggReset AggFocus AggNext.  In other words, you must execute
04477 ** AggReset first, then zero or more AggFocus operations, then
04478 ** zero or more AggNext operations.  You must not execute an AggFocus
04479 ** in between an AggNext and an AggReset.
04480 */
04481 case OP_AggFocus: {
04482   AggElem *pElem;
04483   char *zKey;
04484   int nKey;
04485 
04486   assert( pTos>=p->aStack );
04487   Stringify(pTos);
04488   zKey = pTos->z;
04489   nKey = pTos->n;
04490   pElem = sqliteHashFind(&p->agg.hash, zKey, nKey);
04491   if( pElem ){
04492     p->agg.pCurrent = pElem;
04493     pc = pOp->p2 - 1;
04494   }else{
04495     AggInsert(&p->agg, zKey, nKey);
04496     if( sqlite_malloc_failed ) goto no_mem;
04497   }
04498   Release(pTos);
04499   pTos--;
04500   break; 
04501 }
04502 
04503 /* Opcode: AggSet * P2 *
04504 **
04505 ** Move the top of the stack into the P2-th field of the current
04506 ** aggregate.  String values are duplicated into new memory.
04507 */
04508 case OP_AggSet: {
04509   AggElem *pFocus = AggInFocus(p->agg);
04510   Mem *pMem;
04511   int i = pOp->p2;
04512   assert( pTos>=p->aStack );
04513   if( pFocus==0 ) goto no_mem;
04514   assert( i>=0 && i<p->agg.nMem );
04515   Deephemeralize(pTos);
04516   pMem = &pFocus->aMem[i];
04517   Release(pMem);
04518   *pMem = *pTos;
04519   if( pMem->flags & MEM_Dyn ){
04520     pTos->flags = MEM_Null;
04521   }else if( pMem->flags & MEM_Short ){
04522     pMem->z = pMem->zShort;
04523   }
04524   Release(pTos);
04525   pTos--;
04526   break;
04527 }
04528 
04529 /* Opcode: AggGet * P2 *
04530 **
04531 ** Push a new entry onto the stack which is a copy of the P2-th field
04532 ** of the current aggregate.  Strings are not duplicated so
04533 ** string values will be ephemeral.
04534 */
04535 case OP_AggGet: {
04536   AggElem *pFocus = AggInFocus(p->agg);
04537   Mem *pMem;
04538   int i = pOp->p2;
04539   if( pFocus==0 ) goto no_mem;
04540   assert( i>=0 && i<p->agg.nMem );
04541   pTos++;
04542   pMem = &pFocus->aMem[i];
04543   *pTos = *pMem;
04544   if( pTos->flags & MEM_Str ){
04545     pTos->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short);
04546     pTos->flags |= MEM_Ephem;
04547   }
04548   if( pTos->flags & MEM_AggCtx ){
04549     Release(pTos);
04550     pTos->flags = MEM_Null;
04551   }
04552   break;
04553 }
04554 
04555 /* Opcode: AggNext * P2 *
04556 **
04557 ** Make the next aggregate value the current aggregate.  The prior
04558 ** aggregate is deleted.  If all aggregate values have been consumed,
04559 ** jump to P2.
04560 **
04561 ** The order of aggregator opcodes is important.  The order is:
04562 ** AggReset AggFocus AggNext.  In other words, you must execute
04563 ** AggReset first, then zero or more AggFocus operations, then
04564 ** zero or more AggNext operations.  You must not execute an AggFocus
04565 ** in between an AggNext and an AggReset.
04566 */
04567 case OP_AggNext: {
04568   CHECK_FOR_INTERRUPT;
04569   if( p->agg.pSearch==0 ){
04570     p->agg.pSearch = sqliteHashFirst(&p->agg.hash);
04571   }else{
04572     p->agg.pSearch = sqliteHashNext(p->agg.pSearch);
04573   }
04574   if( p->agg.pSearch==0 ){
04575     pc = pOp->p2 - 1;
04576   } else {
04577     int i;
04578     sqlite_func ctx;
04579     Mem *aMem;
04580     p->agg.pCurrent = sqliteHashData(p->agg.pSearch);
04581     aMem = p->agg.pCurrent->aMem;
04582     for(i=0; i<p->agg.nMem; i++){
04583       int freeCtx;
04584       if( p->agg.apFunc[i]==0 ) continue;
04585       if( p->agg.apFunc[i]->xFinalize==0 ) continue;
04586       ctx.s.flags = MEM_Null;
04587       ctx.s.z = aMem[i].zShort;
04588       ctx.pAgg = (void*)aMem[i].z;
04589       freeCtx = aMem[i].z && aMem[i].z!=aMem[i].zShort;
04590       ctx.cnt = aMem[i].i;
04591       ctx.isStep = 0;
04592       ctx.pFunc = p->agg.apFunc[i];
04593       (*p->agg.apFunc[i]->xFinalize)(&ctx);
04594       if( freeCtx ){
04595         sqliteFree( aMem[i].z );
04596       }
04597       aMem[i] = ctx.s;
04598       if( aMem[i].flags & MEM_Short ){
04599         aMem[i].z = aMem[i].zShort;
04600       }
04601     }
04602   }
04603   break;
04604 }
04605 
04606 /* Opcode: SetInsert P1 * P3
04607 **
04608 ** If Set P1 does not exist then create it.  Then insert value
04609 ** P3 into that set.  If P3 is NULL, then insert the top of the
04610 ** stack into the set.
04611 */
04612 case OP_SetInsert: {
04613   int i = pOp->p1;
04614   if( p->nSet<=i ){
04615     int k;
04616     Set *aSet = sqliteRealloc(p->aSet, (i+1)*sizeof(p->aSet[0]) );
04617     if( aSet==0 ) goto no_mem;
04618     p->aSet = aSet;
04619     for(k=p->nSet; k<=i; k++){
04620       sqliteHashInit(&p->aSet[k].hash, SQLITE_HASH_BINARY, 1);
04621     }
04622     p->nSet = i+1;
04623   }
04624   if( pOp->p3 ){
04625     sqliteHashInsert(&p->aSet[i].hash, pOp->p3, strlen(pOp->p3)+1, p);
04626   }else{
04627     assert( pTos>=p->aStack );
04628     Stringify(pTos);
04629     sqliteHashInsert(&p->aSet[i].hash, pTos->z, pTos->n, p);
04630     Release(pTos);
04631     pTos--;
04632   }
04633   if( sqlite_malloc_failed ) goto no_mem;
04634   break;
04635 }
04636 
04637 /* Opcode: SetFound P1 P2 *
04638 **
04639 ** Pop the stack once and compare the value popped off with the
04640 ** contents of set P1.  If the element popped exists in set P1,
04641 ** then jump to P2.  Otherwise fall through.
04642 */
04643 case OP_SetFound: {
04644   int i = pOp->p1;
04645   assert( pTos>=p->aStack );
04646   Stringify(pTos);
04647   if( i>=0 && i<p->nSet && sqliteHashFind(&p->aSet[i].hash, pTos->z, pTos->n)){
04648     pc = pOp->p2 - 1;
04649   }
04650   Release(pTos);
04651   pTos--;
04652   break;
04653 }
04654 
04655 /* Opcode: SetNotFound P1 P2 *
04656 **
04657 ** Pop the stack once and compare the value popped off with the
04658 ** contents of set P1.  If the element popped does not exists in 
04659 ** set P1, then jump to P2.  Otherwise fall through.
04660 */
04661 case OP_SetNotFound: {
04662   int i = pOp->p1;
04663   assert( pTos>=p->aStack );
04664   Stringify(pTos);
04665   if( i<0 || i>=p->nSet ||
04666        sqliteHashFind(&p->aSet[i].hash, pTos->z, pTos->n)==0 ){
04667     pc = pOp->p2 - 1;
04668   }
04669   Release(pTos);
04670   pTos--;
04671   break;
04672 }
04673 
04674 /* Opcode: SetFirst P1 P2 *
04675 **
04676 ** Read the first element from set P1 and push it onto the stack.  If the
04677 ** set is empty, push nothing and jump immediately to P2.  This opcode is
04678 ** used in combination with OP_SetNext to loop over all elements of a set.
04679 */
04680 /* Opcode: SetNext P1 P2 *
04681 **
04682 ** Read the next element from set P1 and push it onto the stack.  If there
04683 ** are no more elements in the set, do not do the push and fall through.
04684 ** Otherwise, jump to P2 after pushing the next set element.
04685 */
04686 case OP_SetFirst: 
04687 case OP_SetNext: {
04688   Set *pSet;
04689   CHECK_FOR_INTERRUPT;
04690   if( pOp->p1<0 || pOp->p1>=p->nSet ){
04691     if( pOp->opcode==OP_SetFirst ) pc = pOp->p2 - 1;
04692     break;
04693   }
04694   pSet = &p->aSet[pOp->p1];
04695   if( pOp->opcode==OP_SetFirst ){
04696     pSet->prev = sqliteHashFirst(&pSet->hash);
04697     if( pSet->prev==0 ){
04698       pc = pOp->p2 - 1;
04699       break;
04700     }
04701   }else{
04702     if( pSet->prev ){
04703       pSet->prev = sqliteHashNext(pSet->prev);
04704     }
04705     if( pSet->prev==0 ){
04706       break;
04707     }else{
04708       pc = pOp->p2 - 1;
04709     }
04710   }
04711   pTos++;
04712   pTos->z = sqliteHashKey(pSet->prev);
04713   pTos->n = sqliteHashKeysize(pSet->prev);
04714   pTos->flags = MEM_Str | MEM_Ephem;
04715   break;
04716 }
04717 
04718 /* Opcode: Vacuum * * *
04719 **
04720 ** Vacuum the entire database.  This opcode will cause other virtual
04721 ** machines to be created and run.  It may not be called from within
04722 ** a transaction.
04723 */
04724 case OP_Vacuum: {
04725   if( sqliteSafetyOff(db) ) goto abort_due_to_misuse; 
04726   rc = sqliteRunVacuum(&p->zErrMsg, db);
04727   if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
04728   break;
04729 }
04730 
04731 /* Opcode: StackDepth * * *
04732 **
04733 ** Push an integer onto the stack which is the depth of the stack prior
04734 ** to that integer being pushed.
04735 */
04736 case OP_StackDepth: {
04737   int depth = (&pTos[1]) - p->aStack;
04738   pTos++;
04739   pTos->i = depth;
04740   pTos->flags = MEM_Int;
04741   break;
04742 }
04743 
04744 /* Opcode: StackReset * * *
04745 **
04746 ** Pop a single integer off of the stack.  Then pop the stack
04747 ** as many times as necessary to get the depth of the stack down
04748 ** to the value of the integer that was popped.
04749 */
04750 case OP_StackReset: {
04751   int depth, goal;
04752   assert( pTos>=p->aStack );
04753   Integerify(pTos);
04754   goal = pTos->i;
04755   depth = (&pTos[1]) - p->aStack;
04756   assert( goal<depth );
04757   popStack(&pTos, depth-goal);
04758   break;
04759 }
04760 
04761 /* An other opcode is illegal...
04762 */
04763 default: {
04764   sqlite_snprintf(sizeof(zBuf),zBuf,"%d",pOp->opcode);
04765   sqliteSetString(&p->zErrMsg, "unknown opcode ", zBuf, (char*)0);
04766   rc = SQLITE_INTERNAL;
04767   break;
04768 }
04769 
04770 /*****************************************************************************
04771 ** The cases of the switch statement above this line should all be indented
04772 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
04773 ** readability.  From this point on down, the normal indentation rules are
04774 ** restored.
04775 *****************************************************************************/
04776     }
04777 
04778 #ifdef VDBE_PROFILE
04779     {
04780       long long elapse = hwtime() - start;
04781       pOp->cycles += elapse;
04782       pOp->cnt++;
04783 #if 0
04784         fprintf(stdout, "%10lld ", elapse);
04785         sqliteVdbePrintOp(stdout, origPc, &p->aOp[origPc]);
04786 #endif
04787     }
04788 #endif
04789 
04790     /* The following code adds nothing to the actual functionality
04791     ** of the program.  It is only here for testing and debugging.
04792     ** On the other hand, it does burn CPU cycles every time through
04793     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
04794     */
04795 #ifndef NDEBUG
04796     /* Sanity checking on the top element of the stack */
04797     if( pTos>=p->aStack ){
04798       assert( pTos->flags!=0 );  /* Must define some type */
04799       if( pTos->flags & MEM_Str ){
04800         int x = pTos->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
04801         assert( x!=0 );            /* Strings must define a string subtype */
04802         assert( (x & (x-1))==0 );  /* Only one string subtype can be defined */
04803         assert( pTos->z!=0 );      /* Strings must have a value */
04804         /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
04805         assert( (pTos->flags & MEM_Short)==0 || pTos->z==pTos->zShort );
04806         assert( (pTos->flags & MEM_Short)!=0 || pTos->z!=pTos->zShort );
04807       }else{
04808         /* Cannot define a string subtype for non-string objects */
04809         assert( (pTos->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
04810       }
04811       /* MEM_Null excludes all other types */
04812       assert( pTos->flags==MEM_Null || (pTos->flags&MEM_Null)==0 );
04813     }
04814     if( pc<-1 || pc>=p->nOp ){
04815       sqliteSetString(&p->zErrMsg, "jump destination out of range", (char*)0);
04816       rc = SQLITE_INTERNAL;
04817     }
04818     if( p->trace && pTos>=p->aStack ){
04819       int i;
04820       fprintf(p->trace, "Stack:");
04821       for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
04822         if( pTos[i].flags & MEM_Null ){
04823           fprintf(p->trace, " NULL");
04824         }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
04825           fprintf(p->trace, " si:%d", pTos[i].i);
04826         }else if( pTos[i].flags & MEM_Int ){
04827           fprintf(p->trace, " i:%d", pTos[i].i);
04828         }else if( pTos[i].flags & MEM_Real ){
04829           fprintf(p->trace, " r:%g", pTos[i].r);
04830         }else if( pTos[i].flags & MEM_Str ){
04831           int j, k;
04832           char zBuf[100];
04833           zBuf[0] = ' ';
04834           if( pTos[i].flags & MEM_Dyn ){
04835             zBuf[1] = 'z';
04836             assert( (pTos[i].flags & (MEM_Static|MEM_Ephem))==0 );
04837           }else if( pTos[i].flags & MEM_Static ){
04838             zBuf[1] = 't';
04839             assert( (pTos[i].flags & (MEM_Dyn|MEM_Ephem))==0 );
04840           }else if( pTos[i].flags & MEM_Ephem ){
04841             zBuf[1] = 'e';
04842             assert( (pTos[i].flags & (MEM_Static|MEM_Dyn))==0 );
04843           }else{
04844             zBuf[1] = 's';
04845           }
04846           zBuf[2] = '[';
04847           k = 3;
04848           for(j=0; j<20 && j<pTos[i].n; j++){
04849             int c = pTos[i].z[j];
04850             if( c==0 && j==pTos[i].n-1 ) break;
04851             if( isprint(c) && !isspace(c) ){
04852               zBuf[k++] = c;
04853             }else{
04854               zBuf[k++] = '.';
04855             }
04856           }
04857           zBuf[k++] = ']';
04858           zBuf[k++] = 0;
04859           fprintf(p->trace, "%s", zBuf);
04860         }else{
04861           fprintf(p->trace, " ???");
04862         }
04863       }
04864       if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
04865       fprintf(p->trace,"\n");
04866     }
04867 #endif
04868   }  /* The end of the for(;;) loop the loops through opcodes */
04869 
04870   /* If we reach this point, it means that execution is finished.
04871   */
04872 vdbe_halt:
04873   CHECK_FOR_INTERRUPT
04874   if( rc ){
04875     p->rc = rc;
04876     rc = SQLITE_ERROR;
04877   }else{
04878     rc = SQLITE_DONE;
04879   }
04880   p->magic = VDBE_MAGIC_HALT;
04881   p->pTos = pTos;
04882   return rc;
04883 
04884   /* Jump to here if a malloc() fails.  It's hard to get a malloc()
04885   ** to fail on a modern VM computer, so this code is untested.
04886   */
04887 no_mem:
04888   sqliteSetString(&p->zErrMsg, "out of memory", (char*)0);
04889   rc = SQLITE_NOMEM;
04890   goto vdbe_halt;
04891 
04892   /* Jump to here for an SQLITE_MISUSE error.
04893   */
04894 abort_due_to_misuse:
04895   rc = SQLITE_MISUSE;
04896   /* Fall thru into abort_due_to_error */
04897 
04898   /* Jump to here for any other kind of fatal error.  The "rc" variable
04899   ** should hold the error number.
04900   */
04901 abort_due_to_error:
04902   if( p->zErrMsg==0 ){
04903     if( sqlite_malloc_failed ) rc = SQLITE_NOMEM;
04904     sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), (char*)0);
04905   }
04906   goto vdbe_halt;
04907 
04908   /* Jump to here if the sqlite_interrupt() API sets the interrupt
04909   ** flag.
04910   */
04911 abort_due_to_interrupt:
04912   assert( db->flags & SQLITE_Interrupt );
04913   db->flags &= ~SQLITE_Interrupt;
04914   if( db->magic!=SQLITE_MAGIC_BUSY ){
04915     rc = SQLITE_MISUSE;
04916   }else{
04917     rc = SQLITE_INTERRUPT;
04918   }
04919   sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), (char*)0);
04920   goto vdbe_halt;
04921 }