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