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