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