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