xref: /sqlite-3.40.0/src/vdbe.c (revision e8f2c9dc)
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 the function that runs the
13 ** bytecode of a prepared statement.
14 **
15 ** Various scripts scan this source file in order to generate HTML
16 ** documentation, headers files, or other derived files.  The formatting
17 ** of the code in this file is, therefore, important.  See other comments
18 ** in this file for details.  If in doubt, do not deviate from existing
19 ** commenting and indentation practices when changing or adding code.
20 */
21 #include "sqliteInt.h"
22 #include "vdbeInt.h"
23 
24 /*
25 ** Invoke this macro on memory cells just prior to changing the
26 ** value of the cell.  This macro verifies that shallow copies are
27 ** not misused.  A shallow copy of a string or blob just copies a
28 ** pointer to the string or blob, not the content.  If the original
29 ** is changed while the copy is still in use, the string or blob might
30 ** be changed out from under the copy.  This macro verifies that nothing
31 ** like that ever happens.
32 */
33 #ifdef SQLITE_DEBUG
34 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
35 #else
36 # define memAboutToChange(P,M)
37 #endif
38 
39 /*
40 ** The following global variable is incremented every time a cursor
41 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
42 ** procedures use this information to make sure that indices are
43 ** working correctly.  This variable has no function other than to
44 ** help verify the correct operation of the library.
45 */
46 #ifdef SQLITE_TEST
47 int sqlite3_search_count = 0;
48 #endif
49 
50 /*
51 ** When this global variable is positive, it gets decremented once before
52 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
53 ** field of the sqlite3 structure is set in order to simulate an interrupt.
54 **
55 ** This facility is used for testing purposes only.  It does not function
56 ** in an ordinary build.
57 */
58 #ifdef SQLITE_TEST
59 int sqlite3_interrupt_count = 0;
60 #endif
61 
62 /*
63 ** The next global variable is incremented each type the OP_Sort opcode
64 ** is executed.  The test procedures use this information to make sure that
65 ** sorting is occurring or not occurring at appropriate times.   This variable
66 ** has no function other than to help verify the correct operation of the
67 ** library.
68 */
69 #ifdef SQLITE_TEST
70 int sqlite3_sort_count = 0;
71 #endif
72 
73 /*
74 ** The next global variable records the size of the largest MEM_Blob
75 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
76 ** use this information to make sure that the zero-blob functionality
77 ** is working correctly.   This variable has no function other than to
78 ** help verify the correct operation of the library.
79 */
80 #ifdef SQLITE_TEST
81 int sqlite3_max_blobsize = 0;
82 static void updateMaxBlobsize(Mem *p){
83   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
84     sqlite3_max_blobsize = p->n;
85   }
86 }
87 #endif
88 
89 /*
90 ** The next global variable is incremented each time the OP_Found opcode
91 ** is executed. This is used to test whether or not the foreign key
92 ** operation implemented using OP_FkIsZero is working. This variable
93 ** has no function other than to help verify the correct operation of the
94 ** library.
95 */
96 #ifdef SQLITE_TEST
97 int sqlite3_found_count = 0;
98 #endif
99 
100 /*
101 ** Test a register to see if it exceeds the current maximum blob size.
102 ** If it does, record the new maximum blob size.
103 */
104 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
105 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
106 #else
107 # define UPDATE_MAX_BLOBSIZE(P)
108 #endif
109 
110 /*
111 ** Invoke the VDBE coverage callback, if that callback is defined.  This
112 ** feature is used for test suite validation only and does not appear an
113 ** production builds.
114 **
115 ** M is an integer, 2 or 3, that indices how many different ways the
116 ** branch can go.  It is usually 2.  "I" is the direction the branch
117 ** goes.  0 means falls through.  1 means branch is taken.  2 means the
118 ** second alternative branch is taken.
119 **
120 ** iSrcLine is the source code line (from the __LINE__ macro) that
121 ** generated the VDBE instruction.  This instrumentation assumes that all
122 ** source code is in a single file (the amalgamation).  Special values 1
123 ** and 2 for the iSrcLine parameter mean that this particular branch is
124 ** always taken or never taken, respectively.
125 */
126 #if !defined(SQLITE_VDBE_COVERAGE)
127 # define VdbeBranchTaken(I,M)
128 #else
129 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
130   static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
131     if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
132       M = iSrcLine;
133       /* Assert the truth of VdbeCoverageAlwaysTaken() and
134       ** VdbeCoverageNeverTaken() */
135       assert( (M & I)==I );
136     }else{
137       if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
138       sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
139                                       iSrcLine,I,M);
140     }
141   }
142 #endif
143 
144 /*
145 ** Convert the given register into a string if it isn't one
146 ** already. Return non-zero if a malloc() fails.
147 */
148 #define Stringify(P, enc) \
149    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
150      { goto no_mem; }
151 
152 /*
153 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
154 ** a pointer to a dynamically allocated string where some other entity
155 ** is responsible for deallocating that string.  Because the register
156 ** does not control the string, it might be deleted without the register
157 ** knowing it.
158 **
159 ** This routine converts an ephemeral string into a dynamically allocated
160 ** string that the register itself controls.  In other words, it
161 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
162 */
163 #define Deephemeralize(P) \
164    if( ((P)->flags&MEM_Ephem)!=0 \
165        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
166 
167 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
168 #define isSorter(x) ((x)->pSorter!=0)
169 
170 /*
171 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
172 ** if we run out of memory.
173 */
174 static VdbeCursor *allocateCursor(
175   Vdbe *p,              /* The virtual machine */
176   int iCur,             /* Index of the new VdbeCursor */
177   int nField,           /* Number of fields in the table or index */
178   int iDb,              /* Database the cursor belongs to, or -1 */
179   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
180 ){
181   /* Find the memory cell that will be used to store the blob of memory
182   ** required for this VdbeCursor structure. It is convenient to use a
183   ** vdbe memory cell to manage the memory allocation required for a
184   ** VdbeCursor structure for the following reasons:
185   **
186   **   * Sometimes cursor numbers are used for a couple of different
187   **     purposes in a vdbe program. The different uses might require
188   **     different sized allocations. Memory cells provide growable
189   **     allocations.
190   **
191   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
192   **     be freed lazily via the sqlite3_release_memory() API. This
193   **     minimizes the number of malloc calls made by the system.
194   **
195   ** Memory cells for cursors are allocated at the top of the address
196   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
197   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
198   */
199   Mem *pMem = &p->aMem[p->nMem-iCur];
200 
201   int nByte;
202   VdbeCursor *pCx = 0;
203   nByte =
204       ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
205       (isBtreeCursor?sqlite3BtreeCursorSize():0);
206 
207   assert( iCur<p->nCursor );
208   if( p->apCsr[iCur] ){
209     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
210     p->apCsr[iCur] = 0;
211   }
212   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
213     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
214     memset(pCx, 0, sizeof(VdbeCursor));
215     pCx->iDb = iDb;
216     pCx->nField = nField;
217     if( isBtreeCursor ){
218       pCx->pCursor = (BtCursor*)
219           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
220       sqlite3BtreeCursorZero(pCx->pCursor);
221     }
222   }
223   return pCx;
224 }
225 
226 /*
227 ** Try to convert a value into a numeric representation if we can
228 ** do so without loss of information.  In other words, if the string
229 ** looks like a number, convert it into a number.  If it does not
230 ** look like a number, leave it alone.
231 */
232 static void applyNumericAffinity(Mem *pRec){
233   double rValue;
234   i64 iValue;
235   u8 enc = pRec->enc;
236   if( (pRec->flags&MEM_Str)==0 ) return;
237   if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
238   if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
239     pRec->u.i = iValue;
240     pRec->flags |= MEM_Int;
241   }else{
242     pRec->r = rValue;
243     pRec->flags |= MEM_Real;
244   }
245 }
246 #define ApplyNumericAffinity(X)  \
247    if(((X)->flags&(MEM_Real|MEM_Int))==0){applyNumericAffinity(X);}
248 
249 /*
250 ** Processing is determine by the affinity parameter:
251 **
252 ** SQLITE_AFF_INTEGER:
253 ** SQLITE_AFF_REAL:
254 ** SQLITE_AFF_NUMERIC:
255 **    Try to convert pRec to an integer representation or a
256 **    floating-point representation if an integer representation
257 **    is not possible.  Note that the integer representation is
258 **    always preferred, even if the affinity is REAL, because
259 **    an integer representation is more space efficient on disk.
260 **
261 ** SQLITE_AFF_TEXT:
262 **    Convert pRec to a text representation.
263 **
264 ** SQLITE_AFF_NONE:
265 **    No-op.  pRec is unchanged.
266 */
267 static void applyAffinity(
268   Mem *pRec,          /* The value to apply affinity to */
269   char affinity,      /* The affinity to be applied */
270   u8 enc              /* Use this text encoding */
271 ){
272   if( affinity==SQLITE_AFF_TEXT ){
273     /* Only attempt the conversion to TEXT if there is an integer or real
274     ** representation (blob and NULL do not get converted) but no string
275     ** representation.
276     */
277     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
278       sqlite3VdbeMemStringify(pRec, enc);
279     }
280     pRec->flags &= ~(MEM_Real|MEM_Int);
281   }else if( affinity!=SQLITE_AFF_NONE ){
282     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
283              || affinity==SQLITE_AFF_NUMERIC );
284     ApplyNumericAffinity(pRec);
285     if( pRec->flags & MEM_Real ){
286       sqlite3VdbeIntegerAffinity(pRec);
287     }
288   }
289 }
290 
291 /*
292 ** Try to convert the type of a function argument or a result column
293 ** into a numeric representation.  Use either INTEGER or REAL whichever
294 ** is appropriate.  But only do the conversion if it is possible without
295 ** loss of information and return the revised type of the argument.
296 */
297 int sqlite3_value_numeric_type(sqlite3_value *pVal){
298   int eType = sqlite3_value_type(pVal);
299   if( eType==SQLITE_TEXT ){
300     Mem *pMem = (Mem*)pVal;
301     applyNumericAffinity(pMem);
302     eType = sqlite3_value_type(pVal);
303   }
304   return eType;
305 }
306 
307 /*
308 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
309 ** not the internal Mem* type.
310 */
311 void sqlite3ValueApplyAffinity(
312   sqlite3_value *pVal,
313   u8 affinity,
314   u8 enc
315 ){
316   applyAffinity((Mem *)pVal, affinity, enc);
317 }
318 
319 /*
320 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
321 ** none.
322 **
323 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
324 ** But it does set pMem->r and pMem->u.i appropriately.
325 */
326 static u16 numericType(Mem *pMem){
327   if( pMem->flags & (MEM_Int|MEM_Real) ){
328     return pMem->flags & (MEM_Int|MEM_Real);
329   }
330   if( pMem->flags & (MEM_Str|MEM_Blob) ){
331     if( sqlite3AtoF(pMem->z, &pMem->r, pMem->n, pMem->enc)==0 ){
332       return 0;
333     }
334     if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
335       return MEM_Int;
336     }
337     return MEM_Real;
338   }
339   return 0;
340 }
341 
342 #ifdef SQLITE_DEBUG
343 /*
344 ** Write a nice string representation of the contents of cell pMem
345 ** into buffer zBuf, length nBuf.
346 */
347 void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
348   char *zCsr = zBuf;
349   int f = pMem->flags;
350 
351   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
352 
353   if( f&MEM_Blob ){
354     int i;
355     char c;
356     if( f & MEM_Dyn ){
357       c = 'z';
358       assert( (f & (MEM_Static|MEM_Ephem))==0 );
359     }else if( f & MEM_Static ){
360       c = 't';
361       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
362     }else if( f & MEM_Ephem ){
363       c = 'e';
364       assert( (f & (MEM_Static|MEM_Dyn))==0 );
365     }else{
366       c = 's';
367     }
368 
369     sqlite3_snprintf(100, zCsr, "%c", c);
370     zCsr += sqlite3Strlen30(zCsr);
371     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
372     zCsr += sqlite3Strlen30(zCsr);
373     for(i=0; i<16 && i<pMem->n; i++){
374       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
375       zCsr += sqlite3Strlen30(zCsr);
376     }
377     for(i=0; i<16 && i<pMem->n; i++){
378       char z = pMem->z[i];
379       if( z<32 || z>126 ) *zCsr++ = '.';
380       else *zCsr++ = z;
381     }
382 
383     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
384     zCsr += sqlite3Strlen30(zCsr);
385     if( f & MEM_Zero ){
386       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
387       zCsr += sqlite3Strlen30(zCsr);
388     }
389     *zCsr = '\0';
390   }else if( f & MEM_Str ){
391     int j, k;
392     zBuf[0] = ' ';
393     if( f & MEM_Dyn ){
394       zBuf[1] = 'z';
395       assert( (f & (MEM_Static|MEM_Ephem))==0 );
396     }else if( f & MEM_Static ){
397       zBuf[1] = 't';
398       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
399     }else if( f & MEM_Ephem ){
400       zBuf[1] = 'e';
401       assert( (f & (MEM_Static|MEM_Dyn))==0 );
402     }else{
403       zBuf[1] = 's';
404     }
405     k = 2;
406     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
407     k += sqlite3Strlen30(&zBuf[k]);
408     zBuf[k++] = '[';
409     for(j=0; j<15 && j<pMem->n; j++){
410       u8 c = pMem->z[j];
411       if( c>=0x20 && c<0x7f ){
412         zBuf[k++] = c;
413       }else{
414         zBuf[k++] = '.';
415       }
416     }
417     zBuf[k++] = ']';
418     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
419     k += sqlite3Strlen30(&zBuf[k]);
420     zBuf[k++] = 0;
421   }
422 }
423 #endif
424 
425 #ifdef SQLITE_DEBUG
426 /*
427 ** Print the value of a register for tracing purposes:
428 */
429 static void memTracePrint(Mem *p){
430   if( p->flags & MEM_Undefined ){
431     printf(" undefined");
432   }else if( p->flags & MEM_Null ){
433     printf(" NULL");
434   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
435     printf(" si:%lld", p->u.i);
436   }else if( p->flags & MEM_Int ){
437     printf(" i:%lld", p->u.i);
438 #ifndef SQLITE_OMIT_FLOATING_POINT
439   }else if( p->flags & MEM_Real ){
440     printf(" r:%g", p->r);
441 #endif
442   }else if( p->flags & MEM_RowSet ){
443     printf(" (rowset)");
444   }else{
445     char zBuf[200];
446     sqlite3VdbeMemPrettyPrint(p, zBuf);
447     printf(" %s", zBuf);
448   }
449 }
450 static void registerTrace(int iReg, Mem *p){
451   printf("REG[%d] = ", iReg);
452   memTracePrint(p);
453   printf("\n");
454 }
455 #endif
456 
457 #ifdef SQLITE_DEBUG
458 #  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
459 #else
460 #  define REGISTER_TRACE(R,M)
461 #endif
462 
463 
464 #ifdef VDBE_PROFILE
465 
466 /*
467 ** hwtime.h contains inline assembler code for implementing
468 ** high-performance timing routines.
469 */
470 #include "hwtime.h"
471 
472 #endif
473 
474 #ifndef NDEBUG
475 /*
476 ** This function is only called from within an assert() expression. It
477 ** checks that the sqlite3.nTransaction variable is correctly set to
478 ** the number of non-transaction savepoints currently in the
479 ** linked list starting at sqlite3.pSavepoint.
480 **
481 ** Usage:
482 **
483 **     assert( checkSavepointCount(db) );
484 */
485 static int checkSavepointCount(sqlite3 *db){
486   int n = 0;
487   Savepoint *p;
488   for(p=db->pSavepoint; p; p=p->pNext) n++;
489   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
490   return 1;
491 }
492 #endif
493 
494 
495 /*
496 ** Execute as much of a VDBE program as we can.
497 ** This is the core of sqlite3_step().
498 */
499 int sqlite3VdbeExec(
500   Vdbe *p                    /* The VDBE */
501 ){
502   int pc=0;                  /* The program counter */
503   Op *aOp = p->aOp;          /* Copy of p->aOp */
504   Op *pOp;                   /* Current operation */
505   int rc = SQLITE_OK;        /* Value to return */
506   sqlite3 *db = p->db;       /* The database */
507   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
508   u8 encoding = ENC(db);     /* The database encoding */
509   int iCompare = 0;          /* Result of last OP_Compare operation */
510   unsigned nVmStep = 0;      /* Number of virtual machine steps */
511 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
512   unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
513 #endif
514   Mem *aMem = p->aMem;       /* Copy of p->aMem */
515   Mem *pIn1 = 0;             /* 1st input operand */
516   Mem *pIn2 = 0;             /* 2nd input operand */
517   Mem *pIn3 = 0;             /* 3rd input operand */
518   Mem *pOut = 0;             /* Output operand */
519   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
520   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
521 #ifdef VDBE_PROFILE
522   u64 start;                 /* CPU clock count at start of opcode */
523 #endif
524   /*** INSERT STACK UNION HERE ***/
525 
526   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
527   sqlite3VdbeEnter(p);
528   if( p->rc==SQLITE_NOMEM ){
529     /* This happens if a malloc() inside a call to sqlite3_column_text() or
530     ** sqlite3_column_text16() failed.  */
531     goto no_mem;
532   }
533   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
534   assert( p->bIsReader || p->readOnly!=0 );
535   p->rc = SQLITE_OK;
536   p->iCurrentTime = 0;
537   assert( p->explain==0 );
538   p->pResultSet = 0;
539   db->busyHandler.nBusy = 0;
540   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
541   sqlite3VdbeIOTraceSql(p);
542 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
543   if( db->xProgress ){
544     assert( 0 < db->nProgressOps );
545     nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
546     if( nProgressLimit==0 ){
547       nProgressLimit = db->nProgressOps;
548     }else{
549       nProgressLimit %= (unsigned)db->nProgressOps;
550     }
551   }
552 #endif
553 #ifdef SQLITE_DEBUG
554   sqlite3BeginBenignMalloc();
555   if( p->pc==0
556    && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
557   ){
558     int i;
559     int once = 1;
560     sqlite3VdbePrintSql(p);
561     if( p->db->flags & SQLITE_VdbeListing ){
562       printf("VDBE Program Listing:\n");
563       for(i=0; i<p->nOp; i++){
564         sqlite3VdbePrintOp(stdout, i, &aOp[i]);
565       }
566     }
567     if( p->db->flags & SQLITE_VdbeEQP ){
568       for(i=0; i<p->nOp; i++){
569         if( aOp[i].opcode==OP_Explain ){
570           if( once ) printf("VDBE Query Plan:\n");
571           printf("%s\n", aOp[i].p4.z);
572           once = 0;
573         }
574       }
575     }
576     if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
577   }
578   sqlite3EndBenignMalloc();
579 #endif
580   for(pc=p->pc; rc==SQLITE_OK; pc++){
581     assert( pc>=0 && pc<p->nOp );
582     if( db->mallocFailed ) goto no_mem;
583 #ifdef VDBE_PROFILE
584     start = sqlite3Hwtime();
585 #endif
586     nVmStep++;
587     pOp = &aOp[pc];
588 
589     /* Only allow tracing if SQLITE_DEBUG is defined.
590     */
591 #ifdef SQLITE_DEBUG
592     if( db->flags & SQLITE_VdbeTrace ){
593       sqlite3VdbePrintOp(stdout, pc, pOp);
594     }
595 #endif
596 
597 
598     /* Check to see if we need to simulate an interrupt.  This only happens
599     ** if we have a special test build.
600     */
601 #ifdef SQLITE_TEST
602     if( sqlite3_interrupt_count>0 ){
603       sqlite3_interrupt_count--;
604       if( sqlite3_interrupt_count==0 ){
605         sqlite3_interrupt(db);
606       }
607     }
608 #endif
609 
610     /* On any opcode with the "out2-prerelease" tag, free any
611     ** external allocations out of mem[p2] and set mem[p2] to be
612     ** an undefined integer.  Opcodes will either fill in the integer
613     ** value or convert mem[p2] to a different type.
614     */
615     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
616     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
617       assert( pOp->p2>0 );
618       assert( pOp->p2<=(p->nMem-p->nCursor) );
619       pOut = &aMem[pOp->p2];
620       memAboutToChange(p, pOut);
621       VdbeMemRelease(pOut);
622       pOut->flags = MEM_Int;
623     }
624 
625     /* Sanity checking on other operands */
626 #ifdef SQLITE_DEBUG
627     if( (pOp->opflags & OPFLG_IN1)!=0 ){
628       assert( pOp->p1>0 );
629       assert( pOp->p1<=(p->nMem-p->nCursor) );
630       assert( memIsValid(&aMem[pOp->p1]) );
631       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
632       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
633     }
634     if( (pOp->opflags & OPFLG_IN2)!=0 ){
635       assert( pOp->p2>0 );
636       assert( pOp->p2<=(p->nMem-p->nCursor) );
637       assert( memIsValid(&aMem[pOp->p2]) );
638       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
639       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
640     }
641     if( (pOp->opflags & OPFLG_IN3)!=0 ){
642       assert( pOp->p3>0 );
643       assert( pOp->p3<=(p->nMem-p->nCursor) );
644       assert( memIsValid(&aMem[pOp->p3]) );
645       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
646       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
647     }
648     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
649       assert( pOp->p2>0 );
650       assert( pOp->p2<=(p->nMem-p->nCursor) );
651       memAboutToChange(p, &aMem[pOp->p2]);
652     }
653     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
654       assert( pOp->p3>0 );
655       assert( pOp->p3<=(p->nMem-p->nCursor) );
656       memAboutToChange(p, &aMem[pOp->p3]);
657     }
658 #endif
659 
660     switch( pOp->opcode ){
661 
662 /*****************************************************************************
663 ** What follows is a massive switch statement where each case implements a
664 ** separate instruction in the virtual machine.  If we follow the usual
665 ** indentation conventions, each case should be indented by 6 spaces.  But
666 ** that is a lot of wasted space on the left margin.  So the code within
667 ** the switch statement will break with convention and be flush-left. Another
668 ** big comment (similar to this one) will mark the point in the code where
669 ** we transition back to normal indentation.
670 **
671 ** The formatting of each case is important.  The makefile for SQLite
672 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
673 ** file looking for lines that begin with "case OP_".  The opcodes.h files
674 ** will be filled with #defines that give unique integer values to each
675 ** opcode and the opcodes.c file is filled with an array of strings where
676 ** each string is the symbolic name for the corresponding opcode.  If the
677 ** case statement is followed by a comment of the form "/# same as ... #/"
678 ** that comment is used to determine the particular value of the opcode.
679 **
680 ** Other keywords in the comment that follows each case are used to
681 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
682 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
683 ** the mkopcodeh.awk script for additional information.
684 **
685 ** Documentation about VDBE opcodes is generated by scanning this file
686 ** for lines of that contain "Opcode:".  That line and all subsequent
687 ** comment lines are used in the generation of the opcode.html documentation
688 ** file.
689 **
690 ** SUMMARY:
691 **
692 **     Formatting is important to scripts that scan this file.
693 **     Do not deviate from the formatting style currently in use.
694 **
695 *****************************************************************************/
696 
697 /* Opcode:  Goto * P2 * * *
698 **
699 ** An unconditional jump to address P2.
700 ** The next instruction executed will be
701 ** the one at index P2 from the beginning of
702 ** the program.
703 **
704 ** The P1 parameter is not actually used by this opcode.  However, it
705 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
706 ** that this Goto is the bottom of a loop and that the lines from P2 down
707 ** to the current line should be indented for EXPLAIN output.
708 */
709 case OP_Goto: {             /* jump */
710   pc = pOp->p2 - 1;
711 
712   /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
713   ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
714   ** completion.  Check to see if sqlite3_interrupt() has been called
715   ** or if the progress callback needs to be invoked.
716   **
717   ** This code uses unstructured "goto" statements and does not look clean.
718   ** But that is not due to sloppy coding habits. The code is written this
719   ** way for performance, to avoid having to run the interrupt and progress
720   ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
721   ** faster according to "valgrind --tool=cachegrind" */
722 check_for_interrupt:
723   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
724 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
725   /* Call the progress callback if it is configured and the required number
726   ** of VDBE ops have been executed (either since this invocation of
727   ** sqlite3VdbeExec() or since last time the progress callback was called).
728   ** If the progress callback returns non-zero, exit the virtual machine with
729   ** a return code SQLITE_ABORT.
730   */
731   if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
732     assert( db->nProgressOps!=0 );
733     nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
734     if( db->xProgress(db->pProgressArg) ){
735       rc = SQLITE_INTERRUPT;
736       goto vdbe_error_halt;
737     }
738   }
739 #endif
740 
741   break;
742 }
743 
744 /* Opcode:  Gosub P1 P2 * * *
745 **
746 ** Write the current address onto register P1
747 ** and then jump to address P2.
748 */
749 case OP_Gosub: {            /* jump */
750   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
751   pIn1 = &aMem[pOp->p1];
752   assert( VdbeMemDynamic(pIn1)==0 );
753   memAboutToChange(p, pIn1);
754   pIn1->flags = MEM_Int;
755   pIn1->u.i = pc;
756   REGISTER_TRACE(pOp->p1, pIn1);
757   pc = pOp->p2 - 1;
758   break;
759 }
760 
761 /* Opcode:  Return P1 * * * *
762 **
763 ** Jump to the next instruction after the address in register P1.  After
764 ** the jump, register P1 becomes undefined.
765 */
766 case OP_Return: {           /* in1 */
767   pIn1 = &aMem[pOp->p1];
768   assert( pIn1->flags==MEM_Int );
769   pc = (int)pIn1->u.i;
770   pIn1->flags = MEM_Undefined;
771   break;
772 }
773 
774 /* Opcode: InitCoroutine P1 P2 P3 * *
775 **
776 ** Set up register P1 so that it will Yield to the coroutine
777 ** located at address P3.
778 **
779 ** If P2!=0 then the coroutine implementation immediately follows
780 ** this opcode.  So jump over the coroutine implementation to
781 ** address P2.
782 **
783 ** See also: EndCoroutine
784 */
785 case OP_InitCoroutine: {     /* jump */
786   assert( pOp->p1>0 &&  pOp->p1<=(p->nMem-p->nCursor) );
787   assert( pOp->p2>=0 && pOp->p2<p->nOp );
788   assert( pOp->p3>=0 && pOp->p3<p->nOp );
789   pOut = &aMem[pOp->p1];
790   assert( !VdbeMemDynamic(pOut) );
791   pOut->u.i = pOp->p3 - 1;
792   pOut->flags = MEM_Int;
793   if( pOp->p2 ) pc = pOp->p2 - 1;
794   break;
795 }
796 
797 /* Opcode:  EndCoroutine P1 * * * *
798 **
799 ** The instruction at the address in register P1 is a Yield.
800 ** Jump to the P2 parameter of that Yield.
801 ** After the jump, register P1 becomes undefined.
802 **
803 ** See also: InitCoroutine
804 */
805 case OP_EndCoroutine: {           /* in1 */
806   VdbeOp *pCaller;
807   pIn1 = &aMem[pOp->p1];
808   assert( pIn1->flags==MEM_Int );
809   assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
810   pCaller = &aOp[pIn1->u.i];
811   assert( pCaller->opcode==OP_Yield );
812   assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
813   pc = pCaller->p2 - 1;
814   pIn1->flags = MEM_Undefined;
815   break;
816 }
817 
818 /* Opcode:  Yield P1 P2 * * *
819 **
820 ** Swap the program counter with the value in register P1.  This
821 ** has the effect of yielding to a coroutine.
822 **
823 ** If the coroutine that is launched by this instruction ends with
824 ** Yield or Return then continue to the next instruction.  But if
825 ** the coroutine launched by this instruction ends with
826 ** EndCoroutine, then jump to P2 rather than continuing with the
827 ** next instruction.
828 **
829 ** See also: InitCoroutine
830 */
831 case OP_Yield: {            /* in1, jump */
832   int pcDest;
833   pIn1 = &aMem[pOp->p1];
834   assert( VdbeMemDynamic(pIn1)==0 );
835   pIn1->flags = MEM_Int;
836   pcDest = (int)pIn1->u.i;
837   pIn1->u.i = pc;
838   REGISTER_TRACE(pOp->p1, pIn1);
839   pc = pcDest;
840   break;
841 }
842 
843 /* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
844 ** Synopsis:  if r[P3]=null halt
845 **
846 ** Check the value in register P3.  If it is NULL then Halt using
847 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
848 ** value in register P3 is not NULL, then this routine is a no-op.
849 ** The P5 parameter should be 1.
850 */
851 case OP_HaltIfNull: {      /* in3 */
852   pIn3 = &aMem[pOp->p3];
853   if( (pIn3->flags & MEM_Null)==0 ) break;
854   /* Fall through into OP_Halt */
855 }
856 
857 /* Opcode:  Halt P1 P2 * P4 P5
858 **
859 ** Exit immediately.  All open cursors, etc are closed
860 ** automatically.
861 **
862 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
863 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
864 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
865 ** whether or not to rollback the current transaction.  Do not rollback
866 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
867 ** then back out all changes that have occurred during this execution of the
868 ** VDBE, but do not rollback the transaction.
869 **
870 ** If P4 is not null then it is an error message string.
871 **
872 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
873 **
874 **    0:  (no change)
875 **    1:  NOT NULL contraint failed: P4
876 **    2:  UNIQUE constraint failed: P4
877 **    3:  CHECK constraint failed: P4
878 **    4:  FOREIGN KEY constraint failed: P4
879 **
880 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
881 ** omitted.
882 **
883 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
884 ** every program.  So a jump past the last instruction of the program
885 ** is the same as executing Halt.
886 */
887 case OP_Halt: {
888   const char *zType;
889   const char *zLogFmt;
890 
891   if( pOp->p1==SQLITE_OK && p->pFrame ){
892     /* Halt the sub-program. Return control to the parent frame. */
893     VdbeFrame *pFrame = p->pFrame;
894     p->pFrame = pFrame->pParent;
895     p->nFrame--;
896     sqlite3VdbeSetChanges(db, p->nChange);
897     pc = sqlite3VdbeFrameRestore(pFrame);
898     lastRowid = db->lastRowid;
899     if( pOp->p2==OE_Ignore ){
900       /* Instruction pc is the OP_Program that invoked the sub-program
901       ** currently being halted. If the p2 instruction of this OP_Halt
902       ** instruction is set to OE_Ignore, then the sub-program is throwing
903       ** an IGNORE exception. In this case jump to the address specified
904       ** as the p2 of the calling OP_Program.  */
905       pc = p->aOp[pc].p2-1;
906     }
907     aOp = p->aOp;
908     aMem = p->aMem;
909     break;
910   }
911   p->rc = pOp->p1;
912   p->errorAction = (u8)pOp->p2;
913   p->pc = pc;
914   if( p->rc ){
915     if( pOp->p5 ){
916       static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
917                                              "FOREIGN KEY" };
918       assert( pOp->p5>=1 && pOp->p5<=4 );
919       testcase( pOp->p5==1 );
920       testcase( pOp->p5==2 );
921       testcase( pOp->p5==3 );
922       testcase( pOp->p5==4 );
923       zType = azType[pOp->p5-1];
924     }else{
925       zType = 0;
926     }
927     assert( zType!=0 || pOp->p4.z!=0 );
928     zLogFmt = "abort at %d in [%s]: %s";
929     if( zType && pOp->p4.z ){
930       sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
931                        zType, pOp->p4.z);
932     }else if( pOp->p4.z ){
933       sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
934     }else{
935       sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
936     }
937     sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
938   }
939   rc = sqlite3VdbeHalt(p);
940   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
941   if( rc==SQLITE_BUSY ){
942     p->rc = rc = SQLITE_BUSY;
943   }else{
944     assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
945     assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
946     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
947   }
948   goto vdbe_return;
949 }
950 
951 /* Opcode: Integer P1 P2 * * *
952 ** Synopsis: r[P2]=P1
953 **
954 ** The 32-bit integer value P1 is written into register P2.
955 */
956 case OP_Integer: {         /* out2-prerelease */
957   pOut->u.i = pOp->p1;
958   break;
959 }
960 
961 /* Opcode: Int64 * P2 * P4 *
962 ** Synopsis: r[P2]=P4
963 **
964 ** P4 is a pointer to a 64-bit integer value.
965 ** Write that value into register P2.
966 */
967 case OP_Int64: {           /* out2-prerelease */
968   assert( pOp->p4.pI64!=0 );
969   pOut->u.i = *pOp->p4.pI64;
970   break;
971 }
972 
973 #ifndef SQLITE_OMIT_FLOATING_POINT
974 /* Opcode: Real * P2 * P4 *
975 ** Synopsis: r[P2]=P4
976 **
977 ** P4 is a pointer to a 64-bit floating point value.
978 ** Write that value into register P2.
979 */
980 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
981   pOut->flags = MEM_Real;
982   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
983   pOut->r = *pOp->p4.pReal;
984   break;
985 }
986 #endif
987 
988 /* Opcode: String8 * P2 * P4 *
989 ** Synopsis: r[P2]='P4'
990 **
991 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
992 ** into a String before it is executed for the first time.  During
993 ** this transformation, the length of string P4 is computed and stored
994 ** as the P1 parameter.
995 */
996 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
997   assert( pOp->p4.z!=0 );
998   pOp->opcode = OP_String;
999   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
1000 
1001 #ifndef SQLITE_OMIT_UTF16
1002   if( encoding!=SQLITE_UTF8 ){
1003     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
1004     if( rc==SQLITE_TOOBIG ) goto too_big;
1005     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
1006     assert( pOut->zMalloc==pOut->z );
1007     assert( VdbeMemDynamic(pOut)==0 );
1008     pOut->zMalloc = 0;
1009     pOut->flags |= MEM_Static;
1010     if( pOp->p4type==P4_DYNAMIC ){
1011       sqlite3DbFree(db, pOp->p4.z);
1012     }
1013     pOp->p4type = P4_DYNAMIC;
1014     pOp->p4.z = pOut->z;
1015     pOp->p1 = pOut->n;
1016   }
1017 #endif
1018   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1019     goto too_big;
1020   }
1021   /* Fall through to the next case, OP_String */
1022 }
1023 
1024 /* Opcode: String P1 P2 * P4 *
1025 ** Synopsis: r[P2]='P4' (len=P1)
1026 **
1027 ** The string value P4 of length P1 (bytes) is stored in register P2.
1028 */
1029 case OP_String: {          /* out2-prerelease */
1030   assert( pOp->p4.z!=0 );
1031   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
1032   pOut->z = pOp->p4.z;
1033   pOut->n = pOp->p1;
1034   pOut->enc = encoding;
1035   UPDATE_MAX_BLOBSIZE(pOut);
1036   break;
1037 }
1038 
1039 /* Opcode: Null P1 P2 P3 * *
1040 ** Synopsis:  r[P2..P3]=NULL
1041 **
1042 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
1043 ** NULL into register P3 and every register in between P2 and P3.  If P3
1044 ** is less than P2 (typically P3 is zero) then only register P2 is
1045 ** set to NULL.
1046 **
1047 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1048 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1049 ** OP_Ne or OP_Eq.
1050 */
1051 case OP_Null: {           /* out2-prerelease */
1052   int cnt;
1053   u16 nullFlag;
1054   cnt = pOp->p3-pOp->p2;
1055   assert( pOp->p3<=(p->nMem-p->nCursor) );
1056   pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
1057   while( cnt>0 ){
1058     pOut++;
1059     memAboutToChange(p, pOut);
1060     VdbeMemRelease(pOut);
1061     pOut->flags = nullFlag;
1062     cnt--;
1063   }
1064   break;
1065 }
1066 
1067 /* Opcode: SoftNull P1 * * * *
1068 ** Synopsis:  r[P1]=NULL
1069 **
1070 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1071 ** instruction, but do not free any string or blob memory associated with
1072 ** the register, so that if the value was a string or blob that was
1073 ** previously copied using OP_SCopy, the copies will continue to be valid.
1074 */
1075 case OP_SoftNull: {
1076   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
1077   pOut = &aMem[pOp->p1];
1078   pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
1079   break;
1080 }
1081 
1082 /* Opcode: Blob P1 P2 * P4 *
1083 ** Synopsis: r[P2]=P4 (len=P1)
1084 **
1085 ** P4 points to a blob of data P1 bytes long.  Store this
1086 ** blob in register P2.
1087 */
1088 case OP_Blob: {                /* out2-prerelease */
1089   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
1090   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
1091   pOut->enc = encoding;
1092   UPDATE_MAX_BLOBSIZE(pOut);
1093   break;
1094 }
1095 
1096 /* Opcode: Variable P1 P2 * P4 *
1097 ** Synopsis: r[P2]=parameter(P1,P4)
1098 **
1099 ** Transfer the values of bound parameter P1 into register P2
1100 **
1101 ** If the parameter is named, then its name appears in P4.
1102 ** The P4 value is used by sqlite3_bind_parameter_name().
1103 */
1104 case OP_Variable: {            /* out2-prerelease */
1105   Mem *pVar;       /* Value being transferred */
1106 
1107   assert( pOp->p1>0 && pOp->p1<=p->nVar );
1108   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
1109   pVar = &p->aVar[pOp->p1 - 1];
1110   if( sqlite3VdbeMemTooBig(pVar) ){
1111     goto too_big;
1112   }
1113   sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
1114   UPDATE_MAX_BLOBSIZE(pOut);
1115   break;
1116 }
1117 
1118 /* Opcode: Move P1 P2 P3 * *
1119 ** Synopsis:  r[P2@P3]=r[P1@P3]
1120 **
1121 ** Move the P3 values in register P1..P1+P3-1 over into
1122 ** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
1123 ** left holding a NULL.  It is an error for register ranges
1124 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
1125 ** for P3 to be less than 1.
1126 */
1127 case OP_Move: {
1128   char *zMalloc;   /* Holding variable for allocated memory */
1129   int n;           /* Number of registers left to copy */
1130   int p1;          /* Register to copy from */
1131   int p2;          /* Register to copy to */
1132 
1133   n = pOp->p3;
1134   p1 = pOp->p1;
1135   p2 = pOp->p2;
1136   assert( n>0 && p1>0 && p2>0 );
1137   assert( p1+n<=p2 || p2+n<=p1 );
1138 
1139   pIn1 = &aMem[p1];
1140   pOut = &aMem[p2];
1141   do{
1142     assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
1143     assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
1144     assert( memIsValid(pIn1) );
1145     memAboutToChange(p, pOut);
1146     VdbeMemRelease(pOut);
1147     zMalloc = pOut->zMalloc;
1148     memcpy(pOut, pIn1, sizeof(Mem));
1149 #ifdef SQLITE_DEBUG
1150     if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
1151       pOut->pScopyFrom += p1 - pOp->p2;
1152     }
1153 #endif
1154     pIn1->flags = MEM_Undefined;
1155     pIn1->xDel = 0;
1156     pIn1->zMalloc = zMalloc;
1157     REGISTER_TRACE(p2++, pOut);
1158     pIn1++;
1159     pOut++;
1160   }while( --n );
1161   break;
1162 }
1163 
1164 /* Opcode: Copy P1 P2 P3 * *
1165 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1166 **
1167 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1168 **
1169 ** This instruction makes a deep copy of the value.  A duplicate
1170 ** is made of any string or blob constant.  See also OP_SCopy.
1171 */
1172 case OP_Copy: {
1173   int n;
1174 
1175   n = pOp->p3;
1176   pIn1 = &aMem[pOp->p1];
1177   pOut = &aMem[pOp->p2];
1178   assert( pOut!=pIn1 );
1179   while( 1 ){
1180     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1181     Deephemeralize(pOut);
1182 #ifdef SQLITE_DEBUG
1183     pOut->pScopyFrom = 0;
1184 #endif
1185     REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
1186     if( (n--)==0 ) break;
1187     pOut++;
1188     pIn1++;
1189   }
1190   break;
1191 }
1192 
1193 /* Opcode: SCopy P1 P2 * * *
1194 ** Synopsis: r[P2]=r[P1]
1195 **
1196 ** Make a shallow copy of register P1 into register P2.
1197 **
1198 ** This instruction makes a shallow copy of the value.  If the value
1199 ** is a string or blob, then the copy is only a pointer to the
1200 ** original and hence if the original changes so will the copy.
1201 ** Worse, if the original is deallocated, the copy becomes invalid.
1202 ** Thus the program must guarantee that the original will not change
1203 ** during the lifetime of the copy.  Use OP_Copy to make a complete
1204 ** copy.
1205 */
1206 case OP_SCopy: {            /* out2 */
1207   pIn1 = &aMem[pOp->p1];
1208   pOut = &aMem[pOp->p2];
1209   assert( pOut!=pIn1 );
1210   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1211 #ifdef SQLITE_DEBUG
1212   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
1213 #endif
1214   break;
1215 }
1216 
1217 /* Opcode: ResultRow P1 P2 * * *
1218 ** Synopsis:  output=r[P1@P2]
1219 **
1220 ** The registers P1 through P1+P2-1 contain a single row of
1221 ** results. This opcode causes the sqlite3_step() call to terminate
1222 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1223 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1224 ** the result row.
1225 */
1226 case OP_ResultRow: {
1227   Mem *pMem;
1228   int i;
1229   assert( p->nResColumn==pOp->p2 );
1230   assert( pOp->p1>0 );
1231   assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
1232 
1233 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1234   /* Run the progress counter just before returning.
1235   */
1236   if( db->xProgress!=0
1237    && nVmStep>=nProgressLimit
1238    && db->xProgress(db->pProgressArg)!=0
1239   ){
1240     rc = SQLITE_INTERRUPT;
1241     goto vdbe_error_halt;
1242   }
1243 #endif
1244 
1245   /* If this statement has violated immediate foreign key constraints, do
1246   ** not return the number of rows modified. And do not RELEASE the statement
1247   ** transaction. It needs to be rolled back.  */
1248   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
1249     assert( db->flags&SQLITE_CountRows );
1250     assert( p->usesStmtJournal );
1251     break;
1252   }
1253 
1254   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
1255   ** DML statements invoke this opcode to return the number of rows
1256   ** modified to the user. This is the only way that a VM that
1257   ** opens a statement transaction may invoke this opcode.
1258   **
1259   ** In case this is such a statement, close any statement transaction
1260   ** opened by this VM before returning control to the user. This is to
1261   ** ensure that statement-transactions are always nested, not overlapping.
1262   ** If the open statement-transaction is not closed here, then the user
1263   ** may step another VM that opens its own statement transaction. This
1264   ** may lead to overlapping statement transactions.
1265   **
1266   ** The statement transaction is never a top-level transaction.  Hence
1267   ** the RELEASE call below can never fail.
1268   */
1269   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
1270   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
1271   if( NEVER(rc!=SQLITE_OK) ){
1272     break;
1273   }
1274 
1275   /* Invalidate all ephemeral cursor row caches */
1276   p->cacheCtr = (p->cacheCtr + 2)|1;
1277 
1278   /* Make sure the results of the current row are \000 terminated
1279   ** and have an assigned type.  The results are de-ephemeralized as
1280   ** a side effect.
1281   */
1282   pMem = p->pResultSet = &aMem[pOp->p1];
1283   for(i=0; i<pOp->p2; i++){
1284     assert( memIsValid(&pMem[i]) );
1285     Deephemeralize(&pMem[i]);
1286     assert( (pMem[i].flags & MEM_Ephem)==0
1287             || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
1288     sqlite3VdbeMemNulTerminate(&pMem[i]);
1289     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1290   }
1291   if( db->mallocFailed ) goto no_mem;
1292 
1293   /* Return SQLITE_ROW
1294   */
1295   p->pc = pc + 1;
1296   rc = SQLITE_ROW;
1297   goto vdbe_return;
1298 }
1299 
1300 /* Opcode: Concat P1 P2 P3 * *
1301 ** Synopsis: r[P3]=r[P2]+r[P1]
1302 **
1303 ** Add the text in register P1 onto the end of the text in
1304 ** register P2 and store the result in register P3.
1305 ** If either the P1 or P2 text are NULL then store NULL in P3.
1306 **
1307 **   P3 = P2 || P1
1308 **
1309 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1310 ** if P3 is the same register as P2, the implementation is able
1311 ** to avoid a memcpy().
1312 */
1313 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
1314   i64 nByte;
1315 
1316   pIn1 = &aMem[pOp->p1];
1317   pIn2 = &aMem[pOp->p2];
1318   pOut = &aMem[pOp->p3];
1319   assert( pIn1!=pOut );
1320   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1321     sqlite3VdbeMemSetNull(pOut);
1322     break;
1323   }
1324   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
1325   Stringify(pIn1, encoding);
1326   Stringify(pIn2, encoding);
1327   nByte = pIn1->n + pIn2->n;
1328   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1329     goto too_big;
1330   }
1331   if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
1332     goto no_mem;
1333   }
1334   MemSetTypeFlag(pOut, MEM_Str);
1335   if( pOut!=pIn2 ){
1336     memcpy(pOut->z, pIn2->z, pIn2->n);
1337   }
1338   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1339   pOut->z[nByte]=0;
1340   pOut->z[nByte+1] = 0;
1341   pOut->flags |= MEM_Term;
1342   pOut->n = (int)nByte;
1343   pOut->enc = encoding;
1344   UPDATE_MAX_BLOBSIZE(pOut);
1345   break;
1346 }
1347 
1348 /* Opcode: Add P1 P2 P3 * *
1349 ** Synopsis:  r[P3]=r[P1]+r[P2]
1350 **
1351 ** Add the value in register P1 to the value in register P2
1352 ** and store the result in register P3.
1353 ** If either input is NULL, the result is NULL.
1354 */
1355 /* Opcode: Multiply P1 P2 P3 * *
1356 ** Synopsis:  r[P3]=r[P1]*r[P2]
1357 **
1358 **
1359 ** Multiply the value in register P1 by the value in register P2
1360 ** and store the result in register P3.
1361 ** If either input is NULL, the result is NULL.
1362 */
1363 /* Opcode: Subtract P1 P2 P3 * *
1364 ** Synopsis:  r[P3]=r[P2]-r[P1]
1365 **
1366 ** Subtract the value in register P1 from the value in register P2
1367 ** and store the result in register P3.
1368 ** If either input is NULL, the result is NULL.
1369 */
1370 /* Opcode: Divide P1 P2 P3 * *
1371 ** Synopsis:  r[P3]=r[P2]/r[P1]
1372 **
1373 ** Divide the value in register P1 by the value in register P2
1374 ** and store the result in register P3 (P3=P2/P1). If the value in
1375 ** register P1 is zero, then the result is NULL. If either input is
1376 ** NULL, the result is NULL.
1377 */
1378 /* Opcode: Remainder P1 P2 P3 * *
1379 ** Synopsis:  r[P3]=r[P2]%r[P1]
1380 **
1381 ** Compute the remainder after integer register P2 is divided by
1382 ** register P1 and store the result in register P3.
1383 ** If the value in register P1 is zero the result is NULL.
1384 ** If either operand is NULL, the result is NULL.
1385 */
1386 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
1387 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
1388 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
1389 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
1390 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
1391   char bIntint;   /* Started out as two integer operands */
1392   u16 flags;      /* Combined MEM_* flags from both inputs */
1393   u16 type1;      /* Numeric type of left operand */
1394   u16 type2;      /* Numeric type of right operand */
1395   i64 iA;         /* Integer value of left operand */
1396   i64 iB;         /* Integer value of right operand */
1397   double rA;      /* Real value of left operand */
1398   double rB;      /* Real value of right operand */
1399 
1400   pIn1 = &aMem[pOp->p1];
1401   type1 = numericType(pIn1);
1402   pIn2 = &aMem[pOp->p2];
1403   type2 = numericType(pIn2);
1404   pOut = &aMem[pOp->p3];
1405   flags = pIn1->flags | pIn2->flags;
1406   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
1407   if( (type1 & type2 & MEM_Int)!=0 ){
1408     iA = pIn1->u.i;
1409     iB = pIn2->u.i;
1410     bIntint = 1;
1411     switch( pOp->opcode ){
1412       case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
1413       case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
1414       case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
1415       case OP_Divide: {
1416         if( iA==0 ) goto arithmetic_result_is_null;
1417         if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
1418         iB /= iA;
1419         break;
1420       }
1421       default: {
1422         if( iA==0 ) goto arithmetic_result_is_null;
1423         if( iA==-1 ) iA = 1;
1424         iB %= iA;
1425         break;
1426       }
1427     }
1428     pOut->u.i = iB;
1429     MemSetTypeFlag(pOut, MEM_Int);
1430   }else{
1431     bIntint = 0;
1432 fp_math:
1433     rA = sqlite3VdbeRealValue(pIn1);
1434     rB = sqlite3VdbeRealValue(pIn2);
1435     switch( pOp->opcode ){
1436       case OP_Add:         rB += rA;       break;
1437       case OP_Subtract:    rB -= rA;       break;
1438       case OP_Multiply:    rB *= rA;       break;
1439       case OP_Divide: {
1440         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1441         if( rA==(double)0 ) goto arithmetic_result_is_null;
1442         rB /= rA;
1443         break;
1444       }
1445       default: {
1446         iA = (i64)rA;
1447         iB = (i64)rB;
1448         if( iA==0 ) goto arithmetic_result_is_null;
1449         if( iA==-1 ) iA = 1;
1450         rB = (double)(iB % iA);
1451         break;
1452       }
1453     }
1454 #ifdef SQLITE_OMIT_FLOATING_POINT
1455     pOut->u.i = rB;
1456     MemSetTypeFlag(pOut, MEM_Int);
1457 #else
1458     if( sqlite3IsNaN(rB) ){
1459       goto arithmetic_result_is_null;
1460     }
1461     pOut->r = rB;
1462     MemSetTypeFlag(pOut, MEM_Real);
1463     if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
1464       sqlite3VdbeIntegerAffinity(pOut);
1465     }
1466 #endif
1467   }
1468   break;
1469 
1470 arithmetic_result_is_null:
1471   sqlite3VdbeMemSetNull(pOut);
1472   break;
1473 }
1474 
1475 /* Opcode: CollSeq P1 * * P4
1476 **
1477 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
1478 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1479 ** be returned. This is used by the built-in min(), max() and nullif()
1480 ** functions.
1481 **
1482 ** If P1 is not zero, then it is a register that a subsequent min() or
1483 ** max() aggregate will set to 1 if the current row is not the minimum or
1484 ** maximum.  The P1 register is initialized to 0 by this instruction.
1485 **
1486 ** The interface used by the implementation of the aforementioned functions
1487 ** to retrieve the collation sequence set by this opcode is not available
1488 ** publicly, only to user functions defined in func.c.
1489 */
1490 case OP_CollSeq: {
1491   assert( pOp->p4type==P4_COLLSEQ );
1492   if( pOp->p1 ){
1493     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
1494   }
1495   break;
1496 }
1497 
1498 /* Opcode: Function P1 P2 P3 P4 P5
1499 ** Synopsis: r[P3]=func(r[P2@P5])
1500 **
1501 ** Invoke a user function (P4 is a pointer to a Function structure that
1502 ** defines the function) with P5 arguments taken from register P2 and
1503 ** successors.  The result of the function is stored in register P3.
1504 ** Register P3 must not be one of the function inputs.
1505 **
1506 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
1507 ** function was determined to be constant at compile time. If the first
1508 ** argument was constant then bit 0 of P1 is set. This is used to determine
1509 ** whether meta data associated with a user function argument using the
1510 ** sqlite3_set_auxdata() API may be safely retained until the next
1511 ** invocation of this opcode.
1512 **
1513 ** See also: AggStep and AggFinal
1514 */
1515 case OP_Function: {
1516   int i;
1517   Mem *pArg;
1518   sqlite3_context ctx;
1519   sqlite3_value **apVal;
1520   int n;
1521 
1522   n = pOp->p5;
1523   apVal = p->apArg;
1524   assert( apVal || n==0 );
1525   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
1526   pOut = &aMem[pOp->p3];
1527   memAboutToChange(p, pOut);
1528 
1529   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
1530   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
1531   pArg = &aMem[pOp->p2];
1532   for(i=0; i<n; i++, pArg++){
1533     assert( memIsValid(pArg) );
1534     apVal[i] = pArg;
1535     Deephemeralize(pArg);
1536     REGISTER_TRACE(pOp->p2+i, pArg);
1537   }
1538 
1539   assert( pOp->p4type==P4_FUNCDEF );
1540   ctx.pFunc = pOp->p4.pFunc;
1541   ctx.iOp = pc;
1542   ctx.pVdbe = p;
1543 
1544   /* The output cell may already have a buffer allocated. Move
1545   ** the pointer to ctx.s so in case the user-function can use
1546   ** the already allocated buffer instead of allocating a new one.
1547   */
1548   memcpy(&ctx.s, pOut, sizeof(Mem));
1549   pOut->flags = MEM_Null;
1550   pOut->xDel = 0;
1551   pOut->zMalloc = 0;
1552   MemSetTypeFlag(&ctx.s, MEM_Null);
1553 
1554   ctx.fErrorOrAux = 0;
1555   if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
1556     assert( pOp>aOp );
1557     assert( pOp[-1].p4type==P4_COLLSEQ );
1558     assert( pOp[-1].opcode==OP_CollSeq );
1559     ctx.pColl = pOp[-1].p4.pColl;
1560   }
1561   db->lastRowid = lastRowid;
1562   (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
1563   lastRowid = db->lastRowid;
1564 
1565   if( db->mallocFailed ){
1566     /* Even though a malloc() has failed, the implementation of the
1567     ** user function may have called an sqlite3_result_XXX() function
1568     ** to return a value. The following call releases any resources
1569     ** associated with such a value.
1570     */
1571     sqlite3VdbeMemRelease(&ctx.s);
1572     goto no_mem;
1573   }
1574 
1575   /* If the function returned an error, throw an exception */
1576   if( ctx.fErrorOrAux ){
1577     if( ctx.isError ){
1578       sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
1579       rc = ctx.isError;
1580     }
1581     sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
1582   }
1583 
1584   /* Copy the result of the function into register P3 */
1585   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
1586   assert( pOut->flags==MEM_Null );
1587   memcpy(pOut, &ctx.s, sizeof(Mem));
1588   if( sqlite3VdbeMemTooBig(pOut) ){
1589     goto too_big;
1590   }
1591 
1592 #if 0
1593   /* The app-defined function has done something that as caused this
1594   ** statement to expire.  (Perhaps the function called sqlite3_exec()
1595   ** with a CREATE TABLE statement.)
1596   */
1597   if( p->expired ) rc = SQLITE_ABORT;
1598 #endif
1599 
1600   REGISTER_TRACE(pOp->p3, pOut);
1601   UPDATE_MAX_BLOBSIZE(pOut);
1602   break;
1603 }
1604 
1605 /* Opcode: BitAnd P1 P2 P3 * *
1606 ** Synopsis:  r[P3]=r[P1]&r[P2]
1607 **
1608 ** Take the bit-wise AND of the values in register P1 and P2 and
1609 ** store the result in register P3.
1610 ** If either input is NULL, the result is NULL.
1611 */
1612 /* Opcode: BitOr P1 P2 P3 * *
1613 ** Synopsis:  r[P3]=r[P1]|r[P2]
1614 **
1615 ** Take the bit-wise OR of the values in register P1 and P2 and
1616 ** store the result in register P3.
1617 ** If either input is NULL, the result is NULL.
1618 */
1619 /* Opcode: ShiftLeft P1 P2 P3 * *
1620 ** Synopsis:  r[P3]=r[P2]<<r[P1]
1621 **
1622 ** Shift the integer value in register P2 to the left by the
1623 ** number of bits specified by the integer in register P1.
1624 ** Store the result in register P3.
1625 ** If either input is NULL, the result is NULL.
1626 */
1627 /* Opcode: ShiftRight P1 P2 P3 * *
1628 ** Synopsis:  r[P3]=r[P2]>>r[P1]
1629 **
1630 ** Shift the integer value in register P2 to the right by the
1631 ** number of bits specified by the integer in register P1.
1632 ** Store the result in register P3.
1633 ** If either input is NULL, the result is NULL.
1634 */
1635 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
1636 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
1637 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
1638 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
1639   i64 iA;
1640   u64 uA;
1641   i64 iB;
1642   u8 op;
1643 
1644   pIn1 = &aMem[pOp->p1];
1645   pIn2 = &aMem[pOp->p2];
1646   pOut = &aMem[pOp->p3];
1647   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1648     sqlite3VdbeMemSetNull(pOut);
1649     break;
1650   }
1651   iA = sqlite3VdbeIntValue(pIn2);
1652   iB = sqlite3VdbeIntValue(pIn1);
1653   op = pOp->opcode;
1654   if( op==OP_BitAnd ){
1655     iA &= iB;
1656   }else if( op==OP_BitOr ){
1657     iA |= iB;
1658   }else if( iB!=0 ){
1659     assert( op==OP_ShiftRight || op==OP_ShiftLeft );
1660 
1661     /* If shifting by a negative amount, shift in the other direction */
1662     if( iB<0 ){
1663       assert( OP_ShiftRight==OP_ShiftLeft+1 );
1664       op = 2*OP_ShiftLeft + 1 - op;
1665       iB = iB>(-64) ? -iB : 64;
1666     }
1667 
1668     if( iB>=64 ){
1669       iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
1670     }else{
1671       memcpy(&uA, &iA, sizeof(uA));
1672       if( op==OP_ShiftLeft ){
1673         uA <<= iB;
1674       }else{
1675         uA >>= iB;
1676         /* Sign-extend on a right shift of a negative number */
1677         if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
1678       }
1679       memcpy(&iA, &uA, sizeof(iA));
1680     }
1681   }
1682   pOut->u.i = iA;
1683   MemSetTypeFlag(pOut, MEM_Int);
1684   break;
1685 }
1686 
1687 /* Opcode: AddImm  P1 P2 * * *
1688 ** Synopsis:  r[P1]=r[P1]+P2
1689 **
1690 ** Add the constant P2 to the value in register P1.
1691 ** The result is always an integer.
1692 **
1693 ** To force any register to be an integer, just add 0.
1694 */
1695 case OP_AddImm: {            /* in1 */
1696   pIn1 = &aMem[pOp->p1];
1697   memAboutToChange(p, pIn1);
1698   sqlite3VdbeMemIntegerify(pIn1);
1699   pIn1->u.i += pOp->p2;
1700   break;
1701 }
1702 
1703 /* Opcode: MustBeInt P1 P2 * * *
1704 **
1705 ** Force the value in register P1 to be an integer.  If the value
1706 ** in P1 is not an integer and cannot be converted into an integer
1707 ** without data loss, then jump immediately to P2, or if P2==0
1708 ** raise an SQLITE_MISMATCH exception.
1709 */
1710 case OP_MustBeInt: {            /* jump, in1 */
1711   pIn1 = &aMem[pOp->p1];
1712   if( (pIn1->flags & MEM_Int)==0 ){
1713     applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
1714     VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
1715     if( (pIn1->flags & MEM_Int)==0 ){
1716       if( pOp->p2==0 ){
1717         rc = SQLITE_MISMATCH;
1718         goto abort_due_to_error;
1719       }else{
1720         pc = pOp->p2 - 1;
1721         break;
1722       }
1723     }
1724   }
1725   MemSetTypeFlag(pIn1, MEM_Int);
1726   break;
1727 }
1728 
1729 #ifndef SQLITE_OMIT_FLOATING_POINT
1730 /* Opcode: RealAffinity P1 * * * *
1731 **
1732 ** If register P1 holds an integer convert it to a real value.
1733 **
1734 ** This opcode is used when extracting information from a column that
1735 ** has REAL affinity.  Such column values may still be stored as
1736 ** integers, for space efficiency, but after extraction we want them
1737 ** to have only a real value.
1738 */
1739 case OP_RealAffinity: {                  /* in1 */
1740   pIn1 = &aMem[pOp->p1];
1741   if( pIn1->flags & MEM_Int ){
1742     sqlite3VdbeMemRealify(pIn1);
1743   }
1744   break;
1745 }
1746 #endif
1747 
1748 #ifndef SQLITE_OMIT_CAST
1749 /* Opcode: ToText P1 * * * *
1750 **
1751 ** Force the value in register P1 to be text.
1752 ** If the value is numeric, convert it to a string using the
1753 ** equivalent of sprintf().  Blob values are unchanged and
1754 ** are afterwards simply interpreted as text.
1755 **
1756 ** A NULL value is not changed by this routine.  It remains NULL.
1757 */
1758 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
1759   pIn1 = &aMem[pOp->p1];
1760   memAboutToChange(p, pIn1);
1761   if( pIn1->flags & MEM_Null ) break;
1762   assert( MEM_Str==(MEM_Blob>>3) );
1763   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
1764   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
1765   rc = ExpandBlob(pIn1);
1766   assert( pIn1->flags & MEM_Str || db->mallocFailed );
1767   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
1768   UPDATE_MAX_BLOBSIZE(pIn1);
1769   break;
1770 }
1771 
1772 /* Opcode: ToBlob P1 * * * *
1773 **
1774 ** Force the value in register P1 to be a BLOB.
1775 ** If the value is numeric, convert it to a string first.
1776 ** Strings are simply reinterpreted as blobs with no change
1777 ** to the underlying data.
1778 **
1779 ** A NULL value is not changed by this routine.  It remains NULL.
1780 */
1781 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
1782   pIn1 = &aMem[pOp->p1];
1783   if( pIn1->flags & MEM_Null ) break;
1784   if( (pIn1->flags & MEM_Blob)==0 ){
1785     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
1786     assert( pIn1->flags & MEM_Str || db->mallocFailed );
1787     MemSetTypeFlag(pIn1, MEM_Blob);
1788   }else{
1789     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
1790   }
1791   UPDATE_MAX_BLOBSIZE(pIn1);
1792   break;
1793 }
1794 
1795 /* Opcode: ToNumeric P1 * * * *
1796 **
1797 ** Force the value in register P1 to be numeric (either an
1798 ** integer or a floating-point number.)
1799 ** If the value is text or blob, try to convert it to an using the
1800 ** equivalent of atoi() or atof() and store 0 if no such conversion
1801 ** is possible.
1802 **
1803 ** A NULL value is not changed by this routine.  It remains NULL.
1804 */
1805 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
1806   pIn1 = &aMem[pOp->p1];
1807   sqlite3VdbeMemNumerify(pIn1);
1808   break;
1809 }
1810 #endif /* SQLITE_OMIT_CAST */
1811 
1812 /* Opcode: ToInt P1 * * * *
1813 **
1814 ** Force the value in register P1 to be an integer.  If
1815 ** The value is currently a real number, drop its fractional part.
1816 ** If the value is text or blob, try to convert it to an integer using the
1817 ** equivalent of atoi() and store 0 if no such conversion is possible.
1818 **
1819 ** A NULL value is not changed by this routine.  It remains NULL.
1820 */
1821 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
1822   pIn1 = &aMem[pOp->p1];
1823   if( (pIn1->flags & MEM_Null)==0 ){
1824     sqlite3VdbeMemIntegerify(pIn1);
1825   }
1826   break;
1827 }
1828 
1829 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
1830 /* Opcode: ToReal P1 * * * *
1831 **
1832 ** Force the value in register P1 to be a floating point number.
1833 ** If The value is currently an integer, convert it.
1834 ** If the value is text or blob, try to convert it to an integer using the
1835 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
1836 **
1837 ** A NULL value is not changed by this routine.  It remains NULL.
1838 */
1839 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
1840   pIn1 = &aMem[pOp->p1];
1841   memAboutToChange(p, pIn1);
1842   if( (pIn1->flags & MEM_Null)==0 ){
1843     sqlite3VdbeMemRealify(pIn1);
1844   }
1845   break;
1846 }
1847 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
1848 
1849 /* Opcode: Lt P1 P2 P3 P4 P5
1850 ** Synopsis: if r[P1]<r[P3] goto P2
1851 **
1852 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
1853 ** jump to address P2.
1854 **
1855 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
1856 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
1857 ** bit is clear then fall through if either operand is NULL.
1858 **
1859 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1860 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1861 ** to coerce both inputs according to this affinity before the
1862 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1863 ** affinity is used. Note that the affinity conversions are stored
1864 ** back into the input registers P1 and P3.  So this opcode can cause
1865 ** persistent changes to registers P1 and P3.
1866 **
1867 ** Once any conversions have taken place, and neither value is NULL,
1868 ** the values are compared. If both values are blobs then memcmp() is
1869 ** used to determine the results of the comparison.  If both values
1870 ** are text, then the appropriate collating function specified in
1871 ** P4 is  used to do the comparison.  If P4 is not specified then
1872 ** memcmp() is used to compare text string.  If both values are
1873 ** numeric, then a numeric comparison is used. If the two values
1874 ** are of different types, then numbers are considered less than
1875 ** strings and strings are considered less than blobs.
1876 **
1877 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
1878 ** store a boolean result (either 0, or 1, or NULL) in register P2.
1879 **
1880 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
1881 ** equal to one another, provided that they do not have their MEM_Cleared
1882 ** bit set.
1883 */
1884 /* Opcode: Ne P1 P2 P3 P4 P5
1885 ** Synopsis: if r[P1]!=r[P3] goto P2
1886 **
1887 ** This works just like the Lt opcode except that the jump is taken if
1888 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
1889 ** additional information.
1890 **
1891 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1892 ** true or false and is never NULL.  If both operands are NULL then the result
1893 ** of comparison is false.  If either operand is NULL then the result is true.
1894 ** If neither operand is NULL the result is the same as it would be if
1895 ** the SQLITE_NULLEQ flag were omitted from P5.
1896 */
1897 /* Opcode: Eq P1 P2 P3 P4 P5
1898 ** Synopsis: if r[P1]==r[P3] goto P2
1899 **
1900 ** This works just like the Lt opcode except that the jump is taken if
1901 ** the operands in registers P1 and P3 are equal.
1902 ** See the Lt opcode for additional information.
1903 **
1904 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1905 ** true or false and is never NULL.  If both operands are NULL then the result
1906 ** of comparison is true.  If either operand is NULL then the result is false.
1907 ** If neither operand is NULL the result is the same as it would be if
1908 ** the SQLITE_NULLEQ flag were omitted from P5.
1909 */
1910 /* Opcode: Le P1 P2 P3 P4 P5
1911 ** Synopsis: if r[P1]<=r[P3] goto P2
1912 **
1913 ** This works just like the Lt opcode except that the jump is taken if
1914 ** the content of register P3 is less than or equal to the content of
1915 ** register P1.  See the Lt opcode for additional information.
1916 */
1917 /* Opcode: Gt P1 P2 P3 P4 P5
1918 ** Synopsis: if r[P1]>r[P3] goto P2
1919 **
1920 ** This works just like the Lt opcode except that the jump is taken if
1921 ** the content of register P3 is greater than the content of
1922 ** register P1.  See the Lt opcode for additional information.
1923 */
1924 /* Opcode: Ge P1 P2 P3 P4 P5
1925 ** Synopsis: if r[P1]>=r[P3] goto P2
1926 **
1927 ** This works just like the Lt opcode except that the jump is taken if
1928 ** the content of register P3 is greater than or equal to the content of
1929 ** register P1.  See the Lt opcode for additional information.
1930 */
1931 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
1932 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
1933 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
1934 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
1935 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
1936 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
1937   int res;            /* Result of the comparison of pIn1 against pIn3 */
1938   char affinity;      /* Affinity to use for comparison */
1939   u16 flags1;         /* Copy of initial value of pIn1->flags */
1940   u16 flags3;         /* Copy of initial value of pIn3->flags */
1941 
1942   pIn1 = &aMem[pOp->p1];
1943   pIn3 = &aMem[pOp->p3];
1944   flags1 = pIn1->flags;
1945   flags3 = pIn3->flags;
1946   if( (flags1 | flags3)&MEM_Null ){
1947     /* One or both operands are NULL */
1948     if( pOp->p5 & SQLITE_NULLEQ ){
1949       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
1950       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
1951       ** or not both operands are null.
1952       */
1953       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
1954       assert( (flags1 & MEM_Cleared)==0 );
1955       assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
1956       if( (flags1&MEM_Null)!=0
1957        && (flags3&MEM_Null)!=0
1958        && (flags3&MEM_Cleared)==0
1959       ){
1960         res = 0;  /* Results are equal */
1961       }else{
1962         res = 1;  /* Results are not equal */
1963       }
1964     }else{
1965       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
1966       ** then the result is always NULL.
1967       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
1968       */
1969       if( pOp->p5 & SQLITE_STOREP2 ){
1970         pOut = &aMem[pOp->p2];
1971         MemSetTypeFlag(pOut, MEM_Null);
1972         REGISTER_TRACE(pOp->p2, pOut);
1973       }else{
1974         VdbeBranchTaken(2,3);
1975         if( pOp->p5 & SQLITE_JUMPIFNULL ){
1976           pc = pOp->p2-1;
1977         }
1978       }
1979       break;
1980     }
1981   }else{
1982     /* Neither operand is NULL.  Do a comparison. */
1983     affinity = pOp->p5 & SQLITE_AFF_MASK;
1984     if( affinity ){
1985       applyAffinity(pIn1, affinity, encoding);
1986       applyAffinity(pIn3, affinity, encoding);
1987       if( db->mallocFailed ) goto no_mem;
1988     }
1989 
1990     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
1991     ExpandBlob(pIn1);
1992     ExpandBlob(pIn3);
1993     res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
1994   }
1995   switch( pOp->opcode ){
1996     case OP_Eq:    res = res==0;     break;
1997     case OP_Ne:    res = res!=0;     break;
1998     case OP_Lt:    res = res<0;      break;
1999     case OP_Le:    res = res<=0;     break;
2000     case OP_Gt:    res = res>0;      break;
2001     default:       res = res>=0;     break;
2002   }
2003 
2004   if( pOp->p5 & SQLITE_STOREP2 ){
2005     pOut = &aMem[pOp->p2];
2006     memAboutToChange(p, pOut);
2007     MemSetTypeFlag(pOut, MEM_Int);
2008     pOut->u.i = res;
2009     REGISTER_TRACE(pOp->p2, pOut);
2010   }else{
2011     VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2012     if( res ){
2013       pc = pOp->p2-1;
2014     }
2015   }
2016   /* Undo any changes made by applyAffinity() to the input registers. */
2017   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (flags1&MEM_TypeMask);
2018   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (flags3&MEM_TypeMask);
2019   break;
2020 }
2021 
2022 /* Opcode: Permutation * * * P4 *
2023 **
2024 ** Set the permutation used by the OP_Compare operator to be the array
2025 ** of integers in P4.
2026 **
2027 ** The permutation is only valid until the next OP_Compare that has
2028 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
2029 ** occur immediately prior to the OP_Compare.
2030 */
2031 case OP_Permutation: {
2032   assert( pOp->p4type==P4_INTARRAY );
2033   assert( pOp->p4.ai );
2034   aPermute = pOp->p4.ai;
2035   break;
2036 }
2037 
2038 /* Opcode: Compare P1 P2 P3 P4 P5
2039 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2040 **
2041 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2042 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
2043 ** the comparison for use by the next OP_Jump instruct.
2044 **
2045 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2046 ** determined by the most recent OP_Permutation operator.  If the
2047 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2048 ** order.
2049 **
2050 ** P4 is a KeyInfo structure that defines collating sequences and sort
2051 ** orders for the comparison.  The permutation applies to registers
2052 ** only.  The KeyInfo elements are used sequentially.
2053 **
2054 ** The comparison is a sort comparison, so NULLs compare equal,
2055 ** NULLs are less than numbers, numbers are less than strings,
2056 ** and strings are less than blobs.
2057 */
2058 case OP_Compare: {
2059   int n;
2060   int i;
2061   int p1;
2062   int p2;
2063   const KeyInfo *pKeyInfo;
2064   int idx;
2065   CollSeq *pColl;    /* Collating sequence to use on this term */
2066   int bRev;          /* True for DESCENDING sort order */
2067 
2068   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
2069   n = pOp->p3;
2070   pKeyInfo = pOp->p4.pKeyInfo;
2071   assert( n>0 );
2072   assert( pKeyInfo!=0 );
2073   p1 = pOp->p1;
2074   p2 = pOp->p2;
2075 #if SQLITE_DEBUG
2076   if( aPermute ){
2077     int k, mx = 0;
2078     for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
2079     assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
2080     assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
2081   }else{
2082     assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
2083     assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
2084   }
2085 #endif /* SQLITE_DEBUG */
2086   for(i=0; i<n; i++){
2087     idx = aPermute ? aPermute[i] : i;
2088     assert( memIsValid(&aMem[p1+idx]) );
2089     assert( memIsValid(&aMem[p2+idx]) );
2090     REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
2091     REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
2092     assert( i<pKeyInfo->nField );
2093     pColl = pKeyInfo->aColl[i];
2094     bRev = pKeyInfo->aSortOrder[i];
2095     iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
2096     if( iCompare ){
2097       if( bRev ) iCompare = -iCompare;
2098       break;
2099     }
2100   }
2101   aPermute = 0;
2102   break;
2103 }
2104 
2105 /* Opcode: Jump P1 P2 P3 * *
2106 **
2107 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2108 ** in the most recent OP_Compare instruction the P1 vector was less than
2109 ** equal to, or greater than the P2 vector, respectively.
2110 */
2111 case OP_Jump: {             /* jump */
2112   if( iCompare<0 ){
2113     pc = pOp->p1 - 1;  VdbeBranchTaken(0,3);
2114   }else if( iCompare==0 ){
2115     pc = pOp->p2 - 1;  VdbeBranchTaken(1,3);
2116   }else{
2117     pc = pOp->p3 - 1;  VdbeBranchTaken(2,3);
2118   }
2119   break;
2120 }
2121 
2122 /* Opcode: And P1 P2 P3 * *
2123 ** Synopsis: r[P3]=(r[P1] && r[P2])
2124 **
2125 ** Take the logical AND of the values in registers P1 and P2 and
2126 ** write the result into register P3.
2127 **
2128 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2129 ** the other input is NULL.  A NULL and true or two NULLs give
2130 ** a NULL output.
2131 */
2132 /* Opcode: Or P1 P2 P3 * *
2133 ** Synopsis: r[P3]=(r[P1] || r[P2])
2134 **
2135 ** Take the logical OR of the values in register P1 and P2 and
2136 ** store the answer in register P3.
2137 **
2138 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2139 ** even if the other input is NULL.  A NULL and false or two NULLs
2140 ** give a NULL output.
2141 */
2142 case OP_And:              /* same as TK_AND, in1, in2, out3 */
2143 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
2144   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2145   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2146 
2147   pIn1 = &aMem[pOp->p1];
2148   if( pIn1->flags & MEM_Null ){
2149     v1 = 2;
2150   }else{
2151     v1 = sqlite3VdbeIntValue(pIn1)!=0;
2152   }
2153   pIn2 = &aMem[pOp->p2];
2154   if( pIn2->flags & MEM_Null ){
2155     v2 = 2;
2156   }else{
2157     v2 = sqlite3VdbeIntValue(pIn2)!=0;
2158   }
2159   if( pOp->opcode==OP_And ){
2160     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2161     v1 = and_logic[v1*3+v2];
2162   }else{
2163     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2164     v1 = or_logic[v1*3+v2];
2165   }
2166   pOut = &aMem[pOp->p3];
2167   if( v1==2 ){
2168     MemSetTypeFlag(pOut, MEM_Null);
2169   }else{
2170     pOut->u.i = v1;
2171     MemSetTypeFlag(pOut, MEM_Int);
2172   }
2173   break;
2174 }
2175 
2176 /* Opcode: Not P1 P2 * * *
2177 ** Synopsis: r[P2]= !r[P1]
2178 **
2179 ** Interpret the value in register P1 as a boolean value.  Store the
2180 ** boolean complement in register P2.  If the value in register P1 is
2181 ** NULL, then a NULL is stored in P2.
2182 */
2183 case OP_Not: {                /* same as TK_NOT, in1, out2 */
2184   pIn1 = &aMem[pOp->p1];
2185   pOut = &aMem[pOp->p2];
2186   if( pIn1->flags & MEM_Null ){
2187     sqlite3VdbeMemSetNull(pOut);
2188   }else{
2189     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
2190   }
2191   break;
2192 }
2193 
2194 /* Opcode: BitNot P1 P2 * * *
2195 ** Synopsis: r[P1]= ~r[P1]
2196 **
2197 ** Interpret the content of register P1 as an integer.  Store the
2198 ** ones-complement of the P1 value into register P2.  If P1 holds
2199 ** a NULL then store a NULL in P2.
2200 */
2201 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
2202   pIn1 = &aMem[pOp->p1];
2203   pOut = &aMem[pOp->p2];
2204   if( pIn1->flags & MEM_Null ){
2205     sqlite3VdbeMemSetNull(pOut);
2206   }else{
2207     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
2208   }
2209   break;
2210 }
2211 
2212 /* Opcode: Once P1 P2 * * *
2213 **
2214 ** Check the "once" flag number P1. If it is set, jump to instruction P2.
2215 ** Otherwise, set the flag and fall through to the next instruction.
2216 ** In other words, this opcode causes all following opcodes up through P2
2217 ** (but not including P2) to run just once and to be skipped on subsequent
2218 ** times through the loop.
2219 **
2220 ** All "once" flags are initially cleared whenever a prepared statement
2221 ** first begins to run.
2222 */
2223 case OP_Once: {             /* jump */
2224   assert( pOp->p1<p->nOnceFlag );
2225   VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
2226   if( p->aOnceFlag[pOp->p1] ){
2227     pc = pOp->p2-1;
2228   }else{
2229     p->aOnceFlag[pOp->p1] = 1;
2230   }
2231   break;
2232 }
2233 
2234 /* Opcode: If P1 P2 P3 * *
2235 **
2236 ** Jump to P2 if the value in register P1 is true.  The value
2237 ** is considered true if it is numeric and non-zero.  If the value
2238 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2239 */
2240 /* Opcode: IfNot P1 P2 P3 * *
2241 **
2242 ** Jump to P2 if the value in register P1 is False.  The value
2243 ** is considered false if it has a numeric value of zero.  If the value
2244 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2245 */
2246 case OP_If:                 /* jump, in1 */
2247 case OP_IfNot: {            /* jump, in1 */
2248   int c;
2249   pIn1 = &aMem[pOp->p1];
2250   if( pIn1->flags & MEM_Null ){
2251     c = pOp->p3;
2252   }else{
2253 #ifdef SQLITE_OMIT_FLOATING_POINT
2254     c = sqlite3VdbeIntValue(pIn1)!=0;
2255 #else
2256     c = sqlite3VdbeRealValue(pIn1)!=0.0;
2257 #endif
2258     if( pOp->opcode==OP_IfNot ) c = !c;
2259   }
2260   VdbeBranchTaken(c!=0, 2);
2261   if( c ){
2262     pc = pOp->p2-1;
2263   }
2264   break;
2265 }
2266 
2267 /* Opcode: IsNull P1 P2 * * *
2268 ** Synopsis:  if r[P1]==NULL goto P2
2269 **
2270 ** Jump to P2 if the value in register P1 is NULL.
2271 */
2272 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
2273   pIn1 = &aMem[pOp->p1];
2274   VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
2275   if( (pIn1->flags & MEM_Null)!=0 ){
2276     pc = pOp->p2 - 1;
2277   }
2278   break;
2279 }
2280 
2281 /* Opcode: NotNull P1 P2 * * *
2282 ** Synopsis: if r[P1]!=NULL goto P2
2283 **
2284 ** Jump to P2 if the value in register P1 is not NULL.
2285 */
2286 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
2287   pIn1 = &aMem[pOp->p1];
2288   VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
2289   if( (pIn1->flags & MEM_Null)==0 ){
2290     pc = pOp->p2 - 1;
2291   }
2292   break;
2293 }
2294 
2295 /* Opcode: Column P1 P2 P3 P4 P5
2296 ** Synopsis:  r[P3]=PX
2297 **
2298 ** Interpret the data that cursor P1 points to as a structure built using
2299 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
2300 ** information about the format of the data.)  Extract the P2-th column
2301 ** from this record.  If there are less that (P2+1)
2302 ** values in the record, extract a NULL.
2303 **
2304 ** The value extracted is stored in register P3.
2305 **
2306 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
2307 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2308 ** the result.
2309 **
2310 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
2311 ** then the cache of the cursor is reset prior to extracting the column.
2312 ** The first OP_Column against a pseudo-table after the value of the content
2313 ** register has changed should have this bit set.
2314 **
2315 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
2316 ** the result is guaranteed to only be used as the argument of a length()
2317 ** or typeof() function, respectively.  The loading of large blobs can be
2318 ** skipped for length() and all content loading can be skipped for typeof().
2319 */
2320 case OP_Column: {
2321   i64 payloadSize64; /* Number of bytes in the record */
2322   int p2;            /* column number to retrieve */
2323   VdbeCursor *pC;    /* The VDBE cursor */
2324   BtCursor *pCrsr;   /* The BTree cursor */
2325   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
2326   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
2327   int len;           /* The length of the serialized data for the column */
2328   int i;             /* Loop counter */
2329   Mem *pDest;        /* Where to write the extracted value */
2330   Mem sMem;          /* For storing the record being decoded */
2331   const u8 *zData;   /* Part of the record being decoded */
2332   const u8 *zHdr;    /* Next unparsed byte of the header */
2333   const u8 *zEndHdr; /* Pointer to first byte after the header */
2334   u32 offset;        /* Offset into the data */
2335   u32 szField;       /* Number of bytes in the content of a field */
2336   u32 avail;         /* Number of bytes of available data */
2337   u32 t;             /* A type code from the record header */
2338   Mem *pReg;         /* PseudoTable input register */
2339 
2340   p2 = pOp->p2;
2341   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
2342   pDest = &aMem[pOp->p3];
2343   memAboutToChange(p, pDest);
2344   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2345   pC = p->apCsr[pOp->p1];
2346   assert( pC!=0 );
2347   assert( p2<pC->nField );
2348   aType = pC->aType;
2349   aOffset = aType + pC->nField;
2350 #ifndef SQLITE_OMIT_VIRTUALTABLE
2351   assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
2352 #endif
2353   pCrsr = pC->pCursor;
2354   assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
2355   assert( pCrsr!=0 || pC->nullRow );          /* pC->nullRow on PseudoTables */
2356 
2357   /* If the cursor cache is stale, bring it up-to-date */
2358   rc = sqlite3VdbeCursorMoveto(pC);
2359   if( rc ) goto abort_due_to_error;
2360   if( pC->cacheStatus!=p->cacheCtr || (pOp->p5&OPFLAG_CLEARCACHE)!=0 ){
2361     if( pC->nullRow ){
2362       if( pCrsr==0 ){
2363         assert( pC->pseudoTableReg>0 );
2364         pReg = &aMem[pC->pseudoTableReg];
2365         assert( pReg->flags & MEM_Blob );
2366         assert( memIsValid(pReg) );
2367         pC->payloadSize = pC->szRow = avail = pReg->n;
2368         pC->aRow = (u8*)pReg->z;
2369       }else{
2370         MemSetTypeFlag(pDest, MEM_Null);
2371         goto op_column_out;
2372       }
2373     }else{
2374       assert( pCrsr );
2375       if( pC->isTable==0 ){
2376         assert( sqlite3BtreeCursorIsValid(pCrsr) );
2377         VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
2378         assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
2379         /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
2380         ** payload size, so it is impossible for payloadSize64 to be
2381         ** larger than 32 bits. */
2382         assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
2383         pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
2384         pC->payloadSize = (u32)payloadSize64;
2385       }else{
2386         assert( sqlite3BtreeCursorIsValid(pCrsr) );
2387         VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
2388         assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
2389         pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
2390       }
2391       assert( avail<=65536 );  /* Maximum page size is 64KiB */
2392       if( pC->payloadSize <= (u32)avail ){
2393         pC->szRow = pC->payloadSize;
2394       }else{
2395         pC->szRow = avail;
2396       }
2397       if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
2398         goto too_big;
2399       }
2400     }
2401     pC->cacheStatus = p->cacheCtr;
2402     pC->iHdrOffset = getVarint32(pC->aRow, offset);
2403     pC->nHdrParsed = 0;
2404     aOffset[0] = offset;
2405     if( avail<offset ){
2406       /* pC->aRow does not have to hold the entire row, but it does at least
2407       ** need to cover the header of the record.  If pC->aRow does not contain
2408       ** the complete header, then set it to zero, forcing the header to be
2409       ** dynamically allocated. */
2410       pC->aRow = 0;
2411       pC->szRow = 0;
2412     }
2413 
2414     /* Make sure a corrupt database has not given us an oversize header.
2415     ** Do this now to avoid an oversize memory allocation.
2416     **
2417     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
2418     ** types use so much data space that there can only be 4096 and 32 of
2419     ** them, respectively.  So the maximum header length results from a
2420     ** 3-byte type for each of the maximum of 32768 columns plus three
2421     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
2422     */
2423     if( offset > 98307 || offset > pC->payloadSize ){
2424       rc = SQLITE_CORRUPT_BKPT;
2425       goto op_column_error;
2426     }
2427   }
2428 
2429   /* Make sure at least the first p2+1 entries of the header have been
2430   ** parsed and valid information is in aOffset[] and aType[].
2431   */
2432   if( pC->nHdrParsed<=p2 ){
2433     /* If there is more header available for parsing in the record, try
2434     ** to extract additional fields up through the p2+1-th field
2435     */
2436     if( pC->iHdrOffset<aOffset[0] ){
2437       /* Make sure zData points to enough of the record to cover the header. */
2438       if( pC->aRow==0 ){
2439         memset(&sMem, 0, sizeof(sMem));
2440         rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
2441                                      !pC->isTable, &sMem);
2442         if( rc!=SQLITE_OK ){
2443           goto op_column_error;
2444         }
2445         zData = (u8*)sMem.z;
2446       }else{
2447         zData = pC->aRow;
2448       }
2449 
2450       /* Fill in aType[i] and aOffset[i] values through the p2-th field. */
2451       i = pC->nHdrParsed;
2452       offset = aOffset[i];
2453       zHdr = zData + pC->iHdrOffset;
2454       zEndHdr = zData + aOffset[0];
2455       assert( i<=p2 && zHdr<zEndHdr );
2456       do{
2457         if( zHdr[0]<0x80 ){
2458           t = zHdr[0];
2459           zHdr++;
2460         }else{
2461           zHdr += sqlite3GetVarint32(zHdr, &t);
2462         }
2463         aType[i] = t;
2464         szField = sqlite3VdbeSerialTypeLen(t);
2465         offset += szField;
2466         if( offset<szField ){  /* True if offset overflows */
2467           zHdr = &zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
2468           break;
2469         }
2470         i++;
2471         aOffset[i] = offset;
2472       }while( i<=p2 && zHdr<zEndHdr );
2473       pC->nHdrParsed = i;
2474       pC->iHdrOffset = (u32)(zHdr - zData);
2475       if( pC->aRow==0 ){
2476         sqlite3VdbeMemRelease(&sMem);
2477         sMem.flags = MEM_Null;
2478       }
2479 
2480       /* If we have read more header data than was contained in the header,
2481       ** or if the end of the last field appears to be past the end of the
2482       ** record, or if the end of the last field appears to be before the end
2483       ** of the record (when all fields present), then we must be dealing
2484       ** with a corrupt database.
2485       */
2486       if( (zHdr > zEndHdr)
2487        || (offset > pC->payloadSize)
2488        || (zHdr==zEndHdr && offset!=pC->payloadSize)
2489       ){
2490         rc = SQLITE_CORRUPT_BKPT;
2491         goto op_column_error;
2492       }
2493     }
2494 
2495     /* If after trying to extra new entries from the header, nHdrParsed is
2496     ** still not up to p2, that means that the record has fewer than p2
2497     ** columns.  So the result will be either the default value or a NULL.
2498     */
2499     if( pC->nHdrParsed<=p2 ){
2500       if( pOp->p4type==P4_MEM ){
2501         sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
2502       }else{
2503         MemSetTypeFlag(pDest, MEM_Null);
2504       }
2505       goto op_column_out;
2506     }
2507   }
2508 
2509   /* Extract the content for the p2+1-th column.  Control can only
2510   ** reach this point if aOffset[p2], aOffset[p2+1], and aType[p2] are
2511   ** all valid.
2512   */
2513   assert( p2<pC->nHdrParsed );
2514   assert( rc==SQLITE_OK );
2515   assert( sqlite3VdbeCheckMemInvariants(pDest) );
2516   if( pC->szRow>=aOffset[p2+1] ){
2517     /* This is the common case where the desired content fits on the original
2518     ** page - where the content is not on an overflow page */
2519     VdbeMemRelease(pDest);
2520     sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], aType[p2], pDest);
2521   }else{
2522     /* This branch happens only when content is on overflow pages */
2523     t = aType[p2];
2524     if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
2525           && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
2526      || (len = sqlite3VdbeSerialTypeLen(t))==0
2527     ){
2528       /* Content is irrelevant for the typeof() function and for
2529       ** the length(X) function if X is a blob.  So we might as well use
2530       ** bogus content rather than reading content from disk.  NULL works
2531       ** for text and blob and whatever is in the payloadSize64 variable
2532       ** will work for everything else.  Content is also irrelevant if
2533       ** the content length is 0. */
2534       zData = t<=13 ? (u8*)&payloadSize64 : 0;
2535       sMem.zMalloc = 0;
2536     }else{
2537       memset(&sMem, 0, sizeof(sMem));
2538       sqlite3VdbeMemMove(&sMem, pDest);
2539       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
2540                                    &sMem);
2541       if( rc!=SQLITE_OK ){
2542         goto op_column_error;
2543       }
2544       zData = (u8*)sMem.z;
2545     }
2546     sqlite3VdbeSerialGet(zData, t, pDest);
2547     /* If we dynamically allocated space to hold the data (in the
2548     ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
2549     ** dynamically allocated space over to the pDest structure.
2550     ** This prevents a memory copy. */
2551     if( sMem.zMalloc ){
2552       assert( sMem.z==sMem.zMalloc );
2553       assert( VdbeMemDynamic(pDest)==0 );
2554       assert( (pDest->flags & (MEM_Blob|MEM_Str))==0 || pDest->z==sMem.z );
2555       pDest->flags &= ~(MEM_Ephem|MEM_Static);
2556       pDest->flags |= MEM_Term;
2557       pDest->z = sMem.z;
2558       pDest->zMalloc = sMem.zMalloc;
2559     }
2560   }
2561   pDest->enc = encoding;
2562 
2563 op_column_out:
2564   Deephemeralize(pDest);
2565 op_column_error:
2566   UPDATE_MAX_BLOBSIZE(pDest);
2567   REGISTER_TRACE(pOp->p3, pDest);
2568   break;
2569 }
2570 
2571 /* Opcode: Affinity P1 P2 * P4 *
2572 ** Synopsis: affinity(r[P1@P2])
2573 **
2574 ** Apply affinities to a range of P2 registers starting with P1.
2575 **
2576 ** P4 is a string that is P2 characters long. The nth character of the
2577 ** string indicates the column affinity that should be used for the nth
2578 ** memory cell in the range.
2579 */
2580 case OP_Affinity: {
2581   const char *zAffinity;   /* The affinity to be applied */
2582   char cAff;               /* A single character of affinity */
2583 
2584   zAffinity = pOp->p4.z;
2585   assert( zAffinity!=0 );
2586   assert( zAffinity[pOp->p2]==0 );
2587   pIn1 = &aMem[pOp->p1];
2588   while( (cAff = *(zAffinity++))!=0 ){
2589     assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
2590     assert( memIsValid(pIn1) );
2591     applyAffinity(pIn1, cAff, encoding);
2592     pIn1++;
2593   }
2594   break;
2595 }
2596 
2597 /* Opcode: MakeRecord P1 P2 P3 P4 *
2598 ** Synopsis: r[P3]=mkrec(r[P1@P2])
2599 **
2600 ** Convert P2 registers beginning with P1 into the [record format]
2601 ** use as a data record in a database table or as a key
2602 ** in an index.  The OP_Column opcode can decode the record later.
2603 **
2604 ** P4 may be a string that is P2 characters long.  The nth character of the
2605 ** string indicates the column affinity that should be used for the nth
2606 ** field of the index key.
2607 **
2608 ** The mapping from character to affinity is given by the SQLITE_AFF_
2609 ** macros defined in sqliteInt.h.
2610 **
2611 ** If P4 is NULL then all index fields have the affinity NONE.
2612 */
2613 case OP_MakeRecord: {
2614   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
2615   Mem *pRec;             /* The new record */
2616   u64 nData;             /* Number of bytes of data space */
2617   int nHdr;              /* Number of bytes of header space */
2618   i64 nByte;             /* Data space required for this record */
2619   int nZero;             /* Number of zero bytes at the end of the record */
2620   int nVarint;           /* Number of bytes in a varint */
2621   u32 serial_type;       /* Type field */
2622   Mem *pData0;           /* First field to be combined into the record */
2623   Mem *pLast;            /* Last field of the record */
2624   int nField;            /* Number of fields in the record */
2625   char *zAffinity;       /* The affinity string for the record */
2626   int file_format;       /* File format to use for encoding */
2627   int i;                 /* Space used in zNewRecord[] header */
2628   int j;                 /* Space used in zNewRecord[] content */
2629   int len;               /* Length of a field */
2630 
2631   /* Assuming the record contains N fields, the record format looks
2632   ** like this:
2633   **
2634   ** ------------------------------------------------------------------------
2635   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2636   ** ------------------------------------------------------------------------
2637   **
2638   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
2639   ** and so froth.
2640   **
2641   ** Each type field is a varint representing the serial type of the
2642   ** corresponding data element (see sqlite3VdbeSerialType()). The
2643   ** hdr-size field is also a varint which is the offset from the beginning
2644   ** of the record to data0.
2645   */
2646   nData = 0;         /* Number of bytes of data space */
2647   nHdr = 0;          /* Number of bytes of header space */
2648   nZero = 0;         /* Number of zero bytes at the end of the record */
2649   nField = pOp->p1;
2650   zAffinity = pOp->p4.z;
2651   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
2652   pData0 = &aMem[nField];
2653   nField = pOp->p2;
2654   pLast = &pData0[nField-1];
2655   file_format = p->minWriteFileFormat;
2656 
2657   /* Identify the output register */
2658   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
2659   pOut = &aMem[pOp->p3];
2660   memAboutToChange(p, pOut);
2661 
2662   /* Apply the requested affinity to all inputs
2663   */
2664   assert( pData0<=pLast );
2665   if( zAffinity ){
2666     pRec = pData0;
2667     do{
2668       applyAffinity(pRec++, *(zAffinity++), encoding);
2669       assert( zAffinity[0]==0 || pRec<=pLast );
2670     }while( zAffinity[0] );
2671   }
2672 
2673   /* Loop through the elements that will make up the record to figure
2674   ** out how much space is required for the new record.
2675   */
2676   pRec = pLast;
2677   do{
2678     assert( memIsValid(pRec) );
2679     serial_type = sqlite3VdbeSerialType(pRec, file_format);
2680     len = sqlite3VdbeSerialTypeLen(serial_type);
2681     if( pRec->flags & MEM_Zero ){
2682       if( nData ){
2683         sqlite3VdbeMemExpandBlob(pRec);
2684       }else{
2685         nZero += pRec->u.nZero;
2686         len -= pRec->u.nZero;
2687       }
2688     }
2689     nData += len;
2690     testcase( serial_type==127 );
2691     testcase( serial_type==128 );
2692     nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
2693   }while( (--pRec)>=pData0 );
2694 
2695   /* Add the initial header varint and total the size */
2696   testcase( nHdr==126 );
2697   testcase( nHdr==127 );
2698   if( nHdr<=126 ){
2699     /* The common case */
2700     nHdr += 1;
2701   }else{
2702     /* Rare case of a really large header */
2703     nVarint = sqlite3VarintLen(nHdr);
2704     nHdr += nVarint;
2705     if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
2706   }
2707   nByte = nHdr+nData;
2708   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
2709     goto too_big;
2710   }
2711 
2712   /* Make sure the output register has a buffer large enough to store
2713   ** the new record. The output register (pOp->p3) is not allowed to
2714   ** be one of the input registers (because the following call to
2715   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
2716   */
2717   if( sqlite3VdbeMemGrow(pOut, (int)nByte, 0) ){
2718     goto no_mem;
2719   }
2720   zNewRecord = (u8 *)pOut->z;
2721 
2722   /* Write the record */
2723   i = putVarint32(zNewRecord, nHdr);
2724   j = nHdr;
2725   assert( pData0<=pLast );
2726   pRec = pData0;
2727   do{
2728     serial_type = sqlite3VdbeSerialType(pRec, file_format);
2729     i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
2730     j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
2731   }while( (++pRec)<=pLast );
2732   assert( i==nHdr );
2733   assert( j==nByte );
2734 
2735   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
2736   pOut->n = (int)nByte;
2737   pOut->flags = MEM_Blob;
2738   pOut->xDel = 0;
2739   if( nZero ){
2740     pOut->u.nZero = nZero;
2741     pOut->flags |= MEM_Zero;
2742   }
2743   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
2744   REGISTER_TRACE(pOp->p3, pOut);
2745   UPDATE_MAX_BLOBSIZE(pOut);
2746   break;
2747 }
2748 
2749 /* Opcode: Count P1 P2 * * *
2750 ** Synopsis: r[P2]=count()
2751 **
2752 ** Store the number of entries (an integer value) in the table or index
2753 ** opened by cursor P1 in register P2
2754 */
2755 #ifndef SQLITE_OMIT_BTREECOUNT
2756 case OP_Count: {         /* out2-prerelease */
2757   i64 nEntry;
2758   BtCursor *pCrsr;
2759 
2760   pCrsr = p->apCsr[pOp->p1]->pCursor;
2761   assert( pCrsr );
2762   nEntry = 0;  /* Not needed.  Only used to silence a warning. */
2763   rc = sqlite3BtreeCount(pCrsr, &nEntry);
2764   pOut->u.i = nEntry;
2765   break;
2766 }
2767 #endif
2768 
2769 /* Opcode: Savepoint P1 * * P4 *
2770 **
2771 ** Open, release or rollback the savepoint named by parameter P4, depending
2772 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
2773 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
2774 */
2775 case OP_Savepoint: {
2776   int p1;                         /* Value of P1 operand */
2777   char *zName;                    /* Name of savepoint */
2778   int nName;
2779   Savepoint *pNew;
2780   Savepoint *pSavepoint;
2781   Savepoint *pTmp;
2782   int iSavepoint;
2783   int ii;
2784 
2785   p1 = pOp->p1;
2786   zName = pOp->p4.z;
2787 
2788   /* Assert that the p1 parameter is valid. Also that if there is no open
2789   ** transaction, then there cannot be any savepoints.
2790   */
2791   assert( db->pSavepoint==0 || db->autoCommit==0 );
2792   assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
2793   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
2794   assert( checkSavepointCount(db) );
2795   assert( p->bIsReader );
2796 
2797   if( p1==SAVEPOINT_BEGIN ){
2798     if( db->nVdbeWrite>0 ){
2799       /* A new savepoint cannot be created if there are active write
2800       ** statements (i.e. open read/write incremental blob handles).
2801       */
2802       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
2803         "SQL statements in progress");
2804       rc = SQLITE_BUSY;
2805     }else{
2806       nName = sqlite3Strlen30(zName);
2807 
2808 #ifndef SQLITE_OMIT_VIRTUALTABLE
2809       /* This call is Ok even if this savepoint is actually a transaction
2810       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
2811       ** If this is a transaction savepoint being opened, it is guaranteed
2812       ** that the db->aVTrans[] array is empty.  */
2813       assert( db->autoCommit==0 || db->nVTrans==0 );
2814       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
2815                                 db->nStatement+db->nSavepoint);
2816       if( rc!=SQLITE_OK ) goto abort_due_to_error;
2817 #endif
2818 
2819       /* Create a new savepoint structure. */
2820       pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
2821       if( pNew ){
2822         pNew->zName = (char *)&pNew[1];
2823         memcpy(pNew->zName, zName, nName+1);
2824 
2825         /* If there is no open transaction, then mark this as a special
2826         ** "transaction savepoint". */
2827         if( db->autoCommit ){
2828           db->autoCommit = 0;
2829           db->isTransactionSavepoint = 1;
2830         }else{
2831           db->nSavepoint++;
2832         }
2833 
2834         /* Link the new savepoint into the database handle's list. */
2835         pNew->pNext = db->pSavepoint;
2836         db->pSavepoint = pNew;
2837         pNew->nDeferredCons = db->nDeferredCons;
2838         pNew->nDeferredImmCons = db->nDeferredImmCons;
2839       }
2840     }
2841   }else{
2842     iSavepoint = 0;
2843 
2844     /* Find the named savepoint. If there is no such savepoint, then an
2845     ** an error is returned to the user.  */
2846     for(
2847       pSavepoint = db->pSavepoint;
2848       pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
2849       pSavepoint = pSavepoint->pNext
2850     ){
2851       iSavepoint++;
2852     }
2853     if( !pSavepoint ){
2854       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
2855       rc = SQLITE_ERROR;
2856     }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
2857       /* It is not possible to release (commit) a savepoint if there are
2858       ** active write statements.
2859       */
2860       sqlite3SetString(&p->zErrMsg, db,
2861         "cannot release savepoint - SQL statements in progress"
2862       );
2863       rc = SQLITE_BUSY;
2864     }else{
2865 
2866       /* Determine whether or not this is a transaction savepoint. If so,
2867       ** and this is a RELEASE command, then the current transaction
2868       ** is committed.
2869       */
2870       int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
2871       if( isTransaction && p1==SAVEPOINT_RELEASE ){
2872         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
2873           goto vdbe_return;
2874         }
2875         db->autoCommit = 1;
2876         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
2877           p->pc = pc;
2878           db->autoCommit = 0;
2879           p->rc = rc = SQLITE_BUSY;
2880           goto vdbe_return;
2881         }
2882         db->isTransactionSavepoint = 0;
2883         rc = p->rc;
2884       }else{
2885         iSavepoint = db->nSavepoint - iSavepoint - 1;
2886         if( p1==SAVEPOINT_ROLLBACK ){
2887           for(ii=0; ii<db->nDb; ii++){
2888             sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, SQLITE_ABORT);
2889           }
2890         }
2891         for(ii=0; ii<db->nDb; ii++){
2892           rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
2893           if( rc!=SQLITE_OK ){
2894             goto abort_due_to_error;
2895           }
2896         }
2897         if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
2898           sqlite3ExpirePreparedStatements(db);
2899           sqlite3ResetAllSchemasOfConnection(db);
2900           db->flags = (db->flags | SQLITE_InternChanges);
2901         }
2902       }
2903 
2904       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
2905       ** savepoints nested inside of the savepoint being operated on. */
2906       while( db->pSavepoint!=pSavepoint ){
2907         pTmp = db->pSavepoint;
2908         db->pSavepoint = pTmp->pNext;
2909         sqlite3DbFree(db, pTmp);
2910         db->nSavepoint--;
2911       }
2912 
2913       /* If it is a RELEASE, then destroy the savepoint being operated on
2914       ** too. If it is a ROLLBACK TO, then set the number of deferred
2915       ** constraint violations present in the database to the value stored
2916       ** when the savepoint was created.  */
2917       if( p1==SAVEPOINT_RELEASE ){
2918         assert( pSavepoint==db->pSavepoint );
2919         db->pSavepoint = pSavepoint->pNext;
2920         sqlite3DbFree(db, pSavepoint);
2921         if( !isTransaction ){
2922           db->nSavepoint--;
2923         }
2924       }else{
2925         db->nDeferredCons = pSavepoint->nDeferredCons;
2926         db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
2927       }
2928 
2929       if( !isTransaction ){
2930         rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
2931         if( rc!=SQLITE_OK ) goto abort_due_to_error;
2932       }
2933     }
2934   }
2935 
2936   break;
2937 }
2938 
2939 /* Opcode: AutoCommit P1 P2 * * *
2940 **
2941 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
2942 ** back any currently active btree transactions. If there are any active
2943 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
2944 ** there are active writing VMs or active VMs that use shared cache.
2945 **
2946 ** This instruction causes the VM to halt.
2947 */
2948 case OP_AutoCommit: {
2949   int desiredAutoCommit;
2950   int iRollback;
2951   int turnOnAC;
2952 
2953   desiredAutoCommit = pOp->p1;
2954   iRollback = pOp->p2;
2955   turnOnAC = desiredAutoCommit && !db->autoCommit;
2956   assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
2957   assert( desiredAutoCommit==1 || iRollback==0 );
2958   assert( db->nVdbeActive>0 );  /* At least this one VM is active */
2959   assert( p->bIsReader );
2960 
2961 #if 0
2962   if( turnOnAC && iRollback && db->nVdbeActive>1 ){
2963     /* If this instruction implements a ROLLBACK and other VMs are
2964     ** still running, and a transaction is active, return an error indicating
2965     ** that the other VMs must complete first.
2966     */
2967     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
2968         "SQL statements in progress");
2969     rc = SQLITE_BUSY;
2970   }else
2971 #endif
2972   if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
2973     /* If this instruction implements a COMMIT and other VMs are writing
2974     ** return an error indicating that the other VMs must complete first.
2975     */
2976     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
2977         "SQL statements in progress");
2978     rc = SQLITE_BUSY;
2979   }else if( desiredAutoCommit!=db->autoCommit ){
2980     if( iRollback ){
2981       assert( desiredAutoCommit==1 );
2982       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2983       db->autoCommit = 1;
2984     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
2985       goto vdbe_return;
2986     }else{
2987       db->autoCommit = (u8)desiredAutoCommit;
2988       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
2989         p->pc = pc;
2990         db->autoCommit = (u8)(1-desiredAutoCommit);
2991         p->rc = rc = SQLITE_BUSY;
2992         goto vdbe_return;
2993       }
2994     }
2995     assert( db->nStatement==0 );
2996     sqlite3CloseSavepoints(db);
2997     if( p->rc==SQLITE_OK ){
2998       rc = SQLITE_DONE;
2999     }else{
3000       rc = SQLITE_ERROR;
3001     }
3002     goto vdbe_return;
3003   }else{
3004     sqlite3SetString(&p->zErrMsg, db,
3005         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3006         (iRollback)?"cannot rollback - no transaction is active":
3007                    "cannot commit - no transaction is active"));
3008 
3009     rc = SQLITE_ERROR;
3010   }
3011   break;
3012 }
3013 
3014 /* Opcode: Transaction P1 P2 P3 P4 P5
3015 **
3016 ** Begin a transaction on database P1 if a transaction is not already
3017 ** active.
3018 ** If P2 is non-zero, then a write-transaction is started, or if a
3019 ** read-transaction is already active, it is upgraded to a write-transaction.
3020 ** If P2 is zero, then a read-transaction is started.
3021 **
3022 ** P1 is the index of the database file on which the transaction is
3023 ** started.  Index 0 is the main database file and index 1 is the
3024 ** file used for temporary tables.  Indices of 2 or more are used for
3025 ** attached databases.
3026 **
3027 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3028 ** true (this flag is set if the Vdbe may modify more than one row and may
3029 ** throw an ABORT exception), a statement transaction may also be opened.
3030 ** More specifically, a statement transaction is opened iff the database
3031 ** connection is currently not in autocommit mode, or if there are other
3032 ** active statements. A statement transaction allows the changes made by this
3033 ** VDBE to be rolled back after an error without having to roll back the
3034 ** entire transaction. If no error is encountered, the statement transaction
3035 ** will automatically commit when the VDBE halts.
3036 **
3037 ** If P5!=0 then this opcode also checks the schema cookie against P3
3038 ** and the schema generation counter against P4.
3039 ** The cookie changes its value whenever the database schema changes.
3040 ** This operation is used to detect when that the cookie has changed
3041 ** and that the current process needs to reread the schema.  If the schema
3042 ** cookie in P3 differs from the schema cookie in the database header or
3043 ** if the schema generation counter in P4 differs from the current
3044 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
3045 ** halts.  The sqlite3_step() wrapper function might then reprepare the
3046 ** statement and rerun it from the beginning.
3047 */
3048 case OP_Transaction: {
3049   Btree *pBt;
3050   int iMeta;
3051   int iGen;
3052 
3053   assert( p->bIsReader );
3054   assert( p->readOnly==0 || pOp->p2==0 );
3055   assert( pOp->p1>=0 && pOp->p1<db->nDb );
3056   assert( DbMaskTest(p->btreeMask, pOp->p1) );
3057   if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
3058     rc = SQLITE_READONLY;
3059     goto abort_due_to_error;
3060   }
3061   pBt = db->aDb[pOp->p1].pBt;
3062 
3063   if( pBt ){
3064     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
3065     if( rc==SQLITE_BUSY ){
3066       p->pc = pc;
3067       p->rc = rc = SQLITE_BUSY;
3068       goto vdbe_return;
3069     }
3070     if( rc!=SQLITE_OK ){
3071       goto abort_due_to_error;
3072     }
3073 
3074     if( pOp->p2 && p->usesStmtJournal
3075      && (db->autoCommit==0 || db->nVdbeRead>1)
3076     ){
3077       assert( sqlite3BtreeIsInTrans(pBt) );
3078       if( p->iStatement==0 ){
3079         assert( db->nStatement>=0 && db->nSavepoint>=0 );
3080         db->nStatement++;
3081         p->iStatement = db->nSavepoint + db->nStatement;
3082       }
3083 
3084       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
3085       if( rc==SQLITE_OK ){
3086         rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
3087       }
3088 
3089       /* Store the current value of the database handles deferred constraint
3090       ** counter. If the statement transaction needs to be rolled back,
3091       ** the value of this counter needs to be restored too.  */
3092       p->nStmtDefCons = db->nDeferredCons;
3093       p->nStmtDefImmCons = db->nDeferredImmCons;
3094     }
3095 
3096     /* Gather the schema version number for checking */
3097     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
3098     iGen = db->aDb[pOp->p1].pSchema->iGeneration;
3099   }else{
3100     iGen = iMeta = 0;
3101   }
3102   assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
3103   if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
3104     sqlite3DbFree(db, p->zErrMsg);
3105     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
3106     /* If the schema-cookie from the database file matches the cookie
3107     ** stored with the in-memory representation of the schema, do
3108     ** not reload the schema from the database file.
3109     **
3110     ** If virtual-tables are in use, this is not just an optimization.
3111     ** Often, v-tables store their data in other SQLite tables, which
3112     ** are queried from within xNext() and other v-table methods using
3113     ** prepared queries. If such a query is out-of-date, we do not want to
3114     ** discard the database schema, as the user code implementing the
3115     ** v-table would have to be ready for the sqlite3_vtab structure itself
3116     ** to be invalidated whenever sqlite3_step() is called from within
3117     ** a v-table method.
3118     */
3119     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
3120       sqlite3ResetOneSchema(db, pOp->p1);
3121     }
3122     p->expired = 1;
3123     rc = SQLITE_SCHEMA;
3124   }
3125   break;
3126 }
3127 
3128 /* Opcode: ReadCookie P1 P2 P3 * *
3129 **
3130 ** Read cookie number P3 from database P1 and write it into register P2.
3131 ** P3==1 is the schema version.  P3==2 is the database format.
3132 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
3133 ** the main database file and P1==1 is the database file used to store
3134 ** temporary tables.
3135 **
3136 ** There must be a read-lock on the database (either a transaction
3137 ** must be started or there must be an open cursor) before
3138 ** executing this instruction.
3139 */
3140 case OP_ReadCookie: {               /* out2-prerelease */
3141   int iMeta;
3142   int iDb;
3143   int iCookie;
3144 
3145   assert( p->bIsReader );
3146   iDb = pOp->p1;
3147   iCookie = pOp->p3;
3148   assert( pOp->p3<SQLITE_N_BTREE_META );
3149   assert( iDb>=0 && iDb<db->nDb );
3150   assert( db->aDb[iDb].pBt!=0 );
3151   assert( DbMaskTest(p->btreeMask, iDb) );
3152 
3153   sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
3154   pOut->u.i = iMeta;
3155   break;
3156 }
3157 
3158 /* Opcode: SetCookie P1 P2 P3 * *
3159 **
3160 ** Write the content of register P3 (interpreted as an integer)
3161 ** into cookie number P2 of database P1.  P2==1 is the schema version.
3162 ** P2==2 is the database format. P2==3 is the recommended pager cache
3163 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
3164 ** database file used to store temporary tables.
3165 **
3166 ** A transaction must be started before executing this opcode.
3167 */
3168 case OP_SetCookie: {       /* in3 */
3169   Db *pDb;
3170   assert( pOp->p2<SQLITE_N_BTREE_META );
3171   assert( pOp->p1>=0 && pOp->p1<db->nDb );
3172   assert( DbMaskTest(p->btreeMask, pOp->p1) );
3173   assert( p->readOnly==0 );
3174   pDb = &db->aDb[pOp->p1];
3175   assert( pDb->pBt!=0 );
3176   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
3177   pIn3 = &aMem[pOp->p3];
3178   sqlite3VdbeMemIntegerify(pIn3);
3179   /* See note about index shifting on OP_ReadCookie */
3180   rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
3181   if( pOp->p2==BTREE_SCHEMA_VERSION ){
3182     /* When the schema cookie changes, record the new cookie internally */
3183     pDb->pSchema->schema_cookie = (int)pIn3->u.i;
3184     db->flags |= SQLITE_InternChanges;
3185   }else if( pOp->p2==BTREE_FILE_FORMAT ){
3186     /* Record changes in the file format */
3187     pDb->pSchema->file_format = (u8)pIn3->u.i;
3188   }
3189   if( pOp->p1==1 ){
3190     /* Invalidate all prepared statements whenever the TEMP database
3191     ** schema is changed.  Ticket #1644 */
3192     sqlite3ExpirePreparedStatements(db);
3193     p->expired = 0;
3194   }
3195   break;
3196 }
3197 
3198 /* Opcode: OpenRead P1 P2 P3 P4 P5
3199 ** Synopsis: root=P2 iDb=P3
3200 **
3201 ** Open a read-only cursor for the database table whose root page is
3202 ** P2 in a database file.  The database file is determined by P3.
3203 ** P3==0 means the main database, P3==1 means the database used for
3204 ** temporary tables, and P3>1 means used the corresponding attached
3205 ** database.  Give the new cursor an identifier of P1.  The P1
3206 ** values need not be contiguous but all P1 values should be small integers.
3207 ** It is an error for P1 to be negative.
3208 **
3209 ** If P5!=0 then use the content of register P2 as the root page, not
3210 ** the value of P2 itself.
3211 **
3212 ** There will be a read lock on the database whenever there is an
3213 ** open cursor.  If the database was unlocked prior to this instruction
3214 ** then a read lock is acquired as part of this instruction.  A read
3215 ** lock allows other processes to read the database but prohibits
3216 ** any other process from modifying the database.  The read lock is
3217 ** released when all cursors are closed.  If this instruction attempts
3218 ** to get a read lock but fails, the script terminates with an
3219 ** SQLITE_BUSY error code.
3220 **
3221 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3222 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3223 ** structure, then said structure defines the content and collating
3224 ** sequence of the index being opened. Otherwise, if P4 is an integer
3225 ** value, it is set to the number of columns in the table.
3226 **
3227 ** See also: OpenWrite, ReopenIdx
3228 */
3229 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
3230 ** Synopsis: root=P2 iDb=P3
3231 **
3232 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
3233 ** checks to see if the cursor on P1 is already open with a root page
3234 ** number of P2 and if it is this opcode becomes a no-op.  In other words,
3235 ** if the cursor is already open, do not reopen it.
3236 **
3237 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
3238 ** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
3239 ** every other ReopenIdx or OpenRead for the same cursor number.
3240 **
3241 ** See the OpenRead opcode documentation for additional information.
3242 */
3243 /* Opcode: OpenWrite P1 P2 P3 P4 P5
3244 ** Synopsis: root=P2 iDb=P3
3245 **
3246 ** Open a read/write cursor named P1 on the table or index whose root
3247 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
3248 ** root page.
3249 **
3250 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3251 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3252 ** structure, then said structure defines the content and collating
3253 ** sequence of the index being opened. Otherwise, if P4 is an integer
3254 ** value, it is set to the number of columns in the table, or to the
3255 ** largest index of any column of the table that is actually used.
3256 **
3257 ** This instruction works just like OpenRead except that it opens the cursor
3258 ** in read/write mode.  For a given table, there can be one or more read-only
3259 ** cursors or a single read/write cursor but not both.
3260 **
3261 ** See also OpenRead.
3262 */
3263 case OP_ReopenIdx: {
3264   VdbeCursor *pCur;
3265 
3266   assert( pOp->p5==0 );
3267   assert( pOp->p4type==P4_KEYINFO );
3268   pCur = p->apCsr[pOp->p1];
3269   if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
3270     assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
3271     break;
3272   }
3273   /* If the cursor is not currently open or is open on a different
3274   ** index, then fall through into OP_OpenRead to force a reopen */
3275 }
3276 case OP_OpenRead:
3277 case OP_OpenWrite: {
3278   int nField;
3279   KeyInfo *pKeyInfo;
3280   int p2;
3281   int iDb;
3282   int wrFlag;
3283   Btree *pX;
3284   VdbeCursor *pCur;
3285   Db *pDb;
3286 
3287   assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
3288   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
3289   assert( p->bIsReader );
3290   assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
3291           || p->readOnly==0 );
3292 
3293   if( p->expired ){
3294     rc = SQLITE_ABORT;
3295     break;
3296   }
3297 
3298   nField = 0;
3299   pKeyInfo = 0;
3300   p2 = pOp->p2;
3301   iDb = pOp->p3;
3302   assert( iDb>=0 && iDb<db->nDb );
3303   assert( DbMaskTest(p->btreeMask, iDb) );
3304   pDb = &db->aDb[iDb];
3305   pX = pDb->pBt;
3306   assert( pX!=0 );
3307   if( pOp->opcode==OP_OpenWrite ){
3308     wrFlag = 1;
3309     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3310     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
3311       p->minWriteFileFormat = pDb->pSchema->file_format;
3312     }
3313   }else{
3314     wrFlag = 0;
3315   }
3316   if( pOp->p5 & OPFLAG_P2ISREG ){
3317     assert( p2>0 );
3318     assert( p2<=(p->nMem-p->nCursor) );
3319     pIn2 = &aMem[p2];
3320     assert( memIsValid(pIn2) );
3321     assert( (pIn2->flags & MEM_Int)!=0 );
3322     sqlite3VdbeMemIntegerify(pIn2);
3323     p2 = (int)pIn2->u.i;
3324     /* The p2 value always comes from a prior OP_CreateTable opcode and
3325     ** that opcode will always set the p2 value to 2 or more or else fail.
3326     ** If there were a failure, the prepared statement would have halted
3327     ** before reaching this instruction. */
3328     if( NEVER(p2<2) ) {
3329       rc = SQLITE_CORRUPT_BKPT;
3330       goto abort_due_to_error;
3331     }
3332   }
3333   if( pOp->p4type==P4_KEYINFO ){
3334     pKeyInfo = pOp->p4.pKeyInfo;
3335     assert( pKeyInfo->enc==ENC(db) );
3336     assert( pKeyInfo->db==db );
3337     nField = pKeyInfo->nField+pKeyInfo->nXField;
3338   }else if( pOp->p4type==P4_INT32 ){
3339     nField = pOp->p4.i;
3340   }
3341   assert( pOp->p1>=0 );
3342   assert( nField>=0 );
3343   testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
3344   pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
3345   if( pCur==0 ) goto no_mem;
3346   pCur->nullRow = 1;
3347   pCur->isOrdered = 1;
3348   pCur->pgnoRoot = p2;
3349   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
3350   pCur->pKeyInfo = pKeyInfo;
3351   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
3352   sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
3353 
3354   /* Since it performs no memory allocation or IO, the only value that
3355   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
3356   assert( rc==SQLITE_OK );
3357 
3358   /* Set the VdbeCursor.isTable variable. Previous versions of
3359   ** SQLite used to check if the root-page flags were sane at this point
3360   ** and report database corruption if they were not, but this check has
3361   ** since moved into the btree layer.  */
3362   pCur->isTable = pOp->p4type!=P4_KEYINFO;
3363   break;
3364 }
3365 
3366 /* Opcode: OpenEphemeral P1 P2 * P4 P5
3367 ** Synopsis: nColumn=P2
3368 **
3369 ** Open a new cursor P1 to a transient table.
3370 ** The cursor is always opened read/write even if
3371 ** the main database is read-only.  The ephemeral
3372 ** table is deleted automatically when the cursor is closed.
3373 **
3374 ** P2 is the number of columns in the ephemeral table.
3375 ** The cursor points to a BTree table if P4==0 and to a BTree index
3376 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
3377 ** that defines the format of keys in the index.
3378 **
3379 ** The P5 parameter can be a mask of the BTREE_* flags defined
3380 ** in btree.h.  These flags control aspects of the operation of
3381 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
3382 ** added automatically.
3383 */
3384 /* Opcode: OpenAutoindex P1 P2 * P4 *
3385 ** Synopsis: nColumn=P2
3386 **
3387 ** This opcode works the same as OP_OpenEphemeral.  It has a
3388 ** different name to distinguish its use.  Tables created using
3389 ** by this opcode will be used for automatically created transient
3390 ** indices in joins.
3391 */
3392 case OP_OpenAutoindex:
3393 case OP_OpenEphemeral: {
3394   VdbeCursor *pCx;
3395   KeyInfo *pKeyInfo;
3396 
3397   static const int vfsFlags =
3398       SQLITE_OPEN_READWRITE |
3399       SQLITE_OPEN_CREATE |
3400       SQLITE_OPEN_EXCLUSIVE |
3401       SQLITE_OPEN_DELETEONCLOSE |
3402       SQLITE_OPEN_TRANSIENT_DB;
3403   assert( pOp->p1>=0 );
3404   assert( pOp->p2>=0 );
3405   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
3406   if( pCx==0 ) goto no_mem;
3407   pCx->nullRow = 1;
3408   pCx->isEphemeral = 1;
3409   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
3410                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
3411   if( rc==SQLITE_OK ){
3412     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
3413   }
3414   if( rc==SQLITE_OK ){
3415     /* If a transient index is required, create it by calling
3416     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
3417     ** opening it. If a transient table is required, just use the
3418     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
3419     */
3420     if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
3421       int pgno;
3422       assert( pOp->p4type==P4_KEYINFO );
3423       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
3424       if( rc==SQLITE_OK ){
3425         assert( pgno==MASTER_ROOT+1 );
3426         assert( pKeyInfo->db==db );
3427         assert( pKeyInfo->enc==ENC(db) );
3428         pCx->pKeyInfo = pKeyInfo;
3429         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
3430       }
3431       pCx->isTable = 0;
3432     }else{
3433       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
3434       pCx->isTable = 1;
3435     }
3436   }
3437   pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
3438   break;
3439 }
3440 
3441 /* Opcode: SorterOpen P1 P2 * P4 *
3442 **
3443 ** This opcode works like OP_OpenEphemeral except that it opens
3444 ** a transient index that is specifically designed to sort large
3445 ** tables using an external merge-sort algorithm.
3446 */
3447 case OP_SorterOpen: {
3448   VdbeCursor *pCx;
3449 
3450   assert( pOp->p1>=0 );
3451   assert( pOp->p2>=0 );
3452   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
3453   if( pCx==0 ) goto no_mem;
3454   pCx->pKeyInfo = pOp->p4.pKeyInfo;
3455   assert( pCx->pKeyInfo->db==db );
3456   assert( pCx->pKeyInfo->enc==ENC(db) );
3457   rc = sqlite3VdbeSorterInit(db, pCx);
3458   break;
3459 }
3460 
3461 /* Opcode: OpenPseudo P1 P2 P3 * *
3462 ** Synopsis: P3 columns in r[P2]
3463 **
3464 ** Open a new cursor that points to a fake table that contains a single
3465 ** row of data.  The content of that one row is the content of memory
3466 ** register P2.  In other words, cursor P1 becomes an alias for the
3467 ** MEM_Blob content contained in register P2.
3468 **
3469 ** A pseudo-table created by this opcode is used to hold a single
3470 ** row output from the sorter so that the row can be decomposed into
3471 ** individual columns using the OP_Column opcode.  The OP_Column opcode
3472 ** is the only cursor opcode that works with a pseudo-table.
3473 **
3474 ** P3 is the number of fields in the records that will be stored by
3475 ** the pseudo-table.
3476 */
3477 case OP_OpenPseudo: {
3478   VdbeCursor *pCx;
3479 
3480   assert( pOp->p1>=0 );
3481   assert( pOp->p3>=0 );
3482   pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
3483   if( pCx==0 ) goto no_mem;
3484   pCx->nullRow = 1;
3485   pCx->pseudoTableReg = pOp->p2;
3486   pCx->isTable = 1;
3487   assert( pOp->p5==0 );
3488   break;
3489 }
3490 
3491 /* Opcode: Close P1 * * * *
3492 **
3493 ** Close a cursor previously opened as P1.  If P1 is not
3494 ** currently open, this instruction is a no-op.
3495 */
3496 case OP_Close: {
3497   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3498   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
3499   p->apCsr[pOp->p1] = 0;
3500   break;
3501 }
3502 
3503 /* Opcode: SeekGE P1 P2 P3 P4 *
3504 ** Synopsis: key=r[P3@P4]
3505 **
3506 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3507 ** use the value in register P3 as the key.  If cursor P1 refers
3508 ** to an SQL index, then P3 is the first in an array of P4 registers
3509 ** that are used as an unpacked index key.
3510 **
3511 ** Reposition cursor P1 so that  it points to the smallest entry that
3512 ** is greater than or equal to the key value. If there are no records
3513 ** greater than or equal to the key and P2 is not zero, then jump to P2.
3514 **
3515 ** This opcode leaves the cursor configured to move in forward order,
3516 ** from the beginning toward the end.  In other words, the cursor is
3517 ** configured to use Next, not Prev.
3518 **
3519 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
3520 */
3521 /* Opcode: SeekGT P1 P2 P3 P4 *
3522 ** Synopsis: key=r[P3@P4]
3523 **
3524 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3525 ** use the value in register P3 as a key. If cursor P1 refers
3526 ** to an SQL index, then P3 is the first in an array of P4 registers
3527 ** that are used as an unpacked index key.
3528 **
3529 ** Reposition cursor P1 so that  it points to the smallest entry that
3530 ** is greater than the key value. If there are no records greater than
3531 ** the key and P2 is not zero, then jump to P2.
3532 **
3533 ** This opcode leaves the cursor configured to move in forward order,
3534 ** from the begining toward the end.  In other words, the cursor is
3535 ** configured to use Next, not Prev.
3536 **
3537 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
3538 */
3539 /* Opcode: SeekLT P1 P2 P3 P4 *
3540 ** Synopsis: key=r[P3@P4]
3541 **
3542 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3543 ** use the value in register P3 as a key. If cursor P1 refers
3544 ** to an SQL index, then P3 is the first in an array of P4 registers
3545 ** that are used as an unpacked index key.
3546 **
3547 ** Reposition cursor P1 so that  it points to the largest entry that
3548 ** is less than the key value. If there are no records less than
3549 ** the key and P2 is not zero, then jump to P2.
3550 **
3551 ** This opcode leaves the cursor configured to move in reverse order,
3552 ** from the end toward the beginning.  In other words, the cursor is
3553 ** configured to use Prev, not Next.
3554 **
3555 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
3556 */
3557 /* Opcode: SeekLE P1 P2 P3 P4 *
3558 ** Synopsis: key=r[P3@P4]
3559 **
3560 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3561 ** use the value in register P3 as a key. If cursor P1 refers
3562 ** to an SQL index, then P3 is the first in an array of P4 registers
3563 ** that are used as an unpacked index key.
3564 **
3565 ** Reposition cursor P1 so that it points to the largest entry that
3566 ** is less than or equal to the key value. If there are no records
3567 ** less than or equal to the key and P2 is not zero, then jump to P2.
3568 **
3569 ** This opcode leaves the cursor configured to move in reverse order,
3570 ** from the end toward the beginning.  In other words, the cursor is
3571 ** configured to use Prev, not Next.
3572 **
3573 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
3574 */
3575 case OP_SeekLT:         /* jump, in3 */
3576 case OP_SeekLE:         /* jump, in3 */
3577 case OP_SeekGE:         /* jump, in3 */
3578 case OP_SeekGT: {       /* jump, in3 */
3579   int res;
3580   int oc;
3581   VdbeCursor *pC;
3582   UnpackedRecord r;
3583   int nField;
3584   i64 iKey;      /* The rowid we are to seek to */
3585 
3586   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3587   assert( pOp->p2!=0 );
3588   pC = p->apCsr[pOp->p1];
3589   assert( pC!=0 );
3590   assert( pC->pseudoTableReg==0 );
3591   assert( OP_SeekLE == OP_SeekLT+1 );
3592   assert( OP_SeekGE == OP_SeekLT+2 );
3593   assert( OP_SeekGT == OP_SeekLT+3 );
3594   assert( pC->isOrdered );
3595   assert( pC->pCursor!=0 );
3596   oc = pOp->opcode;
3597   pC->nullRow = 0;
3598 #ifdef SQLITE_DEBUG
3599   pC->seekOp = pOp->opcode;
3600 #endif
3601   if( pC->isTable ){
3602     /* The input value in P3 might be of any type: integer, real, string,
3603     ** blob, or NULL.  But it needs to be an integer before we can do
3604     ** the seek, so covert it. */
3605     pIn3 = &aMem[pOp->p3];
3606     ApplyNumericAffinity(pIn3);
3607     iKey = sqlite3VdbeIntValue(pIn3);
3608     pC->rowidIsValid = 0;
3609 
3610     /* If the P3 value could not be converted into an integer without
3611     ** loss of information, then special processing is required... */
3612     if( (pIn3->flags & MEM_Int)==0 ){
3613       if( (pIn3->flags & MEM_Real)==0 ){
3614         /* If the P3 value cannot be converted into any kind of a number,
3615         ** then the seek is not possible, so jump to P2 */
3616         pc = pOp->p2 - 1;  VdbeBranchTaken(1,2);
3617         break;
3618       }
3619 
3620       /* If the approximation iKey is larger than the actual real search
3621       ** term, substitute >= for > and < for <=. e.g. if the search term
3622       ** is 4.9 and the integer approximation 5:
3623       **
3624       **        (x >  4.9)    ->     (x >= 5)
3625       **        (x <= 4.9)    ->     (x <  5)
3626       */
3627       if( pIn3->r<(double)iKey ){
3628         assert( OP_SeekGE==(OP_SeekGT-1) );
3629         assert( OP_SeekLT==(OP_SeekLE-1) );
3630         assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
3631         if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
3632       }
3633 
3634       /* If the approximation iKey is smaller than the actual real search
3635       ** term, substitute <= for < and > for >=.  */
3636       else if( pIn3->r>(double)iKey ){
3637         assert( OP_SeekLE==(OP_SeekLT+1) );
3638         assert( OP_SeekGT==(OP_SeekGE+1) );
3639         assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
3640         if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
3641       }
3642     }
3643     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
3644     if( rc!=SQLITE_OK ){
3645       goto abort_due_to_error;
3646     }
3647     if( res==0 ){
3648       pC->rowidIsValid = 1;
3649       pC->lastRowid = iKey;
3650     }
3651   }else{
3652     nField = pOp->p4.i;
3653     assert( pOp->p4type==P4_INT32 );
3654     assert( nField>0 );
3655     r.pKeyInfo = pC->pKeyInfo;
3656     r.nField = (u16)nField;
3657 
3658     /* The next line of code computes as follows, only faster:
3659     **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
3660     **     r.default_rc = -1;
3661     **   }else{
3662     **     r.default_rc = +1;
3663     **   }
3664     */
3665     r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
3666     assert( oc!=OP_SeekGT || r.default_rc==-1 );
3667     assert( oc!=OP_SeekLE || r.default_rc==-1 );
3668     assert( oc!=OP_SeekGE || r.default_rc==+1 );
3669     assert( oc!=OP_SeekLT || r.default_rc==+1 );
3670 
3671     r.aMem = &aMem[pOp->p3];
3672 #ifdef SQLITE_DEBUG
3673     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
3674 #endif
3675     ExpandBlob(r.aMem);
3676     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
3677     if( rc!=SQLITE_OK ){
3678       goto abort_due_to_error;
3679     }
3680     pC->rowidIsValid = 0;
3681   }
3682   pC->deferredMoveto = 0;
3683   pC->cacheStatus = CACHE_STALE;
3684 #ifdef SQLITE_TEST
3685   sqlite3_search_count++;
3686 #endif
3687   if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
3688     if( res<0 || (res==0 && oc==OP_SeekGT) ){
3689       res = 0;
3690       rc = sqlite3BtreeNext(pC->pCursor, &res);
3691       if( rc!=SQLITE_OK ) goto abort_due_to_error;
3692       pC->rowidIsValid = 0;
3693     }else{
3694       res = 0;
3695     }
3696   }else{
3697     assert( oc==OP_SeekLT || oc==OP_SeekLE );
3698     if( res>0 || (res==0 && oc==OP_SeekLT) ){
3699       res = 0;
3700       rc = sqlite3BtreePrevious(pC->pCursor, &res);
3701       if( rc!=SQLITE_OK ) goto abort_due_to_error;
3702       pC->rowidIsValid = 0;
3703     }else{
3704       /* res might be negative because the table is empty.  Check to
3705       ** see if this is the case.
3706       */
3707       res = sqlite3BtreeEof(pC->pCursor);
3708     }
3709   }
3710   assert( pOp->p2>0 );
3711   VdbeBranchTaken(res!=0,2);
3712   if( res ){
3713     pc = pOp->p2 - 1;
3714   }
3715   break;
3716 }
3717 
3718 /* Opcode: Seek P1 P2 * * *
3719 ** Synopsis:  intkey=r[P2]
3720 **
3721 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
3722 ** for P1 to move so that it points to the rowid given by P2.
3723 **
3724 ** This is actually a deferred seek.  Nothing actually happens until
3725 ** the cursor is used to read a record.  That way, if no reads
3726 ** occur, no unnecessary I/O happens.
3727 */
3728 case OP_Seek: {    /* in2 */
3729   VdbeCursor *pC;
3730 
3731   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3732   pC = p->apCsr[pOp->p1];
3733   assert( pC!=0 );
3734   assert( pC->pCursor!=0 );
3735   assert( pC->isTable );
3736   pC->nullRow = 0;
3737   pIn2 = &aMem[pOp->p2];
3738   pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
3739   pC->rowidIsValid = 0;
3740   pC->deferredMoveto = 1;
3741   break;
3742 }
3743 
3744 
3745 /* Opcode: Found P1 P2 P3 P4 *
3746 ** Synopsis: key=r[P3@P4]
3747 **
3748 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
3749 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
3750 ** record.
3751 **
3752 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
3753 ** is a prefix of any entry in P1 then a jump is made to P2 and
3754 ** P1 is left pointing at the matching entry.
3755 **
3756 ** This operation leaves the cursor in a state where it can be
3757 ** advanced in the forward direction.  The Next instruction will work,
3758 ** but not the Prev instruction.
3759 **
3760 ** See also: NotFound, NoConflict, NotExists. SeekGe
3761 */
3762 /* Opcode: NotFound P1 P2 P3 P4 *
3763 ** Synopsis: key=r[P3@P4]
3764 **
3765 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
3766 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
3767 ** record.
3768 **
3769 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
3770 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
3771 ** does contain an entry whose prefix matches the P3/P4 record then control
3772 ** falls through to the next instruction and P1 is left pointing at the
3773 ** matching entry.
3774 **
3775 ** This operation leaves the cursor in a state where it cannot be
3776 ** advanced in either direction.  In other words, the Next and Prev
3777 ** opcodes do not work after this operation.
3778 **
3779 ** See also: Found, NotExists, NoConflict
3780 */
3781 /* Opcode: NoConflict P1 P2 P3 P4 *
3782 ** Synopsis: key=r[P3@P4]
3783 **
3784 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
3785 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
3786 ** record.
3787 **
3788 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
3789 ** contains any NULL value, jump immediately to P2.  If all terms of the
3790 ** record are not-NULL then a check is done to determine if any row in the
3791 ** P1 index btree has a matching key prefix.  If there are no matches, jump
3792 ** immediately to P2.  If there is a match, fall through and leave the P1
3793 ** cursor pointing to the matching row.
3794 **
3795 ** This opcode is similar to OP_NotFound with the exceptions that the
3796 ** branch is always taken if any part of the search key input is NULL.
3797 **
3798 ** This operation leaves the cursor in a state where it cannot be
3799 ** advanced in either direction.  In other words, the Next and Prev
3800 ** opcodes do not work after this operation.
3801 **
3802 ** See also: NotFound, Found, NotExists
3803 */
3804 case OP_NoConflict:     /* jump, in3 */
3805 case OP_NotFound:       /* jump, in3 */
3806 case OP_Found: {        /* jump, in3 */
3807   int alreadyExists;
3808   int ii;
3809   VdbeCursor *pC;
3810   int res;
3811   char *pFree;
3812   UnpackedRecord *pIdxKey;
3813   UnpackedRecord r;
3814   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
3815 
3816 #ifdef SQLITE_TEST
3817   if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
3818 #endif
3819 
3820   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3821   assert( pOp->p4type==P4_INT32 );
3822   pC = p->apCsr[pOp->p1];
3823   assert( pC!=0 );
3824 #ifdef SQLITE_DEBUG
3825   pC->seekOp = pOp->opcode;
3826 #endif
3827   pIn3 = &aMem[pOp->p3];
3828   assert( pC->pCursor!=0 );
3829   assert( pC->isTable==0 );
3830   pFree = 0;  /* Not needed.  Only used to suppress a compiler warning. */
3831   if( pOp->p4.i>0 ){
3832     r.pKeyInfo = pC->pKeyInfo;
3833     r.nField = (u16)pOp->p4.i;
3834     r.aMem = pIn3;
3835     for(ii=0; ii<r.nField; ii++){
3836       assert( memIsValid(&r.aMem[ii]) );
3837       ExpandBlob(&r.aMem[ii]);
3838 #ifdef SQLITE_DEBUG
3839       if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
3840 #endif
3841     }
3842     pIdxKey = &r;
3843   }else{
3844     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
3845         pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
3846     );
3847     if( pIdxKey==0 ) goto no_mem;
3848     assert( pIn3->flags & MEM_Blob );
3849     assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
3850     sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
3851   }
3852   pIdxKey->default_rc = 0;
3853   if( pOp->opcode==OP_NoConflict ){
3854     /* For the OP_NoConflict opcode, take the jump if any of the
3855     ** input fields are NULL, since any key with a NULL will not
3856     ** conflict */
3857     for(ii=0; ii<r.nField; ii++){
3858       if( r.aMem[ii].flags & MEM_Null ){
3859         pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
3860         break;
3861       }
3862     }
3863   }
3864   rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
3865   if( pOp->p4.i==0 ){
3866     sqlite3DbFree(db, pFree);
3867   }
3868   if( rc!=SQLITE_OK ){
3869     break;
3870   }
3871   pC->seekResult = res;
3872   alreadyExists = (res==0);
3873   pC->nullRow = 1-alreadyExists;
3874   pC->deferredMoveto = 0;
3875   pC->cacheStatus = CACHE_STALE;
3876   if( pOp->opcode==OP_Found ){
3877     VdbeBranchTaken(alreadyExists!=0,2);
3878     if( alreadyExists ) pc = pOp->p2 - 1;
3879   }else{
3880     VdbeBranchTaken(alreadyExists==0,2);
3881     if( !alreadyExists ) pc = pOp->p2 - 1;
3882   }
3883   break;
3884 }
3885 
3886 /* Opcode: NotExists P1 P2 P3 * *
3887 ** Synopsis: intkey=r[P3]
3888 **
3889 ** P1 is the index of a cursor open on an SQL table btree (with integer
3890 ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
3891 ** rowid P3 then jump immediately to P2.  If P1 does contain a record
3892 ** with rowid P3 then leave the cursor pointing at that record and fall
3893 ** through to the next instruction.
3894 **
3895 ** The OP_NotFound opcode performs the same operation on index btrees
3896 ** (with arbitrary multi-value keys).
3897 **
3898 ** This opcode leaves the cursor in a state where it cannot be advanced
3899 ** in either direction.  In other words, the Next and Prev opcodes will
3900 ** not work following this opcode.
3901 **
3902 ** See also: Found, NotFound, NoConflict
3903 */
3904 case OP_NotExists: {        /* jump, in3 */
3905   VdbeCursor *pC;
3906   BtCursor *pCrsr;
3907   int res;
3908   u64 iKey;
3909 
3910   pIn3 = &aMem[pOp->p3];
3911   assert( pIn3->flags & MEM_Int );
3912   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3913   pC = p->apCsr[pOp->p1];
3914   assert( pC!=0 );
3915 #ifdef SQLITE_DEBUG
3916   pC->seekOp = 0;
3917 #endif
3918   assert( pC->isTable );
3919   assert( pC->pseudoTableReg==0 );
3920   pCrsr = pC->pCursor;
3921   assert( pCrsr!=0 );
3922   res = 0;
3923   iKey = pIn3->u.i;
3924   rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
3925   pC->lastRowid = pIn3->u.i;
3926   pC->rowidIsValid = res==0 ?1:0;
3927   pC->nullRow = 0;
3928   pC->cacheStatus = CACHE_STALE;
3929   pC->deferredMoveto = 0;
3930   VdbeBranchTaken(res!=0,2);
3931   if( res!=0 ){
3932     pc = pOp->p2 - 1;
3933     assert( pC->rowidIsValid==0 );
3934   }
3935   pC->seekResult = res;
3936   break;
3937 }
3938 
3939 /* Opcode: Sequence P1 P2 * * *
3940 ** Synopsis: r[P2]=cursor[P1].ctr++
3941 **
3942 ** Find the next available sequence number for cursor P1.
3943 ** Write the sequence number into register P2.
3944 ** The sequence number on the cursor is incremented after this
3945 ** instruction.
3946 */
3947 case OP_Sequence: {           /* out2-prerelease */
3948   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3949   assert( p->apCsr[pOp->p1]!=0 );
3950   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
3951   break;
3952 }
3953 
3954 
3955 /* Opcode: NewRowid P1 P2 P3 * *
3956 ** Synopsis: r[P2]=rowid
3957 **
3958 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
3959 ** The record number is not previously used as a key in the database
3960 ** table that cursor P1 points to.  The new record number is written
3961 ** written to register P2.
3962 **
3963 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
3964 ** the largest previously generated record number. No new record numbers are
3965 ** allowed to be less than this value. When this value reaches its maximum,
3966 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
3967 ** generated record number. This P3 mechanism is used to help implement the
3968 ** AUTOINCREMENT feature.
3969 */
3970 case OP_NewRowid: {           /* out2-prerelease */
3971   i64 v;                 /* The new rowid */
3972   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
3973   int res;               /* Result of an sqlite3BtreeLast() */
3974   int cnt;               /* Counter to limit the number of searches */
3975   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
3976   VdbeFrame *pFrame;     /* Root frame of VDBE */
3977 
3978   v = 0;
3979   res = 0;
3980   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3981   pC = p->apCsr[pOp->p1];
3982   assert( pC!=0 );
3983   if( NEVER(pC->pCursor==0) ){
3984     /* The zero initialization above is all that is needed */
3985   }else{
3986     /* The next rowid or record number (different terms for the same
3987     ** thing) is obtained in a two-step algorithm.
3988     **
3989     ** First we attempt to find the largest existing rowid and add one
3990     ** to that.  But if the largest existing rowid is already the maximum
3991     ** positive integer, we have to fall through to the second
3992     ** probabilistic algorithm
3993     **
3994     ** The second algorithm is to select a rowid at random and see if
3995     ** it already exists in the table.  If it does not exist, we have
3996     ** succeeded.  If the random rowid does exist, we select a new one
3997     ** and try again, up to 100 times.
3998     */
3999     assert( pC->isTable );
4000 
4001 #ifdef SQLITE_32BIT_ROWID
4002 #   define MAX_ROWID 0x7fffffff
4003 #else
4004     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
4005     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
4006     ** to provide the constant while making all compilers happy.
4007     */
4008 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
4009 #endif
4010 
4011     if( !pC->useRandomRowid ){
4012       rc = sqlite3BtreeLast(pC->pCursor, &res);
4013       if( rc!=SQLITE_OK ){
4014         goto abort_due_to_error;
4015       }
4016       if( res ){
4017         v = 1;   /* IMP: R-61914-48074 */
4018       }else{
4019         assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
4020         rc = sqlite3BtreeKeySize(pC->pCursor, &v);
4021         assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
4022         if( v>=MAX_ROWID ){
4023           pC->useRandomRowid = 1;
4024         }else{
4025           v++;   /* IMP: R-29538-34987 */
4026         }
4027       }
4028     }
4029 
4030 #ifndef SQLITE_OMIT_AUTOINCREMENT
4031     if( pOp->p3 ){
4032       /* Assert that P3 is a valid memory cell. */
4033       assert( pOp->p3>0 );
4034       if( p->pFrame ){
4035         for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
4036         /* Assert that P3 is a valid memory cell. */
4037         assert( pOp->p3<=pFrame->nMem );
4038         pMem = &pFrame->aMem[pOp->p3];
4039       }else{
4040         /* Assert that P3 is a valid memory cell. */
4041         assert( pOp->p3<=(p->nMem-p->nCursor) );
4042         pMem = &aMem[pOp->p3];
4043         memAboutToChange(p, pMem);
4044       }
4045       assert( memIsValid(pMem) );
4046 
4047       REGISTER_TRACE(pOp->p3, pMem);
4048       sqlite3VdbeMemIntegerify(pMem);
4049       assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
4050       if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
4051         rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
4052         goto abort_due_to_error;
4053       }
4054       if( v<pMem->u.i+1 ){
4055         v = pMem->u.i + 1;
4056       }
4057       pMem->u.i = v;
4058     }
4059 #endif
4060     if( pC->useRandomRowid ){
4061       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
4062       ** largest possible integer (9223372036854775807) then the database
4063       ** engine starts picking positive candidate ROWIDs at random until
4064       ** it finds one that is not previously used. */
4065       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
4066                              ** an AUTOINCREMENT table. */
4067       /* on the first attempt, simply do one more than previous */
4068       v = lastRowid;
4069       v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
4070       v++; /* ensure non-zero */
4071       cnt = 0;
4072       while(   ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
4073                                                  0, &res))==SQLITE_OK)
4074             && (res==0)
4075             && (++cnt<100)){
4076         /* collision - try another random rowid */
4077         sqlite3_randomness(sizeof(v), &v);
4078         if( cnt<5 ){
4079           /* try "small" random rowids for the initial attempts */
4080           v &= 0xffffff;
4081         }else{
4082           v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
4083         }
4084         v++; /* ensure non-zero */
4085       }
4086       if( rc==SQLITE_OK && res==0 ){
4087         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
4088         goto abort_due_to_error;
4089       }
4090       assert( v>0 );  /* EV: R-40812-03570 */
4091     }
4092     pC->rowidIsValid = 0;
4093     pC->deferredMoveto = 0;
4094     pC->cacheStatus = CACHE_STALE;
4095   }
4096   pOut->u.i = v;
4097   break;
4098 }
4099 
4100 /* Opcode: Insert P1 P2 P3 P4 P5
4101 ** Synopsis: intkey=r[P3] data=r[P2]
4102 **
4103 ** Write an entry into the table of cursor P1.  A new entry is
4104 ** created if it doesn't already exist or the data for an existing
4105 ** entry is overwritten.  The data is the value MEM_Blob stored in register
4106 ** number P2. The key is stored in register P3. The key must
4107 ** be a MEM_Int.
4108 **
4109 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
4110 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
4111 ** then rowid is stored for subsequent return by the
4112 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
4113 **
4114 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
4115 ** the last seek operation (OP_NotExists) was a success, then this
4116 ** operation will not attempt to find the appropriate row before doing
4117 ** the insert but will instead overwrite the row that the cursor is
4118 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
4119 ** has already positioned the cursor correctly.  This is an optimization
4120 ** that boosts performance by avoiding redundant seeks.
4121 **
4122 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
4123 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
4124 ** is part of an INSERT operation.  The difference is only important to
4125 ** the update hook.
4126 **
4127 ** Parameter P4 may point to a string containing the table-name, or
4128 ** may be NULL. If it is not NULL, then the update-hook
4129 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
4130 **
4131 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
4132 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
4133 ** and register P2 becomes ephemeral.  If the cursor is changed, the
4134 ** value of register P2 will then change.  Make sure this does not
4135 ** cause any problems.)
4136 **
4137 ** This instruction only works on tables.  The equivalent instruction
4138 ** for indices is OP_IdxInsert.
4139 */
4140 /* Opcode: InsertInt P1 P2 P3 P4 P5
4141 ** Synopsis:  intkey=P3 data=r[P2]
4142 **
4143 ** This works exactly like OP_Insert except that the key is the
4144 ** integer value P3, not the value of the integer stored in register P3.
4145 */
4146 case OP_Insert:
4147 case OP_InsertInt: {
4148   Mem *pData;       /* MEM cell holding data for the record to be inserted */
4149   Mem *pKey;        /* MEM cell holding key  for the record */
4150   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
4151   VdbeCursor *pC;   /* Cursor to table into which insert is written */
4152   int nZero;        /* Number of zero-bytes to append */
4153   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
4154   const char *zDb;  /* database name - used by the update hook */
4155   const char *zTbl; /* Table name - used by the opdate hook */
4156   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
4157 
4158   pData = &aMem[pOp->p2];
4159   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4160   assert( memIsValid(pData) );
4161   pC = p->apCsr[pOp->p1];
4162   assert( pC!=0 );
4163   assert( pC->pCursor!=0 );
4164   assert( pC->pseudoTableReg==0 );
4165   assert( pC->isTable );
4166   REGISTER_TRACE(pOp->p2, pData);
4167 
4168   if( pOp->opcode==OP_Insert ){
4169     pKey = &aMem[pOp->p3];
4170     assert( pKey->flags & MEM_Int );
4171     assert( memIsValid(pKey) );
4172     REGISTER_TRACE(pOp->p3, pKey);
4173     iKey = pKey->u.i;
4174   }else{
4175     assert( pOp->opcode==OP_InsertInt );
4176     iKey = pOp->p3;
4177   }
4178 
4179   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
4180   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
4181   if( pData->flags & MEM_Null ){
4182     pData->z = 0;
4183     pData->n = 0;
4184   }else{
4185     assert( pData->flags & (MEM_Blob|MEM_Str) );
4186   }
4187   seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
4188   if( pData->flags & MEM_Zero ){
4189     nZero = pData->u.nZero;
4190   }else{
4191     nZero = 0;
4192   }
4193   rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
4194                           pData->z, pData->n, nZero,
4195                           (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
4196   );
4197   pC->rowidIsValid = 0;
4198   pC->deferredMoveto = 0;
4199   pC->cacheStatus = CACHE_STALE;
4200 
4201   /* Invoke the update-hook if required. */
4202   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
4203     zDb = db->aDb[pC->iDb].zName;
4204     zTbl = pOp->p4.z;
4205     op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
4206     assert( pC->isTable );
4207     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
4208     assert( pC->iDb>=0 );
4209   }
4210   break;
4211 }
4212 
4213 /* Opcode: Delete P1 P2 * P4 *
4214 **
4215 ** Delete the record at which the P1 cursor is currently pointing.
4216 **
4217 ** The cursor will be left pointing at either the next or the previous
4218 ** record in the table. If it is left pointing at the next record, then
4219 ** the next Next instruction will be a no-op.  Hence it is OK to delete
4220 ** a record from within a Next loop.
4221 **
4222 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
4223 ** incremented (otherwise not).
4224 **
4225 ** P1 must not be pseudo-table.  It has to be a real table with
4226 ** multiple rows.
4227 **
4228 ** If P4 is not NULL, then it is the name of the table that P1 is
4229 ** pointing to.  The update hook will be invoked, if it exists.
4230 ** If P4 is not NULL then the P1 cursor must have been positioned
4231 ** using OP_NotFound prior to invoking this opcode.
4232 */
4233 case OP_Delete: {
4234   i64 iKey;
4235   VdbeCursor *pC;
4236 
4237   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4238   pC = p->apCsr[pOp->p1];
4239   assert( pC!=0 );
4240   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
4241   iKey = pC->lastRowid;      /* Only used for the update hook */
4242 
4243   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
4244   ** OP_Column on the same table without any intervening operations that
4245   ** might move or invalidate the cursor.  Hence cursor pC is always pointing
4246   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
4247   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
4248   ** to guard against future changes to the code generator.
4249   **/
4250   assert( pC->deferredMoveto==0 );
4251   rc = sqlite3VdbeCursorMoveto(pC);
4252   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
4253 
4254   rc = sqlite3BtreeDelete(pC->pCursor);
4255   pC->cacheStatus = CACHE_STALE;
4256 
4257   /* Invoke the update-hook if required. */
4258   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
4259     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
4260                         db->aDb[pC->iDb].zName, pOp->p4.z, iKey);
4261     assert( pC->iDb>=0 );
4262   }
4263   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
4264   break;
4265 }
4266 /* Opcode: ResetCount * * * * *
4267 **
4268 ** The value of the change counter is copied to the database handle
4269 ** change counter (returned by subsequent calls to sqlite3_changes()).
4270 ** Then the VMs internal change counter resets to 0.
4271 ** This is used by trigger programs.
4272 */
4273 case OP_ResetCount: {
4274   sqlite3VdbeSetChanges(db, p->nChange);
4275   p->nChange = 0;
4276   break;
4277 }
4278 
4279 /* Opcode: SorterCompare P1 P2 P3 P4
4280 ** Synopsis:  if key(P1)!=trim(r[P3],P4) goto P2
4281 **
4282 ** P1 is a sorter cursor. This instruction compares a prefix of the
4283 ** record blob in register P3 against a prefix of the entry that
4284 ** the sorter cursor currently points to.  Only the first P4 fields
4285 ** of r[P3] and the sorter record are compared.
4286 **
4287 ** If either P3 or the sorter contains a NULL in one of their significant
4288 ** fields (not counting the P4 fields at the end which are ignored) then
4289 ** the comparison is assumed to be equal.
4290 **
4291 ** Fall through to next instruction if the two records compare equal to
4292 ** each other.  Jump to P2 if they are different.
4293 */
4294 case OP_SorterCompare: {
4295   VdbeCursor *pC;
4296   int res;
4297   int nKeyCol;
4298 
4299   pC = p->apCsr[pOp->p1];
4300   assert( isSorter(pC) );
4301   assert( pOp->p4type==P4_INT32 );
4302   pIn3 = &aMem[pOp->p3];
4303   nKeyCol = pOp->p4.i;
4304   rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
4305   VdbeBranchTaken(res!=0,2);
4306   if( res ){
4307     pc = pOp->p2-1;
4308   }
4309   break;
4310 };
4311 
4312 /* Opcode: SorterData P1 P2 * * *
4313 ** Synopsis: r[P2]=data
4314 **
4315 ** Write into register P2 the current sorter data for sorter cursor P1.
4316 */
4317 case OP_SorterData: {
4318   VdbeCursor *pC;
4319 
4320   pOut = &aMem[pOp->p2];
4321   pC = p->apCsr[pOp->p1];
4322   assert( isSorter(pC) );
4323   rc = sqlite3VdbeSorterRowkey(pC, pOut);
4324   assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
4325   break;
4326 }
4327 
4328 /* Opcode: RowData P1 P2 * * *
4329 ** Synopsis: r[P2]=data
4330 **
4331 ** Write into register P2 the complete row data for cursor P1.
4332 ** There is no interpretation of the data.
4333 ** It is just copied onto the P2 register exactly as
4334 ** it is found in the database file.
4335 **
4336 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
4337 ** of a real table, not a pseudo-table.
4338 */
4339 /* Opcode: RowKey P1 P2 * * *
4340 ** Synopsis: r[P2]=key
4341 **
4342 ** Write into register P2 the complete row key for cursor P1.
4343 ** There is no interpretation of the data.
4344 ** The key is copied onto the P2 register exactly as
4345 ** it is found in the database file.
4346 **
4347 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
4348 ** of a real table, not a pseudo-table.
4349 */
4350 case OP_RowKey:
4351 case OP_RowData: {
4352   VdbeCursor *pC;
4353   BtCursor *pCrsr;
4354   u32 n;
4355   i64 n64;
4356 
4357   pOut = &aMem[pOp->p2];
4358   memAboutToChange(p, pOut);
4359 
4360   /* Note that RowKey and RowData are really exactly the same instruction */
4361   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4362   pC = p->apCsr[pOp->p1];
4363   assert( isSorter(pC)==0 );
4364   assert( pC->isTable || pOp->opcode!=OP_RowData );
4365   assert( pC->isTable==0 || pOp->opcode==OP_RowData );
4366   assert( pC!=0 );
4367   assert( pC->nullRow==0 );
4368   assert( pC->pseudoTableReg==0 );
4369   assert( pC->pCursor!=0 );
4370   pCrsr = pC->pCursor;
4371   assert( sqlite3BtreeCursorIsValid(pCrsr) );
4372 
4373   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
4374   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
4375   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
4376   ** a no-op and can never fail.  But we leave it in place as a safety.
4377   */
4378   assert( pC->deferredMoveto==0 );
4379   rc = sqlite3VdbeCursorMoveto(pC);
4380   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
4381 
4382   if( pC->isTable==0 ){
4383     assert( !pC->isTable );
4384     VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
4385     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
4386     if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
4387       goto too_big;
4388     }
4389     n = (u32)n64;
4390   }else{
4391     VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
4392     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
4393     if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
4394       goto too_big;
4395     }
4396   }
4397   if( sqlite3VdbeMemGrow(pOut, n, 0) ){
4398     goto no_mem;
4399   }
4400   pOut->n = n;
4401   MemSetTypeFlag(pOut, MEM_Blob);
4402   if( pC->isTable==0 ){
4403     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
4404   }else{
4405     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
4406   }
4407   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
4408   UPDATE_MAX_BLOBSIZE(pOut);
4409   REGISTER_TRACE(pOp->p2, pOut);
4410   break;
4411 }
4412 
4413 /* Opcode: Rowid P1 P2 * * *
4414 ** Synopsis: r[P2]=rowid
4415 **
4416 ** Store in register P2 an integer which is the key of the table entry that
4417 ** P1 is currently point to.
4418 **
4419 ** P1 can be either an ordinary table or a virtual table.  There used to
4420 ** be a separate OP_VRowid opcode for use with virtual tables, but this
4421 ** one opcode now works for both table types.
4422 */
4423 case OP_Rowid: {                 /* out2-prerelease */
4424   VdbeCursor *pC;
4425   i64 v;
4426   sqlite3_vtab *pVtab;
4427   const sqlite3_module *pModule;
4428 
4429   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4430   pC = p->apCsr[pOp->p1];
4431   assert( pC!=0 );
4432   assert( pC->pseudoTableReg==0 || pC->nullRow );
4433   if( pC->nullRow ){
4434     pOut->flags = MEM_Null;
4435     break;
4436   }else if( pC->deferredMoveto ){
4437     v = pC->movetoTarget;
4438 #ifndef SQLITE_OMIT_VIRTUALTABLE
4439   }else if( pC->pVtabCursor ){
4440     pVtab = pC->pVtabCursor->pVtab;
4441     pModule = pVtab->pModule;
4442     assert( pModule->xRowid );
4443     rc = pModule->xRowid(pC->pVtabCursor, &v);
4444     sqlite3VtabImportErrmsg(p, pVtab);
4445 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4446   }else{
4447     assert( pC->pCursor!=0 );
4448     rc = sqlite3VdbeCursorMoveto(pC);
4449     if( rc ) goto abort_due_to_error;
4450     if( pC->rowidIsValid ){
4451       v = pC->lastRowid;
4452     }else{
4453       rc = sqlite3BtreeKeySize(pC->pCursor, &v);
4454       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
4455     }
4456   }
4457   pOut->u.i = v;
4458   break;
4459 }
4460 
4461 /* Opcode: NullRow P1 * * * *
4462 **
4463 ** Move the cursor P1 to a null row.  Any OP_Column operations
4464 ** that occur while the cursor is on the null row will always
4465 ** write a NULL.
4466 */
4467 case OP_NullRow: {
4468   VdbeCursor *pC;
4469 
4470   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4471   pC = p->apCsr[pOp->p1];
4472   assert( pC!=0 );
4473   pC->nullRow = 1;
4474   pC->rowidIsValid = 0;
4475   pC->cacheStatus = CACHE_STALE;
4476   if( pC->pCursor ){
4477     sqlite3BtreeClearCursor(pC->pCursor);
4478   }
4479   break;
4480 }
4481 
4482 /* Opcode: Last P1 P2 * * *
4483 **
4484 ** The next use of the Rowid or Column or Prev instruction for P1
4485 ** will refer to the last entry in the database table or index.
4486 ** If the table or index is empty and P2>0, then jump immediately to P2.
4487 ** If P2 is 0 or if the table or index is not empty, fall through
4488 ** to the following instruction.
4489 **
4490 ** This opcode leaves the cursor configured to move in reverse order,
4491 ** from the end toward the beginning.  In other words, the cursor is
4492 ** configured to use Prev, not Next.
4493 */
4494 case OP_Last: {        /* jump */
4495   VdbeCursor *pC;
4496   BtCursor *pCrsr;
4497   int res;
4498 
4499   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4500   pC = p->apCsr[pOp->p1];
4501   assert( pC!=0 );
4502   pCrsr = pC->pCursor;
4503   res = 0;
4504   assert( pCrsr!=0 );
4505   rc = sqlite3BtreeLast(pCrsr, &res);
4506   pC->nullRow = (u8)res;
4507   pC->deferredMoveto = 0;
4508   pC->rowidIsValid = 0;
4509   pC->cacheStatus = CACHE_STALE;
4510 #ifdef SQLITE_DEBUG
4511   pC->seekOp = OP_Last;
4512 #endif
4513   if( pOp->p2>0 ){
4514     VdbeBranchTaken(res!=0,2);
4515     if( res ) pc = pOp->p2 - 1;
4516   }
4517   break;
4518 }
4519 
4520 
4521 /* Opcode: Sort P1 P2 * * *
4522 **
4523 ** This opcode does exactly the same thing as OP_Rewind except that
4524 ** it increments an undocumented global variable used for testing.
4525 **
4526 ** Sorting is accomplished by writing records into a sorting index,
4527 ** then rewinding that index and playing it back from beginning to
4528 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
4529 ** rewinding so that the global variable will be incremented and
4530 ** regression tests can determine whether or not the optimizer is
4531 ** correctly optimizing out sorts.
4532 */
4533 case OP_SorterSort:    /* jump */
4534 case OP_Sort: {        /* jump */
4535 #ifdef SQLITE_TEST
4536   sqlite3_sort_count++;
4537   sqlite3_search_count--;
4538 #endif
4539   p->aCounter[SQLITE_STMTSTATUS_SORT]++;
4540   /* Fall through into OP_Rewind */
4541 }
4542 /* Opcode: Rewind P1 P2 * * *
4543 **
4544 ** The next use of the Rowid or Column or Next instruction for P1
4545 ** will refer to the first entry in the database table or index.
4546 ** If the table or index is empty and P2>0, then jump immediately to P2.
4547 ** If P2 is 0 or if the table or index is not empty, fall through
4548 ** to the following instruction.
4549 **
4550 ** This opcode leaves the cursor configured to move in forward order,
4551 ** from the begining toward the end.  In other words, the cursor is
4552 ** configured to use Next, not Prev.
4553 */
4554 case OP_Rewind: {        /* jump */
4555   VdbeCursor *pC;
4556   BtCursor *pCrsr;
4557   int res;
4558 
4559   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4560   pC = p->apCsr[pOp->p1];
4561   assert( pC!=0 );
4562   assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
4563   res = 1;
4564 #ifdef SQLITE_DEBUG
4565   pC->seekOp = OP_Rewind;
4566 #endif
4567   if( isSorter(pC) ){
4568     rc = sqlite3VdbeSorterRewind(db, pC, &res);
4569   }else{
4570     pCrsr = pC->pCursor;
4571     assert( pCrsr );
4572     rc = sqlite3BtreeFirst(pCrsr, &res);
4573     pC->deferredMoveto = 0;
4574     pC->cacheStatus = CACHE_STALE;
4575     pC->rowidIsValid = 0;
4576   }
4577   pC->nullRow = (u8)res;
4578   assert( pOp->p2>0 && pOp->p2<p->nOp );
4579   VdbeBranchTaken(res!=0,2);
4580   if( res ){
4581     pc = pOp->p2 - 1;
4582   }
4583   break;
4584 }
4585 
4586 /* Opcode: Next P1 P2 P3 P4 P5
4587 **
4588 ** Advance cursor P1 so that it points to the next key/data pair in its
4589 ** table or index.  If there are no more key/value pairs then fall through
4590 ** to the following instruction.  But if the cursor advance was successful,
4591 ** jump immediately to P2.
4592 **
4593 ** The Next opcode is only valid following an SeekGT, SeekGE, or
4594 ** OP_Rewind opcode used to position the cursor.  Next is not allowed
4595 ** to follow SeekLT, SeekLE, or OP_Last.
4596 **
4597 ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
4598 ** been opened prior to this opcode or the program will segfault.
4599 **
4600 ** The P3 value is a hint to the btree implementation. If P3==1, that
4601 ** means P1 is an SQL index and that this instruction could have been
4602 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
4603 ** always either 0 or 1.
4604 **
4605 ** P4 is always of type P4_ADVANCE. The function pointer points to
4606 ** sqlite3BtreeNext().
4607 **
4608 ** If P5 is positive and the jump is taken, then event counter
4609 ** number P5-1 in the prepared statement is incremented.
4610 **
4611 ** See also: Prev, NextIfOpen
4612 */
4613 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
4614 **
4615 ** This opcode works just like Next except that if cursor P1 is not
4616 ** open it behaves a no-op.
4617 */
4618 /* Opcode: Prev P1 P2 P3 P4 P5
4619 **
4620 ** Back up cursor P1 so that it points to the previous key/data pair in its
4621 ** table or index.  If there is no previous key/value pairs then fall through
4622 ** to the following instruction.  But if the cursor backup was successful,
4623 ** jump immediately to P2.
4624 **
4625 **
4626 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
4627 ** OP_Last opcode used to position the cursor.  Prev is not allowed
4628 ** to follow SeekGT, SeekGE, or OP_Rewind.
4629 **
4630 ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
4631 ** not open then the behavior is undefined.
4632 **
4633 ** The P3 value is a hint to the btree implementation. If P3==1, that
4634 ** means P1 is an SQL index and that this instruction could have been
4635 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
4636 ** always either 0 or 1.
4637 **
4638 ** P4 is always of type P4_ADVANCE. The function pointer points to
4639 ** sqlite3BtreePrevious().
4640 **
4641 ** If P5 is positive and the jump is taken, then event counter
4642 ** number P5-1 in the prepared statement is incremented.
4643 */
4644 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
4645 **
4646 ** This opcode works just like Prev except that if cursor P1 is not
4647 ** open it behaves a no-op.
4648 */
4649 case OP_SorterNext: {  /* jump */
4650   VdbeCursor *pC;
4651   int res;
4652 
4653   pC = p->apCsr[pOp->p1];
4654   assert( isSorter(pC) );
4655   res = 0;
4656   rc = sqlite3VdbeSorterNext(db, pC, &res);
4657   goto next_tail;
4658 case OP_PrevIfOpen:    /* jump */
4659 case OP_NextIfOpen:    /* jump */
4660   if( p->apCsr[pOp->p1]==0 ) break;
4661   /* Fall through */
4662 case OP_Prev:          /* jump */
4663 case OP_Next:          /* jump */
4664   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4665   assert( pOp->p5<ArraySize(p->aCounter) );
4666   pC = p->apCsr[pOp->p1];
4667   res = pOp->p3;
4668   assert( pC!=0 );
4669   assert( pC->deferredMoveto==0 );
4670   assert( pC->pCursor );
4671   assert( res==0 || (res==1 && pC->isTable==0) );
4672   testcase( res==1 );
4673   assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
4674   assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
4675   assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
4676   assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
4677 
4678   /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
4679   ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
4680   assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
4681        || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
4682        || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
4683   assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
4684        || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
4685        || pC->seekOp==OP_Last );
4686 
4687   rc = pOp->p4.xAdvance(pC->pCursor, &res);
4688 next_tail:
4689   pC->cacheStatus = CACHE_STALE;
4690   VdbeBranchTaken(res==0,2);
4691   if( res==0 ){
4692     pC->nullRow = 0;
4693     pc = pOp->p2 - 1;
4694     p->aCounter[pOp->p5]++;
4695 #ifdef SQLITE_TEST
4696     sqlite3_search_count++;
4697 #endif
4698   }else{
4699     pC->nullRow = 1;
4700   }
4701   pC->rowidIsValid = 0;
4702   goto check_for_interrupt;
4703 }
4704 
4705 /* Opcode: IdxInsert P1 P2 P3 * P5
4706 ** Synopsis: key=r[P2]
4707 **
4708 ** Register P2 holds an SQL index key made using the
4709 ** MakeRecord instructions.  This opcode writes that key
4710 ** into the index P1.  Data for the entry is nil.
4711 **
4712 ** P3 is a flag that provides a hint to the b-tree layer that this
4713 ** insert is likely to be an append.
4714 **
4715 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
4716 ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
4717 ** then the change counter is unchanged.
4718 **
4719 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
4720 ** just done a seek to the spot where the new entry is to be inserted.
4721 ** This flag avoids doing an extra seek.
4722 **
4723 ** This instruction only works for indices.  The equivalent instruction
4724 ** for tables is OP_Insert.
4725 */
4726 case OP_SorterInsert:       /* in2 */
4727 case OP_IdxInsert: {        /* in2 */
4728   VdbeCursor *pC;
4729   BtCursor *pCrsr;
4730   int nKey;
4731   const char *zKey;
4732 
4733   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4734   pC = p->apCsr[pOp->p1];
4735   assert( pC!=0 );
4736   assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
4737   pIn2 = &aMem[pOp->p2];
4738   assert( pIn2->flags & MEM_Blob );
4739   pCrsr = pC->pCursor;
4740   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
4741   assert( pCrsr!=0 );
4742   assert( pC->isTable==0 );
4743   rc = ExpandBlob(pIn2);
4744   if( rc==SQLITE_OK ){
4745     if( isSorter(pC) ){
4746       rc = sqlite3VdbeSorterWrite(db, pC, pIn2);
4747     }else{
4748       nKey = pIn2->n;
4749       zKey = pIn2->z;
4750       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
4751           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
4752           );
4753       assert( pC->deferredMoveto==0 );
4754       pC->cacheStatus = CACHE_STALE;
4755     }
4756   }
4757   break;
4758 }
4759 
4760 /* Opcode: IdxDelete P1 P2 P3 * *
4761 ** Synopsis: key=r[P2@P3]
4762 **
4763 ** The content of P3 registers starting at register P2 form
4764 ** an unpacked index key. This opcode removes that entry from the
4765 ** index opened by cursor P1.
4766 */
4767 case OP_IdxDelete: {
4768   VdbeCursor *pC;
4769   BtCursor *pCrsr;
4770   int res;
4771   UnpackedRecord r;
4772 
4773   assert( pOp->p3>0 );
4774   assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
4775   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4776   pC = p->apCsr[pOp->p1];
4777   assert( pC!=0 );
4778   pCrsr = pC->pCursor;
4779   assert( pCrsr!=0 );
4780   assert( pOp->p5==0 );
4781   r.pKeyInfo = pC->pKeyInfo;
4782   r.nField = (u16)pOp->p3;
4783   r.default_rc = 0;
4784   r.aMem = &aMem[pOp->p2];
4785 #ifdef SQLITE_DEBUG
4786   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
4787 #endif
4788   rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
4789   if( rc==SQLITE_OK && res==0 ){
4790     rc = sqlite3BtreeDelete(pCrsr);
4791   }
4792   assert( pC->deferredMoveto==0 );
4793   pC->cacheStatus = CACHE_STALE;
4794   break;
4795 }
4796 
4797 /* Opcode: IdxRowid P1 P2 * * *
4798 ** Synopsis: r[P2]=rowid
4799 **
4800 ** Write into register P2 an integer which is the last entry in the record at
4801 ** the end of the index key pointed to by cursor P1.  This integer should be
4802 ** the rowid of the table entry to which this index entry points.
4803 **
4804 ** See also: Rowid, MakeRecord.
4805 */
4806 case OP_IdxRowid: {              /* out2-prerelease */
4807   BtCursor *pCrsr;
4808   VdbeCursor *pC;
4809   i64 rowid;
4810 
4811   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4812   pC = p->apCsr[pOp->p1];
4813   assert( pC!=0 );
4814   pCrsr = pC->pCursor;
4815   assert( pCrsr!=0 );
4816   pOut->flags = MEM_Null;
4817   rc = sqlite3VdbeCursorMoveto(pC);
4818   if( NEVER(rc) ) goto abort_due_to_error;
4819   assert( pC->deferredMoveto==0 );
4820   assert( pC->isTable==0 );
4821   if( !pC->nullRow ){
4822     rowid = 0;  /* Not needed.  Only used to silence a warning. */
4823     rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
4824     if( rc!=SQLITE_OK ){
4825       goto abort_due_to_error;
4826     }
4827     pOut->u.i = rowid;
4828     pOut->flags = MEM_Int;
4829   }
4830   break;
4831 }
4832 
4833 /* Opcode: IdxGE P1 P2 P3 P4 P5
4834 ** Synopsis: key=r[P3@P4]
4835 **
4836 ** The P4 register values beginning with P3 form an unpacked index
4837 ** key that omits the PRIMARY KEY.  Compare this key value against the index
4838 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
4839 ** fields at the end.
4840 **
4841 ** If the P1 index entry is greater than or equal to the key value
4842 ** then jump to P2.  Otherwise fall through to the next instruction.
4843 */
4844 /* Opcode: IdxGT P1 P2 P3 P4 P5
4845 ** Synopsis: key=r[P3@P4]
4846 **
4847 ** The P4 register values beginning with P3 form an unpacked index
4848 ** key that omits the PRIMARY KEY.  Compare this key value against the index
4849 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
4850 ** fields at the end.
4851 **
4852 ** If the P1 index entry is greater than the key value
4853 ** then jump to P2.  Otherwise fall through to the next instruction.
4854 */
4855 /* Opcode: IdxLT P1 P2 P3 P4 P5
4856 ** Synopsis: key=r[P3@P4]
4857 **
4858 ** The P4 register values beginning with P3 form an unpacked index
4859 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
4860 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
4861 ** ROWID on the P1 index.
4862 **
4863 ** If the P1 index entry is less than the key value then jump to P2.
4864 ** Otherwise fall through to the next instruction.
4865 */
4866 /* Opcode: IdxLE P1 P2 P3 P4 P5
4867 ** Synopsis: key=r[P3@P4]
4868 **
4869 ** The P4 register values beginning with P3 form an unpacked index
4870 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
4871 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
4872 ** ROWID on the P1 index.
4873 **
4874 ** If the P1 index entry is less than or equal to the key value then jump
4875 ** to P2. Otherwise fall through to the next instruction.
4876 */
4877 case OP_IdxLE:          /* jump */
4878 case OP_IdxGT:          /* jump */
4879 case OP_IdxLT:          /* jump */
4880 case OP_IdxGE:  {       /* jump */
4881   VdbeCursor *pC;
4882   int res;
4883   UnpackedRecord r;
4884 
4885   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4886   pC = p->apCsr[pOp->p1];
4887   assert( pC!=0 );
4888   assert( pC->isOrdered );
4889   assert( pC->pCursor!=0);
4890   assert( pC->deferredMoveto==0 );
4891   assert( pOp->p5==0 || pOp->p5==1 );
4892   assert( pOp->p4type==P4_INT32 );
4893   r.pKeyInfo = pC->pKeyInfo;
4894   r.nField = (u16)pOp->p4.i;
4895   if( pOp->opcode<OP_IdxLT ){
4896     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
4897     r.default_rc = -1;
4898   }else{
4899     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
4900     r.default_rc = 0;
4901   }
4902   r.aMem = &aMem[pOp->p3];
4903 #ifdef SQLITE_DEBUG
4904   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
4905 #endif
4906   res = 0;  /* Not needed.  Only used to silence a warning. */
4907   rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
4908   assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
4909   if( (pOp->opcode&1)==(OP_IdxLT&1) ){
4910     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
4911     res = -res;
4912   }else{
4913     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
4914     res++;
4915   }
4916   VdbeBranchTaken(res>0,2);
4917   if( res>0 ){
4918     pc = pOp->p2 - 1 ;
4919   }
4920   break;
4921 }
4922 
4923 /* Opcode: Destroy P1 P2 P3 * *
4924 **
4925 ** Delete an entire database table or index whose root page in the database
4926 ** file is given by P1.
4927 **
4928 ** The table being destroyed is in the main database file if P3==0.  If
4929 ** P3==1 then the table to be clear is in the auxiliary database file
4930 ** that is used to store tables create using CREATE TEMPORARY TABLE.
4931 **
4932 ** If AUTOVACUUM is enabled then it is possible that another root page
4933 ** might be moved into the newly deleted root page in order to keep all
4934 ** root pages contiguous at the beginning of the database.  The former
4935 ** value of the root page that moved - its value before the move occurred -
4936 ** is stored in register P2.  If no page
4937 ** movement was required (because the table being dropped was already
4938 ** the last one in the database) then a zero is stored in register P2.
4939 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
4940 **
4941 ** See also: Clear
4942 */
4943 case OP_Destroy: {     /* out2-prerelease */
4944   int iMoved;
4945   int iCnt;
4946   Vdbe *pVdbe;
4947   int iDb;
4948 
4949   assert( p->readOnly==0 );
4950 #ifndef SQLITE_OMIT_VIRTUALTABLE
4951   iCnt = 0;
4952   for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
4953     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader
4954      && pVdbe->inVtabMethod<2 && pVdbe->pc>=0
4955     ){
4956       iCnt++;
4957     }
4958   }
4959 #else
4960   iCnt = db->nVdbeRead;
4961 #endif
4962   pOut->flags = MEM_Null;
4963   if( iCnt>1 ){
4964     rc = SQLITE_LOCKED;
4965     p->errorAction = OE_Abort;
4966   }else{
4967     iDb = pOp->p3;
4968     assert( iCnt==1 );
4969     assert( DbMaskTest(p->btreeMask, iDb) );
4970     iMoved = 0;  /* Not needed.  Only to silence a warning. */
4971     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
4972     pOut->flags = MEM_Int;
4973     pOut->u.i = iMoved;
4974 #ifndef SQLITE_OMIT_AUTOVACUUM
4975     if( rc==SQLITE_OK && iMoved!=0 ){
4976       sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
4977       /* All OP_Destroy operations occur on the same btree */
4978       assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
4979       resetSchemaOnFault = iDb+1;
4980     }
4981 #endif
4982   }
4983   break;
4984 }
4985 
4986 /* Opcode: Clear P1 P2 P3
4987 **
4988 ** Delete all contents of the database table or index whose root page
4989 ** in the database file is given by P1.  But, unlike Destroy, do not
4990 ** remove the table or index from the database file.
4991 **
4992 ** The table being clear is in the main database file if P2==0.  If
4993 ** P2==1 then the table to be clear is in the auxiliary database file
4994 ** that is used to store tables create using CREATE TEMPORARY TABLE.
4995 **
4996 ** If the P3 value is non-zero, then the table referred to must be an
4997 ** intkey table (an SQL table, not an index). In this case the row change
4998 ** count is incremented by the number of rows in the table being cleared.
4999 ** If P3 is greater than zero, then the value stored in register P3 is
5000 ** also incremented by the number of rows in the table being cleared.
5001 **
5002 ** See also: Destroy
5003 */
5004 case OP_Clear: {
5005   int nChange;
5006 
5007   nChange = 0;
5008   assert( p->readOnly==0 );
5009   assert( DbMaskTest(p->btreeMask, pOp->p2) );
5010   rc = sqlite3BtreeClearTable(
5011       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
5012   );
5013   if( pOp->p3 ){
5014     p->nChange += nChange;
5015     if( pOp->p3>0 ){
5016       assert( memIsValid(&aMem[pOp->p3]) );
5017       memAboutToChange(p, &aMem[pOp->p3]);
5018       aMem[pOp->p3].u.i += nChange;
5019     }
5020   }
5021   break;
5022 }
5023 
5024 /* Opcode: ResetSorter P1 * * * *
5025 **
5026 ** Delete all contents from the ephemeral table or sorter
5027 ** that is open on cursor P1.
5028 **
5029 ** This opcode only works for cursors used for sorting and
5030 ** opened with OP_OpenEphemeral or OP_SorterOpen.
5031 */
5032 case OP_ResetSorter: {
5033   VdbeCursor *pC;
5034 
5035   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5036   pC = p->apCsr[pOp->p1];
5037   assert( pC!=0 );
5038   if( pC->pSorter ){
5039     sqlite3VdbeSorterReset(db, pC->pSorter);
5040   }else{
5041     assert( pC->isEphemeral );
5042     rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
5043   }
5044   break;
5045 }
5046 
5047 /* Opcode: CreateTable P1 P2 * * *
5048 ** Synopsis: r[P2]=root iDb=P1
5049 **
5050 ** Allocate a new table in the main database file if P1==0 or in the
5051 ** auxiliary database file if P1==1 or in an attached database if
5052 ** P1>1.  Write the root page number of the new table into
5053 ** register P2
5054 **
5055 ** The difference between a table and an index is this:  A table must
5056 ** have a 4-byte integer key and can have arbitrary data.  An index
5057 ** has an arbitrary key but no data.
5058 **
5059 ** See also: CreateIndex
5060 */
5061 /* Opcode: CreateIndex P1 P2 * * *
5062 ** Synopsis: r[P2]=root iDb=P1
5063 **
5064 ** Allocate a new index in the main database file if P1==0 or in the
5065 ** auxiliary database file if P1==1 or in an attached database if
5066 ** P1>1.  Write the root page number of the new table into
5067 ** register P2.
5068 **
5069 ** See documentation on OP_CreateTable for additional information.
5070 */
5071 case OP_CreateIndex:            /* out2-prerelease */
5072 case OP_CreateTable: {          /* out2-prerelease */
5073   int pgno;
5074   int flags;
5075   Db *pDb;
5076 
5077   pgno = 0;
5078   assert( pOp->p1>=0 && pOp->p1<db->nDb );
5079   assert( DbMaskTest(p->btreeMask, pOp->p1) );
5080   assert( p->readOnly==0 );
5081   pDb = &db->aDb[pOp->p1];
5082   assert( pDb->pBt!=0 );
5083   if( pOp->opcode==OP_CreateTable ){
5084     /* flags = BTREE_INTKEY; */
5085     flags = BTREE_INTKEY;
5086   }else{
5087     flags = BTREE_BLOBKEY;
5088   }
5089   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
5090   pOut->u.i = pgno;
5091   break;
5092 }
5093 
5094 /* Opcode: ParseSchema P1 * * P4 *
5095 **
5096 ** Read and parse all entries from the SQLITE_MASTER table of database P1
5097 ** that match the WHERE clause P4.
5098 **
5099 ** This opcode invokes the parser to create a new virtual machine,
5100 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
5101 */
5102 case OP_ParseSchema: {
5103   int iDb;
5104   const char *zMaster;
5105   char *zSql;
5106   InitData initData;
5107 
5108   /* Any prepared statement that invokes this opcode will hold mutexes
5109   ** on every btree.  This is a prerequisite for invoking
5110   ** sqlite3InitCallback().
5111   */
5112 #ifdef SQLITE_DEBUG
5113   for(iDb=0; iDb<db->nDb; iDb++){
5114     assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
5115   }
5116 #endif
5117 
5118   iDb = pOp->p1;
5119   assert( iDb>=0 && iDb<db->nDb );
5120   assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
5121   /* Used to be a conditional */ {
5122     zMaster = SCHEMA_TABLE(iDb);
5123     initData.db = db;
5124     initData.iDb = pOp->p1;
5125     initData.pzErrMsg = &p->zErrMsg;
5126     zSql = sqlite3MPrintf(db,
5127        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
5128        db->aDb[iDb].zName, zMaster, pOp->p4.z);
5129     if( zSql==0 ){
5130       rc = SQLITE_NOMEM;
5131     }else{
5132       assert( db->init.busy==0 );
5133       db->init.busy = 1;
5134       initData.rc = SQLITE_OK;
5135       assert( !db->mallocFailed );
5136       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
5137       if( rc==SQLITE_OK ) rc = initData.rc;
5138       sqlite3DbFree(db, zSql);
5139       db->init.busy = 0;
5140     }
5141   }
5142   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
5143   if( rc==SQLITE_NOMEM ){
5144     goto no_mem;
5145   }
5146   break;
5147 }
5148 
5149 #if !defined(SQLITE_OMIT_ANALYZE)
5150 /* Opcode: LoadAnalysis P1 * * * *
5151 **
5152 ** Read the sqlite_stat1 table for database P1 and load the content
5153 ** of that table into the internal index hash table.  This will cause
5154 ** the analysis to be used when preparing all subsequent queries.
5155 */
5156 case OP_LoadAnalysis: {
5157   assert( pOp->p1>=0 && pOp->p1<db->nDb );
5158   rc = sqlite3AnalysisLoad(db, pOp->p1);
5159   break;
5160 }
5161 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
5162 
5163 /* Opcode: DropTable P1 * * P4 *
5164 **
5165 ** Remove the internal (in-memory) data structures that describe
5166 ** the table named P4 in database P1.  This is called after a table
5167 ** is dropped from disk (using the Destroy opcode) in order to keep
5168 ** the internal representation of the
5169 ** schema consistent with what is on disk.
5170 */
5171 case OP_DropTable: {
5172   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
5173   break;
5174 }
5175 
5176 /* Opcode: DropIndex P1 * * P4 *
5177 **
5178 ** Remove the internal (in-memory) data structures that describe
5179 ** the index named P4 in database P1.  This is called after an index
5180 ** is dropped from disk (using the Destroy opcode)
5181 ** in order to keep the internal representation of the
5182 ** schema consistent with what is on disk.
5183 */
5184 case OP_DropIndex: {
5185   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
5186   break;
5187 }
5188 
5189 /* Opcode: DropTrigger P1 * * P4 *
5190 **
5191 ** Remove the internal (in-memory) data structures that describe
5192 ** the trigger named P4 in database P1.  This is called after a trigger
5193 ** is dropped from disk (using the Destroy opcode) in order to keep
5194 ** the internal representation of the
5195 ** schema consistent with what is on disk.
5196 */
5197 case OP_DropTrigger: {
5198   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
5199   break;
5200 }
5201 
5202 
5203 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
5204 /* Opcode: IntegrityCk P1 P2 P3 * P5
5205 **
5206 ** Do an analysis of the currently open database.  Store in
5207 ** register P1 the text of an error message describing any problems.
5208 ** If no problems are found, store a NULL in register P1.
5209 **
5210 ** The register P3 contains the maximum number of allowed errors.
5211 ** At most reg(P3) errors will be reported.
5212 ** In other words, the analysis stops as soon as reg(P1) errors are
5213 ** seen.  Reg(P1) is updated with the number of errors remaining.
5214 **
5215 ** The root page numbers of all tables in the database are integer
5216 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
5217 ** total.
5218 **
5219 ** If P5 is not zero, the check is done on the auxiliary database
5220 ** file, not the main database file.
5221 **
5222 ** This opcode is used to implement the integrity_check pragma.
5223 */
5224 case OP_IntegrityCk: {
5225   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
5226   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
5227   int j;          /* Loop counter */
5228   int nErr;       /* Number of errors reported */
5229   char *z;        /* Text of the error report */
5230   Mem *pnErr;     /* Register keeping track of errors remaining */
5231 
5232   assert( p->bIsReader );
5233   nRoot = pOp->p2;
5234   assert( nRoot>0 );
5235   aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
5236   if( aRoot==0 ) goto no_mem;
5237   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
5238   pnErr = &aMem[pOp->p3];
5239   assert( (pnErr->flags & MEM_Int)!=0 );
5240   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
5241   pIn1 = &aMem[pOp->p1];
5242   for(j=0; j<nRoot; j++){
5243     aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
5244   }
5245   aRoot[j] = 0;
5246   assert( pOp->p5<db->nDb );
5247   assert( DbMaskTest(p->btreeMask, pOp->p5) );
5248   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
5249                                  (int)pnErr->u.i, &nErr);
5250   sqlite3DbFree(db, aRoot);
5251   pnErr->u.i -= nErr;
5252   sqlite3VdbeMemSetNull(pIn1);
5253   if( nErr==0 ){
5254     assert( z==0 );
5255   }else if( z==0 ){
5256     goto no_mem;
5257   }else{
5258     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
5259   }
5260   UPDATE_MAX_BLOBSIZE(pIn1);
5261   sqlite3VdbeChangeEncoding(pIn1, encoding);
5262   break;
5263 }
5264 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
5265 
5266 /* Opcode: RowSetAdd P1 P2 * * *
5267 ** Synopsis:  rowset(P1)=r[P2]
5268 **
5269 ** Insert the integer value held by register P2 into a boolean index
5270 ** held in register P1.
5271 **
5272 ** An assertion fails if P2 is not an integer.
5273 */
5274 case OP_RowSetAdd: {       /* in1, in2 */
5275   pIn1 = &aMem[pOp->p1];
5276   pIn2 = &aMem[pOp->p2];
5277   assert( (pIn2->flags & MEM_Int)!=0 );
5278   if( (pIn1->flags & MEM_RowSet)==0 ){
5279     sqlite3VdbeMemSetRowSet(pIn1);
5280     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
5281   }
5282   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
5283   break;
5284 }
5285 
5286 /* Opcode: RowSetRead P1 P2 P3 * *
5287 ** Synopsis:  r[P3]=rowset(P1)
5288 **
5289 ** Extract the smallest value from boolean index P1 and put that value into
5290 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
5291 ** unchanged and jump to instruction P2.
5292 */
5293 case OP_RowSetRead: {       /* jump, in1, out3 */
5294   i64 val;
5295 
5296   pIn1 = &aMem[pOp->p1];
5297   if( (pIn1->flags & MEM_RowSet)==0
5298    || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
5299   ){
5300     /* The boolean index is empty */
5301     sqlite3VdbeMemSetNull(pIn1);
5302     pc = pOp->p2 - 1;
5303     VdbeBranchTaken(1,2);
5304   }else{
5305     /* A value was pulled from the index */
5306     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
5307     VdbeBranchTaken(0,2);
5308   }
5309   goto check_for_interrupt;
5310 }
5311 
5312 /* Opcode: RowSetTest P1 P2 P3 P4
5313 ** Synopsis: if r[P3] in rowset(P1) goto P2
5314 **
5315 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
5316 ** contains a RowSet object and that RowSet object contains
5317 ** the value held in P3, jump to register P2. Otherwise, insert the
5318 ** integer in P3 into the RowSet and continue on to the
5319 ** next opcode.
5320 **
5321 ** The RowSet object is optimized for the case where successive sets
5322 ** of integers, where each set contains no duplicates. Each set
5323 ** of values is identified by a unique P4 value. The first set
5324 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
5325 ** non-negative.  For non-negative values of P4 only the lower 4
5326 ** bits are significant.
5327 **
5328 ** This allows optimizations: (a) when P4==0 there is no need to test
5329 ** the rowset object for P3, as it is guaranteed not to contain it,
5330 ** (b) when P4==-1 there is no need to insert the value, as it will
5331 ** never be tested for, and (c) when a value that is part of set X is
5332 ** inserted, there is no need to search to see if the same value was
5333 ** previously inserted as part of set X (only if it was previously
5334 ** inserted as part of some other set).
5335 */
5336 case OP_RowSetTest: {                     /* jump, in1, in3 */
5337   int iSet;
5338   int exists;
5339 
5340   pIn1 = &aMem[pOp->p1];
5341   pIn3 = &aMem[pOp->p3];
5342   iSet = pOp->p4.i;
5343   assert( pIn3->flags&MEM_Int );
5344 
5345   /* If there is anything other than a rowset object in memory cell P1,
5346   ** delete it now and initialize P1 with an empty rowset
5347   */
5348   if( (pIn1->flags & MEM_RowSet)==0 ){
5349     sqlite3VdbeMemSetRowSet(pIn1);
5350     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
5351   }
5352 
5353   assert( pOp->p4type==P4_INT32 );
5354   assert( iSet==-1 || iSet>=0 );
5355   if( iSet ){
5356     exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
5357     VdbeBranchTaken(exists!=0,2);
5358     if( exists ){
5359       pc = pOp->p2 - 1;
5360       break;
5361     }
5362   }
5363   if( iSet>=0 ){
5364     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
5365   }
5366   break;
5367 }
5368 
5369 
5370 #ifndef SQLITE_OMIT_TRIGGER
5371 
5372 /* Opcode: Program P1 P2 P3 P4 P5
5373 **
5374 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
5375 **
5376 ** P1 contains the address of the memory cell that contains the first memory
5377 ** cell in an array of values used as arguments to the sub-program. P2
5378 ** contains the address to jump to if the sub-program throws an IGNORE
5379 ** exception using the RAISE() function. Register P3 contains the address
5380 ** of a memory cell in this (the parent) VM that is used to allocate the
5381 ** memory required by the sub-vdbe at runtime.
5382 **
5383 ** P4 is a pointer to the VM containing the trigger program.
5384 **
5385 ** If P5 is non-zero, then recursive program invocation is enabled.
5386 */
5387 case OP_Program: {        /* jump */
5388   int nMem;               /* Number of memory registers for sub-program */
5389   int nByte;              /* Bytes of runtime space required for sub-program */
5390   Mem *pRt;               /* Register to allocate runtime space */
5391   Mem *pMem;              /* Used to iterate through memory cells */
5392   Mem *pEnd;              /* Last memory cell in new array */
5393   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
5394   SubProgram *pProgram;   /* Sub-program to execute */
5395   void *t;                /* Token identifying trigger */
5396 
5397   pProgram = pOp->p4.pProgram;
5398   pRt = &aMem[pOp->p3];
5399   assert( pProgram->nOp>0 );
5400 
5401   /* If the p5 flag is clear, then recursive invocation of triggers is
5402   ** disabled for backwards compatibility (p5 is set if this sub-program
5403   ** is really a trigger, not a foreign key action, and the flag set
5404   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
5405   **
5406   ** It is recursive invocation of triggers, at the SQL level, that is
5407   ** disabled. In some cases a single trigger may generate more than one
5408   ** SubProgram (if the trigger may be executed with more than one different
5409   ** ON CONFLICT algorithm). SubProgram structures associated with a
5410   ** single trigger all have the same value for the SubProgram.token
5411   ** variable.  */
5412   if( pOp->p5 ){
5413     t = pProgram->token;
5414     for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
5415     if( pFrame ) break;
5416   }
5417 
5418   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
5419     rc = SQLITE_ERROR;
5420     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
5421     break;
5422   }
5423 
5424   /* Register pRt is used to store the memory required to save the state
5425   ** of the current program, and the memory required at runtime to execute
5426   ** the trigger program. If this trigger has been fired before, then pRt
5427   ** is already allocated. Otherwise, it must be initialized.  */
5428   if( (pRt->flags&MEM_Frame)==0 ){
5429     /* SubProgram.nMem is set to the number of memory cells used by the
5430     ** program stored in SubProgram.aOp. As well as these, one memory
5431     ** cell is required for each cursor used by the program. Set local
5432     ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
5433     */
5434     nMem = pProgram->nMem + pProgram->nCsr;
5435     nByte = ROUND8(sizeof(VdbeFrame))
5436               + nMem * sizeof(Mem)
5437               + pProgram->nCsr * sizeof(VdbeCursor *)
5438               + pProgram->nOnce * sizeof(u8);
5439     pFrame = sqlite3DbMallocZero(db, nByte);
5440     if( !pFrame ){
5441       goto no_mem;
5442     }
5443     sqlite3VdbeMemRelease(pRt);
5444     pRt->flags = MEM_Frame;
5445     pRt->u.pFrame = pFrame;
5446 
5447     pFrame->v = p;
5448     pFrame->nChildMem = nMem;
5449     pFrame->nChildCsr = pProgram->nCsr;
5450     pFrame->pc = pc;
5451     pFrame->aMem = p->aMem;
5452     pFrame->nMem = p->nMem;
5453     pFrame->apCsr = p->apCsr;
5454     pFrame->nCursor = p->nCursor;
5455     pFrame->aOp = p->aOp;
5456     pFrame->nOp = p->nOp;
5457     pFrame->token = pProgram->token;
5458     pFrame->aOnceFlag = p->aOnceFlag;
5459     pFrame->nOnceFlag = p->nOnceFlag;
5460 
5461     pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
5462     for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
5463       pMem->flags = MEM_Undefined;
5464       pMem->db = db;
5465     }
5466   }else{
5467     pFrame = pRt->u.pFrame;
5468     assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
5469     assert( pProgram->nCsr==pFrame->nChildCsr );
5470     assert( pc==pFrame->pc );
5471   }
5472 
5473   p->nFrame++;
5474   pFrame->pParent = p->pFrame;
5475   pFrame->lastRowid = lastRowid;
5476   pFrame->nChange = p->nChange;
5477   p->nChange = 0;
5478   p->pFrame = pFrame;
5479   p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
5480   p->nMem = pFrame->nChildMem;
5481   p->nCursor = (u16)pFrame->nChildCsr;
5482   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
5483   p->aOp = aOp = pProgram->aOp;
5484   p->nOp = pProgram->nOp;
5485   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
5486   p->nOnceFlag = pProgram->nOnce;
5487   pc = -1;
5488   memset(p->aOnceFlag, 0, p->nOnceFlag);
5489 
5490   break;
5491 }
5492 
5493 /* Opcode: Param P1 P2 * * *
5494 **
5495 ** This opcode is only ever present in sub-programs called via the
5496 ** OP_Program instruction. Copy a value currently stored in a memory
5497 ** cell of the calling (parent) frame to cell P2 in the current frames
5498 ** address space. This is used by trigger programs to access the new.*
5499 ** and old.* values.
5500 **
5501 ** The address of the cell in the parent frame is determined by adding
5502 ** the value of the P1 argument to the value of the P1 argument to the
5503 ** calling OP_Program instruction.
5504 */
5505 case OP_Param: {           /* out2-prerelease */
5506   VdbeFrame *pFrame;
5507   Mem *pIn;
5508   pFrame = p->pFrame;
5509   pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
5510   sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
5511   break;
5512 }
5513 
5514 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
5515 
5516 #ifndef SQLITE_OMIT_FOREIGN_KEY
5517 /* Opcode: FkCounter P1 P2 * * *
5518 ** Synopsis: fkctr[P1]+=P2
5519 **
5520 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
5521 ** If P1 is non-zero, the database constraint counter is incremented
5522 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
5523 ** statement counter is incremented (immediate foreign key constraints).
5524 */
5525 case OP_FkCounter: {
5526   if( db->flags & SQLITE_DeferFKs ){
5527     db->nDeferredImmCons += pOp->p2;
5528   }else if( pOp->p1 ){
5529     db->nDeferredCons += pOp->p2;
5530   }else{
5531     p->nFkConstraint += pOp->p2;
5532   }
5533   break;
5534 }
5535 
5536 /* Opcode: FkIfZero P1 P2 * * *
5537 ** Synopsis: if fkctr[P1]==0 goto P2
5538 **
5539 ** This opcode tests if a foreign key constraint-counter is currently zero.
5540 ** If so, jump to instruction P2. Otherwise, fall through to the next
5541 ** instruction.
5542 **
5543 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
5544 ** is zero (the one that counts deferred constraint violations). If P1 is
5545 ** zero, the jump is taken if the statement constraint-counter is zero
5546 ** (immediate foreign key constraint violations).
5547 */
5548 case OP_FkIfZero: {         /* jump */
5549   if( pOp->p1 ){
5550     VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
5551     if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
5552   }else{
5553     VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
5554     if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
5555   }
5556   break;
5557 }
5558 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
5559 
5560 #ifndef SQLITE_OMIT_AUTOINCREMENT
5561 /* Opcode: MemMax P1 P2 * * *
5562 ** Synopsis: r[P1]=max(r[P1],r[P2])
5563 **
5564 ** P1 is a register in the root frame of this VM (the root frame is
5565 ** different from the current frame if this instruction is being executed
5566 ** within a sub-program). Set the value of register P1 to the maximum of
5567 ** its current value and the value in register P2.
5568 **
5569 ** This instruction throws an error if the memory cell is not initially
5570 ** an integer.
5571 */
5572 case OP_MemMax: {        /* in2 */
5573   VdbeFrame *pFrame;
5574   if( p->pFrame ){
5575     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
5576     pIn1 = &pFrame->aMem[pOp->p1];
5577   }else{
5578     pIn1 = &aMem[pOp->p1];
5579   }
5580   assert( memIsValid(pIn1) );
5581   sqlite3VdbeMemIntegerify(pIn1);
5582   pIn2 = &aMem[pOp->p2];
5583   sqlite3VdbeMemIntegerify(pIn2);
5584   if( pIn1->u.i<pIn2->u.i){
5585     pIn1->u.i = pIn2->u.i;
5586   }
5587   break;
5588 }
5589 #endif /* SQLITE_OMIT_AUTOINCREMENT */
5590 
5591 /* Opcode: IfPos P1 P2 * * *
5592 ** Synopsis: if r[P1]>0 goto P2
5593 **
5594 ** If the value of register P1 is 1 or greater, jump to P2.
5595 **
5596 ** It is illegal to use this instruction on a register that does
5597 ** not contain an integer.  An assertion fault will result if you try.
5598 */
5599 case OP_IfPos: {        /* jump, in1 */
5600   pIn1 = &aMem[pOp->p1];
5601   assert( pIn1->flags&MEM_Int );
5602   VdbeBranchTaken( pIn1->u.i>0, 2);
5603   if( pIn1->u.i>0 ){
5604      pc = pOp->p2 - 1;
5605   }
5606   break;
5607 }
5608 
5609 /* Opcode: IfNeg P1 P2 P3 * *
5610 ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
5611 **
5612 ** Register P1 must contain an integer.  Add literal P3 to the value in
5613 ** register P1 then if the value of register P1 is less than zero, jump to P2.
5614 */
5615 case OP_IfNeg: {        /* jump, in1 */
5616   pIn1 = &aMem[pOp->p1];
5617   assert( pIn1->flags&MEM_Int );
5618   pIn1->u.i += pOp->p3;
5619   VdbeBranchTaken(pIn1->u.i<0, 2);
5620   if( pIn1->u.i<0 ){
5621      pc = pOp->p2 - 1;
5622   }
5623   break;
5624 }
5625 
5626 /* Opcode: IfZero P1 P2 P3 * *
5627 ** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2
5628 **
5629 ** The register P1 must contain an integer.  Add literal P3 to the
5630 ** value in register P1.  If the result is exactly 0, jump to P2.
5631 */
5632 case OP_IfZero: {        /* jump, in1 */
5633   pIn1 = &aMem[pOp->p1];
5634   assert( pIn1->flags&MEM_Int );
5635   pIn1->u.i += pOp->p3;
5636   VdbeBranchTaken(pIn1->u.i==0, 2);
5637   if( pIn1->u.i==0 ){
5638      pc = pOp->p2 - 1;
5639   }
5640   break;
5641 }
5642 
5643 /* Opcode: AggStep * P2 P3 P4 P5
5644 ** Synopsis: accum=r[P3] step(r[P2@P5])
5645 **
5646 ** Execute the step function for an aggregate.  The
5647 ** function has P5 arguments.   P4 is a pointer to the FuncDef
5648 ** structure that specifies the function.  Use register
5649 ** P3 as the accumulator.
5650 **
5651 ** The P5 arguments are taken from register P2 and its
5652 ** successors.
5653 */
5654 case OP_AggStep: {
5655   int n;
5656   int i;
5657   Mem *pMem;
5658   Mem *pRec;
5659   sqlite3_context ctx;
5660   sqlite3_value **apVal;
5661 
5662   n = pOp->p5;
5663   assert( n>=0 );
5664   pRec = &aMem[pOp->p2];
5665   apVal = p->apArg;
5666   assert( apVal || n==0 );
5667   for(i=0; i<n; i++, pRec++){
5668     assert( memIsValid(pRec) );
5669     apVal[i] = pRec;
5670     memAboutToChange(p, pRec);
5671   }
5672   ctx.pFunc = pOp->p4.pFunc;
5673   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
5674   ctx.pMem = pMem = &aMem[pOp->p3];
5675   pMem->n++;
5676   ctx.s.flags = MEM_Null;
5677   ctx.s.z = 0;
5678   ctx.s.zMalloc = 0;
5679   ctx.s.xDel = 0;
5680   ctx.s.db = db;
5681   ctx.isError = 0;
5682   ctx.pColl = 0;
5683   ctx.skipFlag = 0;
5684   if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
5685     assert( pOp>p->aOp );
5686     assert( pOp[-1].p4type==P4_COLLSEQ );
5687     assert( pOp[-1].opcode==OP_CollSeq );
5688     ctx.pColl = pOp[-1].p4.pColl;
5689   }
5690   (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
5691   if( ctx.isError ){
5692     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
5693     rc = ctx.isError;
5694   }
5695   if( ctx.skipFlag ){
5696     assert( pOp[-1].opcode==OP_CollSeq );
5697     i = pOp[-1].p1;
5698     if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
5699   }
5700 
5701   sqlite3VdbeMemRelease(&ctx.s);
5702 
5703   break;
5704 }
5705 
5706 /* Opcode: AggFinal P1 P2 * P4 *
5707 ** Synopsis: accum=r[P1] N=P2
5708 **
5709 ** Execute the finalizer function for an aggregate.  P1 is
5710 ** the memory location that is the accumulator for the aggregate.
5711 **
5712 ** P2 is the number of arguments that the step function takes and
5713 ** P4 is a pointer to the FuncDef for this function.  The P2
5714 ** argument is not used by this opcode.  It is only there to disambiguate
5715 ** functions that can take varying numbers of arguments.  The
5716 ** P4 argument is only needed for the degenerate case where
5717 ** the step function was not previously called.
5718 */
5719 case OP_AggFinal: {
5720   Mem *pMem;
5721   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
5722   pMem = &aMem[pOp->p1];
5723   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
5724   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
5725   if( rc ){
5726     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
5727   }
5728   sqlite3VdbeChangeEncoding(pMem, encoding);
5729   UPDATE_MAX_BLOBSIZE(pMem);
5730   if( sqlite3VdbeMemTooBig(pMem) ){
5731     goto too_big;
5732   }
5733   break;
5734 }
5735 
5736 #ifndef SQLITE_OMIT_WAL
5737 /* Opcode: Checkpoint P1 P2 P3 * *
5738 **
5739 ** Checkpoint database P1. This is a no-op if P1 is not currently in
5740 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
5741 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
5742 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
5743 ** WAL after the checkpoint into mem[P3+1] and the number of pages
5744 ** in the WAL that have been checkpointed after the checkpoint
5745 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
5746 ** mem[P3+2] are initialized to -1.
5747 */
5748 case OP_Checkpoint: {
5749   int i;                          /* Loop counter */
5750   int aRes[3];                    /* Results */
5751   Mem *pMem;                      /* Write results here */
5752 
5753   assert( p->readOnly==0 );
5754   aRes[0] = 0;
5755   aRes[1] = aRes[2] = -1;
5756   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
5757        || pOp->p2==SQLITE_CHECKPOINT_FULL
5758        || pOp->p2==SQLITE_CHECKPOINT_RESTART
5759   );
5760   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
5761   if( rc==SQLITE_BUSY ){
5762     rc = SQLITE_OK;
5763     aRes[0] = 1;
5764   }
5765   for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
5766     sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
5767   }
5768   break;
5769 };
5770 #endif
5771 
5772 #ifndef SQLITE_OMIT_PRAGMA
5773 /* Opcode: JournalMode P1 P2 P3 * *
5774 **
5775 ** Change the journal mode of database P1 to P3. P3 must be one of the
5776 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
5777 ** modes (delete, truncate, persist, off and memory), this is a simple
5778 ** operation. No IO is required.
5779 **
5780 ** If changing into or out of WAL mode the procedure is more complicated.
5781 **
5782 ** Write a string containing the final journal-mode to register P2.
5783 */
5784 case OP_JournalMode: {    /* out2-prerelease */
5785   Btree *pBt;                     /* Btree to change journal mode of */
5786   Pager *pPager;                  /* Pager associated with pBt */
5787   int eNew;                       /* New journal mode */
5788   int eOld;                       /* The old journal mode */
5789 #ifndef SQLITE_OMIT_WAL
5790   const char *zFilename;          /* Name of database file for pPager */
5791 #endif
5792 
5793   eNew = pOp->p3;
5794   assert( eNew==PAGER_JOURNALMODE_DELETE
5795        || eNew==PAGER_JOURNALMODE_TRUNCATE
5796        || eNew==PAGER_JOURNALMODE_PERSIST
5797        || eNew==PAGER_JOURNALMODE_OFF
5798        || eNew==PAGER_JOURNALMODE_MEMORY
5799        || eNew==PAGER_JOURNALMODE_WAL
5800        || eNew==PAGER_JOURNALMODE_QUERY
5801   );
5802   assert( pOp->p1>=0 && pOp->p1<db->nDb );
5803   assert( p->readOnly==0 );
5804 
5805   pBt = db->aDb[pOp->p1].pBt;
5806   pPager = sqlite3BtreePager(pBt);
5807   eOld = sqlite3PagerGetJournalMode(pPager);
5808   if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
5809   if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
5810 
5811 #ifndef SQLITE_OMIT_WAL
5812   zFilename = sqlite3PagerFilename(pPager, 1);
5813 
5814   /* Do not allow a transition to journal_mode=WAL for a database
5815   ** in temporary storage or if the VFS does not support shared memory
5816   */
5817   if( eNew==PAGER_JOURNALMODE_WAL
5818    && (sqlite3Strlen30(zFilename)==0           /* Temp file */
5819        || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
5820   ){
5821     eNew = eOld;
5822   }
5823 
5824   if( (eNew!=eOld)
5825    && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
5826   ){
5827     if( !db->autoCommit || db->nVdbeRead>1 ){
5828       rc = SQLITE_ERROR;
5829       sqlite3SetString(&p->zErrMsg, db,
5830           "cannot change %s wal mode from within a transaction",
5831           (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
5832       );
5833       break;
5834     }else{
5835 
5836       if( eOld==PAGER_JOURNALMODE_WAL ){
5837         /* If leaving WAL mode, close the log file. If successful, the call
5838         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
5839         ** file. An EXCLUSIVE lock may still be held on the database file
5840         ** after a successful return.
5841         */
5842         rc = sqlite3PagerCloseWal(pPager);
5843         if( rc==SQLITE_OK ){
5844           sqlite3PagerSetJournalMode(pPager, eNew);
5845         }
5846       }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
5847         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
5848         ** as an intermediate */
5849         sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
5850       }
5851 
5852       /* Open a transaction on the database file. Regardless of the journal
5853       ** mode, this transaction always uses a rollback journal.
5854       */
5855       assert( sqlite3BtreeIsInTrans(pBt)==0 );
5856       if( rc==SQLITE_OK ){
5857         rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
5858       }
5859     }
5860   }
5861 #endif /* ifndef SQLITE_OMIT_WAL */
5862 
5863   if( rc ){
5864     eNew = eOld;
5865   }
5866   eNew = sqlite3PagerSetJournalMode(pPager, eNew);
5867 
5868   pOut = &aMem[pOp->p2];
5869   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
5870   pOut->z = (char *)sqlite3JournalModename(eNew);
5871   pOut->n = sqlite3Strlen30(pOut->z);
5872   pOut->enc = SQLITE_UTF8;
5873   sqlite3VdbeChangeEncoding(pOut, encoding);
5874   break;
5875 };
5876 #endif /* SQLITE_OMIT_PRAGMA */
5877 
5878 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
5879 /* Opcode: Vacuum * * * * *
5880 **
5881 ** Vacuum the entire database.  This opcode will cause other virtual
5882 ** machines to be created and run.  It may not be called from within
5883 ** a transaction.
5884 */
5885 case OP_Vacuum: {
5886   assert( p->readOnly==0 );
5887   rc = sqlite3RunVacuum(&p->zErrMsg, db);
5888   break;
5889 }
5890 #endif
5891 
5892 #if !defined(SQLITE_OMIT_AUTOVACUUM)
5893 /* Opcode: IncrVacuum P1 P2 * * *
5894 **
5895 ** Perform a single step of the incremental vacuum procedure on
5896 ** the P1 database. If the vacuum has finished, jump to instruction
5897 ** P2. Otherwise, fall through to the next instruction.
5898 */
5899 case OP_IncrVacuum: {        /* jump */
5900   Btree *pBt;
5901 
5902   assert( pOp->p1>=0 && pOp->p1<db->nDb );
5903   assert( DbMaskTest(p->btreeMask, pOp->p1) );
5904   assert( p->readOnly==0 );
5905   pBt = db->aDb[pOp->p1].pBt;
5906   rc = sqlite3BtreeIncrVacuum(pBt);
5907   VdbeBranchTaken(rc==SQLITE_DONE,2);
5908   if( rc==SQLITE_DONE ){
5909     pc = pOp->p2 - 1;
5910     rc = SQLITE_OK;
5911   }
5912   break;
5913 }
5914 #endif
5915 
5916 /* Opcode: Expire P1 * * * *
5917 **
5918 ** Cause precompiled statements to expire.  When an expired statement
5919 ** is executed using sqlite3_step() it will either automatically
5920 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
5921 ** or it will fail with SQLITE_SCHEMA.
5922 **
5923 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
5924 ** then only the currently executing statement is expired.
5925 */
5926 case OP_Expire: {
5927   if( !pOp->p1 ){
5928     sqlite3ExpirePreparedStatements(db);
5929   }else{
5930     p->expired = 1;
5931   }
5932   break;
5933 }
5934 
5935 #ifndef SQLITE_OMIT_SHARED_CACHE
5936 /* Opcode: TableLock P1 P2 P3 P4 *
5937 ** Synopsis: iDb=P1 root=P2 write=P3
5938 **
5939 ** Obtain a lock on a particular table. This instruction is only used when
5940 ** the shared-cache feature is enabled.
5941 **
5942 ** P1 is the index of the database in sqlite3.aDb[] of the database
5943 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
5944 ** a write lock if P3==1.
5945 **
5946 ** P2 contains the root-page of the table to lock.
5947 **
5948 ** P4 contains a pointer to the name of the table being locked. This is only
5949 ** used to generate an error message if the lock cannot be obtained.
5950 */
5951 case OP_TableLock: {
5952   u8 isWriteLock = (u8)pOp->p3;
5953   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
5954     int p1 = pOp->p1;
5955     assert( p1>=0 && p1<db->nDb );
5956     assert( DbMaskTest(p->btreeMask, p1) );
5957     assert( isWriteLock==0 || isWriteLock==1 );
5958     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
5959     if( (rc&0xFF)==SQLITE_LOCKED ){
5960       const char *z = pOp->p4.z;
5961       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
5962     }
5963   }
5964   break;
5965 }
5966 #endif /* SQLITE_OMIT_SHARED_CACHE */
5967 
5968 #ifndef SQLITE_OMIT_VIRTUALTABLE
5969 /* Opcode: VBegin * * * P4 *
5970 **
5971 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
5972 ** xBegin method for that table.
5973 **
5974 ** Also, whether or not P4 is set, check that this is not being called from
5975 ** within a callback to a virtual table xSync() method. If it is, the error
5976 ** code will be set to SQLITE_LOCKED.
5977 */
5978 case OP_VBegin: {
5979   VTable *pVTab;
5980   pVTab = pOp->p4.pVtab;
5981   rc = sqlite3VtabBegin(db, pVTab);
5982   if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
5983   break;
5984 }
5985 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5986 
5987 #ifndef SQLITE_OMIT_VIRTUALTABLE
5988 /* Opcode: VCreate P1 * * P4 *
5989 **
5990 ** P4 is the name of a virtual table in database P1. Call the xCreate method
5991 ** for that table.
5992 */
5993 case OP_VCreate: {
5994   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
5995   break;
5996 }
5997 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5998 
5999 #ifndef SQLITE_OMIT_VIRTUALTABLE
6000 /* Opcode: VDestroy P1 * * P4 *
6001 **
6002 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
6003 ** of that table.
6004 */
6005 case OP_VDestroy: {
6006   p->inVtabMethod = 2;
6007   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
6008   p->inVtabMethod = 0;
6009   break;
6010 }
6011 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6012 
6013 #ifndef SQLITE_OMIT_VIRTUALTABLE
6014 /* Opcode: VOpen P1 * * P4 *
6015 **
6016 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6017 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
6018 ** table and stores that cursor in P1.
6019 */
6020 case OP_VOpen: {
6021   VdbeCursor *pCur;
6022   sqlite3_vtab_cursor *pVtabCursor;
6023   sqlite3_vtab *pVtab;
6024   sqlite3_module *pModule;
6025 
6026   assert( p->bIsReader );
6027   pCur = 0;
6028   pVtabCursor = 0;
6029   pVtab = pOp->p4.pVtab->pVtab;
6030   pModule = (sqlite3_module *)pVtab->pModule;
6031   assert(pVtab && pModule);
6032   rc = pModule->xOpen(pVtab, &pVtabCursor);
6033   sqlite3VtabImportErrmsg(p, pVtab);
6034   if( SQLITE_OK==rc ){
6035     /* Initialize sqlite3_vtab_cursor base class */
6036     pVtabCursor->pVtab = pVtab;
6037 
6038     /* Initialize vdbe cursor object */
6039     pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
6040     if( pCur ){
6041       pCur->pVtabCursor = pVtabCursor;
6042     }else{
6043       db->mallocFailed = 1;
6044       pModule->xClose(pVtabCursor);
6045     }
6046   }
6047   break;
6048 }
6049 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6050 
6051 #ifndef SQLITE_OMIT_VIRTUALTABLE
6052 /* Opcode: VFilter P1 P2 P3 P4 *
6053 ** Synopsis: iplan=r[P3] zplan='P4'
6054 **
6055 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
6056 ** the filtered result set is empty.
6057 **
6058 ** P4 is either NULL or a string that was generated by the xBestIndex
6059 ** method of the module.  The interpretation of the P4 string is left
6060 ** to the module implementation.
6061 **
6062 ** This opcode invokes the xFilter method on the virtual table specified
6063 ** by P1.  The integer query plan parameter to xFilter is stored in register
6064 ** P3. Register P3+1 stores the argc parameter to be passed to the
6065 ** xFilter method. Registers P3+2..P3+1+argc are the argc
6066 ** additional parameters which are passed to
6067 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
6068 **
6069 ** A jump is made to P2 if the result set after filtering would be empty.
6070 */
6071 case OP_VFilter: {   /* jump */
6072   int nArg;
6073   int iQuery;
6074   const sqlite3_module *pModule;
6075   Mem *pQuery;
6076   Mem *pArgc;
6077   sqlite3_vtab_cursor *pVtabCursor;
6078   sqlite3_vtab *pVtab;
6079   VdbeCursor *pCur;
6080   int res;
6081   int i;
6082   Mem **apArg;
6083 
6084   pQuery = &aMem[pOp->p3];
6085   pArgc = &pQuery[1];
6086   pCur = p->apCsr[pOp->p1];
6087   assert( memIsValid(pQuery) );
6088   REGISTER_TRACE(pOp->p3, pQuery);
6089   assert( pCur->pVtabCursor );
6090   pVtabCursor = pCur->pVtabCursor;
6091   pVtab = pVtabCursor->pVtab;
6092   pModule = pVtab->pModule;
6093 
6094   /* Grab the index number and argc parameters */
6095   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
6096   nArg = (int)pArgc->u.i;
6097   iQuery = (int)pQuery->u.i;
6098 
6099   /* Invoke the xFilter method */
6100   {
6101     res = 0;
6102     apArg = p->apArg;
6103     for(i = 0; i<nArg; i++){
6104       apArg[i] = &pArgc[i+1];
6105     }
6106 
6107     p->inVtabMethod = 1;
6108     rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
6109     p->inVtabMethod = 0;
6110     sqlite3VtabImportErrmsg(p, pVtab);
6111     if( rc==SQLITE_OK ){
6112       res = pModule->xEof(pVtabCursor);
6113     }
6114     VdbeBranchTaken(res!=0,2);
6115     if( res ){
6116       pc = pOp->p2 - 1;
6117     }
6118   }
6119   pCur->nullRow = 0;
6120 
6121   break;
6122 }
6123 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6124 
6125 #ifndef SQLITE_OMIT_VIRTUALTABLE
6126 /* Opcode: VColumn P1 P2 P3 * *
6127 ** Synopsis: r[P3]=vcolumn(P2)
6128 **
6129 ** Store the value of the P2-th column of
6130 ** the row of the virtual-table that the
6131 ** P1 cursor is pointing to into register P3.
6132 */
6133 case OP_VColumn: {
6134   sqlite3_vtab *pVtab;
6135   const sqlite3_module *pModule;
6136   Mem *pDest;
6137   sqlite3_context sContext;
6138 
6139   VdbeCursor *pCur = p->apCsr[pOp->p1];
6140   assert( pCur->pVtabCursor );
6141   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
6142   pDest = &aMem[pOp->p3];
6143   memAboutToChange(p, pDest);
6144   if( pCur->nullRow ){
6145     sqlite3VdbeMemSetNull(pDest);
6146     break;
6147   }
6148   pVtab = pCur->pVtabCursor->pVtab;
6149   pModule = pVtab->pModule;
6150   assert( pModule->xColumn );
6151   memset(&sContext, 0, sizeof(sContext));
6152 
6153   /* The output cell may already have a buffer allocated. Move
6154   ** the current contents to sContext.s so in case the user-function
6155   ** can use the already allocated buffer instead of allocating a
6156   ** new one.
6157   */
6158   sqlite3VdbeMemMove(&sContext.s, pDest);
6159   MemSetTypeFlag(&sContext.s, MEM_Null);
6160 
6161   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
6162   sqlite3VtabImportErrmsg(p, pVtab);
6163   if( sContext.isError ){
6164     rc = sContext.isError;
6165   }
6166 
6167   /* Copy the result of the function to the P3 register. We
6168   ** do this regardless of whether or not an error occurred to ensure any
6169   ** dynamic allocation in sContext.s (a Mem struct) is  released.
6170   */
6171   sqlite3VdbeChangeEncoding(&sContext.s, encoding);
6172   sqlite3VdbeMemMove(pDest, &sContext.s);
6173   REGISTER_TRACE(pOp->p3, pDest);
6174   UPDATE_MAX_BLOBSIZE(pDest);
6175 
6176   if( sqlite3VdbeMemTooBig(pDest) ){
6177     goto too_big;
6178   }
6179   break;
6180 }
6181 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6182 
6183 #ifndef SQLITE_OMIT_VIRTUALTABLE
6184 /* Opcode: VNext P1 P2 * * *
6185 **
6186 ** Advance virtual table P1 to the next row in its result set and
6187 ** jump to instruction P2.  Or, if the virtual table has reached
6188 ** the end of its result set, then fall through to the next instruction.
6189 */
6190 case OP_VNext: {   /* jump */
6191   sqlite3_vtab *pVtab;
6192   const sqlite3_module *pModule;
6193   int res;
6194   VdbeCursor *pCur;
6195 
6196   res = 0;
6197   pCur = p->apCsr[pOp->p1];
6198   assert( pCur->pVtabCursor );
6199   if( pCur->nullRow ){
6200     break;
6201   }
6202   pVtab = pCur->pVtabCursor->pVtab;
6203   pModule = pVtab->pModule;
6204   assert( pModule->xNext );
6205 
6206   /* Invoke the xNext() method of the module. There is no way for the
6207   ** underlying implementation to return an error if one occurs during
6208   ** xNext(). Instead, if an error occurs, true is returned (indicating that
6209   ** data is available) and the error code returned when xColumn or
6210   ** some other method is next invoked on the save virtual table cursor.
6211   */
6212   p->inVtabMethod = 1;
6213   rc = pModule->xNext(pCur->pVtabCursor);
6214   p->inVtabMethod = 0;
6215   sqlite3VtabImportErrmsg(p, pVtab);
6216   if( rc==SQLITE_OK ){
6217     res = pModule->xEof(pCur->pVtabCursor);
6218   }
6219   VdbeBranchTaken(!res,2);
6220   if( !res ){
6221     /* If there is data, jump to P2 */
6222     pc = pOp->p2 - 1;
6223   }
6224   goto check_for_interrupt;
6225 }
6226 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6227 
6228 #ifndef SQLITE_OMIT_VIRTUALTABLE
6229 /* Opcode: VRename P1 * * P4 *
6230 **
6231 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6232 ** This opcode invokes the corresponding xRename method. The value
6233 ** in register P1 is passed as the zName argument to the xRename method.
6234 */
6235 case OP_VRename: {
6236   sqlite3_vtab *pVtab;
6237   Mem *pName;
6238 
6239   pVtab = pOp->p4.pVtab->pVtab;
6240   pName = &aMem[pOp->p1];
6241   assert( pVtab->pModule->xRename );
6242   assert( memIsValid(pName) );
6243   assert( p->readOnly==0 );
6244   REGISTER_TRACE(pOp->p1, pName);
6245   assert( pName->flags & MEM_Str );
6246   testcase( pName->enc==SQLITE_UTF8 );
6247   testcase( pName->enc==SQLITE_UTF16BE );
6248   testcase( pName->enc==SQLITE_UTF16LE );
6249   rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
6250   if( rc==SQLITE_OK ){
6251     rc = pVtab->pModule->xRename(pVtab, pName->z);
6252     sqlite3VtabImportErrmsg(p, pVtab);
6253     p->expired = 0;
6254   }
6255   break;
6256 }
6257 #endif
6258 
6259 #ifndef SQLITE_OMIT_VIRTUALTABLE
6260 /* Opcode: VUpdate P1 P2 P3 P4 P5
6261 ** Synopsis: data=r[P3@P2]
6262 **
6263 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
6264 ** This opcode invokes the corresponding xUpdate method. P2 values
6265 ** are contiguous memory cells starting at P3 to pass to the xUpdate
6266 ** invocation. The value in register (P3+P2-1) corresponds to the
6267 ** p2th element of the argv array passed to xUpdate.
6268 **
6269 ** The xUpdate method will do a DELETE or an INSERT or both.
6270 ** The argv[0] element (which corresponds to memory cell P3)
6271 ** is the rowid of a row to delete.  If argv[0] is NULL then no
6272 ** deletion occurs.  The argv[1] element is the rowid of the new
6273 ** row.  This can be NULL to have the virtual table select the new
6274 ** rowid for itself.  The subsequent elements in the array are
6275 ** the values of columns in the new row.
6276 **
6277 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
6278 ** a row to delete.
6279 **
6280 ** P1 is a boolean flag. If it is set to true and the xUpdate call
6281 ** is successful, then the value returned by sqlite3_last_insert_rowid()
6282 ** is set to the value of the rowid for the row just inserted.
6283 **
6284 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
6285 ** apply in the case of a constraint failure on an insert or update.
6286 */
6287 case OP_VUpdate: {
6288   sqlite3_vtab *pVtab;
6289   sqlite3_module *pModule;
6290   int nArg;
6291   int i;
6292   sqlite_int64 rowid;
6293   Mem **apArg;
6294   Mem *pX;
6295 
6296   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
6297        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
6298   );
6299   assert( p->readOnly==0 );
6300   pVtab = pOp->p4.pVtab->pVtab;
6301   pModule = (sqlite3_module *)pVtab->pModule;
6302   nArg = pOp->p2;
6303   assert( pOp->p4type==P4_VTAB );
6304   if( ALWAYS(pModule->xUpdate) ){
6305     u8 vtabOnConflict = db->vtabOnConflict;
6306     apArg = p->apArg;
6307     pX = &aMem[pOp->p3];
6308     for(i=0; i<nArg; i++){
6309       assert( memIsValid(pX) );
6310       memAboutToChange(p, pX);
6311       apArg[i] = pX;
6312       pX++;
6313     }
6314     db->vtabOnConflict = pOp->p5;
6315     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
6316     db->vtabOnConflict = vtabOnConflict;
6317     sqlite3VtabImportErrmsg(p, pVtab);
6318     if( rc==SQLITE_OK && pOp->p1 ){
6319       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
6320       db->lastRowid = lastRowid = rowid;
6321     }
6322     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
6323       if( pOp->p5==OE_Ignore ){
6324         rc = SQLITE_OK;
6325       }else{
6326         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
6327       }
6328     }else{
6329       p->nChange++;
6330     }
6331   }
6332   break;
6333 }
6334 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6335 
6336 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
6337 /* Opcode: Pagecount P1 P2 * * *
6338 **
6339 ** Write the current number of pages in database P1 to memory cell P2.
6340 */
6341 case OP_Pagecount: {            /* out2-prerelease */
6342   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
6343   break;
6344 }
6345 #endif
6346 
6347 
6348 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
6349 /* Opcode: MaxPgcnt P1 P2 P3 * *
6350 **
6351 ** Try to set the maximum page count for database P1 to the value in P3.
6352 ** Do not let the maximum page count fall below the current page count and
6353 ** do not change the maximum page count value if P3==0.
6354 **
6355 ** Store the maximum page count after the change in register P2.
6356 */
6357 case OP_MaxPgcnt: {            /* out2-prerelease */
6358   unsigned int newMax;
6359   Btree *pBt;
6360 
6361   pBt = db->aDb[pOp->p1].pBt;
6362   newMax = 0;
6363   if( pOp->p3 ){
6364     newMax = sqlite3BtreeLastPage(pBt);
6365     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
6366   }
6367   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
6368   break;
6369 }
6370 #endif
6371 
6372 
6373 /* Opcode: Init * P2 * P4 *
6374 ** Synopsis:  Start at P2
6375 **
6376 ** Programs contain a single instance of this opcode as the very first
6377 ** opcode.
6378 **
6379 ** If tracing is enabled (by the sqlite3_trace()) interface, then
6380 ** the UTF-8 string contained in P4 is emitted on the trace callback.
6381 ** Or if P4 is blank, use the string returned by sqlite3_sql().
6382 **
6383 ** If P2 is not zero, jump to instruction P2.
6384 */
6385 case OP_Init: {          /* jump */
6386   char *zTrace;
6387   char *z;
6388 
6389   if( pOp->p2 ){
6390     pc = pOp->p2 - 1;
6391   }
6392 #ifndef SQLITE_OMIT_TRACE
6393   if( db->xTrace
6394    && !p->doingRerun
6395    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
6396   ){
6397     z = sqlite3VdbeExpandSql(p, zTrace);
6398     db->xTrace(db->pTraceArg, z);
6399     sqlite3DbFree(db, z);
6400   }
6401 #ifdef SQLITE_USE_FCNTL_TRACE
6402   zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
6403   if( zTrace ){
6404     int i;
6405     for(i=0; i<db->nDb; i++){
6406       if( DbMaskTest(p->btreeMask, i)==0 ) continue;
6407       sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
6408     }
6409   }
6410 #endif /* SQLITE_USE_FCNTL_TRACE */
6411 #ifdef SQLITE_DEBUG
6412   if( (db->flags & SQLITE_SqlTrace)!=0
6413    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
6414   ){
6415     sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
6416   }
6417 #endif /* SQLITE_DEBUG */
6418 #endif /* SQLITE_OMIT_TRACE */
6419   break;
6420 }
6421 
6422 
6423 /* Opcode: Noop * * * * *
6424 **
6425 ** Do nothing.  This instruction is often useful as a jump
6426 ** destination.
6427 */
6428 /*
6429 ** The magic Explain opcode are only inserted when explain==2 (which
6430 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
6431 ** This opcode records information from the optimizer.  It is the
6432 ** the same as a no-op.  This opcodesnever appears in a real VM program.
6433 */
6434 default: {          /* This is really OP_Noop and OP_Explain */
6435   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
6436   break;
6437 }
6438 
6439 /*****************************************************************************
6440 ** The cases of the switch statement above this line should all be indented
6441 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
6442 ** readability.  From this point on down, the normal indentation rules are
6443 ** restored.
6444 *****************************************************************************/
6445     }
6446 
6447 #ifdef VDBE_PROFILE
6448     {
6449       u64 endTime = sqlite3Hwtime();
6450       if( endTime>start ) pOp->cycles += endTime - start;
6451       pOp->cnt++;
6452     }
6453 #endif
6454 
6455     /* The following code adds nothing to the actual functionality
6456     ** of the program.  It is only here for testing and debugging.
6457     ** On the other hand, it does burn CPU cycles every time through
6458     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
6459     */
6460 #ifndef NDEBUG
6461     assert( pc>=-1 && pc<p->nOp );
6462 
6463 #ifdef SQLITE_DEBUG
6464     if( db->flags & SQLITE_VdbeTrace ){
6465       if( rc!=0 ) printf("rc=%d\n",rc);
6466       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
6467         registerTrace(pOp->p2, &aMem[pOp->p2]);
6468       }
6469       if( pOp->opflags & OPFLG_OUT3 ){
6470         registerTrace(pOp->p3, &aMem[pOp->p3]);
6471       }
6472     }
6473 #endif  /* SQLITE_DEBUG */
6474 #endif  /* NDEBUG */
6475   }  /* The end of the for(;;) loop the loops through opcodes */
6476 
6477   /* If we reach this point, it means that execution is finished with
6478   ** an error of some kind.
6479   */
6480 vdbe_error_halt:
6481   assert( rc );
6482   p->rc = rc;
6483   testcase( sqlite3GlobalConfig.xLog!=0 );
6484   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
6485                    pc, p->zSql, p->zErrMsg);
6486   sqlite3VdbeHalt(p);
6487   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
6488   rc = SQLITE_ERROR;
6489   if( resetSchemaOnFault>0 ){
6490     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
6491   }
6492 
6493   /* This is the only way out of this procedure.  We have to
6494   ** release the mutexes on btrees that were acquired at the
6495   ** top. */
6496 vdbe_return:
6497   db->lastRowid = lastRowid;
6498   testcase( nVmStep>0 );
6499   p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
6500   sqlite3VdbeLeave(p);
6501   return rc;
6502 
6503   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
6504   ** is encountered.
6505   */
6506 too_big:
6507   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
6508   rc = SQLITE_TOOBIG;
6509   goto vdbe_error_halt;
6510 
6511   /* Jump to here if a malloc() fails.
6512   */
6513 no_mem:
6514   db->mallocFailed = 1;
6515   sqlite3SetString(&p->zErrMsg, db, "out of memory");
6516   rc = SQLITE_NOMEM;
6517   goto vdbe_error_halt;
6518 
6519   /* Jump to here for any other kind of fatal error.  The "rc" variable
6520   ** should hold the error number.
6521   */
6522 abort_due_to_error:
6523   assert( p->zErrMsg==0 );
6524   if( db->mallocFailed ) rc = SQLITE_NOMEM;
6525   if( rc!=SQLITE_IOERR_NOMEM ){
6526     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
6527   }
6528   goto vdbe_error_halt;
6529 
6530   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
6531   ** flag.
6532   */
6533 abort_due_to_interrupt:
6534   assert( db->u1.isInterrupted );
6535   rc = SQLITE_INTERRUPT;
6536   p->rc = rc;
6537   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
6538   goto vdbe_error_halt;
6539 }
6540