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